UNPKG

6.6 MBJavaScriptView Raw
1/*! *****************************************************************************
2Copyright (c) Microsoft Corporation. All rights reserved.
3Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4this file except in compliance with the License. You may obtain a copy of the
5License at http://www.apache.org/licenses/LICENSE-2.0
6
7THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10MERCHANTABLITY OR NON-INFRINGEMENT.
11
12See the Apache Version 2.0 License for specific language governing permissions
13and limitations under the License.
14***************************************************************************** */
15
16
17"use strict";
18var __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};
25var __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};
36var __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};
40var __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};
67var __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})();
80var 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.0";
85 /** The version of the TypeScript compiler release */
86 ts.version = "4.0.6";
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 */
118var 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]);
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 ? Object.entries : function (obj) {
1275 var keys = getOwnKeys(obj);
1276 var result = Array(keys.length);
1277 for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
1278 var key = keys_1[_i];
1279 result.push([key, obj[key]]);
1280 }
1281 return result;
1282 };
1283 function getEntries(obj) {
1284 return obj ? _entries(obj) : [];
1285 }
1286 ts.getEntries = getEntries;
1287 function arrayOf(count, f) {
1288 var result = new Array(count);
1289 for (var i = 0; i < count; i++) {
1290 result[i] = f(i);
1291 }
1292 return result;
1293 }
1294 ts.arrayOf = arrayOf;
1295 function arrayFrom(iterator, map) {
1296 var result = [];
1297 for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1298 result.push(map ? map(iterResult.value) : iterResult.value);
1299 }
1300 return result;
1301 }
1302 ts.arrayFrom = arrayFrom;
1303 function assign(t) {
1304 var args = [];
1305 for (var _i = 1; _i < arguments.length; _i++) {
1306 args[_i - 1] = arguments[_i];
1307 }
1308 for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1309 var arg = args_1[_a];
1310 if (arg === undefined)
1311 continue;
1312 for (var p in arg) {
1313 if (hasProperty(arg, p)) {
1314 t[p] = arg[p];
1315 }
1316 }
1317 }
1318 return t;
1319 }
1320 ts.assign = assign;
1321 /**
1322 * Performs a shallow equality comparison of the contents of two map-likes.
1323 *
1324 * @param left A map-like whose properties should be compared.
1325 * @param right A map-like whose properties should be compared.
1326 */
1327 function equalOwnProperties(left, right, equalityComparer) {
1328 if (equalityComparer === void 0) { equalityComparer = equateValues; }
1329 if (left === right)
1330 return true;
1331 if (!left || !right)
1332 return false;
1333 for (var key in left) {
1334 if (hasOwnProperty.call(left, key)) {
1335 if (!hasOwnProperty.call(right, key))
1336 return false;
1337 if (!equalityComparer(left[key], right[key]))
1338 return false;
1339 }
1340 }
1341 for (var key in right) {
1342 if (hasOwnProperty.call(right, key)) {
1343 if (!hasOwnProperty.call(left, key))
1344 return false;
1345 }
1346 }
1347 return true;
1348 }
1349 ts.equalOwnProperties = equalOwnProperties;
1350 function arrayToMap(array, makeKey, makeValue) {
1351 if (makeValue === void 0) { makeValue = identity; }
1352 var result = new ts.Map();
1353 for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1354 var value = array_6[_i];
1355 var key = makeKey(value);
1356 if (key !== undefined)
1357 result.set(key, makeValue(value));
1358 }
1359 return result;
1360 }
1361 ts.arrayToMap = arrayToMap;
1362 function arrayToNumericMap(array, makeKey, makeValue) {
1363 if (makeValue === void 0) { makeValue = identity; }
1364 var result = [];
1365 for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1366 var value = array_7[_i];
1367 result[makeKey(value)] = makeValue(value);
1368 }
1369 return result;
1370 }
1371 ts.arrayToNumericMap = arrayToNumericMap;
1372 function arrayToMultiMap(values, makeKey, makeValue) {
1373 if (makeValue === void 0) { makeValue = identity; }
1374 var result = createMultiMap();
1375 for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1376 var value = values_1[_i];
1377 result.add(makeKey(value), makeValue(value));
1378 }
1379 return result;
1380 }
1381 ts.arrayToMultiMap = arrayToMultiMap;
1382 function group(values, getGroupId, resultSelector) {
1383 if (resultSelector === void 0) { resultSelector = identity; }
1384 return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1385 }
1386 ts.group = group;
1387 function clone(object) {
1388 var result = {};
1389 for (var id in object) {
1390 if (hasOwnProperty.call(object, id)) {
1391 result[id] = object[id];
1392 }
1393 }
1394 return result;
1395 }
1396 ts.clone = clone;
1397 /**
1398 * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1399 *
1400 * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1401 */
1402 function extend(first, second) {
1403 var result = {};
1404 for (var id in second) {
1405 if (hasOwnProperty.call(second, id)) {
1406 result[id] = second[id];
1407 }
1408 }
1409 for (var id in first) {
1410 if (hasOwnProperty.call(first, id)) {
1411 result[id] = first[id];
1412 }
1413 }
1414 return result;
1415 }
1416 ts.extend = extend;
1417 function copyProperties(first, second) {
1418 for (var id in second) {
1419 if (hasOwnProperty.call(second, id)) {
1420 first[id] = second[id];
1421 }
1422 }
1423 }
1424 ts.copyProperties = copyProperties;
1425 function maybeBind(obj, fn) {
1426 return fn ? fn.bind(obj) : undefined;
1427 }
1428 ts.maybeBind = maybeBind;
1429 function createMultiMap() {
1430 var map = new ts.Map();
1431 map.add = multiMapAdd;
1432 map.remove = multiMapRemove;
1433 return map;
1434 }
1435 ts.createMultiMap = createMultiMap;
1436 function multiMapAdd(key, value) {
1437 var values = this.get(key);
1438 if (values) {
1439 values.push(value);
1440 }
1441 else {
1442 this.set(key, values = [value]);
1443 }
1444 return values;
1445 }
1446 function multiMapRemove(key, value) {
1447 var values = this.get(key);
1448 if (values) {
1449 unorderedRemoveItem(values, value);
1450 if (!values.length) {
1451 this.delete(key);
1452 }
1453 }
1454 }
1455 function createUnderscoreEscapedMultiMap() {
1456 return createMultiMap();
1457 }
1458 ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1459 /**
1460 * Tests whether a value is an array.
1461 */
1462 function isArray(value) {
1463 return Array.isArray ? Array.isArray(value) : value instanceof Array;
1464 }
1465 ts.isArray = isArray;
1466 function toArray(value) {
1467 return isArray(value) ? value : [value];
1468 }
1469 ts.toArray = toArray;
1470 /**
1471 * Tests whether a value is string
1472 */
1473 function isString(text) {
1474 return typeof text === "string";
1475 }
1476 ts.isString = isString;
1477 function isNumber(x) {
1478 return typeof x === "number";
1479 }
1480 ts.isNumber = isNumber;
1481 function tryCast(value, test) {
1482 return value !== undefined && test(value) ? value : undefined;
1483 }
1484 ts.tryCast = tryCast;
1485 function cast(value, test) {
1486 if (value !== undefined && test(value))
1487 return value;
1488 return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1489 }
1490 ts.cast = cast;
1491 /** Does nothing. */
1492 function noop(_) { }
1493 ts.noop = noop;
1494 /** Do nothing and return false */
1495 function returnFalse() { return false; }
1496 ts.returnFalse = returnFalse;
1497 /** Do nothing and return true */
1498 function returnTrue() { return true; }
1499 ts.returnTrue = returnTrue;
1500 /** Do nothing and return undefined */
1501 function returnUndefined() { return undefined; }
1502 ts.returnUndefined = returnUndefined;
1503 /** Returns its argument. */
1504 function identity(x) { return x; }
1505 ts.identity = identity;
1506 /** Returns lower case string */
1507 function toLowerCase(x) { return x.toLowerCase(); }
1508 ts.toLowerCase = toLowerCase;
1509 // We convert the file names to lower case as key for file name on case insensitive file system
1510 // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1511 // it to lower case, fileName with its lowercase form can exist along side it.
1512 // Handle special characters and make those case sensitive instead
1513 //
1514 // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1515 // | 1. | i | 105 | Ascii i |
1516 // | 2. | I | 73 | Ascii I |
1517 // |-------- Special characters ------------------------------------------------------------------------|
1518 // | 3. | \u0130 | 304 | Uppper case I with dot above |
1519 // | 4. | i,\u0307 | 105,775 | i, followed by 775: Lower case of (3rd item) |
1520 // | 5. | I,\u0307 | 73,775 | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1521 // | 6. | \u0131 | 305 | Lower case i without dot, upper case is I (2nd item) |
1522 // | 7. | \u00DF | 223 | Lower case sharp s |
1523 //
1524 // Because item 3 is special where in its lowercase character has its own
1525 // upper case form we cant convert its case.
1526 // Rest special characters are either already in lower case format or
1527 // they have corresponding upper case character so they dont need special handling
1528 //
1529 // But to avoid having to do string building for most common cases, also ignore
1530 // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1531 var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1532 /**
1533 * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1534 * This function is used in places where we want to make file name as a key on these systems
1535 * 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
1536 * 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
1537 * Technically we would want this function to be platform sepcific as well but
1538 * 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
1539 * We could use upper case and we would still need to deal with the descripencies but
1540 * 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
1541 * 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
1542 */
1543 function toFileNameLowerCase(x) {
1544 return fileNameLowerCaseRegExp.test(x) ?
1545 x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1546 x;
1547 }
1548 ts.toFileNameLowerCase = toFileNameLowerCase;
1549 /** Throws an error because a function is not implemented. */
1550 function notImplemented() {
1551 throw new Error("Not implemented");
1552 }
1553 ts.notImplemented = notImplemented;
1554 function memoize(callback) {
1555 var value;
1556 return function () {
1557 if (callback) {
1558 value = callback();
1559 callback = undefined;
1560 }
1561 return value;
1562 };
1563 }
1564 ts.memoize = memoize;
1565 /** A version of `memoize` that supports a single primitive argument */
1566 function memoizeOne(callback) {
1567 var map = new ts.Map();
1568 return function (arg) {
1569 var key = typeof arg + ":" + arg;
1570 var value = map.get(key);
1571 if (value === undefined && !map.has(key)) {
1572 value = callback(arg);
1573 map.set(key, value);
1574 }
1575 return value;
1576 };
1577 }
1578 ts.memoizeOne = memoizeOne;
1579 function compose(a, b, c, d, e) {
1580 if (!!e) {
1581 var args_2 = [];
1582 for (var i = 0; i < arguments.length; i++) {
1583 args_2[i] = arguments[i];
1584 }
1585 return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1586 }
1587 else if (d) {
1588 return function (t) { return d(c(b(a(t)))); };
1589 }
1590 else if (c) {
1591 return function (t) { return c(b(a(t))); };
1592 }
1593 else if (b) {
1594 return function (t) { return b(a(t)); };
1595 }
1596 else if (a) {
1597 return function (t) { return a(t); };
1598 }
1599 else {
1600 return function (t) { return t; };
1601 }
1602 }
1603 ts.compose = compose;
1604 var AssertionLevel;
1605 (function (AssertionLevel) {
1606 AssertionLevel[AssertionLevel["None"] = 0] = "None";
1607 AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1608 AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1609 AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1610 })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1611 function equateValues(a, b) {
1612 return a === b;
1613 }
1614 ts.equateValues = equateValues;
1615 /**
1616 * Compare the equality of two strings using a case-sensitive ordinal comparison.
1617 *
1618 * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1619 * value of each code-point after applying `toUpperCase` to each string. We always map both
1620 * strings to their upper-case form as some unicode characters do not properly round-trip to
1621 * lowercase (such as `ẞ` (German sharp capital s)).
1622 */
1623 function equateStringsCaseInsensitive(a, b) {
1624 return a === b
1625 || a !== undefined
1626 && b !== undefined
1627 && a.toUpperCase() === b.toUpperCase();
1628 }
1629 ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1630 /**
1631 * Compare the equality of two strings using a case-sensitive ordinal comparison.
1632 *
1633 * Case-sensitive comparisons compare both strings one code-point at a time using the
1634 * integer value of each code-point.
1635 */
1636 function equateStringsCaseSensitive(a, b) {
1637 return equateValues(a, b);
1638 }
1639 ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1640 function compareComparableValues(a, b) {
1641 return a === b ? 0 /* EqualTo */ :
1642 a === undefined ? -1 /* LessThan */ :
1643 b === undefined ? 1 /* GreaterThan */ :
1644 a < b ? -1 /* LessThan */ :
1645 1 /* GreaterThan */;
1646 }
1647 /**
1648 * Compare two numeric values for their order relative to each other.
1649 * To compare strings, use any of the `compareStrings` functions.
1650 */
1651 function compareValues(a, b) {
1652 return compareComparableValues(a, b);
1653 }
1654 ts.compareValues = compareValues;
1655 /**
1656 * Compare two TextSpans, first by `start`, then by `length`.
1657 */
1658 function compareTextSpans(a, b) {
1659 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);
1660 }
1661 ts.compareTextSpans = compareTextSpans;
1662 function min(a, b, compare) {
1663 return compare(a, b) === -1 /* LessThan */ ? a : b;
1664 }
1665 ts.min = min;
1666 /**
1667 * Compare two strings using a case-insensitive ordinal comparison.
1668 *
1669 * Ordinal comparisons are based on the difference between the unicode code points of both
1670 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1671 * comparisons provide predictable ordering, but place "a" after "B".
1672 *
1673 * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1674 * value of each code-point after applying `toUpperCase` to each string. We always map both
1675 * strings to their upper-case form as some unicode characters do not properly round-trip to
1676 * lowercase (such as `ẞ` (German sharp capital s)).
1677 */
1678 function compareStringsCaseInsensitive(a, b) {
1679 if (a === b)
1680 return 0 /* EqualTo */;
1681 if (a === undefined)
1682 return -1 /* LessThan */;
1683 if (b === undefined)
1684 return 1 /* GreaterThan */;
1685 a = a.toUpperCase();
1686 b = b.toUpperCase();
1687 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1688 }
1689 ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1690 /**
1691 * Compare two strings using a case-sensitive ordinal comparison.
1692 *
1693 * Ordinal comparisons are based on the difference between the unicode code points of both
1694 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1695 * comparisons provide predictable ordering, but place "a" after "B".
1696 *
1697 * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1698 * value of each code-point.
1699 */
1700 function compareStringsCaseSensitive(a, b) {
1701 return compareComparableValues(a, b);
1702 }
1703 ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1704 function getStringComparer(ignoreCase) {
1705 return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1706 }
1707 ts.getStringComparer = getStringComparer;
1708 /**
1709 * Creates a string comparer for use with string collation in the UI.
1710 */
1711 var createUIStringComparer = (function () {
1712 var defaultComparer;
1713 var enUSComparer;
1714 var stringComparerFactory = getStringComparerFactory();
1715 return createStringComparer;
1716 function compareWithCallback(a, b, comparer) {
1717 if (a === b)
1718 return 0 /* EqualTo */;
1719 if (a === undefined)
1720 return -1 /* LessThan */;
1721 if (b === undefined)
1722 return 1 /* GreaterThan */;
1723 var value = comparer(a, b);
1724 return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1725 }
1726 function createIntlCollatorStringComparer(locale) {
1727 // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1728 // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1729 var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1730 return function (a, b) { return compareWithCallback(a, b, comparer); };
1731 }
1732 function createLocaleCompareStringComparer(locale) {
1733 // if the locale is not the default locale (`undefined`), use the fallback comparer.
1734 if (locale !== undefined)
1735 return createFallbackStringComparer();
1736 return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1737 function compareStrings(a, b) {
1738 return a.localeCompare(b);
1739 }
1740 }
1741 function createFallbackStringComparer() {
1742 // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1743 // We first sort case insensitively. So "Aaa" will come before "baa".
1744 // Then we sort case sensitively, so "aaa" will come before "Aaa".
1745 //
1746 // For case insensitive comparisons we always map both strings to their
1747 // upper-case form as some unicode characters do not properly round-trip to
1748 // lowercase (such as `ẞ` (German sharp capital s)).
1749 return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1750 function compareDictionaryOrder(a, b) {
1751 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1752 }
1753 function compareStrings(a, b) {
1754 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1755 }
1756 }
1757 function getStringComparerFactory() {
1758 // If the host supports Intl, we use it for comparisons using the default locale.
1759 if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1760 return createIntlCollatorStringComparer;
1761 }
1762 // If the host does not support Intl, we fall back to localeCompare.
1763 // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1764 if (typeof String.prototype.localeCompare === "function" &&
1765 typeof String.prototype.toLocaleUpperCase === "function" &&
1766 "a".localeCompare("B") < 0) {
1767 return createLocaleCompareStringComparer;
1768 }
1769 // Otherwise, fall back to ordinal comparison:
1770 return createFallbackStringComparer;
1771 }
1772 function createStringComparer(locale) {
1773 // Hold onto common string comparers. This avoids constantly reallocating comparers during
1774 // tests.
1775 if (locale === undefined) {
1776 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1777 }
1778 else if (locale === "en-US") {
1779 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1780 }
1781 else {
1782 return stringComparerFactory(locale);
1783 }
1784 }
1785 })();
1786 var uiComparerCaseSensitive;
1787 var uiLocale;
1788 function getUILocale() {
1789 return uiLocale;
1790 }
1791 ts.getUILocale = getUILocale;
1792 function setUILocale(value) {
1793 if (uiLocale !== value) {
1794 uiLocale = value;
1795 uiComparerCaseSensitive = undefined;
1796 }
1797 }
1798 ts.setUILocale = setUILocale;
1799 /**
1800 * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1801 *
1802 * Ordering is not predictable between different host locales, but is best for displaying
1803 * ordered data for UI presentation. Characters with multiple unicode representations may
1804 * be considered equal.
1805 *
1806 * Case-sensitive comparisons compare strings that differ in base characters, or
1807 * accents/diacritic marks, or case as unequal.
1808 */
1809 function compareStringsCaseSensitiveUI(a, b) {
1810 var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1811 return comparer(a, b);
1812 }
1813 ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1814 function compareProperties(a, b, key, comparer) {
1815 return a === b ? 0 /* EqualTo */ :
1816 a === undefined ? -1 /* LessThan */ :
1817 b === undefined ? 1 /* GreaterThan */ :
1818 comparer(a[key], b[key]);
1819 }
1820 ts.compareProperties = compareProperties;
1821 /** True is greater than false. */
1822 function compareBooleans(a, b) {
1823 return compareValues(a ? 1 : 0, b ? 1 : 0);
1824 }
1825 ts.compareBooleans = compareBooleans;
1826 /**
1827 * 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.
1828 * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1829 *
1830 * If there is a candidate that's the same except for case, return that.
1831 * If there is a candidate that's within one edit of the name, return that.
1832 * Otherwise, return the candidate with the smallest Levenshtein distance,
1833 * except for candidates:
1834 * * With no name
1835 * * Whose length differs from the target name by more than 0.34 of the length of the name.
1836 * * Whose levenshtein distance is more than 0.4 of the length of the name
1837 * (0.4 allows 1 substitution/transposition for every 5 characters,
1838 * and 1 insertion/deletion at 3 characters)
1839 */
1840 function getSpellingSuggestion(name, candidates, getName) {
1841 var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1842 var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1843 var bestCandidate;
1844 var justCheckExactMatches = false;
1845 var nameLowerCase = name.toLowerCase();
1846 for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1847 var candidate = candidates_1[_i];
1848 var candidateName = getName(candidate);
1849 if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1850 var candidateNameLowerCase = candidateName.toLowerCase();
1851 if (candidateNameLowerCase === nameLowerCase) {
1852 if (candidateName === name) {
1853 continue;
1854 }
1855 return candidate;
1856 }
1857 if (justCheckExactMatches) {
1858 continue;
1859 }
1860 if (candidateName.length < 3) {
1861 // Don't bother, user would have noticed a 2-character name having an extra character
1862 continue;
1863 }
1864 // Only care about a result better than the best so far.
1865 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1866 if (distance === undefined) {
1867 continue;
1868 }
1869 if (distance < 3) {
1870 justCheckExactMatches = true;
1871 bestCandidate = candidate;
1872 }
1873 else {
1874 ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1875 bestDistance = distance;
1876 bestCandidate = candidate;
1877 }
1878 }
1879 }
1880 return bestCandidate;
1881 }
1882 ts.getSpellingSuggestion = getSpellingSuggestion;
1883 function levenshteinWithMax(s1, s2, max) {
1884 var previous = new Array(s2.length + 1);
1885 var current = new Array(s2.length + 1);
1886 /** Represents any value > max. We don't care about the particular value. */
1887 var big = max + 1;
1888 for (var i = 0; i <= s2.length; i++) {
1889 previous[i] = i;
1890 }
1891 for (var i = 1; i <= s1.length; i++) {
1892 var c1 = s1.charCodeAt(i - 1);
1893 var minJ = i > max ? i - max : 1;
1894 var maxJ = s2.length > max + i ? max + i : s2.length;
1895 current[0] = i;
1896 /** Smallest value of the matrix in the ith column. */
1897 var colMin = i;
1898 for (var j = 1; j < minJ; j++) {
1899 current[j] = big;
1900 }
1901 for (var j = minJ; j <= maxJ; j++) {
1902 var dist = c1 === s2.charCodeAt(j - 1)
1903 ? previous[j - 1]
1904 : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1905 current[j] = dist;
1906 colMin = Math.min(colMin, dist);
1907 }
1908 for (var j = maxJ + 1; j <= s2.length; j++) {
1909 current[j] = big;
1910 }
1911 if (colMin > max) {
1912 // Give up -- everything in this column is > max and it can't get better in future columns.
1913 return undefined;
1914 }
1915 var temp = previous;
1916 previous = current;
1917 current = temp;
1918 }
1919 var res = previous[s2.length];
1920 return res > max ? undefined : res;
1921 }
1922 function endsWith(str, suffix) {
1923 var expectedPos = str.length - suffix.length;
1924 return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1925 }
1926 ts.endsWith = endsWith;
1927 function removeSuffix(str, suffix) {
1928 return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1929 }
1930 ts.removeSuffix = removeSuffix;
1931 function tryRemoveSuffix(str, suffix) {
1932 return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1933 }
1934 ts.tryRemoveSuffix = tryRemoveSuffix;
1935 function stringContains(str, substring) {
1936 return str.indexOf(substring) !== -1;
1937 }
1938 ts.stringContains = stringContains;
1939 /**
1940 * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1941 */
1942 function removeMinAndVersionNumbers(fileName) {
1943 // Match a "." or "-" followed by a version number or 'min' at the end of the name
1944 var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1945 // The "min" or version may both be present, in either order, so try applying the above twice.
1946 return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1947 }
1948 ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1949 /** Remove an item from an array, moving everything to its right one space left. */
1950 function orderedRemoveItem(array, item) {
1951 for (var i = 0; i < array.length; i++) {
1952 if (array[i] === item) {
1953 orderedRemoveItemAt(array, i);
1954 return true;
1955 }
1956 }
1957 return false;
1958 }
1959 ts.orderedRemoveItem = orderedRemoveItem;
1960 /** Remove an item by index from an array, moving everything to its right one space left. */
1961 function orderedRemoveItemAt(array, index) {
1962 // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1963 for (var i = index; i < array.length - 1; i++) {
1964 array[i] = array[i + 1];
1965 }
1966 array.pop();
1967 }
1968 ts.orderedRemoveItemAt = orderedRemoveItemAt;
1969 function unorderedRemoveItemAt(array, index) {
1970 // Fill in the "hole" left at `index`.
1971 array[index] = array[array.length - 1];
1972 array.pop();
1973 }
1974 ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1975 /** Remove the *first* occurrence of `item` from the array. */
1976 function unorderedRemoveItem(array, item) {
1977 return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1978 }
1979 ts.unorderedRemoveItem = unorderedRemoveItem;
1980 /** Remove the *first* element satisfying `predicate`. */
1981 function unorderedRemoveFirstItemWhere(array, predicate) {
1982 for (var i = 0; i < array.length; i++) {
1983 if (predicate(array[i])) {
1984 unorderedRemoveItemAt(array, i);
1985 return true;
1986 }
1987 }
1988 return false;
1989 }
1990 function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1991 return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1992 }
1993 ts.createGetCanonicalFileName = createGetCanonicalFileName;
1994 function patternText(_a) {
1995 var prefix = _a.prefix, suffix = _a.suffix;
1996 return prefix + "*" + suffix;
1997 }
1998 ts.patternText = patternText;
1999 /**
2000 * Given that candidate matches pattern, returns the text matching the '*'.
2001 * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2002 */
2003 function matchedText(pattern, candidate) {
2004 ts.Debug.assert(isPatternMatch(pattern, candidate));
2005 return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2006 }
2007 ts.matchedText = matchedText;
2008 /** Return the object corresponding to the best pattern to match `candidate`. */
2009 function findBestPatternMatch(values, getPattern, candidate) {
2010 var matchedValue;
2011 // use length of prefix as betterness criteria
2012 var longestMatchPrefixLength = -1;
2013 for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2014 var v = values_2[_i];
2015 var pattern = getPattern(v);
2016 if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2017 longestMatchPrefixLength = pattern.prefix.length;
2018 matchedValue = v;
2019 }
2020 }
2021 return matchedValue;
2022 }
2023 ts.findBestPatternMatch = findBestPatternMatch;
2024 function startsWith(str, prefix) {
2025 return str.lastIndexOf(prefix, 0) === 0;
2026 }
2027 ts.startsWith = startsWith;
2028 function removePrefix(str, prefix) {
2029 return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2030 }
2031 ts.removePrefix = removePrefix;
2032 function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2033 if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2034 return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2035 }
2036 ts.tryRemovePrefix = tryRemovePrefix;
2037 function isPatternMatch(_a, candidate) {
2038 var prefix = _a.prefix, suffix = _a.suffix;
2039 return candidate.length >= prefix.length + suffix.length &&
2040 startsWith(candidate, prefix) &&
2041 endsWith(candidate, suffix);
2042 }
2043 function and(f, g) {
2044 return function (arg) { return f(arg) && g(arg); };
2045 }
2046 ts.and = and;
2047 function or() {
2048 var fs = [];
2049 for (var _i = 0; _i < arguments.length; _i++) {
2050 fs[_i] = arguments[_i];
2051 }
2052 return function () {
2053 var args = [];
2054 for (var _i = 0; _i < arguments.length; _i++) {
2055 args[_i] = arguments[_i];
2056 }
2057 for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2058 var f = fs_1[_a];
2059 if (f.apply(void 0, args)) {
2060 return true;
2061 }
2062 }
2063 return false;
2064 };
2065 }
2066 ts.or = or;
2067 function not(fn) {
2068 return function () {
2069 var args = [];
2070 for (var _i = 0; _i < arguments.length; _i++) {
2071 args[_i] = arguments[_i];
2072 }
2073 return !fn.apply(void 0, args);
2074 };
2075 }
2076 ts.not = not;
2077 function assertType(_) { }
2078 ts.assertType = assertType;
2079 function singleElementArray(t) {
2080 return t === undefined ? undefined : [t];
2081 }
2082 ts.singleElementArray = singleElementArray;
2083 function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2084 unchanged = unchanged || noop;
2085 var newIndex = 0;
2086 var oldIndex = 0;
2087 var newLen = newItems.length;
2088 var oldLen = oldItems.length;
2089 var hasChanges = false;
2090 while (newIndex < newLen && oldIndex < oldLen) {
2091 var newItem = newItems[newIndex];
2092 var oldItem = oldItems[oldIndex];
2093 var compareResult = comparer(newItem, oldItem);
2094 if (compareResult === -1 /* LessThan */) {
2095 inserted(newItem);
2096 newIndex++;
2097 hasChanges = true;
2098 }
2099 else if (compareResult === 1 /* GreaterThan */) {
2100 deleted(oldItem);
2101 oldIndex++;
2102 hasChanges = true;
2103 }
2104 else {
2105 unchanged(oldItem, newItem);
2106 newIndex++;
2107 oldIndex++;
2108 }
2109 }
2110 while (newIndex < newLen) {
2111 inserted(newItems[newIndex++]);
2112 hasChanges = true;
2113 }
2114 while (oldIndex < oldLen) {
2115 deleted(oldItems[oldIndex++]);
2116 hasChanges = true;
2117 }
2118 return hasChanges;
2119 }
2120 ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2121 function fill(length, cb) {
2122 var result = Array(length);
2123 for (var i = 0; i < length; i++) {
2124 result[i] = cb(i);
2125 }
2126 return result;
2127 }
2128 ts.fill = fill;
2129 function cartesianProduct(arrays) {
2130 var result = [];
2131 cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2132 return result;
2133 }
2134 ts.cartesianProduct = cartesianProduct;
2135 function cartesianProductWorker(arrays, result, outer, index) {
2136 for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2137 var element = _a[_i];
2138 var inner = void 0;
2139 if (outer) {
2140 inner = outer.slice();
2141 inner.push(element);
2142 }
2143 else {
2144 inner = [element];
2145 }
2146 if (index === arrays.length - 1) {
2147 result.push(inner);
2148 }
2149 else {
2150 cartesianProductWorker(arrays, result, inner, index + 1);
2151 }
2152 }
2153 }
2154 function padLeft(s, length) {
2155 while (s.length < length) {
2156 s = " " + s;
2157 }
2158 return s;
2159 }
2160 ts.padLeft = padLeft;
2161 function padRight(s, length) {
2162 while (s.length < length) {
2163 s = s + " ";
2164 }
2165 return s;
2166 }
2167 ts.padRight = padRight;
2168})(ts || (ts = {}));
2169/* @internal */
2170var ts;
2171(function (ts) {
2172 var LogLevel;
2173 (function (LogLevel) {
2174 LogLevel[LogLevel["Off"] = 0] = "Off";
2175 LogLevel[LogLevel["Error"] = 1] = "Error";
2176 LogLevel[LogLevel["Warning"] = 2] = "Warning";
2177 LogLevel[LogLevel["Info"] = 3] = "Info";
2178 LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
2179 })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
2180 var Debug;
2181 (function (Debug) {
2182 var typeScriptVersion;
2183 /* eslint-disable prefer-const */
2184 var currentAssertionLevel = 0 /* None */;
2185 Debug.currentLogLevel = LogLevel.Warning;
2186 Debug.isDebugging = false;
2187 function getTypeScriptVersion() {
2188 return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
2189 }
2190 Debug.getTypeScriptVersion = getTypeScriptVersion;
2191 function shouldLog(level) {
2192 return Debug.currentLogLevel <= level;
2193 }
2194 Debug.shouldLog = shouldLog;
2195 function logMessage(level, s) {
2196 if (Debug.loggingHost && shouldLog(level)) {
2197 Debug.loggingHost.log(level, s);
2198 }
2199 }
2200 function log(s) {
2201 logMessage(LogLevel.Info, s);
2202 }
2203 Debug.log = log;
2204 (function (log_1) {
2205 function error(s) {
2206 logMessage(LogLevel.Error, s);
2207 }
2208 log_1.error = error;
2209 function warn(s) {
2210 logMessage(LogLevel.Warning, s);
2211 }
2212 log_1.warn = warn;
2213 function log(s) {
2214 logMessage(LogLevel.Info, s);
2215 }
2216 log_1.log = log;
2217 function trace(s) {
2218 logMessage(LogLevel.Verbose, s);
2219 }
2220 log_1.trace = trace;
2221 })(log = Debug.log || (Debug.log = {}));
2222 var assertionCache = {};
2223 function getAssertionLevel() {
2224 return currentAssertionLevel;
2225 }
2226 Debug.getAssertionLevel = getAssertionLevel;
2227 function setAssertionLevel(level) {
2228 var prevAssertionLevel = currentAssertionLevel;
2229 currentAssertionLevel = level;
2230 if (level > prevAssertionLevel) {
2231 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2232 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2233 var key = _a[_i];
2234 var cachedFunc = assertionCache[key];
2235 if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2236 Debug[key] = cachedFunc;
2237 assertionCache[key] = undefined;
2238 }
2239 }
2240 }
2241 }
2242 Debug.setAssertionLevel = setAssertionLevel;
2243 function shouldAssert(level) {
2244 return currentAssertionLevel >= level;
2245 }
2246 Debug.shouldAssert = shouldAssert;
2247 /**
2248 * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2249 * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2250 * @param level The minimum assertion level required.
2251 * @param name The name of the current assertion function.
2252 */
2253 function shouldAssertFunction(level, name) {
2254 if (!shouldAssert(level)) {
2255 assertionCache[name] = { level: level, assertion: Debug[name] };
2256 Debug[name] = ts.noop;
2257 return false;
2258 }
2259 return true;
2260 }
2261 function fail(message, stackCrawlMark) {
2262 debugger;
2263 var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2264 if (Error.captureStackTrace) {
2265 Error.captureStackTrace(e, stackCrawlMark || fail);
2266 }
2267 throw e;
2268 }
2269 Debug.fail = fail;
2270 function failBadSyntaxKind(node, message, stackCrawlMark) {
2271 return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2272 }
2273 Debug.failBadSyntaxKind = failBadSyntaxKind;
2274 function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2275 if (!expression) {
2276 message = message ? "False expression: " + message : "False expression.";
2277 if (verboseDebugInfo) {
2278 message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2279 }
2280 fail(message, stackCrawlMark || assert);
2281 }
2282 }
2283 Debug.assert = assert;
2284 function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2285 if (a !== b) {
2286 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2287 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2288 }
2289 }
2290 Debug.assertEqual = assertEqual;
2291 function assertLessThan(a, b, msg, stackCrawlMark) {
2292 if (a >= b) {
2293 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2294 }
2295 }
2296 Debug.assertLessThan = assertLessThan;
2297 function assertLessThanOrEqual(a, b, stackCrawlMark) {
2298 if (a > b) {
2299 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2300 }
2301 }
2302 Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2303 function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2304 if (a < b) {
2305 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2306 }
2307 }
2308 Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2309 function assertIsDefined(value, message, stackCrawlMark) {
2310 // eslint-disable-next-line no-null/no-null
2311 if (value === undefined || value === null) {
2312 fail(message, stackCrawlMark || assertIsDefined);
2313 }
2314 }
2315 Debug.assertIsDefined = assertIsDefined;
2316 function checkDefined(value, message, stackCrawlMark) {
2317 assertIsDefined(value, message, stackCrawlMark || checkDefined);
2318 return value;
2319 }
2320 Debug.checkDefined = checkDefined;
2321 /**
2322 * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2323 * a value is defined at the statement level.
2324 */
2325 Debug.assertDefined = checkDefined;
2326 function assertEachIsDefined(value, message, stackCrawlMark) {
2327 for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2328 var v = value_1[_i];
2329 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2330 }
2331 }
2332 Debug.assertEachIsDefined = assertEachIsDefined;
2333 function checkEachDefined(value, message, stackCrawlMark) {
2334 assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2335 return value;
2336 }
2337 Debug.checkEachDefined = checkEachDefined;
2338 /**
2339 * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2340 * the elements of an array are defined at the statement level.
2341 */
2342 Debug.assertEachDefined = checkEachDefined;
2343 function assertNever(member, message, stackCrawlMark) {
2344 if (message === void 0) { message = "Illegal value:"; }
2345 var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2346 return fail(message + " " + detail, stackCrawlMark || assertNever);
2347 }
2348 Debug.assertNever = assertNever;
2349 function assertEachNode(nodes, test, message, stackCrawlMark) {
2350 if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2351 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2352 }
2353 }
2354 Debug.assertEachNode = assertEachNode;
2355 function assertNode(node, test, message, stackCrawlMark) {
2356 if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2357 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2358 }
2359 }
2360 Debug.assertNode = assertNode;
2361 function assertNotNode(node, test, message, stackCrawlMark) {
2362 if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2363 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);
2364 }
2365 }
2366 Debug.assertNotNode = assertNotNode;
2367 function assertOptionalNode(node, test, message, stackCrawlMark) {
2368 if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2369 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2370 }
2371 }
2372 Debug.assertOptionalNode = assertOptionalNode;
2373 function assertOptionalToken(node, kind, message, stackCrawlMark) {
2374 if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2375 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);
2376 }
2377 }
2378 Debug.assertOptionalToken = assertOptionalToken;
2379 function assertMissingNode(node, message, stackCrawlMark) {
2380 if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2381 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2382 }
2383 }
2384 Debug.assertMissingNode = assertMissingNode;
2385 function getFunctionName(func) {
2386 if (typeof func !== "function") {
2387 return "";
2388 }
2389 else if (func.hasOwnProperty("name")) {
2390 return func.name;
2391 }
2392 else {
2393 var text = Function.prototype.toString.call(func);
2394 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2395 return match ? match[1] : "";
2396 }
2397 }
2398 Debug.getFunctionName = getFunctionName;
2399 function formatSymbol(symbol) {
2400 return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2401 }
2402 Debug.formatSymbol = formatSymbol;
2403 /**
2404 * Formats an enum value as a string for debugging and debug assertions.
2405 */
2406 function formatEnum(value, enumObject, isFlags) {
2407 if (value === void 0) { value = 0; }
2408 var members = getEnumMembers(enumObject);
2409 if (value === 0) {
2410 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2411 }
2412 if (isFlags) {
2413 var result = "";
2414 var remainingFlags = value;
2415 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2416 var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2417 if (enumValue > value) {
2418 break;
2419 }
2420 if (enumValue !== 0 && enumValue & value) {
2421 result = "" + result + (result ? "|" : "") + enumName;
2422 remainingFlags &= ~enumValue;
2423 }
2424 }
2425 if (remainingFlags === 0) {
2426 return result;
2427 }
2428 }
2429 else {
2430 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2431 var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2432 if (enumValue === value) {
2433 return enumName;
2434 }
2435 }
2436 }
2437 return value.toString();
2438 }
2439 Debug.formatEnum = formatEnum;
2440 function getEnumMembers(enumObject) {
2441 var result = [];
2442 for (var name in enumObject) {
2443 var value = enumObject[name];
2444 if (typeof value === "number") {
2445 result.push([value, name]);
2446 }
2447 }
2448 return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2449 }
2450 function formatSyntaxKind(kind) {
2451 return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2452 }
2453 Debug.formatSyntaxKind = formatSyntaxKind;
2454 function formatNodeFlags(flags) {
2455 return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2456 }
2457 Debug.formatNodeFlags = formatNodeFlags;
2458 function formatModifierFlags(flags) {
2459 return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2460 }
2461 Debug.formatModifierFlags = formatModifierFlags;
2462 function formatTransformFlags(flags) {
2463 return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2464 }
2465 Debug.formatTransformFlags = formatTransformFlags;
2466 function formatEmitFlags(flags) {
2467 return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2468 }
2469 Debug.formatEmitFlags = formatEmitFlags;
2470 function formatSymbolFlags(flags) {
2471 return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2472 }
2473 Debug.formatSymbolFlags = formatSymbolFlags;
2474 function formatTypeFlags(flags) {
2475 return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2476 }
2477 Debug.formatTypeFlags = formatTypeFlags;
2478 function formatObjectFlags(flags) {
2479 return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2480 }
2481 Debug.formatObjectFlags = formatObjectFlags;
2482 var isDebugInfoEnabled = false;
2483 var extendedDebugModule;
2484 function extendedDebug() {
2485 enableDebugInfo();
2486 if (!extendedDebugModule) {
2487 throw new Error("Debugging helpers could not be loaded.");
2488 }
2489 return extendedDebugModule;
2490 }
2491 function printControlFlowGraph(flowNode) {
2492 return console.log(formatControlFlowGraph(flowNode));
2493 }
2494 Debug.printControlFlowGraph = printControlFlowGraph;
2495 function formatControlFlowGraph(flowNode) {
2496 return extendedDebug().formatControlFlowGraph(flowNode);
2497 }
2498 Debug.formatControlFlowGraph = formatControlFlowGraph;
2499 function attachFlowNodeDebugInfo(flowNode) {
2500 if (isDebugInfoEnabled) {
2501 if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2502 Object.defineProperties(flowNode, {
2503 __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2504 __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2505 });
2506 }
2507 }
2508 }
2509 Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2510 /**
2511 * Injects debug information into frequently used types.
2512 */
2513 function enableDebugInfo() {
2514 if (isDebugInfoEnabled)
2515 return;
2516 // Add additional properties in debug mode to assist with debugging.
2517 Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2518 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2519 });
2520 Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2521 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2522 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2523 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
2524 });
2525 var nodeConstructors = [
2526 ts.objectAllocator.getNodeConstructor(),
2527 ts.objectAllocator.getIdentifierConstructor(),
2528 ts.objectAllocator.getTokenConstructor(),
2529 ts.objectAllocator.getSourceFileConstructor()
2530 ];
2531 for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2532 var ctor = nodeConstructors_1[_i];
2533 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2534 Object.defineProperties(ctor.prototype, {
2535 __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2536 __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2537 __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
2538 __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2539 __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2540 __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2541 __debugGetText: {
2542 value: function (includeTrivia) {
2543 if (ts.nodeIsSynthesized(this))
2544 return "";
2545 var parseNode = ts.getParseTreeNode(this);
2546 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2547 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2548 }
2549 }
2550 });
2551 }
2552 }
2553 // attempt to load extended debugging information
2554 try {
2555 if (ts.sys && ts.sys.require) {
2556 var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2557 var result = ts.sys.require(basePath, "./compiler-debug");
2558 if (!result.error) {
2559 result.module.init(ts);
2560 extendedDebugModule = result.module;
2561 }
2562 }
2563 }
2564 catch (_a) {
2565 // do nothing
2566 }
2567 isDebugInfoEnabled = true;
2568 }
2569 Debug.enableDebugInfo = enableDebugInfo;
2570 function formatDeprecationMessage(name, error, errorAfter, since, message) {
2571 var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
2572 deprecationMessage += "'" + name + "' ";
2573 deprecationMessage += since ? "has been deprecated since v" + since : "is deprecated";
2574 deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v" + errorAfter + "." : ".";
2575 deprecationMessage += message ? " " + ts.formatStringFromArgs(message, [name], 0) : "";
2576 return deprecationMessage;
2577 }
2578 function createErrorDeprecation(name, errorAfter, since, message) {
2579 var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
2580 return function () {
2581 throw new TypeError(deprecationMessage);
2582 };
2583 }
2584 function createWarningDeprecation(name, errorAfter, since, message) {
2585 var hasWrittenDeprecation = false;
2586 return function () {
2587 if (!hasWrittenDeprecation) {
2588 log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
2589 hasWrittenDeprecation = true;
2590 }
2591 };
2592 }
2593 function createDeprecation(name, options) {
2594 var _a, _b;
2595 if (options === void 0) { options = {}; }
2596 var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
2597 var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
2598 var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
2599 var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
2600 var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
2601 var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
2602 return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
2603 warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
2604 ts.noop;
2605 }
2606 function wrapFunction(deprecation, func) {
2607 return function () {
2608 deprecation();
2609 return func.apply(this, arguments);
2610 };
2611 }
2612 function deprecate(func, options) {
2613 var deprecation = createDeprecation(getFunctionName(func), options);
2614 return wrapFunction(deprecation, func);
2615 }
2616 Debug.deprecate = deprecate;
2617 })(Debug = ts.Debug || (ts.Debug = {}));
2618})(ts || (ts = {}));
2619/*@internal*/
2620var ts;
2621(function (ts) {
2622 /** Gets a timestamp with (at least) ms resolution */
2623 ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2624})(ts || (ts = {}));
2625/*@internal*/
2626/** Performance measurements for the compiler. */
2627var ts;
2628(function (ts) {
2629 var performance;
2630 (function (performance) {
2631 // NOTE: cannot use ts.noop as core.ts loads after this
2632 var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2633 var enabled = false;
2634 var profilerStart = 0;
2635 var counts;
2636 var marks;
2637 var measures;
2638 function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2639 return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2640 }
2641 performance.createTimerIf = createTimerIf;
2642 function createTimer(measureName, startMarkName, endMarkName) {
2643 var enterCount = 0;
2644 return {
2645 enter: enter,
2646 exit: exit
2647 };
2648 function enter() {
2649 if (++enterCount === 1) {
2650 mark(startMarkName);
2651 }
2652 }
2653 function exit() {
2654 if (--enterCount === 0) {
2655 mark(endMarkName);
2656 measure(measureName, startMarkName, endMarkName);
2657 }
2658 else if (enterCount < 0) {
2659 ts.Debug.fail("enter/exit count does not match.");
2660 }
2661 }
2662 }
2663 performance.createTimer = createTimer;
2664 performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2665 /**
2666 * Marks a performance event.
2667 *
2668 * @param markName The name of the mark.
2669 */
2670 function mark(markName) {
2671 if (enabled) {
2672 marks.set(markName, ts.timestamp());
2673 counts.set(markName, (counts.get(markName) || 0) + 1);
2674 profilerEvent(markName);
2675 }
2676 }
2677 performance.mark = mark;
2678 /**
2679 * Adds a performance measurement with the specified name.
2680 *
2681 * @param measureName The name of the performance measurement.
2682 * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2683 * profiler was enabled is used.
2684 * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2685 * used.
2686 */
2687 function measure(measureName, startMarkName, endMarkName) {
2688 if (enabled) {
2689 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2690 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2691 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2692 }
2693 }
2694 performance.measure = measure;
2695 /**
2696 * Gets the number of times a marker was encountered.
2697 *
2698 * @param markName The name of the mark.
2699 */
2700 function getCount(markName) {
2701 return counts && counts.get(markName) || 0;
2702 }
2703 performance.getCount = getCount;
2704 /**
2705 * Gets the total duration of all measurements with the supplied name.
2706 *
2707 * @param measureName The name of the measure whose durations should be accumulated.
2708 */
2709 function getDuration(measureName) {
2710 return measures && measures.get(measureName) || 0;
2711 }
2712 performance.getDuration = getDuration;
2713 /**
2714 * Iterate over each measure, performing some action
2715 *
2716 * @param cb The action to perform for each measure
2717 */
2718 function forEachMeasure(cb) {
2719 measures.forEach(function (measure, key) {
2720 cb(key, measure);
2721 });
2722 }
2723 performance.forEachMeasure = forEachMeasure;
2724 /** Enables (and resets) performance measurements for the compiler. */
2725 function enable() {
2726 counts = new ts.Map();
2727 marks = new ts.Map();
2728 measures = new ts.Map();
2729 enabled = true;
2730 profilerStart = ts.timestamp();
2731 }
2732 performance.enable = enable;
2733 /** Disables performance measurements for the compiler. */
2734 function disable() {
2735 enabled = false;
2736 }
2737 performance.disable = disable;
2738 })(performance = ts.performance || (ts.performance = {}));
2739})(ts || (ts = {}));
2740/* @internal */
2741var ts;
2742(function (ts) {
2743 var _a;
2744 var nullLogger = {
2745 logEvent: ts.noop,
2746 logErrEvent: ts.noop,
2747 logPerfEvent: ts.noop,
2748 logInfoEvent: ts.noop,
2749 logStartCommand: ts.noop,
2750 logStopCommand: ts.noop,
2751 logStartUpdateProgram: ts.noop,
2752 logStopUpdateProgram: ts.noop,
2753 logStartUpdateGraph: ts.noop,
2754 logStopUpdateGraph: ts.noop,
2755 logStartResolveModule: ts.noop,
2756 logStopResolveModule: ts.noop,
2757 logStartParseSourceFile: ts.noop,
2758 logStopParseSourceFile: ts.noop,
2759 logStartReadFile: ts.noop,
2760 logStopReadFile: ts.noop,
2761 logStartBindFile: ts.noop,
2762 logStopBindFile: ts.noop,
2763 logStartScheduledOperation: ts.noop,
2764 logStopScheduledOperation: ts.noop,
2765 };
2766 // Load optional module to enable Event Tracing for Windows
2767 // See https://github.com/microsoft/typescript-etw for more information
2768 var etwModule;
2769 try {
2770 var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
2771 // require() will throw an exception if the module is not found
2772 // It may also return undefined if not installed properly
2773 etwModule = require(etwModulePath);
2774 }
2775 catch (e) {
2776 etwModule = undefined;
2777 }
2778 /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2779 ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2780})(ts || (ts = {}));
2781/* @internal */
2782var ts;
2783(function (ts) {
2784 // https://semver.org/#spec-item-2
2785 // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2786 // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2787 // > version, and Z is the patch version. Each element MUST increase numerically.
2788 //
2789 // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2790 // value of `0`.
2791 var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2792 // https://semver.org/#spec-item-9
2793 // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2794 // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2795 // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2796 // > MUST NOT include leading zeroes.
2797 var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2798 // https://semver.org/#spec-item-10
2799 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2800 // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2801 // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2802 var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2803 // https://semver.org/#spec-item-9
2804 // > Numeric identifiers MUST NOT include leading zeroes.
2805 var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2806 /**
2807 * Describes a precise semantic version number, https://semver.org
2808 */
2809 var Version = /** @class */ (function () {
2810 function Version(major, minor, patch, prerelease, build) {
2811 if (minor === void 0) { minor = 0; }
2812 if (patch === void 0) { patch = 0; }
2813 if (prerelease === void 0) { prerelease = ""; }
2814 if (build === void 0) { build = ""; }
2815 if (typeof major === "string") {
2816 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2817 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2818 }
2819 ts.Debug.assert(major >= 0, "Invalid argument: major");
2820 ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2821 ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2822 ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2823 ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2824 this.major = major;
2825 this.minor = minor;
2826 this.patch = patch;
2827 this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2828 this.build = build ? build.split(".") : ts.emptyArray;
2829 }
2830 Version.tryParse = function (text) {
2831 var result = tryParseComponents(text);
2832 if (!result)
2833 return undefined;
2834 var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2835 return new Version(major, minor, patch, prerelease, build);
2836 };
2837 Version.prototype.compareTo = function (other) {
2838 // https://semver.org/#spec-item-11
2839 // > Precedence is determined by the first difference when comparing each of these
2840 // > identifiers from left to right as follows: Major, minor, and patch versions are
2841 // > always compared numerically.
2842 //
2843 // https://semver.org/#spec-item-11
2844 // > Precedence for two pre-release versions with the same major, minor, and patch version
2845 // > MUST be determined by comparing each dot separated identifier from left to right until
2846 // > a difference is found [...]
2847 //
2848 // https://semver.org/#spec-item-11
2849 // > Build metadata does not figure into precedence
2850 if (this === other)
2851 return 0 /* EqualTo */;
2852 if (other === undefined)
2853 return 1 /* GreaterThan */;
2854 return ts.compareValues(this.major, other.major)
2855 || ts.compareValues(this.minor, other.minor)
2856 || ts.compareValues(this.patch, other.patch)
2857 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2858 };
2859 Version.prototype.increment = function (field) {
2860 switch (field) {
2861 case "major": return new Version(this.major + 1, 0, 0);
2862 case "minor": return new Version(this.major, this.minor + 1, 0);
2863 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2864 default: return ts.Debug.assertNever(field);
2865 }
2866 };
2867 Version.prototype.toString = function () {
2868 var result = this.major + "." + this.minor + "." + this.patch;
2869 if (ts.some(this.prerelease))
2870 result += "-" + this.prerelease.join(".");
2871 if (ts.some(this.build))
2872 result += "+" + this.build.join(".");
2873 return result;
2874 };
2875 Version.zero = new Version(0, 0, 0);
2876 return Version;
2877 }());
2878 ts.Version = Version;
2879 function tryParseComponents(text) {
2880 var match = versionRegExp.exec(text);
2881 if (!match)
2882 return undefined;
2883 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;
2884 if (prerelease && !prereleaseRegExp.test(prerelease))
2885 return undefined;
2886 if (build && !buildRegExp.test(build))
2887 return undefined;
2888 return {
2889 major: parseInt(major, 10),
2890 minor: parseInt(minor, 10),
2891 patch: parseInt(patch, 10),
2892 prerelease: prerelease,
2893 build: build
2894 };
2895 }
2896 function comparePrerelaseIdentifiers(left, right) {
2897 // https://semver.org/#spec-item-11
2898 // > When major, minor, and patch are equal, a pre-release version has lower precedence
2899 // > than a normal version.
2900 if (left === right)
2901 return 0 /* EqualTo */;
2902 if (left.length === 0)
2903 return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2904 if (right.length === 0)
2905 return -1 /* LessThan */;
2906 // https://semver.org/#spec-item-11
2907 // > Precedence for two pre-release versions with the same major, minor, and patch version
2908 // > MUST be determined by comparing each dot separated identifier from left to right until
2909 // > a difference is found [...]
2910 var length = Math.min(left.length, right.length);
2911 for (var i = 0; i < length; i++) {
2912 var leftIdentifier = left[i];
2913 var rightIdentifier = right[i];
2914 if (leftIdentifier === rightIdentifier)
2915 continue;
2916 var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2917 var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2918 if (leftIsNumeric || rightIsNumeric) {
2919 // https://semver.org/#spec-item-11
2920 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2921 if (leftIsNumeric !== rightIsNumeric)
2922 return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2923 // https://semver.org/#spec-item-11
2924 // > identifiers consisting of only digits are compared numerically
2925 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2926 if (result)
2927 return result;
2928 }
2929 else {
2930 // https://semver.org/#spec-item-11
2931 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2932 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2933 if (result)
2934 return result;
2935 }
2936 }
2937 // https://semver.org/#spec-item-11
2938 // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2939 // > of the preceding identifiers are equal.
2940 return ts.compareValues(left.length, right.length);
2941 }
2942 /**
2943 * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2944 */
2945 var VersionRange = /** @class */ (function () {
2946 function VersionRange(spec) {
2947 this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2948 }
2949 VersionRange.tryParse = function (text) {
2950 var sets = parseRange(text);
2951 if (sets) {
2952 var range = new VersionRange("");
2953 range._alternatives = sets;
2954 return range;
2955 }
2956 return undefined;
2957 };
2958 VersionRange.prototype.test = function (version) {
2959 if (typeof version === "string")
2960 version = new Version(version);
2961 return testDisjunction(version, this._alternatives);
2962 };
2963 VersionRange.prototype.toString = function () {
2964 return formatDisjunction(this._alternatives);
2965 };
2966 return VersionRange;
2967 }());
2968 ts.VersionRange = VersionRange;
2969 // https://github.com/npm/node-semver#range-grammar
2970 //
2971 // range-set ::= range ( logical-or range ) *
2972 // range ::= hyphen | simple ( ' ' simple ) * | ''
2973 // logical-or ::= ( ' ' ) * '||' ( ' ' ) *
2974 var logicalOrRegExp = /\s*\|\|\s*/g;
2975 var whitespaceRegExp = /\s+/g;
2976 // https://github.com/npm/node-semver#range-grammar
2977 //
2978 // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2979 // xr ::= 'x' | 'X' | '*' | nr
2980 // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2981 // qualifier ::= ( '-' pre )? ( '+' build )?
2982 // pre ::= parts
2983 // build ::= parts
2984 // parts ::= part ( '.' part ) *
2985 // part ::= nr | [-0-9A-Za-z]+
2986 var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2987 // https://github.com/npm/node-semver#range-grammar
2988 //
2989 // hyphen ::= partial ' - ' partial
2990 var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2991 // https://github.com/npm/node-semver#range-grammar
2992 //
2993 // simple ::= primitive | partial | tilde | caret
2994 // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2995 // tilde ::= '~' partial
2996 // caret ::= '^' partial
2997 var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2998 function parseRange(text) {
2999 var alternatives = [];
3000 for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
3001 var range = _a[_i];
3002 if (!range)
3003 continue;
3004 var comparators = [];
3005 var match = hyphenRegExp.exec(range);
3006 if (match) {
3007 if (!parseHyphen(match[1], match[2], comparators))
3008 return undefined;
3009 }
3010 else {
3011 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
3012 var simple = _c[_b];
3013 var match_1 = rangeRegExp.exec(simple);
3014 if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
3015 return undefined;
3016 }
3017 }
3018 alternatives.push(comparators);
3019 }
3020 return alternatives;
3021 }
3022 function parsePartial(text) {
3023 var match = partialRegExp.exec(text);
3024 if (!match)
3025 return undefined;
3026 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];
3027 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);
3028 return { version: version, major: major, minor: minor, patch: patch };
3029 }
3030 function parseHyphen(left, right, comparators) {
3031 var leftResult = parsePartial(left);
3032 if (!leftResult)
3033 return false;
3034 var rightResult = parsePartial(right);
3035 if (!rightResult)
3036 return false;
3037 if (!isWildcard(leftResult.major)) {
3038 comparators.push(createComparator(">=", leftResult.version));
3039 }
3040 if (!isWildcard(rightResult.major)) {
3041 comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
3042 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
3043 createComparator("<=", rightResult.version));
3044 }
3045 return true;
3046 }
3047 function parseComparator(operator, text, comparators) {
3048 var result = parsePartial(text);
3049 if (!result)
3050 return false;
3051 var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
3052 if (!isWildcard(major)) {
3053 switch (operator) {
3054 case "~":
3055 comparators.push(createComparator(">=", version));
3056 comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
3057 "minor")));
3058 break;
3059 case "^":
3060 comparators.push(createComparator(">=", version));
3061 comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
3062 version.minor > 0 || isWildcard(patch) ? "minor" :
3063 "patch")));
3064 break;
3065 case "<":
3066 case ">=":
3067 comparators.push(createComparator(operator, version));
3068 break;
3069 case "<=":
3070 case ">":
3071 comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3072 isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3073 createComparator(operator, version));
3074 break;
3075 case "=":
3076 case undefined:
3077 if (isWildcard(minor) || isWildcard(patch)) {
3078 comparators.push(createComparator(">=", version));
3079 comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3080 }
3081 else {
3082 comparators.push(createComparator("=", version));
3083 }
3084 break;
3085 default:
3086 // unrecognized
3087 return false;
3088 }
3089 }
3090 else if (operator === "<" || operator === ">") {
3091 comparators.push(createComparator("<", Version.zero));
3092 }
3093 return true;
3094 }
3095 function isWildcard(part) {
3096 return part === "*" || part === "x" || part === "X";
3097 }
3098 function createComparator(operator, operand) {
3099 return { operator: operator, operand: operand };
3100 }
3101 function testDisjunction(version, alternatives) {
3102 // an empty disjunction is treated as "*" (all versions)
3103 if (alternatives.length === 0)
3104 return true;
3105 for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3106 var alternative = alternatives_1[_i];
3107 if (testAlternative(version, alternative))
3108 return true;
3109 }
3110 return false;
3111 }
3112 function testAlternative(version, comparators) {
3113 for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3114 var comparator = comparators_1[_i];
3115 if (!testComparator(version, comparator.operator, comparator.operand))
3116 return false;
3117 }
3118 return true;
3119 }
3120 function testComparator(version, operator, operand) {
3121 var cmp = version.compareTo(operand);
3122 switch (operator) {
3123 case "<": return cmp < 0;
3124 case "<=": return cmp <= 0;
3125 case ">": return cmp > 0;
3126 case ">=": return cmp >= 0;
3127 case "=": return cmp === 0;
3128 default: return ts.Debug.assertNever(operator);
3129 }
3130 }
3131 function formatDisjunction(alternatives) {
3132 return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3133 }
3134 function formatAlternative(comparators) {
3135 return ts.map(comparators, formatComparator).join(" ");
3136 }
3137 function formatComparator(comparator) {
3138 return "" + comparator.operator + comparator.operand;
3139 }
3140})(ts || (ts = {}));
3141var ts;
3142(function (ts) {
3143 // token > SyntaxKind.Identifier => token is a keyword
3144 // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3145 var SyntaxKind;
3146 (function (SyntaxKind) {
3147 SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3148 SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3149 SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3150 SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3151 SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3152 SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3153 // We detect and preserve #! on the first line
3154 SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3155 // We detect and provide better error recovery when we encounter a git merge marker. This
3156 // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3157 SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3158 // Literals
3159 SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3160 SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3161 SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3162 SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3163 SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3164 SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3165 SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3166 // Pseudo-literals
3167 SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3168 SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3169 SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3170 // Punctuation
3171 SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3172 SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3173 SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3174 SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3175 SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3176 SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3177 SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3178 SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3179 SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3180 SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3181 SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3182 SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3183 SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3184 SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3185 SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3186 SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3187 SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3188 SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3189 SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3190 SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3191 SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3192 SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3193 SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3194 SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3195 SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3196 SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3197 SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3198 SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3199 SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3200 SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3201 SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3202 SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3203 SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3204 SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3205 SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3206 SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3207 SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3208 SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3209 SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3210 SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3211 SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3212 SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3213 SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3214 /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3215 SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3216 // Assignments
3217 SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3218 SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3219 SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3220 SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3221 SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3222 SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3223 SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3224 SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3225 SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3226 SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3227 SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3228 SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3229 SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 74] = "BarBarEqualsToken";
3230 SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 75] = "AmpersandAmpersandEqualsToken";
3231 SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 76] = "QuestionQuestionEqualsToken";
3232 SyntaxKind[SyntaxKind["CaretEqualsToken"] = 77] = "CaretEqualsToken";
3233 // Identifiers and PrivateIdentifiers
3234 SyntaxKind[SyntaxKind["Identifier"] = 78] = "Identifier";
3235 SyntaxKind[SyntaxKind["PrivateIdentifier"] = 79] = "PrivateIdentifier";
3236 // Reserved words
3237 SyntaxKind[SyntaxKind["BreakKeyword"] = 80] = "BreakKeyword";
3238 SyntaxKind[SyntaxKind["CaseKeyword"] = 81] = "CaseKeyword";
3239 SyntaxKind[SyntaxKind["CatchKeyword"] = 82] = "CatchKeyword";
3240 SyntaxKind[SyntaxKind["ClassKeyword"] = 83] = "ClassKeyword";
3241 SyntaxKind[SyntaxKind["ConstKeyword"] = 84] = "ConstKeyword";
3242 SyntaxKind[SyntaxKind["ContinueKeyword"] = 85] = "ContinueKeyword";
3243 SyntaxKind[SyntaxKind["DebuggerKeyword"] = 86] = "DebuggerKeyword";
3244 SyntaxKind[SyntaxKind["DefaultKeyword"] = 87] = "DefaultKeyword";
3245 SyntaxKind[SyntaxKind["DeleteKeyword"] = 88] = "DeleteKeyword";
3246 SyntaxKind[SyntaxKind["DoKeyword"] = 89] = "DoKeyword";
3247 SyntaxKind[SyntaxKind["ElseKeyword"] = 90] = "ElseKeyword";
3248 SyntaxKind[SyntaxKind["EnumKeyword"] = 91] = "EnumKeyword";
3249 SyntaxKind[SyntaxKind["ExportKeyword"] = 92] = "ExportKeyword";
3250 SyntaxKind[SyntaxKind["ExtendsKeyword"] = 93] = "ExtendsKeyword";
3251 SyntaxKind[SyntaxKind["FalseKeyword"] = 94] = "FalseKeyword";
3252 SyntaxKind[SyntaxKind["FinallyKeyword"] = 95] = "FinallyKeyword";
3253 SyntaxKind[SyntaxKind["ForKeyword"] = 96] = "ForKeyword";
3254 SyntaxKind[SyntaxKind["FunctionKeyword"] = 97] = "FunctionKeyword";
3255 SyntaxKind[SyntaxKind["IfKeyword"] = 98] = "IfKeyword";
3256 SyntaxKind[SyntaxKind["ImportKeyword"] = 99] = "ImportKeyword";
3257 SyntaxKind[SyntaxKind["InKeyword"] = 100] = "InKeyword";
3258 SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 101] = "InstanceOfKeyword";
3259 SyntaxKind[SyntaxKind["NewKeyword"] = 102] = "NewKeyword";
3260 SyntaxKind[SyntaxKind["NullKeyword"] = 103] = "NullKeyword";
3261 SyntaxKind[SyntaxKind["ReturnKeyword"] = 104] = "ReturnKeyword";
3262 SyntaxKind[SyntaxKind["SuperKeyword"] = 105] = "SuperKeyword";
3263 SyntaxKind[SyntaxKind["SwitchKeyword"] = 106] = "SwitchKeyword";
3264 SyntaxKind[SyntaxKind["ThisKeyword"] = 107] = "ThisKeyword";
3265 SyntaxKind[SyntaxKind["ThrowKeyword"] = 108] = "ThrowKeyword";
3266 SyntaxKind[SyntaxKind["TrueKeyword"] = 109] = "TrueKeyword";
3267 SyntaxKind[SyntaxKind["TryKeyword"] = 110] = "TryKeyword";
3268 SyntaxKind[SyntaxKind["TypeOfKeyword"] = 111] = "TypeOfKeyword";
3269 SyntaxKind[SyntaxKind["VarKeyword"] = 112] = "VarKeyword";
3270 SyntaxKind[SyntaxKind["VoidKeyword"] = 113] = "VoidKeyword";
3271 SyntaxKind[SyntaxKind["WhileKeyword"] = 114] = "WhileKeyword";
3272 SyntaxKind[SyntaxKind["WithKeyword"] = 115] = "WithKeyword";
3273 // Strict mode reserved words
3274 SyntaxKind[SyntaxKind["ImplementsKeyword"] = 116] = "ImplementsKeyword";
3275 SyntaxKind[SyntaxKind["InterfaceKeyword"] = 117] = "InterfaceKeyword";
3276 SyntaxKind[SyntaxKind["LetKeyword"] = 118] = "LetKeyword";
3277 SyntaxKind[SyntaxKind["PackageKeyword"] = 119] = "PackageKeyword";
3278 SyntaxKind[SyntaxKind["PrivateKeyword"] = 120] = "PrivateKeyword";
3279 SyntaxKind[SyntaxKind["ProtectedKeyword"] = 121] = "ProtectedKeyword";
3280 SyntaxKind[SyntaxKind["PublicKeyword"] = 122] = "PublicKeyword";
3281 SyntaxKind[SyntaxKind["StaticKeyword"] = 123] = "StaticKeyword";
3282 SyntaxKind[SyntaxKind["YieldKeyword"] = 124] = "YieldKeyword";
3283 // Contextual keywords
3284 SyntaxKind[SyntaxKind["AbstractKeyword"] = 125] = "AbstractKeyword";
3285 SyntaxKind[SyntaxKind["AsKeyword"] = 126] = "AsKeyword";
3286 SyntaxKind[SyntaxKind["AssertsKeyword"] = 127] = "AssertsKeyword";
3287 SyntaxKind[SyntaxKind["AnyKeyword"] = 128] = "AnyKeyword";
3288 SyntaxKind[SyntaxKind["AsyncKeyword"] = 129] = "AsyncKeyword";
3289 SyntaxKind[SyntaxKind["AwaitKeyword"] = 130] = "AwaitKeyword";
3290 SyntaxKind[SyntaxKind["BooleanKeyword"] = 131] = "BooleanKeyword";
3291 SyntaxKind[SyntaxKind["ConstructorKeyword"] = 132] = "ConstructorKeyword";
3292 SyntaxKind[SyntaxKind["DeclareKeyword"] = 133] = "DeclareKeyword";
3293 SyntaxKind[SyntaxKind["GetKeyword"] = 134] = "GetKeyword";
3294 SyntaxKind[SyntaxKind["InferKeyword"] = 135] = "InferKeyword";
3295 SyntaxKind[SyntaxKind["IsKeyword"] = 136] = "IsKeyword";
3296 SyntaxKind[SyntaxKind["KeyOfKeyword"] = 137] = "KeyOfKeyword";
3297 SyntaxKind[SyntaxKind["ModuleKeyword"] = 138] = "ModuleKeyword";
3298 SyntaxKind[SyntaxKind["NamespaceKeyword"] = 139] = "NamespaceKeyword";
3299 SyntaxKind[SyntaxKind["NeverKeyword"] = 140] = "NeverKeyword";
3300 SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 141] = "ReadonlyKeyword";
3301 SyntaxKind[SyntaxKind["RequireKeyword"] = 142] = "RequireKeyword";
3302 SyntaxKind[SyntaxKind["NumberKeyword"] = 143] = "NumberKeyword";
3303 SyntaxKind[SyntaxKind["ObjectKeyword"] = 144] = "ObjectKeyword";
3304 SyntaxKind[SyntaxKind["SetKeyword"] = 145] = "SetKeyword";
3305 SyntaxKind[SyntaxKind["StringKeyword"] = 146] = "StringKeyword";
3306 SyntaxKind[SyntaxKind["SymbolKeyword"] = 147] = "SymbolKeyword";
3307 SyntaxKind[SyntaxKind["TypeKeyword"] = 148] = "TypeKeyword";
3308 SyntaxKind[SyntaxKind["UndefinedKeyword"] = 149] = "UndefinedKeyword";
3309 SyntaxKind[SyntaxKind["UniqueKeyword"] = 150] = "UniqueKeyword";
3310 SyntaxKind[SyntaxKind["UnknownKeyword"] = 151] = "UnknownKeyword";
3311 SyntaxKind[SyntaxKind["FromKeyword"] = 152] = "FromKeyword";
3312 SyntaxKind[SyntaxKind["GlobalKeyword"] = 153] = "GlobalKeyword";
3313 SyntaxKind[SyntaxKind["BigIntKeyword"] = 154] = "BigIntKeyword";
3314 SyntaxKind[SyntaxKind["OfKeyword"] = 155] = "OfKeyword";
3315 // Parse tree nodes
3316 // Names
3317 SyntaxKind[SyntaxKind["QualifiedName"] = 156] = "QualifiedName";
3318 SyntaxKind[SyntaxKind["ComputedPropertyName"] = 157] = "ComputedPropertyName";
3319 // Signature elements
3320 SyntaxKind[SyntaxKind["TypeParameter"] = 158] = "TypeParameter";
3321 SyntaxKind[SyntaxKind["Parameter"] = 159] = "Parameter";
3322 SyntaxKind[SyntaxKind["Decorator"] = 160] = "Decorator";
3323 // TypeMember
3324 SyntaxKind[SyntaxKind["PropertySignature"] = 161] = "PropertySignature";
3325 SyntaxKind[SyntaxKind["PropertyDeclaration"] = 162] = "PropertyDeclaration";
3326 SyntaxKind[SyntaxKind["MethodSignature"] = 163] = "MethodSignature";
3327 SyntaxKind[SyntaxKind["MethodDeclaration"] = 164] = "MethodDeclaration";
3328 SyntaxKind[SyntaxKind["Constructor"] = 165] = "Constructor";
3329 SyntaxKind[SyntaxKind["GetAccessor"] = 166] = "GetAccessor";
3330 SyntaxKind[SyntaxKind["SetAccessor"] = 167] = "SetAccessor";
3331 SyntaxKind[SyntaxKind["CallSignature"] = 168] = "CallSignature";
3332 SyntaxKind[SyntaxKind["ConstructSignature"] = 169] = "ConstructSignature";
3333 SyntaxKind[SyntaxKind["IndexSignature"] = 170] = "IndexSignature";
3334 // Type
3335 SyntaxKind[SyntaxKind["TypePredicate"] = 171] = "TypePredicate";
3336 SyntaxKind[SyntaxKind["TypeReference"] = 172] = "TypeReference";
3337 SyntaxKind[SyntaxKind["FunctionType"] = 173] = "FunctionType";
3338 SyntaxKind[SyntaxKind["ConstructorType"] = 174] = "ConstructorType";
3339 SyntaxKind[SyntaxKind["TypeQuery"] = 175] = "TypeQuery";
3340 SyntaxKind[SyntaxKind["TypeLiteral"] = 176] = "TypeLiteral";
3341 SyntaxKind[SyntaxKind["ArrayType"] = 177] = "ArrayType";
3342 SyntaxKind[SyntaxKind["TupleType"] = 178] = "TupleType";
3343 SyntaxKind[SyntaxKind["OptionalType"] = 179] = "OptionalType";
3344 SyntaxKind[SyntaxKind["RestType"] = 180] = "RestType";
3345 SyntaxKind[SyntaxKind["UnionType"] = 181] = "UnionType";
3346 SyntaxKind[SyntaxKind["IntersectionType"] = 182] = "IntersectionType";
3347 SyntaxKind[SyntaxKind["ConditionalType"] = 183] = "ConditionalType";
3348 SyntaxKind[SyntaxKind["InferType"] = 184] = "InferType";
3349 SyntaxKind[SyntaxKind["ParenthesizedType"] = 185] = "ParenthesizedType";
3350 SyntaxKind[SyntaxKind["ThisType"] = 186] = "ThisType";
3351 SyntaxKind[SyntaxKind["TypeOperator"] = 187] = "TypeOperator";
3352 SyntaxKind[SyntaxKind["IndexedAccessType"] = 188] = "IndexedAccessType";
3353 SyntaxKind[SyntaxKind["MappedType"] = 189] = "MappedType";
3354 SyntaxKind[SyntaxKind["LiteralType"] = 190] = "LiteralType";
3355 SyntaxKind[SyntaxKind["NamedTupleMember"] = 191] = "NamedTupleMember";
3356 SyntaxKind[SyntaxKind["ImportType"] = 192] = "ImportType";
3357 // Binding patterns
3358 SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 193] = "ObjectBindingPattern";
3359 SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 194] = "ArrayBindingPattern";
3360 SyntaxKind[SyntaxKind["BindingElement"] = 195] = "BindingElement";
3361 // Expression
3362 SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 196] = "ArrayLiteralExpression";
3363 SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 197] = "ObjectLiteralExpression";
3364 SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 198] = "PropertyAccessExpression";
3365 SyntaxKind[SyntaxKind["ElementAccessExpression"] = 199] = "ElementAccessExpression";
3366 SyntaxKind[SyntaxKind["CallExpression"] = 200] = "CallExpression";
3367 SyntaxKind[SyntaxKind["NewExpression"] = 201] = "NewExpression";
3368 SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 202] = "TaggedTemplateExpression";
3369 SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 203] = "TypeAssertionExpression";
3370 SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 204] = "ParenthesizedExpression";
3371 SyntaxKind[SyntaxKind["FunctionExpression"] = 205] = "FunctionExpression";
3372 SyntaxKind[SyntaxKind["ArrowFunction"] = 206] = "ArrowFunction";
3373 SyntaxKind[SyntaxKind["DeleteExpression"] = 207] = "DeleteExpression";
3374 SyntaxKind[SyntaxKind["TypeOfExpression"] = 208] = "TypeOfExpression";
3375 SyntaxKind[SyntaxKind["VoidExpression"] = 209] = "VoidExpression";
3376 SyntaxKind[SyntaxKind["AwaitExpression"] = 210] = "AwaitExpression";
3377 SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 211] = "PrefixUnaryExpression";
3378 SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 212] = "PostfixUnaryExpression";
3379 SyntaxKind[SyntaxKind["BinaryExpression"] = 213] = "BinaryExpression";
3380 SyntaxKind[SyntaxKind["ConditionalExpression"] = 214] = "ConditionalExpression";
3381 SyntaxKind[SyntaxKind["TemplateExpression"] = 215] = "TemplateExpression";
3382 SyntaxKind[SyntaxKind["YieldExpression"] = 216] = "YieldExpression";
3383 SyntaxKind[SyntaxKind["SpreadElement"] = 217] = "SpreadElement";
3384 SyntaxKind[SyntaxKind["ClassExpression"] = 218] = "ClassExpression";
3385 SyntaxKind[SyntaxKind["OmittedExpression"] = 219] = "OmittedExpression";
3386 SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 220] = "ExpressionWithTypeArguments";
3387 SyntaxKind[SyntaxKind["AsExpression"] = 221] = "AsExpression";
3388 SyntaxKind[SyntaxKind["NonNullExpression"] = 222] = "NonNullExpression";
3389 SyntaxKind[SyntaxKind["MetaProperty"] = 223] = "MetaProperty";
3390 SyntaxKind[SyntaxKind["SyntheticExpression"] = 224] = "SyntheticExpression";
3391 // Misc
3392 SyntaxKind[SyntaxKind["TemplateSpan"] = 225] = "TemplateSpan";
3393 SyntaxKind[SyntaxKind["SemicolonClassElement"] = 226] = "SemicolonClassElement";
3394 // Element
3395 SyntaxKind[SyntaxKind["Block"] = 227] = "Block";
3396 SyntaxKind[SyntaxKind["EmptyStatement"] = 228] = "EmptyStatement";
3397 SyntaxKind[SyntaxKind["VariableStatement"] = 229] = "VariableStatement";
3398 SyntaxKind[SyntaxKind["ExpressionStatement"] = 230] = "ExpressionStatement";
3399 SyntaxKind[SyntaxKind["IfStatement"] = 231] = "IfStatement";
3400 SyntaxKind[SyntaxKind["DoStatement"] = 232] = "DoStatement";
3401 SyntaxKind[SyntaxKind["WhileStatement"] = 233] = "WhileStatement";
3402 SyntaxKind[SyntaxKind["ForStatement"] = 234] = "ForStatement";
3403 SyntaxKind[SyntaxKind["ForInStatement"] = 235] = "ForInStatement";
3404 SyntaxKind[SyntaxKind["ForOfStatement"] = 236] = "ForOfStatement";
3405 SyntaxKind[SyntaxKind["ContinueStatement"] = 237] = "ContinueStatement";
3406 SyntaxKind[SyntaxKind["BreakStatement"] = 238] = "BreakStatement";
3407 SyntaxKind[SyntaxKind["ReturnStatement"] = 239] = "ReturnStatement";
3408 SyntaxKind[SyntaxKind["WithStatement"] = 240] = "WithStatement";
3409 SyntaxKind[SyntaxKind["SwitchStatement"] = 241] = "SwitchStatement";
3410 SyntaxKind[SyntaxKind["LabeledStatement"] = 242] = "LabeledStatement";
3411 SyntaxKind[SyntaxKind["ThrowStatement"] = 243] = "ThrowStatement";
3412 SyntaxKind[SyntaxKind["TryStatement"] = 244] = "TryStatement";
3413 SyntaxKind[SyntaxKind["DebuggerStatement"] = 245] = "DebuggerStatement";
3414 SyntaxKind[SyntaxKind["VariableDeclaration"] = 246] = "VariableDeclaration";
3415 SyntaxKind[SyntaxKind["VariableDeclarationList"] = 247] = "VariableDeclarationList";
3416 SyntaxKind[SyntaxKind["FunctionDeclaration"] = 248] = "FunctionDeclaration";
3417 SyntaxKind[SyntaxKind["ClassDeclaration"] = 249] = "ClassDeclaration";
3418 SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 250] = "InterfaceDeclaration";
3419 SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 251] = "TypeAliasDeclaration";
3420 SyntaxKind[SyntaxKind["EnumDeclaration"] = 252] = "EnumDeclaration";
3421 SyntaxKind[SyntaxKind["ModuleDeclaration"] = 253] = "ModuleDeclaration";
3422 SyntaxKind[SyntaxKind["ModuleBlock"] = 254] = "ModuleBlock";
3423 SyntaxKind[SyntaxKind["CaseBlock"] = 255] = "CaseBlock";
3424 SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 256] = "NamespaceExportDeclaration";
3425 SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 257] = "ImportEqualsDeclaration";
3426 SyntaxKind[SyntaxKind["ImportDeclaration"] = 258] = "ImportDeclaration";
3427 SyntaxKind[SyntaxKind["ImportClause"] = 259] = "ImportClause";
3428 SyntaxKind[SyntaxKind["NamespaceImport"] = 260] = "NamespaceImport";
3429 SyntaxKind[SyntaxKind["NamedImports"] = 261] = "NamedImports";
3430 SyntaxKind[SyntaxKind["ImportSpecifier"] = 262] = "ImportSpecifier";
3431 SyntaxKind[SyntaxKind["ExportAssignment"] = 263] = "ExportAssignment";
3432 SyntaxKind[SyntaxKind["ExportDeclaration"] = 264] = "ExportDeclaration";
3433 SyntaxKind[SyntaxKind["NamedExports"] = 265] = "NamedExports";
3434 SyntaxKind[SyntaxKind["NamespaceExport"] = 266] = "NamespaceExport";
3435 SyntaxKind[SyntaxKind["ExportSpecifier"] = 267] = "ExportSpecifier";
3436 SyntaxKind[SyntaxKind["MissingDeclaration"] = 268] = "MissingDeclaration";
3437 // Module references
3438 SyntaxKind[SyntaxKind["ExternalModuleReference"] = 269] = "ExternalModuleReference";
3439 // JSX
3440 SyntaxKind[SyntaxKind["JsxElement"] = 270] = "JsxElement";
3441 SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 271] = "JsxSelfClosingElement";
3442 SyntaxKind[SyntaxKind["JsxOpeningElement"] = 272] = "JsxOpeningElement";
3443 SyntaxKind[SyntaxKind["JsxClosingElement"] = 273] = "JsxClosingElement";
3444 SyntaxKind[SyntaxKind["JsxFragment"] = 274] = "JsxFragment";
3445 SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 275] = "JsxOpeningFragment";
3446 SyntaxKind[SyntaxKind["JsxClosingFragment"] = 276] = "JsxClosingFragment";
3447 SyntaxKind[SyntaxKind["JsxAttribute"] = 277] = "JsxAttribute";
3448 SyntaxKind[SyntaxKind["JsxAttributes"] = 278] = "JsxAttributes";
3449 SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 279] = "JsxSpreadAttribute";
3450 SyntaxKind[SyntaxKind["JsxExpression"] = 280] = "JsxExpression";
3451 // Clauses
3452 SyntaxKind[SyntaxKind["CaseClause"] = 281] = "CaseClause";
3453 SyntaxKind[SyntaxKind["DefaultClause"] = 282] = "DefaultClause";
3454 SyntaxKind[SyntaxKind["HeritageClause"] = 283] = "HeritageClause";
3455 SyntaxKind[SyntaxKind["CatchClause"] = 284] = "CatchClause";
3456 // Property assignments
3457 SyntaxKind[SyntaxKind["PropertyAssignment"] = 285] = "PropertyAssignment";
3458 SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 286] = "ShorthandPropertyAssignment";
3459 SyntaxKind[SyntaxKind["SpreadAssignment"] = 287] = "SpreadAssignment";
3460 // Enum
3461 SyntaxKind[SyntaxKind["EnumMember"] = 288] = "EnumMember";
3462 // Unparsed
3463 SyntaxKind[SyntaxKind["UnparsedPrologue"] = 289] = "UnparsedPrologue";
3464 SyntaxKind[SyntaxKind["UnparsedPrepend"] = 290] = "UnparsedPrepend";
3465 SyntaxKind[SyntaxKind["UnparsedText"] = 291] = "UnparsedText";
3466 SyntaxKind[SyntaxKind["UnparsedInternalText"] = 292] = "UnparsedInternalText";
3467 SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 293] = "UnparsedSyntheticReference";
3468 // Top-level nodes
3469 SyntaxKind[SyntaxKind["SourceFile"] = 294] = "SourceFile";
3470 SyntaxKind[SyntaxKind["Bundle"] = 295] = "Bundle";
3471 SyntaxKind[SyntaxKind["UnparsedSource"] = 296] = "UnparsedSource";
3472 SyntaxKind[SyntaxKind["InputFiles"] = 297] = "InputFiles";
3473 // JSDoc nodes
3474 SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 298] = "JSDocTypeExpression";
3475 // The * type
3476 SyntaxKind[SyntaxKind["JSDocAllType"] = 299] = "JSDocAllType";
3477 // The ? type
3478 SyntaxKind[SyntaxKind["JSDocUnknownType"] = 300] = "JSDocUnknownType";
3479 SyntaxKind[SyntaxKind["JSDocNullableType"] = 301] = "JSDocNullableType";
3480 SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 302] = "JSDocNonNullableType";
3481 SyntaxKind[SyntaxKind["JSDocOptionalType"] = 303] = "JSDocOptionalType";
3482 SyntaxKind[SyntaxKind["JSDocFunctionType"] = 304] = "JSDocFunctionType";
3483 SyntaxKind[SyntaxKind["JSDocVariadicType"] = 305] = "JSDocVariadicType";
3484 // https://jsdoc.app/about-namepaths.html
3485 SyntaxKind[SyntaxKind["JSDocNamepathType"] = 306] = "JSDocNamepathType";
3486 SyntaxKind[SyntaxKind["JSDocComment"] = 307] = "JSDocComment";
3487 SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 308] = "JSDocTypeLiteral";
3488 SyntaxKind[SyntaxKind["JSDocSignature"] = 309] = "JSDocSignature";
3489 SyntaxKind[SyntaxKind["JSDocTag"] = 310] = "JSDocTag";
3490 SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 311] = "JSDocAugmentsTag";
3491 SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 312] = "JSDocImplementsTag";
3492 SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 313] = "JSDocAuthorTag";
3493 SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 314] = "JSDocDeprecatedTag";
3494 SyntaxKind[SyntaxKind["JSDocClassTag"] = 315] = "JSDocClassTag";
3495 SyntaxKind[SyntaxKind["JSDocPublicTag"] = 316] = "JSDocPublicTag";
3496 SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 317] = "JSDocPrivateTag";
3497 SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 318] = "JSDocProtectedTag";
3498 SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 319] = "JSDocReadonlyTag";
3499 SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 320] = "JSDocCallbackTag";
3500 SyntaxKind[SyntaxKind["JSDocEnumTag"] = 321] = "JSDocEnumTag";
3501 SyntaxKind[SyntaxKind["JSDocParameterTag"] = 322] = "JSDocParameterTag";
3502 SyntaxKind[SyntaxKind["JSDocReturnTag"] = 323] = "JSDocReturnTag";
3503 SyntaxKind[SyntaxKind["JSDocThisTag"] = 324] = "JSDocThisTag";
3504 SyntaxKind[SyntaxKind["JSDocTypeTag"] = 325] = "JSDocTypeTag";
3505 SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 326] = "JSDocTemplateTag";
3506 SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 327] = "JSDocTypedefTag";
3507 SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 328] = "JSDocPropertyTag";
3508 // Synthesized list
3509 SyntaxKind[SyntaxKind["SyntaxList"] = 329] = "SyntaxList";
3510 // Transformation nodes
3511 SyntaxKind[SyntaxKind["NotEmittedStatement"] = 330] = "NotEmittedStatement";
3512 SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 331] = "PartiallyEmittedExpression";
3513 SyntaxKind[SyntaxKind["CommaListExpression"] = 332] = "CommaListExpression";
3514 SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 333] = "MergeDeclarationMarker";
3515 SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 334] = "EndOfDeclarationMarker";
3516 SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 335] = "SyntheticReferenceExpression";
3517 // Enum value count
3518 SyntaxKind[SyntaxKind["Count"] = 336] = "Count";
3519 // Markers
3520 SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3521 SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment";
3522 SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3523 SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 77] = "LastCompoundAssignment";
3524 SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord";
3525 SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord";
3526 SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword";
3527 SyntaxKind[SyntaxKind["LastKeyword"] = 155] = "LastKeyword";
3528 SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord";
3529 SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord";
3530 SyntaxKind[SyntaxKind["FirstTypeNode"] = 171] = "FirstTypeNode";
3531 SyntaxKind[SyntaxKind["LastTypeNode"] = 192] = "LastTypeNode";
3532 SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3533 SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation";
3534 SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3535 SyntaxKind[SyntaxKind["LastToken"] = 155] = "LastToken";
3536 SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3537 SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3538 SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3539 SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3540 SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3541 SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3542 SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3543 SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator";
3544 SyntaxKind[SyntaxKind["FirstStatement"] = 229] = "FirstStatement";
3545 SyntaxKind[SyntaxKind["LastStatement"] = 245] = "LastStatement";
3546 SyntaxKind[SyntaxKind["FirstNode"] = 156] = "FirstNode";
3547 SyntaxKind[SyntaxKind["FirstJSDocNode"] = 298] = "FirstJSDocNode";
3548 SyntaxKind[SyntaxKind["LastJSDocNode"] = 328] = "LastJSDocNode";
3549 SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 310] = "FirstJSDocTagNode";
3550 SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 328] = "LastJSDocTagNode";
3551 /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword";
3552 /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 155] = "LastContextualKeyword";
3553 })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3554 var NodeFlags;
3555 (function (NodeFlags) {
3556 NodeFlags[NodeFlags["None"] = 0] = "None";
3557 NodeFlags[NodeFlags["Let"] = 1] = "Let";
3558 NodeFlags[NodeFlags["Const"] = 2] = "Const";
3559 NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3560 NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3561 NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3562 NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3563 NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3564 NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3565 NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3566 NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3567 NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3568 NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3569 NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3570 NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3571 NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3572 NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3573 NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3574 NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3575 NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3576 NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3577 // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3578 // walking the tree if the flags are not set. However, these flags are just a approximation
3579 // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3580 // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3581 // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3582 // However, the removal operation should not occur often and in the case of the
3583 // removal, it is likely that users will add the import anyway.
3584 // The advantage of this approach is its simplicity. For the case of batch compilation,
3585 // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3586 /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3587 /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3588 NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3589 /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3590 /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3591 NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3592 /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3593 /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
3594 NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3595 NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3596 NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3597 // Parsing context flags
3598 NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3599 // Exclude these flags when parsing a Type
3600 NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3601 // Represents all flags that are potentially set once and
3602 // never cleared on SourceFiles which get re-used in between incremental parses.
3603 // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3604 /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3605 })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3606 var ModifierFlags;
3607 (function (ModifierFlags) {
3608 ModifierFlags[ModifierFlags["None"] = 0] = "None";
3609 ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3610 ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3611 ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3612 ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3613 ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3614 ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3615 ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3616 ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3617 ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3618 ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3619 ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3620 ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
3621 ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
3622 ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3623 ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3624 // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3625 ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3626 ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3627 ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3628 ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3629 ModifierFlags[ModifierFlags["All"] = 11263] = "All";
3630 })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3631 var JsxFlags;
3632 (function (JsxFlags) {
3633 JsxFlags[JsxFlags["None"] = 0] = "None";
3634 /** An element from a named property of the JSX.IntrinsicElements interface */
3635 JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3636 /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3637 JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3638 JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3639 })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3640 /* @internal */
3641 var RelationComparisonResult;
3642 (function (RelationComparisonResult) {
3643 RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3644 RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3645 RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3646 RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3647 RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3648 RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3649 })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3650 var GeneratedIdentifierFlags;
3651 (function (GeneratedIdentifierFlags) {
3652 // Kinds
3653 GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3654 /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3655 /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3656 /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3657 /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3658 /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3659 // Flags
3660 GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3661 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3662 GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3663 })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3664 var TokenFlags;
3665 (function (TokenFlags) {
3666 TokenFlags[TokenFlags["None"] = 0] = "None";
3667 /* @internal */
3668 TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3669 /* @internal */
3670 TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3671 /* @internal */
3672 TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3673 /* @internal */
3674 TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3675 TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3676 TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3677 TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3678 TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3679 TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3680 /* @internal */
3681 TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3682 /* @internal */
3683 TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3684 /* @internal */
3685 TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3686 /* @internal */
3687 TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3688 /* @internal */
3689 TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3690 /* @internal */
3691 TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
3692 })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3693 // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3694 var FlowFlags;
3695 (function (FlowFlags) {
3696 FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3697 FlowFlags[FlowFlags["Start"] = 2] = "Start";
3698 FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3699 FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3700 FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3701 FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3702 FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3703 FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3704 FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3705 FlowFlags[FlowFlags["Call"] = 512] = "Call";
3706 FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3707 FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3708 FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3709 FlowFlags[FlowFlags["Label"] = 12] = "Label";
3710 FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3711 })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3712 /* @internal */
3713 var CommentDirectiveType;
3714 (function (CommentDirectiveType) {
3715 CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3716 CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3717 })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3718 var OperationCanceledException = /** @class */ (function () {
3719 function OperationCanceledException() {
3720 }
3721 return OperationCanceledException;
3722 }());
3723 ts.OperationCanceledException = OperationCanceledException;
3724 /*@internal*/
3725 var RefFileKind;
3726 (function (RefFileKind) {
3727 RefFileKind[RefFileKind["Import"] = 0] = "Import";
3728 RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3729 RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3730 })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3731 /* @internal */
3732 var StructureIsReused;
3733 (function (StructureIsReused) {
3734 StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3735 StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3736 StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3737 })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3738 /** Return code used by getEmitOutput function to indicate status of the function */
3739 var ExitStatus;
3740 (function (ExitStatus) {
3741 // Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
3742 // when -version or -help was provided, or this was a normal compilation, no diagnostics
3743 // were produced, and all outputs were generated successfully.
3744 ExitStatus[ExitStatus["Success"] = 0] = "Success";
3745 // Diagnostics were produced and because of them no code was generated.
3746 ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3747 // Diagnostics were produced and outputs were generated in spite of them.
3748 ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3749 // When build skipped because passed in project is invalid
3750 ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3751 // When build is skipped because project references form cycle
3752 ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3753 /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3754 ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3755 })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3756 /* @internal */
3757 var UnionReduction;
3758 (function (UnionReduction) {
3759 UnionReduction[UnionReduction["None"] = 0] = "None";
3760 UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3761 UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3762 })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3763 /* @internal */
3764 var ContextFlags;
3765 (function (ContextFlags) {
3766 ContextFlags[ContextFlags["None"] = 0] = "None";
3767 ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3768 ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3769 ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3770 ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
3771 })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3772 // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3773 var NodeBuilderFlags;
3774 (function (NodeBuilderFlags) {
3775 NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3776 // Options
3777 NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3778 NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3779 NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3780 NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3781 NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3782 NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3783 NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3784 NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3785 NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3786 NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3787 NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3788 NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3789 NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3790 NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3791 NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3792 NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3793 NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3794 NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
3795 // Error handling
3796 NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3797 NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3798 NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3799 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3800 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3801 NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3802 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3803 // Errors (cont.)
3804 NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3805 /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3806 NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3807 // State
3808 NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3809 NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3810 NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3811 NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3812 })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3813 // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3814 var TypeFormatFlags;
3815 (function (TypeFormatFlags) {
3816 TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3817 TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3818 TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3819 // hole because there's a hole in node builder flags
3820 TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3821 // hole because there's a hole in node builder flags
3822 TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3823 TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3824 // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3825 TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3826 // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3827 TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3828 TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3829 TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3830 TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3831 TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3832 TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3833 TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3834 // Error Handling
3835 TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3836 // TypeFormatFlags exclusive
3837 TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3838 TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3839 // State
3840 TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3841 TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3842 TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3843 TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3844 /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3845 TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3846 })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3847 var SymbolFormatFlags;
3848 (function (SymbolFormatFlags) {
3849 SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3850 // Write symbols's type argument if it is instantiated symbol
3851 // eg. class C<T> { p: T } <-- Show p as C<T>.p here
3852 // var a: C<number>;
3853 // var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3854 SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3855 // Use only external alias information to get the symbol name in the given context
3856 // eg. module m { export class c { } } import x = m.c;
3857 // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3858 SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3859 // Build symbol name using any nodes needed, instead of just components of an entity name
3860 SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3861 // Prefer aliases which are not directly visible
3862 SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3863 // Skip building an accessible symbol chain
3864 /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3865 })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3866 /* @internal */
3867 var SymbolAccessibility;
3868 (function (SymbolAccessibility) {
3869 SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3870 SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3871 SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3872 })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3873 /* @internal */
3874 var SyntheticSymbolKind;
3875 (function (SyntheticSymbolKind) {
3876 SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3877 SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3878 })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3879 var TypePredicateKind;
3880 (function (TypePredicateKind) {
3881 TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3882 TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3883 TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3884 TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3885 })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3886 /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3887 /* @internal */
3888 var TypeReferenceSerializationKind;
3889 (function (TypeReferenceSerializationKind) {
3890 // The TypeReferenceNode could not be resolved.
3891 // The type name should be emitted using a safe fallback.
3892 TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3893 // The TypeReferenceNode resolves to a type with a constructor
3894 // function that can be reached at runtime (e.g. a `class`
3895 // declaration or a `var` declaration for the static side
3896 // of a type, such as the global `Promise` type in lib.d.ts).
3897 TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3898 // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3899 TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3900 // The TypeReferenceNode resolves to a Number-like type.
3901 TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3902 // The TypeReferenceNode resolves to a BigInt-like type.
3903 TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3904 // The TypeReferenceNode resolves to a String-like type.
3905 TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3906 // The TypeReferenceNode resolves to a Boolean-like type.
3907 TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3908 // The TypeReferenceNode resolves to an Array-like type.
3909 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3910 // The TypeReferenceNode resolves to the ESSymbol type.
3911 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3912 // The TypeReferenceNode resolved to the global Promise constructor symbol.
3913 TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3914 // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3915 TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3916 // The TypeReferenceNode resolves to any other type.
3917 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3918 })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3919 var SymbolFlags;
3920 (function (SymbolFlags) {
3921 SymbolFlags[SymbolFlags["None"] = 0] = "None";
3922 SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3923 SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3924 SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3925 SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3926 SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3927 SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3928 SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3929 SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3930 SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3931 SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3932 SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3933 SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3934 SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3935 SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3936 SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3937 SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3938 SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3939 SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3940 SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3941 SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3942 SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3943 SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3944 SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3945 SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3946 SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3947 SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3948 SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3949 SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3950 /* @internal */
3951 SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3952 SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3953 SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3954 SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3955 SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3956 SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3957 SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3958 SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3959 // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3960 // same name, or any other value that is not a variable, e.g. ValueModule or Class
3961 SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3962 // Block-scoped declarations are not allowed to be re-declared
3963 // they can not merge with anything in the value space
3964 SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3965 SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3966 SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3967 SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3968 SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3969 SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3970 SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3971 SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3972 SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3973 SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3974 SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3975 SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3976 SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3977 SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3978 SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3979 SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3980 SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3981 SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3982 SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3983 SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3984 SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3985 SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3986 /* @internal */
3987 SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3988 /* @internal */
3989 SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3990 /* @internal */
3991 // The set of things we consider semantically classifiable. Used to speed up the LS during
3992 // classification.
3993 SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3994 /* @internal */
3995 SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3996 })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3997 /* @internal */
3998 var EnumKind;
3999 (function (EnumKind) {
4000 EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
4001 EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
4002 })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
4003 /* @internal */
4004 var CheckFlags;
4005 (function (CheckFlags) {
4006 CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
4007 CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
4008 CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
4009 CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
4010 CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
4011 CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
4012 CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
4013 CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
4014 CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
4015 CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
4016 CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
4017 CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
4018 CheckFlags[CheckFlags["Late"] = 4096] = "Late";
4019 CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
4020 CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
4021 CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
4022 CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
4023 CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
4024 CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
4025 CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
4026 CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
4027 CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
4028 CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
4029 })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
4030 var InternalSymbolName;
4031 (function (InternalSymbolName) {
4032 InternalSymbolName["Call"] = "__call";
4033 InternalSymbolName["Constructor"] = "__constructor";
4034 InternalSymbolName["New"] = "__new";
4035 InternalSymbolName["Index"] = "__index";
4036 InternalSymbolName["ExportStar"] = "__export";
4037 InternalSymbolName["Global"] = "__global";
4038 InternalSymbolName["Missing"] = "__missing";
4039 InternalSymbolName["Type"] = "__type";
4040 InternalSymbolName["Object"] = "__object";
4041 InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
4042 InternalSymbolName["Class"] = "__class";
4043 InternalSymbolName["Function"] = "__function";
4044 InternalSymbolName["Computed"] = "__computed";
4045 InternalSymbolName["Resolving"] = "__resolving__";
4046 InternalSymbolName["ExportEquals"] = "export=";
4047 InternalSymbolName["Default"] = "default";
4048 InternalSymbolName["This"] = "this";
4049 })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
4050 /* @internal */
4051 var NodeCheckFlags;
4052 (function (NodeCheckFlags) {
4053 NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
4054 NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
4055 NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
4056 NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
4057 NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
4058 NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
4059 NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
4060 NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
4061 NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
4062 NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
4063 NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
4064 NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
4065 NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
4066 NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
4067 NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
4068 NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
4069 NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
4070 NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
4071 NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
4072 NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
4073 NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
4074 NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
4075 NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4076 })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4077 var TypeFlags;
4078 (function (TypeFlags) {
4079 TypeFlags[TypeFlags["Any"] = 1] = "Any";
4080 TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4081 TypeFlags[TypeFlags["String"] = 4] = "String";
4082 TypeFlags[TypeFlags["Number"] = 8] = "Number";
4083 TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4084 TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4085 TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4086 TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4087 TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4088 TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4089 TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4090 TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4091 TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4092 TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4093 TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4094 TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4095 TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4096 TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4097 TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4098 TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4099 TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4100 TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4101 TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4102 TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4103 TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4104 TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4105 TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4106 /* @internal */
4107 TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4108 /* @internal */
4109 TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4110 TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4111 TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4112 TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4113 /* @internal */
4114 TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4115 /* @internal */
4116 TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4117 TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4118 /* @internal */
4119 TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4120 /* @internal */
4121 TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4122 TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
4123 TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4124 TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4125 TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4126 TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4127 TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4128 TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4129 /* @internal */
4130 TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
4131 TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4132 TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4133 TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4134 TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4135 TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
4136 TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
4137 TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
4138 /* @internal */
4139 TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4140 /* @internal */
4141 TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4142 /* @internal */
4143 TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
4144 // 'Narrowable' types are types where narrowing actually narrows.
4145 // This *should* be every type other than null, undefined, void, and never
4146 TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
4147 /* @internal */
4148 TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
4149 // The following flags are aggregated during union and intersection type construction
4150 /* @internal */
4151 TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
4152 // The following flags are used for different purposes during union and intersection type construction
4153 /* @internal */
4154 TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
4155 /* @internal */
4156 TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4157 /* @internal */
4158 TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4159 /* @internal */
4160 TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4161 })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4162 var ObjectFlags;
4163 (function (ObjectFlags) {
4164 ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4165 ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4166 ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4167 ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4168 ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4169 ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4170 ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4171 ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4172 ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4173 ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4174 ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
4175 ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
4176 ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
4177 ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
4178 ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
4179 ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
4180 ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
4181 ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
4182 /* @internal */
4183 ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
4184 /* @internal */
4185 ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
4186 /* @internal */
4187 ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
4188 /* @internal */
4189 ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
4190 /* @internal */
4191 ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
4192 /* @internal */
4193 ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4194 /* @internal */
4195 ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
4196 /* @internal */
4197 ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
4198 /* @internal */
4199 ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
4200 /* @internal */
4201 ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
4202 /* @internal */
4203 ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
4204 /* @internal */
4205 ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
4206 /* @internal */
4207 ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
4208 ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4209 /* @internal */
4210 ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
4211 /* @internal */
4212 ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
4213 })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4214 /* @internal */
4215 var VarianceFlags;
4216 (function (VarianceFlags) {
4217 VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4218 VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4219 VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4220 VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4221 VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4222 VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4223 VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4224 VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4225 VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4226 })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4227 var ElementFlags;
4228 (function (ElementFlags) {
4229 ElementFlags[ElementFlags["Required"] = 1] = "Required";
4230 ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
4231 ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
4232 ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
4233 ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
4234 })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
4235 /* @internal */
4236 var JsxReferenceKind;
4237 (function (JsxReferenceKind) {
4238 JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4239 JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4240 JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4241 })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4242 var SignatureKind;
4243 (function (SignatureKind) {
4244 SignatureKind[SignatureKind["Call"] = 0] = "Call";
4245 SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4246 })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4247 /* @internal */
4248 var SignatureFlags;
4249 (function (SignatureFlags) {
4250 SignatureFlags[SignatureFlags["None"] = 0] = "None";
4251 SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4252 SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4253 SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4254 SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4255 SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4256 // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4257 // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4258 // instantiating the return type.
4259 SignatureFlags[SignatureFlags["PropagatingFlags"] = 19] = "PropagatingFlags";
4260 SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4261 })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4262 var IndexKind;
4263 (function (IndexKind) {
4264 IndexKind[IndexKind["String"] = 0] = "String";
4265 IndexKind[IndexKind["Number"] = 1] = "Number";
4266 })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4267 /* @internal */
4268 var TypeMapKind;
4269 (function (TypeMapKind) {
4270 TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4271 TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4272 TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4273 TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4274 TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4275 })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4276 var InferencePriority;
4277 (function (InferencePriority) {
4278 InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4279 InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
4280 InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType";
4281 InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType";
4282 InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint";
4283 InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional";
4284 InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType";
4285 InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof";
4286 InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints";
4287 InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict";
4288 InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue";
4289 InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination";
4290 InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4291 })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4292 /* @internal */
4293 var InferenceFlags;
4294 (function (InferenceFlags) {
4295 InferenceFlags[InferenceFlags["None"] = 0] = "None";
4296 InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4297 InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4298 InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4299 })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4300 /**
4301 * Ternary values are defined such that
4302 * x & y is False if either x or y is False.
4303 * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4304 * x & y is True if both x and y are True.
4305 * x | y is False if both x and y are False.
4306 * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4307 * x | y is True if either x or y is True.
4308 */
4309 /* @internal */
4310 var Ternary;
4311 (function (Ternary) {
4312 Ternary[Ternary["False"] = 0] = "False";
4313 Ternary[Ternary["Maybe"] = 1] = "Maybe";
4314 Ternary[Ternary["True"] = -1] = "True";
4315 })(Ternary = ts.Ternary || (ts.Ternary = {}));
4316 /* @internal */
4317 var AssignmentDeclarationKind;
4318 (function (AssignmentDeclarationKind) {
4319 AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4320 /// exports.name = expr
4321 AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4322 /// module.exports = expr
4323 AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4324 /// className.prototype.name = expr
4325 AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4326 /// this.name = expr
4327 AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4328 // F.name = expr
4329 AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4330 // F.prototype = { ... }
4331 AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4332 // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4333 // Object.defineProperty(x, 'name', { get: Function, set: Function });
4334 // Object.defineProperty(x, 'name', { get: Function });
4335 // Object.defineProperty(x, 'name', { set: Function });
4336 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4337 // Object.defineProperty(exports || module.exports, 'name', ...);
4338 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4339 // Object.defineProperty(Foo.prototype, 'name', ...);
4340 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4341 })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4342 var DiagnosticCategory;
4343 (function (DiagnosticCategory) {
4344 DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4345 DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4346 DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4347 DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4348 })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4349 /* @internal */
4350 function diagnosticCategoryName(d, lowerCase) {
4351 if (lowerCase === void 0) { lowerCase = true; }
4352 var name = DiagnosticCategory[d.category];
4353 return lowerCase ? name.toLowerCase() : name;
4354 }
4355 ts.diagnosticCategoryName = diagnosticCategoryName;
4356 var ModuleResolutionKind;
4357 (function (ModuleResolutionKind) {
4358 ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4359 ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4360 })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4361 var WatchFileKind;
4362 (function (WatchFileKind) {
4363 WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4364 WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4365 WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4366 WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4367 WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4368 })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4369 var WatchDirectoryKind;
4370 (function (WatchDirectoryKind) {
4371 WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4372 WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4373 WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4374 })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4375 var PollingWatchKind;
4376 (function (PollingWatchKind) {
4377 PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4378 PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4379 PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4380 })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4381 var ModuleKind;
4382 (function (ModuleKind) {
4383 ModuleKind[ModuleKind["None"] = 0] = "None";
4384 ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4385 ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4386 ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4387 ModuleKind[ModuleKind["System"] = 4] = "System";
4388 // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4389 // Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4390 // module kind).
4391 ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4392 ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4393 ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4394 })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4395 var JsxEmit;
4396 (function (JsxEmit) {
4397 JsxEmit[JsxEmit["None"] = 0] = "None";
4398 JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4399 JsxEmit[JsxEmit["React"] = 2] = "React";
4400 JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4401 })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4402 var ImportsNotUsedAsValues;
4403 (function (ImportsNotUsedAsValues) {
4404 ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4405 ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4406 ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4407 })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4408 var NewLineKind;
4409 (function (NewLineKind) {
4410 NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4411 NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4412 })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4413 var ScriptKind;
4414 (function (ScriptKind) {
4415 ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4416 ScriptKind[ScriptKind["JS"] = 1] = "JS";
4417 ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4418 ScriptKind[ScriptKind["TS"] = 3] = "TS";
4419 ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4420 ScriptKind[ScriptKind["External"] = 5] = "External";
4421 ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4422 /**
4423 * Used on extensions that doesn't define the ScriptKind but the content defines it.
4424 * Deferred extensions are going to be included in all project contexts.
4425 */
4426 ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4427 })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4428 var ScriptTarget;
4429 (function (ScriptTarget) {
4430 ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4431 ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4432 ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4433 ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4434 ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4435 ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4436 ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4437 ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4438 ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4439 ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4440 ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4441 })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4442 var LanguageVariant;
4443 (function (LanguageVariant) {
4444 LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4445 LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4446 })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4447 var WatchDirectoryFlags;
4448 (function (WatchDirectoryFlags) {
4449 WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4450 WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4451 })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4452 /* @internal */
4453 var CharacterCodes;
4454 (function (CharacterCodes) {
4455 CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4456 CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4457 CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4458 CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4459 CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4460 CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4461 CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4462 // Unicode 3.0 space characters
4463 CharacterCodes[CharacterCodes["space"] = 32] = "space";
4464 CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4465 CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4466 CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4467 CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4468 CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4469 CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4470 CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4471 CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4472 CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4473 CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4474 CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4475 CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4476 CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4477 CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4478 CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4479 CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4480 CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4481 CharacterCodes[CharacterCodes["_"] = 95] = "_";
4482 CharacterCodes[CharacterCodes["$"] = 36] = "$";
4483 CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4484 CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4485 CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4486 CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4487 CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4488 CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4489 CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4490 CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4491 CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4492 CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4493 CharacterCodes[CharacterCodes["a"] = 97] = "a";
4494 CharacterCodes[CharacterCodes["b"] = 98] = "b";
4495 CharacterCodes[CharacterCodes["c"] = 99] = "c";
4496 CharacterCodes[CharacterCodes["d"] = 100] = "d";
4497 CharacterCodes[CharacterCodes["e"] = 101] = "e";
4498 CharacterCodes[CharacterCodes["f"] = 102] = "f";
4499 CharacterCodes[CharacterCodes["g"] = 103] = "g";
4500 CharacterCodes[CharacterCodes["h"] = 104] = "h";
4501 CharacterCodes[CharacterCodes["i"] = 105] = "i";
4502 CharacterCodes[CharacterCodes["j"] = 106] = "j";
4503 CharacterCodes[CharacterCodes["k"] = 107] = "k";
4504 CharacterCodes[CharacterCodes["l"] = 108] = "l";
4505 CharacterCodes[CharacterCodes["m"] = 109] = "m";
4506 CharacterCodes[CharacterCodes["n"] = 110] = "n";
4507 CharacterCodes[CharacterCodes["o"] = 111] = "o";
4508 CharacterCodes[CharacterCodes["p"] = 112] = "p";
4509 CharacterCodes[CharacterCodes["q"] = 113] = "q";
4510 CharacterCodes[CharacterCodes["r"] = 114] = "r";
4511 CharacterCodes[CharacterCodes["s"] = 115] = "s";
4512 CharacterCodes[CharacterCodes["t"] = 116] = "t";
4513 CharacterCodes[CharacterCodes["u"] = 117] = "u";
4514 CharacterCodes[CharacterCodes["v"] = 118] = "v";
4515 CharacterCodes[CharacterCodes["w"] = 119] = "w";
4516 CharacterCodes[CharacterCodes["x"] = 120] = "x";
4517 CharacterCodes[CharacterCodes["y"] = 121] = "y";
4518 CharacterCodes[CharacterCodes["z"] = 122] = "z";
4519 CharacterCodes[CharacterCodes["A"] = 65] = "A";
4520 CharacterCodes[CharacterCodes["B"] = 66] = "B";
4521 CharacterCodes[CharacterCodes["C"] = 67] = "C";
4522 CharacterCodes[CharacterCodes["D"] = 68] = "D";
4523 CharacterCodes[CharacterCodes["E"] = 69] = "E";
4524 CharacterCodes[CharacterCodes["F"] = 70] = "F";
4525 CharacterCodes[CharacterCodes["G"] = 71] = "G";
4526 CharacterCodes[CharacterCodes["H"] = 72] = "H";
4527 CharacterCodes[CharacterCodes["I"] = 73] = "I";
4528 CharacterCodes[CharacterCodes["J"] = 74] = "J";
4529 CharacterCodes[CharacterCodes["K"] = 75] = "K";
4530 CharacterCodes[CharacterCodes["L"] = 76] = "L";
4531 CharacterCodes[CharacterCodes["M"] = 77] = "M";
4532 CharacterCodes[CharacterCodes["N"] = 78] = "N";
4533 CharacterCodes[CharacterCodes["O"] = 79] = "O";
4534 CharacterCodes[CharacterCodes["P"] = 80] = "P";
4535 CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4536 CharacterCodes[CharacterCodes["R"] = 82] = "R";
4537 CharacterCodes[CharacterCodes["S"] = 83] = "S";
4538 CharacterCodes[CharacterCodes["T"] = 84] = "T";
4539 CharacterCodes[CharacterCodes["U"] = 85] = "U";
4540 CharacterCodes[CharacterCodes["V"] = 86] = "V";
4541 CharacterCodes[CharacterCodes["W"] = 87] = "W";
4542 CharacterCodes[CharacterCodes["X"] = 88] = "X";
4543 CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4544 CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4545 CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4546 CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4547 CharacterCodes[CharacterCodes["at"] = 64] = "at";
4548 CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4549 CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4550 CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4551 CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4552 CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4553 CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4554 CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4555 CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4556 CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4557 CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4558 CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4559 CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4560 CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4561 CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4562 CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4563 CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4564 CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4565 CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4566 CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4567 CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4568 CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4569 CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4570 CharacterCodes[CharacterCodes["question"] = 63] = "question";
4571 CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4572 CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4573 CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4574 CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4575 CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4576 CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4577 CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4578 CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4579 CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4580 })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4581 var Extension;
4582 (function (Extension) {
4583 Extension["Ts"] = ".ts";
4584 Extension["Tsx"] = ".tsx";
4585 Extension["Dts"] = ".d.ts";
4586 Extension["Js"] = ".js";
4587 Extension["Jsx"] = ".jsx";
4588 Extension["Json"] = ".json";
4589 Extension["TsBuildInfo"] = ".tsbuildinfo";
4590 })(Extension = ts.Extension || (ts.Extension = {}));
4591 /* @internal */
4592 var TransformFlags;
4593 (function (TransformFlags) {
4594 TransformFlags[TransformFlags["None"] = 0] = "None";
4595 // Facts
4596 // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4597 TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4598 TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4599 TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4600 TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4601 TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4602 TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4603 TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4604 TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4605 TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4606 TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4607 TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4608 // Markers
4609 // - Flags used to indicate that a subtree contains a specific transformation.
4610 TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4611 TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4612 TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4613 TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4614 TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4615 TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4616 TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4617 TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4618 TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4619 TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4620 TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4621 TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4622 TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait";
4623 // Please leave this as 1 << 29.
4624 // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4625 // It is a good reminder of how much room we have left
4626 TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4627 // Assertions
4628 // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4629 TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4630 TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4631 TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4632 TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4633 TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4634 TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4635 TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4636 TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4637 TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4638 TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4639 TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4640 // Scope Exclusions
4641 // - Bitmasks that exclude flags from propagating out of a specific context
4642 // into the subtree flags of their container.
4643 TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4644 TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4645 TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4646 TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes";
4647 TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes";
4648 TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes";
4649 TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4650 TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4651 TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4652 TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes";
4653 TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4654 TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4655 TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4656 TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4657 TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4658 TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4659 TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4660 // Propagating flags
4661 // - Bitmasks for flags that should propagate from a child
4662 TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4663 // Masks
4664 // - Additional bitmasks
4665 })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4666 var EmitFlags;
4667 (function (EmitFlags) {
4668 EmitFlags[EmitFlags["None"] = 0] = "None";
4669 EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4670 EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4671 EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4672 EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4673 EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4674 EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4675 EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4676 EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4677 EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4678 EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4679 EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4680 EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4681 EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4682 EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4683 EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4684 EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4685 EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4686 EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4687 EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4688 EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4689 EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4690 EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4691 EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4692 EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4693 EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4694 EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4695 EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4696 EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4697 /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4698 /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4699 /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4700 })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4701 /**
4702 * Used by the checker, this enum keeps track of external emit helpers that should be type
4703 * checked.
4704 */
4705 /* @internal */
4706 var ExternalEmitHelpers;
4707 (function (ExternalEmitHelpers) {
4708 ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4709 ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4710 ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4711 ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4712 ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4713 ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4714 ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4715 ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4716 ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4717 ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4718 ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4719 ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4720 ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4721 ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4722 ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4723 ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4724 ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4725 ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 131072] = "ImportStar";
4726 ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 262144] = "ImportDefault";
4727 ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 524288] = "MakeTemplateObject";
4728 ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 1048576] = "ClassPrivateFieldGet";
4729 ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 2097152] = "ClassPrivateFieldSet";
4730 ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
4731 ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4732 ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
4733 // Helpers included by ES2015 for..of
4734 ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4735 // Helpers included by ES2017 for..await..of
4736 ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4737 // Helpers included by ES2017 async generators
4738 ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4739 // Helpers included by yield* in ES2017 async generators
4740 ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4741 // Helpers included by ES2015 spread
4742 ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4743 })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4744 var EmitHint;
4745 (function (EmitHint) {
4746 EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4747 EmitHint[EmitHint["Expression"] = 1] = "Expression";
4748 EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4749 EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4750 EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4751 EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4752 EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4753 })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4754 var OuterExpressionKinds;
4755 (function (OuterExpressionKinds) {
4756 OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
4757 OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
4758 OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
4759 OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
4760 OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
4761 OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
4762 })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
4763 /* @internal */
4764 var LexicalEnvironmentFlags;
4765 (function (LexicalEnvironmentFlags) {
4766 LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4767 LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4768 LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4769 })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4770 /*@internal*/
4771 var BundleFileSectionKind;
4772 (function (BundleFileSectionKind) {
4773 BundleFileSectionKind["Prologue"] = "prologue";
4774 BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4775 BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4776 BundleFileSectionKind["Reference"] = "reference";
4777 BundleFileSectionKind["Type"] = "type";
4778 BundleFileSectionKind["Lib"] = "lib";
4779 BundleFileSectionKind["Prepend"] = "prepend";
4780 BundleFileSectionKind["Text"] = "text";
4781 BundleFileSectionKind["Internal"] = "internal";
4782 // comments?
4783 })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4784 var ListFormat;
4785 (function (ListFormat) {
4786 ListFormat[ListFormat["None"] = 0] = "None";
4787 // Line separators
4788 ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4789 ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4790 ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4791 ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4792 // Delimiters
4793 ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4794 ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4795 ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4796 ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4797 ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4798 ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4799 ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4800 // Whitespace
4801 ListFormat[ListFormat["Indented"] = 128] = "Indented";
4802 ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4803 ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4804 // Brackets/Braces
4805 ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4806 ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4807 ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4808 ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4809 ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4810 ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4811 ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4812 ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4813 // Other
4814 ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4815 ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4816 ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4817 ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4818 ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4819 ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4820 // Precomputed Formats
4821 ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4822 ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4823 ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4824 ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4825 ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
4826 ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
4827 ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4828 ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4829 ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4830 ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4831 ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4832 ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4833 ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4834 ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4835 ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4836 ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4837 ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4838 ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4839 ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4840 ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4841 ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4842 ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4843 ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4844 ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4845 ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4846 ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4847 ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4848 ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4849 ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4850 ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4851 ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4852 ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4853 ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4854 ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4855 ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4856 ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4857 ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4858 ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4859 })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4860 /* @internal */
4861 var PragmaKindFlags;
4862 (function (PragmaKindFlags) {
4863 PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4864 /**
4865 * Triple slash comment of the form
4866 * /// <pragma-name argname="value" />
4867 */
4868 PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4869 /**
4870 * Single line comment of the form
4871 * // @pragma-name argval1 argval2
4872 * or
4873 * /// @pragma-name argval1 argval2
4874 */
4875 PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4876 /**
4877 * Multiline non-jsdoc pragma of the form
4878 * /* @pragma-name argval1 argval2 * /
4879 */
4880 PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4881 PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4882 PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4883 })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4884 // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4885 // fancy effectively defining it twice, once in value-space and once in type-space
4886 /* @internal */
4887 ts.commentPragmas = {
4888 "reference": {
4889 args: [
4890 { name: "types", optional: true, captureSpan: true },
4891 { name: "lib", optional: true, captureSpan: true },
4892 { name: "path", optional: true, captureSpan: true },
4893 { name: "no-default-lib", optional: true }
4894 ],
4895 kind: 1 /* TripleSlashXML */
4896 },
4897 "amd-dependency": {
4898 args: [{ name: "path" }, { name: "name", optional: true }],
4899 kind: 1 /* TripleSlashXML */
4900 },
4901 "amd-module": {
4902 args: [{ name: "name" }],
4903 kind: 1 /* TripleSlashXML */
4904 },
4905 "ts-check": {
4906 kind: 2 /* SingleLine */
4907 },
4908 "ts-nocheck": {
4909 kind: 2 /* SingleLine */
4910 },
4911 "jsx": {
4912 args: [{ name: "factory" }],
4913 kind: 4 /* MultiLine */
4914 },
4915 "jsxfrag": {
4916 args: [{ name: "factory" }],
4917 kind: 4 /* MultiLine */
4918 },
4919 };
4920})(ts || (ts = {}));
4921var ts;
4922(function (ts) {
4923 /**
4924 * djb2 hashing algorithm
4925 * http://www.cse.yorku.ca/~oz/hash.html
4926 */
4927 /* @internal */
4928 function generateDjb2Hash(data) {
4929 var acc = 5381;
4930 for (var i = 0; i < data.length; i++) {
4931 acc = ((acc << 5) + acc) + data.charCodeAt(i);
4932 }
4933 return acc.toString();
4934 }
4935 ts.generateDjb2Hash = generateDjb2Hash;
4936 /**
4937 * Set a high stack trace limit to provide more information in case of an error.
4938 * Called for command-line and server use cases.
4939 * Not called if TypeScript is used as a library.
4940 */
4941 /* @internal */
4942 function setStackTraceLimit() {
4943 if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4944 Error.stackTraceLimit = 100;
4945 }
4946 }
4947 ts.setStackTraceLimit = setStackTraceLimit;
4948 var FileWatcherEventKind;
4949 (function (FileWatcherEventKind) {
4950 FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4951 FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4952 FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4953 })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4954 /* @internal */
4955 var PollingInterval;
4956 (function (PollingInterval) {
4957 PollingInterval[PollingInterval["High"] = 2000] = "High";
4958 PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4959 PollingInterval[PollingInterval["Low"] = 250] = "Low";
4960 })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4961 /* @internal */
4962 ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4963 function createPollingIntervalBasedLevels(levels) {
4964 var _a;
4965 return _a = {},
4966 _a[PollingInterval.Low] = levels.Low,
4967 _a[PollingInterval.Medium] = levels.Medium,
4968 _a[PollingInterval.High] = levels.High,
4969 _a;
4970 }
4971 var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4972 var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4973 /* @internal */
4974 ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4975 /* @internal */
4976 function setCustomPollingValues(system) {
4977 if (!system.getEnvironmentVariable) {
4978 return;
4979 }
4980 var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4981 pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4982 ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4983 function getLevel(envVar, level) {
4984 return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4985 }
4986 function getCustomLevels(baseVariable) {
4987 var customLevels;
4988 setCustomLevel("Low");
4989 setCustomLevel("Medium");
4990 setCustomLevel("High");
4991 return customLevels;
4992 function setCustomLevel(level) {
4993 var customLevel = getLevel(baseVariable, level);
4994 if (customLevel) {
4995 (customLevels || (customLevels = {}))[level] = Number(customLevel);
4996 }
4997 }
4998 }
4999 function setCustomLevels(baseVariable, levels) {
5000 var customLevels = getCustomLevels(baseVariable);
5001 if (customLevels) {
5002 setLevel("Low");
5003 setLevel("Medium");
5004 setLevel("High");
5005 return true;
5006 }
5007 return false;
5008 function setLevel(level) {
5009 levels[level] = customLevels[level] || levels[level];
5010 }
5011 }
5012 function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
5013 var customLevels = getCustomLevels(baseVariable);
5014 return (pollingIntervalChanged || customLevels) &&
5015 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
5016 }
5017 }
5018 ts.setCustomPollingValues = setCustomPollingValues;
5019 /* @internal */
5020 function createDynamicPriorityPollingWatchFile(host) {
5021 var watchedFiles = [];
5022 var changedFilesInLastPoll = [];
5023 var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
5024 var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
5025 var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
5026 return watchFile;
5027 function watchFile(fileName, callback, defaultPollingInterval) {
5028 var file = {
5029 fileName: fileName,
5030 callback: callback,
5031 unchangedPolls: 0,
5032 mtime: getModifiedTime(fileName)
5033 };
5034 watchedFiles.push(file);
5035 addToPollingIntervalQueue(file, defaultPollingInterval);
5036 return {
5037 close: function () {
5038 file.isClosed = true;
5039 // Remove from watchedFiles
5040 ts.unorderedRemoveItem(watchedFiles, file);
5041 // Do not update polling interval queue since that will happen as part of polling
5042 }
5043 };
5044 }
5045 function createPollingIntervalQueue(pollingInterval) {
5046 var queue = [];
5047 queue.pollingInterval = pollingInterval;
5048 queue.pollIndex = 0;
5049 queue.pollScheduled = false;
5050 return queue;
5051 }
5052 function pollPollingIntervalQueue(queue) {
5053 queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
5054 // Set the next polling index and timeout
5055 if (queue.length) {
5056 scheduleNextPoll(queue.pollingInterval);
5057 }
5058 else {
5059 ts.Debug.assert(queue.pollIndex === 0);
5060 queue.pollScheduled = false;
5061 }
5062 }
5063 function pollLowPollingIntervalQueue(queue) {
5064 // Always poll complete list of changedFilesInLastPoll
5065 pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
5066 // Finally do the actual polling of the queue
5067 pollPollingIntervalQueue(queue);
5068 // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
5069 // as pollPollingIntervalQueue wont schedule for next poll
5070 if (!queue.pollScheduled && changedFilesInLastPoll.length) {
5071 scheduleNextPoll(PollingInterval.Low);
5072 }
5073 }
5074 function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
5075 // Max visit would be all elements of the queue
5076 var needsVisit = queue.length;
5077 var definedValueCopyToIndex = pollIndex;
5078 for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
5079 var watchedFile = queue[pollIndex];
5080 if (!watchedFile) {
5081 continue;
5082 }
5083 else if (watchedFile.isClosed) {
5084 queue[pollIndex] = undefined;
5085 continue;
5086 }
5087 polled++;
5088 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
5089 if (watchedFile.isClosed) {
5090 // Closed watcher as part of callback
5091 queue[pollIndex] = undefined;
5092 }
5093 else if (fileChanged) {
5094 watchedFile.unchangedPolls = 0;
5095 // Changed files go to changedFilesInLastPoll queue
5096 if (queue !== changedFilesInLastPoll) {
5097 queue[pollIndex] = undefined;
5098 addChangedFileToLowPollingIntervalQueue(watchedFile);
5099 }
5100 }
5101 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
5102 watchedFile.unchangedPolls++;
5103 }
5104 else if (queue === changedFilesInLastPoll) {
5105 // Restart unchangedPollCount for unchanged file and move to low polling interval queue
5106 watchedFile.unchangedPolls = 1;
5107 queue[pollIndex] = undefined;
5108 addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
5109 }
5110 else if (pollingInterval !== PollingInterval.High) {
5111 watchedFile.unchangedPolls++;
5112 queue[pollIndex] = undefined;
5113 addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
5114 }
5115 if (queue[pollIndex]) {
5116 // Copy this file to the non hole location
5117 if (definedValueCopyToIndex < pollIndex) {
5118 queue[definedValueCopyToIndex] = watchedFile;
5119 queue[pollIndex] = undefined;
5120 }
5121 definedValueCopyToIndex++;
5122 }
5123 }
5124 // Return next poll index
5125 return pollIndex;
5126 function nextPollIndex() {
5127 pollIndex++;
5128 if (pollIndex === queue.length) {
5129 if (definedValueCopyToIndex < pollIndex) {
5130 // There are holes from nextDefinedValueIndex to end of queue, change queue size
5131 queue.length = definedValueCopyToIndex;
5132 }
5133 pollIndex = 0;
5134 definedValueCopyToIndex = 0;
5135 }
5136 }
5137 }
5138 function pollingIntervalQueue(pollingInterval) {
5139 switch (pollingInterval) {
5140 case PollingInterval.Low:
5141 return lowPollingIntervalQueue;
5142 case PollingInterval.Medium:
5143 return mediumPollingIntervalQueue;
5144 case PollingInterval.High:
5145 return highPollingIntervalQueue;
5146 }
5147 }
5148 function addToPollingIntervalQueue(file, pollingInterval) {
5149 pollingIntervalQueue(pollingInterval).push(file);
5150 scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
5151 }
5152 function addChangedFileToLowPollingIntervalQueue(file) {
5153 changedFilesInLastPoll.push(file);
5154 scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
5155 }
5156 function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
5157 if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
5158 scheduleNextPoll(pollingInterval);
5159 }
5160 }
5161 function scheduleNextPoll(pollingInterval) {
5162 pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
5163 }
5164 function getModifiedTime(fileName) {
5165 return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
5166 }
5167 }
5168 ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
5169 function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
5170 // One file can have multiple watchers
5171 var fileWatcherCallbacks = ts.createMultiMap();
5172 var dirWatchers = new ts.Map();
5173 var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
5174 return nonPollingWatchFile;
5175 function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
5176 var filePath = toCanonicalName(fileName);
5177 fileWatcherCallbacks.add(filePath, callback);
5178 var dirPath = ts.getDirectoryPath(filePath) || ".";
5179 var watcher = dirWatchers.get(dirPath) ||
5180 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
5181 watcher.referenceCount++;
5182 return {
5183 close: function () {
5184 if (watcher.referenceCount === 1) {
5185 watcher.close();
5186 dirWatchers.delete(dirPath);
5187 }
5188 else {
5189 watcher.referenceCount--;
5190 }
5191 fileWatcherCallbacks.remove(filePath, callback);
5192 }
5193 };
5194 }
5195 function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
5196 var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
5197 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
5198 if (!ts.isString(relativeFileName)) {
5199 return;
5200 }
5201 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
5202 // Some applications save a working file via rename operations
5203 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
5204 if (callbacks) {
5205 for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
5206 var fileCallback = callbacks_1[_i];
5207 fileCallback(fileName, FileWatcherEventKind.Changed);
5208 }
5209 }
5210 },
5211 /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
5212 watcher.referenceCount = 0;
5213 dirWatchers.set(dirPath, watcher);
5214 return watcher;
5215 }
5216 }
5217 /* @internal */
5218 function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
5219 var cache = new ts.Map();
5220 var callbacksCache = ts.createMultiMap();
5221 var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
5222 return function (fileName, callback, pollingInterval, options) {
5223 var path = toCanonicalFileName(fileName);
5224 var existing = cache.get(path);
5225 if (existing) {
5226 existing.refCount++;
5227 }
5228 else {
5229 cache.set(path, {
5230 watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
5231 refCount: 1
5232 });
5233 }
5234 callbacksCache.add(path, callback);
5235 return {
5236 close: function () {
5237 var watcher = ts.Debug.checkDefined(cache.get(path));
5238 callbacksCache.remove(path, callback);
5239 watcher.refCount--;
5240 if (watcher.refCount)
5241 return;
5242 cache.delete(path);
5243 ts.closeFileWatcherOf(watcher);
5244 }
5245 };
5246 };
5247 }
5248 ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
5249 /**
5250 * Returns true if file status changed
5251 */
5252 /*@internal*/
5253 function onWatchedFileStat(watchedFile, modifiedTime) {
5254 var oldTime = watchedFile.mtime.getTime();
5255 var newTime = modifiedTime.getTime();
5256 if (oldTime !== newTime) {
5257 watchedFile.mtime = modifiedTime;
5258 watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
5259 return true;
5260 }
5261 return false;
5262 }
5263 ts.onWatchedFileStat = onWatchedFileStat;
5264 /*@internal*/
5265 function getFileWatcherEventKind(oldTime, newTime) {
5266 return oldTime === 0
5267 ? FileWatcherEventKind.Created
5268 : newTime === 0
5269 ? FileWatcherEventKind.Deleted
5270 : FileWatcherEventKind.Changed;
5271 }
5272 ts.getFileWatcherEventKind = getFileWatcherEventKind;
5273 /*@internal*/
5274 ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5275 /*@internal*/
5276 ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5277 /*@internal*/
5278 function setSysLog(logger) {
5279 ts.sysLog = logger;
5280 }
5281 ts.setSysLog = setSysLog;
5282 /**
5283 * Watch the directory recursively using host provided method to watch child directories
5284 * that means if this is recursive watcher, watch the children directories as well
5285 * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5286 */
5287 /*@internal*/
5288 function createDirectoryWatcherSupportingRecursive(host) {
5289 var cache = new ts.Map();
5290 var callbackCache = ts.createMultiMap();
5291 var cacheToUpdateChildWatches = new ts.Map();
5292 var timerToUpdateChildWatches;
5293 var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5294 var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5295 return function (dirName, callback, recursive, options) { return recursive ?
5296 createDirectoryWatcher(dirName, options, callback) :
5297 host.watchDirectory(dirName, callback, recursive, options); };
5298 /**
5299 * Create the directory watcher for the dirPath.
5300 */
5301 function createDirectoryWatcher(dirName, options, callback) {
5302 var dirPath = toCanonicalFilePath(dirName);
5303 var directoryWatcher = cache.get(dirPath);
5304 if (directoryWatcher) {
5305 directoryWatcher.refCount++;
5306 }
5307 else {
5308 directoryWatcher = {
5309 watcher: host.watchDirectory(dirName, function (fileName) {
5310 if (isIgnoredPath(fileName))
5311 return;
5312 if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5313 // Call the actual callback
5314 invokeCallbacks(dirPath, fileName);
5315 // Iterate through existing children and update the watches if needed
5316 updateChildWatches(dirName, dirPath, options);
5317 }
5318 else {
5319 nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5320 }
5321 }, /*recursive*/ false, options),
5322 refCount: 1,
5323 childWatches: ts.emptyArray
5324 };
5325 cache.set(dirPath, directoryWatcher);
5326 updateChildWatches(dirName, dirPath, options);
5327 }
5328 var callbackToAdd = callback && { dirName: dirName, callback: callback };
5329 if (callbackToAdd) {
5330 callbackCache.add(dirPath, callbackToAdd);
5331 }
5332 return {
5333 dirName: dirName,
5334 close: function () {
5335 var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5336 if (callbackToAdd)
5337 callbackCache.remove(dirPath, callbackToAdd);
5338 directoryWatcher.refCount--;
5339 if (directoryWatcher.refCount)
5340 return;
5341 cache.delete(dirPath);
5342 ts.closeFileWatcherOf(directoryWatcher);
5343 directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5344 }
5345 };
5346 }
5347 function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
5348 var fileName;
5349 var invokeMap;
5350 if (ts.isString(fileNameOrInvokeMap)) {
5351 fileName = fileNameOrInvokeMap;
5352 }
5353 else {
5354 invokeMap = fileNameOrInvokeMap;
5355 }
5356 // Call the actual callback
5357 callbackCache.forEach(function (callbacks, rootDirName) {
5358 var _a;
5359 if (invokeMap && invokeMap.get(rootDirName) === true)
5360 return;
5361 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5362 if (invokeMap) {
5363 if (fileNames) {
5364 var existing = invokeMap.get(rootDirName);
5365 if (existing) {
5366 (_a = existing).push.apply(_a, fileNames);
5367 }
5368 else {
5369 invokeMap.set(rootDirName, fileNames.slice());
5370 }
5371 }
5372 else {
5373 invokeMap.set(rootDirName, true);
5374 }
5375 }
5376 else {
5377 callbacks.forEach(function (_a) {
5378 var callback = _a.callback;
5379 return callback(fileName);
5380 });
5381 }
5382 }
5383 });
5384 }
5385 function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5386 // Iterate through existing children and update the watches if needed
5387 var parentWatcher = cache.get(dirPath);
5388 if (parentWatcher && host.directoryExists(dirName)) {
5389 // Schedule the update and postpone invoke for callbacks
5390 scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
5391 return;
5392 }
5393 // Call the actual callbacks and remove child watches
5394 invokeCallbacks(dirPath, fileName);
5395 removeChildWatches(parentWatcher);
5396 }
5397 function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
5398 var existing = cacheToUpdateChildWatches.get(dirPath);
5399 if (existing) {
5400 existing.fileNames.push(fileName);
5401 }
5402 else {
5403 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
5404 }
5405 if (timerToUpdateChildWatches) {
5406 host.clearTimeout(timerToUpdateChildWatches);
5407 timerToUpdateChildWatches = undefined;
5408 }
5409 timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5410 }
5411 function onTimerToUpdateChildWatches() {
5412 timerToUpdateChildWatches = undefined;
5413 ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5414 var start = ts.timestamp();
5415 var invokeMap = new ts.Map();
5416 while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5417 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;
5418 ts.Debug.assert(!done);
5419 cacheToUpdateChildWatches.delete(dirPath);
5420 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5421 // to ensure that all the changes are reflected at this time
5422 var hasChanges = updateChildWatches(dirName, dirPath, options);
5423 invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
5424 }
5425 ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5426 callbackCache.forEach(function (callbacks, rootDirName) {
5427 var existing = invokeMap.get(rootDirName);
5428 if (existing) {
5429 callbacks.forEach(function (_a) {
5430 var callback = _a.callback, dirName = _a.dirName;
5431 if (ts.isArray(existing)) {
5432 existing.forEach(callback);
5433 }
5434 else {
5435 callback(dirName);
5436 }
5437 });
5438 }
5439 });
5440 var elapsed = ts.timestamp() - start;
5441 ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5442 }
5443 function removeChildWatches(parentWatcher) {
5444 if (!parentWatcher)
5445 return;
5446 var existingChildWatches = parentWatcher.childWatches;
5447 parentWatcher.childWatches = ts.emptyArray;
5448 for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5449 var childWatcher = existingChildWatches_1[_i];
5450 childWatcher.close();
5451 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5452 }
5453 }
5454 function updateChildWatches(parentDir, parentDirPath, options) {
5455 // Iterate through existing children and update the watches if needed
5456 var parentWatcher = cache.get(parentDirPath);
5457 if (!parentWatcher)
5458 return false;
5459 var newChildWatches;
5460 var hasChanges = ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5461 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5462 // Filter our the symbolic link directories since those arent included in recursive watch
5463 // which is same behaviour when recursive: true is passed to fs.watch
5464 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5465 }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5466 parentWatcher.childWatches = newChildWatches || ts.emptyArray;
5467 return hasChanges;
5468 /**
5469 * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5470 */
5471 function createAndAddChildDirectoryWatcher(childName) {
5472 var result = createDirectoryWatcher(childName, options);
5473 addChildDirectoryWatcher(result);
5474 }
5475 /**
5476 * Add child directory watcher to the new ChildDirectoryWatcher list
5477 */
5478 function addChildDirectoryWatcher(childWatcher) {
5479 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5480 }
5481 }
5482 function isIgnoredPath(path) {
5483 return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5484 }
5485 function isInPath(path, searchPath) {
5486 if (ts.stringContains(path, searchPath))
5487 return true;
5488 if (host.useCaseSensitiveFileNames)
5489 return false;
5490 return ts.stringContains(toCanonicalFilePath(path), searchPath);
5491 }
5492 }
5493 ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5494 /*@internal*/
5495 var FileSystemEntryKind;
5496 (function (FileSystemEntryKind) {
5497 FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5498 FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5499 })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5500 /*@internal*/
5501 function createFileWatcherCallback(callback) {
5502 return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5503 }
5504 ts.createFileWatcherCallback = createFileWatcherCallback;
5505 function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5506 return function (eventName) {
5507 if (eventName === "rename") {
5508 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5509 }
5510 else {
5511 // Change
5512 callback(fileName, FileWatcherEventKind.Changed);
5513 }
5514 };
5515 }
5516 function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5517 return function (eventName, relativeFileName) {
5518 // In watchDirectory we only care about adding and removing files (when event name is
5519 // "rename"); changes made within files are handled by corresponding fileWatchers (when
5520 // event name is "change")
5521 if (eventName === "rename") {
5522 // When deleting a file, the passed baseFileName is null
5523 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5524 }
5525 };
5526 }
5527 /*@internal*/
5528 function createSystemWatchFunctions(_a) {
5529 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;
5530 var dynamicPollingWatchFile;
5531 var nonPollingWatchFile;
5532 var hostRecursiveDirectoryWatcher;
5533 return {
5534 watchFile: watchFile,
5535 watchDirectory: watchDirectory
5536 };
5537 function watchFile(fileName, callback, pollingInterval, options) {
5538 options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5539 var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5540 switch (watchFileKind) {
5541 case ts.WatchFileKind.FixedPollingInterval:
5542 return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5543 case ts.WatchFileKind.PriorityPollingInterval:
5544 return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5545 case ts.WatchFileKind.DynamicPriorityPolling:
5546 return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5547 case ts.WatchFileKind.UseFsEvents:
5548 return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists),
5549 /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5550 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5551 if (!nonPollingWatchFile) {
5552 nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5553 }
5554 return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5555 default:
5556 ts.Debug.assertNever(watchFileKind);
5557 }
5558 }
5559 function ensureDynamicPollingWatchFile() {
5560 return dynamicPollingWatchFile ||
5561 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5562 }
5563 function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5564 if (options && options.watchFile !== undefined)
5565 return options;
5566 switch (tscWatchFile) {
5567 case "PriorityPollingInterval":
5568 // Use polling interval based on priority when create watch using host.watchFile
5569 return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5570 case "DynamicPriorityPolling":
5571 // Use polling interval but change the interval depending on file changes and their default polling interval
5572 return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5573 case "UseFsEvents":
5574 // Use notifications from FS to watch with falling back to fs.watchFile
5575 return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5576 case "UseFsEventsWithFallbackDynamicPolling":
5577 // Use notifications from FS to watch with falling back to dynamic watch file
5578 return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5579 case "UseFsEventsOnParentDirectory":
5580 useNonPollingWatchers = true;
5581 // fall through
5582 default:
5583 return useNonPollingWatchers ?
5584 // Use notifications from FS to watch with falling back to fs.watchFile
5585 generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5586 // Default to do not use fixed polling interval
5587 { watchFile: ts.WatchFileKind.FixedPollingInterval };
5588 }
5589 }
5590 function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5591 var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5592 return {
5593 watchFile: watchFile,
5594 fallbackPolling: defaultFallbackPolling === undefined ?
5595 fallbackPolling :
5596 defaultFallbackPolling
5597 };
5598 }
5599 function watchDirectory(directoryName, callback, recursive, options) {
5600 if (fsSupportsRecursiveFsWatch) {
5601 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5602 }
5603 if (!hostRecursiveDirectoryWatcher) {
5604 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5605 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5606 directoryExists: directoryExists,
5607 getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5608 watchDirectory: nonRecursiveWatchDirectory,
5609 realpath: realpath,
5610 setTimeout: setTimeout,
5611 clearTimeout: clearTimeout
5612 });
5613 }
5614 return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5615 }
5616 function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5617 ts.Debug.assert(!recursive);
5618 options = updateOptionsForWatchDirectory(options);
5619 var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5620 switch (watchDirectoryKind) {
5621 case ts.WatchDirectoryKind.FixedPollingInterval:
5622 return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
5623 /*options*/ undefined);
5624 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5625 return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
5626 /*options*/ undefined);
5627 case ts.WatchDirectoryKind.UseFsEvents:
5628 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5629 default:
5630 ts.Debug.assertNever(watchDirectoryKind);
5631 }
5632 }
5633 function updateOptionsForWatchDirectory(options) {
5634 if (options && options.watchDirectory !== undefined)
5635 return options;
5636 switch (tscWatchDirectory) {
5637 case "RecursiveDirectoryUsingFsWatchFile":
5638 // Use polling interval based on priority when create watch using host.watchFile
5639 return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5640 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5641 // Use polling interval but change the interval depending on file changes and their default polling interval
5642 return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5643 default:
5644 var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5645 return {
5646 watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5647 fallbackPolling: defaultFallbackPolling !== undefined ?
5648 defaultFallbackPolling :
5649 undefined
5650 };
5651 }
5652 }
5653 }
5654 ts.createSystemWatchFunctions = createSystemWatchFunctions;
5655 /**
5656 * patch writefile to create folder before writing the file
5657 */
5658 /*@internal*/
5659 function patchWriteFileEnsuringDirectory(sys) {
5660 // patch writefile to create folder before writing the file
5661 var originalWriteFile = sys.writeFile;
5662 sys.writeFile = function (path, data, writeBom) {
5663 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); });
5664 };
5665 }
5666 ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5667 function getNodeMajorVersion() {
5668 if (typeof process === "undefined") {
5669 return undefined;
5670 }
5671 var version = process.version;
5672 if (!version) {
5673 return undefined;
5674 }
5675 var dot = version.indexOf(".");
5676 if (dot === -1) {
5677 return undefined;
5678 }
5679 return parseInt(version.substring(1, dot));
5680 }
5681 ts.getNodeMajorVersion = getNodeMajorVersion;
5682 // TODO: GH#18217 this is used as if it's certainly defined in many places.
5683 // eslint-disable-next-line prefer-const
5684 ts.sys = (function () {
5685 // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5686 // byte order mark from the specified encoding. Using any other byte order mark does
5687 // not actually work.
5688 var byteOrderMarkIndicator = "\uFEFF";
5689 function getNodeSystem() {
5690 var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5691 var _fs = require("fs");
5692 var _path = require("path");
5693 var _os = require("os");
5694 // crypto can be absent on reduced node installations
5695 var _crypto;
5696 try {
5697 _crypto = require("crypto");
5698 }
5699 catch (_a) {
5700 _crypto = undefined;
5701 }
5702 var activeSession;
5703 var profilePath = "./profile.cpuprofile";
5704 var Buffer = require("buffer").Buffer;
5705 var nodeVersion = getNodeMajorVersion();
5706 var isNode4OrLater = nodeVersion >= 4;
5707 var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5708 var platform = _os.platform();
5709 var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5710 var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5711 var _b = createSystemWatchFunctions({
5712 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5713 getModifiedTime: getModifiedTime,
5714 setTimeout: setTimeout,
5715 clearTimeout: clearTimeout,
5716 fsWatch: fsWatch,
5717 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5718 fileExists: fileExists,
5719 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5720 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5721 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5722 directoryExists: directoryExists,
5723 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5724 realpath: realpath,
5725 tscWatchFile: process.env.TSC_WATCHFILE,
5726 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5727 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5728 }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5729 var nodeSystem = {
5730 args: process.argv.slice(2),
5731 newLine: _os.EOL,
5732 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5733 write: function (s) {
5734 process.stdout.write(s);
5735 },
5736 writeOutputIsTTY: function () {
5737 return process.stdout.isTTY;
5738 },
5739 readFile: readFile,
5740 writeFile: writeFile,
5741 watchFile: watchFile,
5742 watchDirectory: watchDirectory,
5743 resolvePath: function (path) { return _path.resolve(path); },
5744 fileExists: fileExists,
5745 directoryExists: directoryExists,
5746 createDirectory: function (directoryName) {
5747 if (!nodeSystem.directoryExists(directoryName)) {
5748 // Wrapped in a try-catch to prevent crashing if we are in a race
5749 // with another copy of ourselves to create the same directory
5750 try {
5751 _fs.mkdirSync(directoryName);
5752 }
5753 catch (e) {
5754 if (e.code !== "EEXIST") {
5755 // Failed for some other reason (access denied?); still throw
5756 throw e;
5757 }
5758 }
5759 }
5760 },
5761 getExecutingFilePath: function () {
5762 return __filename;
5763 },
5764 getCurrentDirectory: function () {
5765 return process.cwd();
5766 },
5767 getDirectories: getDirectories,
5768 getEnvironmentVariable: function (name) {
5769 return process.env[name] || "";
5770 },
5771 readDirectory: readDirectory,
5772 getModifiedTime: getModifiedTime,
5773 setModifiedTime: setModifiedTime,
5774 deleteFile: deleteFile,
5775 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5776 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5777 getMemoryUsage: function () {
5778 if (global.gc) {
5779 global.gc();
5780 }
5781 return process.memoryUsage().heapUsed;
5782 },
5783 getFileSize: function (path) {
5784 try {
5785 var stat = _fs.statSync(path);
5786 if (stat.isFile()) {
5787 return stat.size;
5788 }
5789 }
5790 catch ( /*ignore*/_a) { /*ignore*/ }
5791 return 0;
5792 },
5793 exit: function (exitCode) {
5794 disableCPUProfiler(function () { return process.exit(exitCode); });
5795 },
5796 enableCPUProfiler: enableCPUProfiler,
5797 disableCPUProfiler: disableCPUProfiler,
5798 realpath: realpath,
5799 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); }),
5800 tryEnableSourceMapsForHost: function () {
5801 try {
5802 require("source-map-support").install();
5803 }
5804 catch (_a) {
5805 // Could not enable source maps.
5806 }
5807 },
5808 setTimeout: setTimeout,
5809 clearTimeout: clearTimeout,
5810 clearScreen: function () {
5811 process.stdout.write("\x1Bc");
5812 },
5813 setBlocking: function () {
5814 if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5815 process.stdout._handle.setBlocking(true);
5816 }
5817 },
5818 bufferFrom: bufferFrom,
5819 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5820 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5821 require: function (baseDir, moduleName) {
5822 try {
5823 var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5824 return { module: require(modulePath), modulePath: modulePath, error: undefined };
5825 }
5826 catch (error) {
5827 return { module: undefined, modulePath: undefined, error: error };
5828 }
5829 }
5830 };
5831 return nodeSystem;
5832 /**
5833 * Uses the builtin inspector APIs to capture a CPU profile
5834 * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5835 */
5836 function enableCPUProfiler(path, cb) {
5837 if (activeSession) {
5838 cb();
5839 return false;
5840 }
5841 var inspector = require("inspector");
5842 if (!inspector || !inspector.Session) {
5843 cb();
5844 return false;
5845 }
5846 var session = new inspector.Session();
5847 session.connect();
5848 session.post("Profiler.enable", function () {
5849 session.post("Profiler.start", function () {
5850 activeSession = session;
5851 profilePath = path;
5852 cb();
5853 });
5854 });
5855 return true;
5856 }
5857 /**
5858 * Strips non-TS paths from the profile, so users with private projects shouldn't
5859 * need to worry about leaking paths by submitting a cpu profile to us
5860 */
5861 function cleanupPaths(profile) {
5862 var externalFileCounter = 0;
5863 var remappedPaths = new ts.Map();
5864 var normalizedDir = ts.normalizeSlashes(__dirname);
5865 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5866 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5867 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5868 var node = _a[_i];
5869 if (node.callFrame.url) {
5870 var url = ts.normalizeSlashes(node.callFrame.url);
5871 if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5872 node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5873 }
5874 else if (!nativePattern.test(url)) {
5875 node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5876 externalFileCounter++;
5877 }
5878 }
5879 }
5880 return profile;
5881 }
5882 function disableCPUProfiler(cb) {
5883 if (activeSession && activeSession !== "stopping") {
5884 var s_1 = activeSession;
5885 activeSession.post("Profiler.stop", function (err, _a) {
5886 var profile = _a.profile;
5887 if (!err) {
5888 try {
5889 if (_fs.statSync(profilePath).isDirectory()) {
5890 profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5891 }
5892 }
5893 catch (_b) {
5894 // do nothing and ignore fallible fs operation
5895 }
5896 try {
5897 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5898 }
5899 catch (_c) {
5900 // do nothing and ignore fallible fs operation
5901 }
5902 _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5903 }
5904 activeSession = undefined;
5905 s_1.disconnect();
5906 cb();
5907 });
5908 activeSession = "stopping";
5909 return true;
5910 }
5911 else {
5912 cb();
5913 return false;
5914 }
5915 }
5916 function bufferFrom(input, encoding) {
5917 // See https://github.com/Microsoft/TypeScript/issues/25652
5918 return Buffer.from && Buffer.from !== Int8Array.from
5919 ? Buffer.from(input, encoding)
5920 : new Buffer(input, encoding);
5921 }
5922 function isFileSystemCaseSensitive() {
5923 // win32\win64 are case insensitive platforms
5924 if (platform === "win32" || platform === "win64") {
5925 return false;
5926 }
5927 // If this file exists under a different case, we must be case-insensitve.
5928 return !fileExists(swapCase(__filename));
5929 }
5930 /** Convert all lowercase chars to uppercase, and vice-versa */
5931 function swapCase(s) {
5932 return s.replace(/\w/g, function (ch) {
5933 var up = ch.toUpperCase();
5934 return ch === up ? ch.toLowerCase() : up;
5935 });
5936 }
5937 function fsWatchFileWorker(fileName, callback, pollingInterval) {
5938 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5939 var eventKind;
5940 return {
5941 close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5942 };
5943 function fileChanged(curr, prev) {
5944 // 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)
5945 // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5946 var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5947 if (+curr.mtime === 0) {
5948 if (isPreviouslyDeleted) {
5949 // Already deleted file, no need to callback again
5950 return;
5951 }
5952 eventKind = FileWatcherEventKind.Deleted;
5953 }
5954 else if (isPreviouslyDeleted) {
5955 eventKind = FileWatcherEventKind.Created;
5956 }
5957 // If there is no change in modified time, ignore the event
5958 else if (+curr.mtime === +prev.mtime) {
5959 return;
5960 }
5961 else {
5962 // File changed
5963 eventKind = FileWatcherEventKind.Changed;
5964 }
5965 callback(fileName, eventKind);
5966 }
5967 }
5968 function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5969 var options;
5970 var lastDirectoryPartWithDirectorySeparator;
5971 var lastDirectoryPart;
5972 if (isLinuxOrMacOs) {
5973 lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5974 lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5975 }
5976 /** Watcher for the file system entry depending on whether it is missing or present */
5977 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5978 watchMissingFileSystemEntry() :
5979 watchPresentFileSystemEntry();
5980 return {
5981 close: function () {
5982 // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5983 watcher.close();
5984 watcher = undefined;
5985 }
5986 };
5987 /**
5988 * Invoke the callback with rename and update the watcher if not closed
5989 * @param createWatcher
5990 */
5991 function invokeCallbackAndUpdateWatcher(createWatcher) {
5992 ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5993 // Call the callback for current directory
5994 callback("rename", "");
5995 // If watcher is not closed, update it
5996 if (watcher) {
5997 watcher.close();
5998 watcher = createWatcher();
5999 }
6000 }
6001 /**
6002 * Watch the file or directory that is currently present
6003 * and when the watched file or directory is deleted, switch to missing file system entry watcher
6004 */
6005 function watchPresentFileSystemEntry() {
6006 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
6007 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
6008 if (options === undefined) {
6009 if (fsSupportsRecursiveFsWatch) {
6010 options = { persistent: true, recursive: !!recursive };
6011 }
6012 else {
6013 options = { persistent: true };
6014 }
6015 }
6016 try {
6017 var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
6018 callbackChangingToMissingFileSystemEntry :
6019 callback);
6020 // Watch the missing file or directory or error
6021 presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
6022 return presentWatcher;
6023 }
6024 catch (e) {
6025 // Catch the exception and use polling instead
6026 // 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
6027 // so instead of throwing error, use fs.watchFile
6028 return watchPresentFileSystemEntryWithFsWatchFile();
6029 }
6030 }
6031 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
6032 // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
6033 // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
6034 return event === "rename" &&
6035 (!relativeName ||
6036 relativeName === lastDirectoryPart ||
6037 relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
6038 !fileSystemEntryExists(fileOrDirectory, entryKind) ?
6039 invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
6040 callback(event, relativeName);
6041 }
6042 /**
6043 * Watch the file or directory using fs.watchFile since fs.watch threw exception
6044 * 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
6045 */
6046 function watchPresentFileSystemEntryWithFsWatchFile() {
6047 ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
6048 return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
6049 }
6050 /**
6051 * Watch the file or directory that is missing
6052 * and switch to existing file or directory when the missing filesystem entry is created
6053 */
6054 function watchMissingFileSystemEntry() {
6055 return watchFile(fileOrDirectory, function (_fileName, eventKind) {
6056 if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
6057 // Call the callback for current file or directory
6058 // For now it could be callback for the inner directory creation,
6059 // but just return current directory, better than current no-op
6060 invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
6061 }
6062 }, fallbackPollingInterval, fallbackOptions);
6063 }
6064 }
6065 function readFileWorker(fileName, _encoding) {
6066 var buffer;
6067 try {
6068 buffer = _fs.readFileSync(fileName);
6069 }
6070 catch (e) {
6071 return undefined;
6072 }
6073 var len = buffer.length;
6074 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
6075 // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
6076 // flip all byte pairs and treat as little endian.
6077 len &= ~1; // Round down to a multiple of 2
6078 for (var i = 0; i < len; i += 2) {
6079 var temp = buffer[i];
6080 buffer[i] = buffer[i + 1];
6081 buffer[i + 1] = temp;
6082 }
6083 return buffer.toString("utf16le", 2);
6084 }
6085 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
6086 // Little endian UTF-16 byte order mark detected
6087 return buffer.toString("utf16le", 2);
6088 }
6089 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
6090 // UTF-8 byte order mark detected
6091 return buffer.toString("utf8", 3);
6092 }
6093 // Default is UTF-8 with no byte order mark
6094 return buffer.toString("utf8");
6095 }
6096 function readFile(fileName, _encoding) {
6097 ts.perfLogger.logStartReadFile(fileName);
6098 var file = readFileWorker(fileName, _encoding);
6099 ts.perfLogger.logStopReadFile();
6100 return file;
6101 }
6102 function writeFile(fileName, data, writeByteOrderMark) {
6103 ts.perfLogger.logEvent("WriteFile: " + fileName);
6104 // If a BOM is required, emit one
6105 if (writeByteOrderMark) {
6106 data = byteOrderMarkIndicator + data;
6107 }
6108 var fd;
6109 try {
6110 fd = _fs.openSync(fileName, "w");
6111 _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
6112 }
6113 finally {
6114 if (fd !== undefined) {
6115 _fs.closeSync(fd);
6116 }
6117 }
6118 }
6119 function getAccessibleFileSystemEntries(path) {
6120 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
6121 try {
6122 var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
6123 var files = [];
6124 var directories = [];
6125 for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
6126 var dirent = entries_1[_i];
6127 // withFileTypes is not supported before Node 10.10.
6128 var entry = typeof dirent === "string" ? dirent : dirent.name;
6129 // This is necessary because on some file system node fails to exclude
6130 // "." and "..". See https://github.com/nodejs/node/issues/4002
6131 if (entry === "." || entry === "..") {
6132 continue;
6133 }
6134 var stat = void 0;
6135 if (typeof dirent === "string" || dirent.isSymbolicLink()) {
6136 var name = ts.combinePaths(path, entry);
6137 try {
6138 stat = _fs.statSync(name);
6139 }
6140 catch (e) {
6141 continue;
6142 }
6143 }
6144 else {
6145 stat = dirent;
6146 }
6147 if (stat.isFile()) {
6148 files.push(entry);
6149 }
6150 else if (stat.isDirectory()) {
6151 directories.push(entry);
6152 }
6153 }
6154 files.sort();
6155 directories.sort();
6156 return { files: files, directories: directories };
6157 }
6158 catch (e) {
6159 return ts.emptyFileSystemEntries;
6160 }
6161 }
6162 function readDirectory(path, extensions, excludes, includes, depth) {
6163 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
6164 }
6165 function fileSystemEntryExists(path, entryKind) {
6166 // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
6167 // the CPU time performance.
6168 var originalStackTraceLimit = Error.stackTraceLimit;
6169 Error.stackTraceLimit = 0;
6170 try {
6171 var stat = _fs.statSync(path);
6172 switch (entryKind) {
6173 case 0 /* File */: return stat.isFile();
6174 case 1 /* Directory */: return stat.isDirectory();
6175 default: return false;
6176 }
6177 }
6178 catch (e) {
6179 return false;
6180 }
6181 finally {
6182 Error.stackTraceLimit = originalStackTraceLimit;
6183 }
6184 }
6185 function fileExists(path) {
6186 return fileSystemEntryExists(path, 0 /* File */);
6187 }
6188 function directoryExists(path) {
6189 return fileSystemEntryExists(path, 1 /* Directory */);
6190 }
6191 function getDirectories(path) {
6192 return getAccessibleFileSystemEntries(path).directories.slice();
6193 }
6194 function realpath(path) {
6195 try {
6196 return _fs.realpathSync(path);
6197 }
6198 catch (_a) {
6199 return path;
6200 }
6201 }
6202 function getModifiedTime(path) {
6203 try {
6204 return _fs.statSync(path).mtime;
6205 }
6206 catch (e) {
6207 return undefined;
6208 }
6209 }
6210 function setModifiedTime(path, time) {
6211 try {
6212 _fs.utimesSync(path, time, time);
6213 }
6214 catch (e) {
6215 return;
6216 }
6217 }
6218 function deleteFile(path) {
6219 try {
6220 return _fs.unlinkSync(path);
6221 }
6222 catch (e) {
6223 return;
6224 }
6225 }
6226 function createSHA256Hash(data) {
6227 var hash = _crypto.createHash("sha256");
6228 hash.update(data);
6229 return hash.digest("hex");
6230 }
6231 }
6232 var sys;
6233 if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
6234 // process and process.nextTick checks if current environment is node-like
6235 // process.browser check excludes webpack and browserify
6236 sys = getNodeSystem();
6237 }
6238 if (sys) {
6239 // patch writefile to create folder before writing the file
6240 patchWriteFileEnsuringDirectory(sys);
6241 }
6242 return sys;
6243 })();
6244 if (ts.sys && ts.sys.getEnvironmentVariable) {
6245 setCustomPollingValues(ts.sys);
6246 ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
6247 ? 1 /* Normal */
6248 : 0 /* None */);
6249 }
6250 if (ts.sys && ts.sys.debugMode) {
6251 ts.Debug.isDebugging = true;
6252 }
6253})(ts || (ts = {}));
6254/* @internal */
6255var ts;
6256(function (ts) {
6257 /**
6258 * Internally, we represent paths as strings with '/' as the directory separator.
6259 * When we make system calls (eg: LanguageServiceHost.getDirectory()),
6260 * we expect the host to correctly handle paths in our specified format.
6261 */
6262 ts.directorySeparator = "/";
6263 var altDirectorySeparator = "\\";
6264 var urlSchemeSeparator = "://";
6265 var backslashRegExp = /\\/g;
6266 //// Path Tests
6267 /**
6268 * Determines whether a charCode corresponds to `/` or `\`.
6269 */
6270 function isAnyDirectorySeparator(charCode) {
6271 return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
6272 }
6273 ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
6274 /**
6275 * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
6276 */
6277 function isUrl(path) {
6278 return getEncodedRootLength(path) < 0;
6279 }
6280 ts.isUrl = isUrl;
6281 /**
6282 * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
6283 * like `c:`, `c:\` or `c:/`).
6284 */
6285 function isRootedDiskPath(path) {
6286 return getEncodedRootLength(path) > 0;
6287 }
6288 ts.isRootedDiskPath = isRootedDiskPath;
6289 /**
6290 * Determines whether a path consists only of a path root.
6291 */
6292 function isDiskPathRoot(path) {
6293 var rootLength = getEncodedRootLength(path);
6294 return rootLength > 0 && rootLength === path.length;
6295 }
6296 ts.isDiskPathRoot = isDiskPathRoot;
6297 /**
6298 * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6299 *
6300 * ```ts
6301 * // POSIX
6302 * pathIsAbsolute("/path/to/file.ext") === true
6303 * // DOS
6304 * pathIsAbsolute("c:/path/to/file.ext") === true
6305 * // URL
6306 * pathIsAbsolute("file:///path/to/file.ext") === true
6307 * // Non-absolute
6308 * pathIsAbsolute("path/to/file.ext") === false
6309 * pathIsAbsolute("./path/to/file.ext") === false
6310 * ```
6311 */
6312 function pathIsAbsolute(path) {
6313 return getEncodedRootLength(path) !== 0;
6314 }
6315 ts.pathIsAbsolute = pathIsAbsolute;
6316 /**
6317 * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6318 */
6319 function pathIsRelative(path) {
6320 return /^\.\.?($|[\\/])/.test(path);
6321 }
6322 ts.pathIsRelative = pathIsRelative;
6323 function hasExtension(fileName) {
6324 return ts.stringContains(getBaseFileName(fileName), ".");
6325 }
6326 ts.hasExtension = hasExtension;
6327 function fileExtensionIs(path, extension) {
6328 return path.length > extension.length && ts.endsWith(path, extension);
6329 }
6330 ts.fileExtensionIs = fileExtensionIs;
6331 function fileExtensionIsOneOf(path, extensions) {
6332 for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6333 var extension = extensions_1[_i];
6334 if (fileExtensionIs(path, extension)) {
6335 return true;
6336 }
6337 }
6338 return false;
6339 }
6340 ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6341 /**
6342 * Determines whether a path has a trailing separator (`/` or `\\`).
6343 */
6344 function hasTrailingDirectorySeparator(path) {
6345 return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6346 }
6347 ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6348 //// Path Parsing
6349 function isVolumeCharacter(charCode) {
6350 return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6351 (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6352 }
6353 function getFileUrlVolumeSeparatorEnd(url, start) {
6354 var ch0 = url.charCodeAt(start);
6355 if (ch0 === 58 /* colon */)
6356 return start + 1;
6357 if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6358 var ch2 = url.charCodeAt(start + 2);
6359 if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6360 return start + 3;
6361 }
6362 return -1;
6363 }
6364 /**
6365 * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6366 * If the root is part of a URL, the twos-complement of the root length is returned.
6367 */
6368 function getEncodedRootLength(path) {
6369 if (!path)
6370 return 0;
6371 var ch0 = path.charCodeAt(0);
6372 // POSIX or UNC
6373 if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6374 if (path.charCodeAt(1) !== ch0)
6375 return 1; // POSIX: "/" (or non-normalized "\")
6376 var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6377 if (p1 < 0)
6378 return path.length; // UNC: "//server" or "\\server"
6379 return p1 + 1; // UNC: "//server/" or "\\server\"
6380 }
6381 // DOS
6382 if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6383 var ch2 = path.charCodeAt(2);
6384 if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6385 return 3; // DOS: "c:/" or "c:\"
6386 if (path.length === 2)
6387 return 2; // DOS: "c:" (but not "c:d")
6388 }
6389 // URL
6390 var schemeEnd = path.indexOf(urlSchemeSeparator);
6391 if (schemeEnd !== -1) {
6392 var authorityStart = schemeEnd + urlSchemeSeparator.length;
6393 var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6394 if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6395 // For local "file" URLs, include the leading DOS volume (if present).
6396 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6397 // special case interpreted as "the machine from which the URL is being interpreted".
6398 var scheme = path.slice(0, schemeEnd);
6399 var authority = path.slice(authorityStart, authorityEnd);
6400 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6401 isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6402 var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6403 if (volumeSeparatorEnd !== -1) {
6404 if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6405 // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6406 return ~(volumeSeparatorEnd + 1);
6407 }
6408 if (volumeSeparatorEnd === path.length) {
6409 // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6410 // but not "file:///c:d" or "file:///c%3ad"
6411 return ~volumeSeparatorEnd;
6412 }
6413 }
6414 }
6415 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6416 }
6417 return ~path.length; // URL: "file://server", "http://server"
6418 }
6419 // relative
6420 return 0;
6421 }
6422 /**
6423 * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6424 *
6425 * For example:
6426 * ```ts
6427 * getRootLength("a") === 0 // ""
6428 * getRootLength("/") === 1 // "/"
6429 * getRootLength("c:") === 2 // "c:"
6430 * getRootLength("c:d") === 0 // ""
6431 * getRootLength("c:/") === 3 // "c:/"
6432 * getRootLength("c:\\") === 3 // "c:\\"
6433 * getRootLength("//server") === 7 // "//server"
6434 * getRootLength("//server/share") === 8 // "//server/"
6435 * getRootLength("\\\\server") === 7 // "\\\\server"
6436 * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
6437 * getRootLength("file:///path") === 8 // "file:///"
6438 * getRootLength("file:///c:") === 10 // "file:///c:"
6439 * getRootLength("file:///c:d") === 8 // "file:///"
6440 * getRootLength("file:///c:/path") === 11 // "file:///c:/"
6441 * getRootLength("file://server") === 13 // "file://server"
6442 * getRootLength("file://server/path") === 14 // "file://server/"
6443 * getRootLength("http://server") === 13 // "http://server"
6444 * getRootLength("http://server/path") === 14 // "http://server/"
6445 * ```
6446 */
6447 function getRootLength(path) {
6448 var rootLength = getEncodedRootLength(path);
6449 return rootLength < 0 ? ~rootLength : rootLength;
6450 }
6451 ts.getRootLength = getRootLength;
6452 function getDirectoryPath(path) {
6453 path = normalizeSlashes(path);
6454 // If the path provided is itself the root, then return it.
6455 var rootLength = getRootLength(path);
6456 if (rootLength === path.length)
6457 return path;
6458 // return the leading portion of the path up to the last (non-terminal) directory separator
6459 // but not including any trailing directory separator.
6460 path = removeTrailingDirectorySeparator(path);
6461 return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6462 }
6463 ts.getDirectoryPath = getDirectoryPath;
6464 function getBaseFileName(path, extensions, ignoreCase) {
6465 path = normalizeSlashes(path);
6466 // if the path provided is itself the root, then it has not file name.
6467 var rootLength = getRootLength(path);
6468 if (rootLength === path.length)
6469 return "";
6470 // return the trailing portion of the path starting after the last (non-terminal) directory
6471 // separator but not including any trailing directory separator.
6472 path = removeTrailingDirectorySeparator(path);
6473 var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6474 var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6475 return extension ? name.slice(0, name.length - extension.length) : name;
6476 }
6477 ts.getBaseFileName = getBaseFileName;
6478 function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6479 if (!ts.startsWith(extension, "."))
6480 extension = "." + extension;
6481 if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6482 var pathExtension = path.slice(path.length - extension.length);
6483 if (stringEqualityComparer(pathExtension, extension)) {
6484 return pathExtension;
6485 }
6486 }
6487 }
6488 function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6489 if (typeof extensions === "string") {
6490 return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6491 }
6492 for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6493 var extension = extensions_2[_i];
6494 var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6495 if (result)
6496 return result;
6497 }
6498 return "";
6499 }
6500 function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6501 // Retrieves any string from the final "." onwards from a base file name.
6502 // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6503 if (extensions) {
6504 return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6505 }
6506 var baseFileName = getBaseFileName(path);
6507 var extensionIndex = baseFileName.lastIndexOf(".");
6508 if (extensionIndex >= 0) {
6509 return baseFileName.substring(extensionIndex);
6510 }
6511 return "";
6512 }
6513 ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6514 function pathComponents(path, rootLength) {
6515 var root = path.substring(0, rootLength);
6516 var rest = path.substring(rootLength).split(ts.directorySeparator);
6517 if (rest.length && !ts.lastOrUndefined(rest))
6518 rest.pop();
6519 return __spreadArrays([root], rest);
6520 }
6521 /**
6522 * Parse a path into an array containing a root component (at index 0) and zero or more path
6523 * components (at indices > 0). The result is not normalized.
6524 * If the path is relative, the root component is `""`.
6525 * If the path is absolute, the root component includes the first path separator (`/`).
6526 *
6527 * ```ts
6528 * // POSIX
6529 * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6530 * getPathComponents("/path/to/") === ["/", "path", "to"]
6531 * getPathComponents("/") === ["/"]
6532 * // DOS
6533 * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6534 * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6535 * getPathComponents("c:/") === ["c:/"]
6536 * getPathComponents("c:") === ["c:"]
6537 * // URL
6538 * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6539 * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6540 * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6541 * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6542 * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6543 * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6544 * getPathComponents("file://server/") === ["file://server/"]
6545 * getPathComponents("file://server") === ["file://server"]
6546 * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6547 * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6548 * getPathComponents("file:///") === ["file:///"]
6549 * getPathComponents("file://") === ["file://"]
6550 */
6551 function getPathComponents(path, currentDirectory) {
6552 if (currentDirectory === void 0) { currentDirectory = ""; }
6553 path = combinePaths(currentDirectory, path);
6554 return pathComponents(path, getRootLength(path));
6555 }
6556 ts.getPathComponents = getPathComponents;
6557 //// Path Formatting
6558 /**
6559 * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6560 * segments (at indices > 0).
6561 *
6562 * ```ts
6563 * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6564 * ```
6565 */
6566 function getPathFromPathComponents(pathComponents) {
6567 if (pathComponents.length === 0)
6568 return "";
6569 var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6570 return root + pathComponents.slice(1).join(ts.directorySeparator);
6571 }
6572 ts.getPathFromPathComponents = getPathFromPathComponents;
6573 //// Path Normalization
6574 /**
6575 * Normalize path separators, converting `\` into `/`.
6576 */
6577 function normalizeSlashes(path) {
6578 return path.replace(backslashRegExp, ts.directorySeparator);
6579 }
6580 ts.normalizeSlashes = normalizeSlashes;
6581 /**
6582 * Reduce an array of path components to a more simplified path by navigating any
6583 * `"."` or `".."` entries in the path.
6584 */
6585 function reducePathComponents(components) {
6586 if (!ts.some(components))
6587 return [];
6588 var reduced = [components[0]];
6589 for (var i = 1; i < components.length; i++) {
6590 var component = components[i];
6591 if (!component)
6592 continue;
6593 if (component === ".")
6594 continue;
6595 if (component === "..") {
6596 if (reduced.length > 1) {
6597 if (reduced[reduced.length - 1] !== "..") {
6598 reduced.pop();
6599 continue;
6600 }
6601 }
6602 else if (reduced[0])
6603 continue;
6604 }
6605 reduced.push(component);
6606 }
6607 return reduced;
6608 }
6609 ts.reducePathComponents = reducePathComponents;
6610 /**
6611 * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6612 *
6613 * ```ts
6614 * // Non-rooted
6615 * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6616 * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6617 * // POSIX
6618 * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6619 * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6620 * // DOS
6621 * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6622 * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6623 * // URL
6624 * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6625 * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6626 * ```
6627 */
6628 function combinePaths(path) {
6629 var paths = [];
6630 for (var _i = 1; _i < arguments.length; _i++) {
6631 paths[_i - 1] = arguments[_i];
6632 }
6633 if (path)
6634 path = normalizeSlashes(path);
6635 for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6636 var relativePath = paths_1[_a];
6637 if (!relativePath)
6638 continue;
6639 relativePath = normalizeSlashes(relativePath);
6640 if (!path || getRootLength(relativePath) !== 0) {
6641 path = relativePath;
6642 }
6643 else {
6644 path = ensureTrailingDirectorySeparator(path) + relativePath;
6645 }
6646 }
6647 return path;
6648 }
6649 ts.combinePaths = combinePaths;
6650 /**
6651 * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6652 * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6653 *
6654 * ```ts
6655 * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6656 * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6657 * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6658 * ```
6659 */
6660 function resolvePath(path) {
6661 var paths = [];
6662 for (var _i = 1; _i < arguments.length; _i++) {
6663 paths[_i - 1] = arguments[_i];
6664 }
6665 return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6666 }
6667 ts.resolvePath = resolvePath;
6668 /**
6669 * Parse a path into an array containing a root component (at index 0) and zero or more path
6670 * components (at indices > 0). The result is normalized.
6671 * If the path is relative, the root component is `""`.
6672 * If the path is absolute, the root component includes the first path separator (`/`).
6673 *
6674 * ```ts
6675 * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6676 * ```
6677 */
6678 function getNormalizedPathComponents(path, currentDirectory) {
6679 return reducePathComponents(getPathComponents(path, currentDirectory));
6680 }
6681 ts.getNormalizedPathComponents = getNormalizedPathComponents;
6682 function getNormalizedAbsolutePath(fileName, currentDirectory) {
6683 return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6684 }
6685 ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6686 function normalizePath(path) {
6687 path = normalizeSlashes(path);
6688 var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6689 return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6690 }
6691 ts.normalizePath = normalizePath;
6692 function getPathWithoutRoot(pathComponents) {
6693 if (pathComponents.length === 0)
6694 return "";
6695 return pathComponents.slice(1).join(ts.directorySeparator);
6696 }
6697 function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6698 return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6699 }
6700 ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6701 function toPath(fileName, basePath, getCanonicalFileName) {
6702 var nonCanonicalizedPath = isRootedDiskPath(fileName)
6703 ? normalizePath(fileName)
6704 : getNormalizedAbsolutePath(fileName, basePath);
6705 return getCanonicalFileName(nonCanonicalizedPath);
6706 }
6707 ts.toPath = toPath;
6708 function normalizePathAndParts(path) {
6709 path = normalizeSlashes(path);
6710 var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6711 if (parts.length) {
6712 var joinedParts = root + parts.join(ts.directorySeparator);
6713 return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6714 }
6715 else {
6716 return { path: root, parts: parts };
6717 }
6718 }
6719 ts.normalizePathAndParts = normalizePathAndParts;
6720 function removeTrailingDirectorySeparator(path) {
6721 if (hasTrailingDirectorySeparator(path)) {
6722 return path.substr(0, path.length - 1);
6723 }
6724 return path;
6725 }
6726 ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6727 function ensureTrailingDirectorySeparator(path) {
6728 if (!hasTrailingDirectorySeparator(path)) {
6729 return path + ts.directorySeparator;
6730 }
6731 return path;
6732 }
6733 ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6734 /**
6735 * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6736 * with `./` or `../`) so as not to be confused with an unprefixed module name.
6737 *
6738 * ```ts
6739 * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6740 * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6741 * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6742 * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6743 * ```
6744 */
6745 function ensurePathIsNonModuleName(path) {
6746 return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6747 }
6748 ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6749 function changeAnyExtension(path, ext, extensions, ignoreCase) {
6750 var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6751 return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6752 }
6753 ts.changeAnyExtension = changeAnyExtension;
6754 //// Path Comparisons
6755 // check path for these segments: '', '.'. '..'
6756 var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6757 function comparePathsWorker(a, b, componentComparer) {
6758 if (a === b)
6759 return 0 /* EqualTo */;
6760 if (a === undefined)
6761 return -1 /* LessThan */;
6762 if (b === undefined)
6763 return 1 /* GreaterThan */;
6764 // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6765 // need to perform path reduction.
6766 var aRoot = a.substring(0, getRootLength(a));
6767 var bRoot = b.substring(0, getRootLength(b));
6768 var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6769 if (result !== 0 /* EqualTo */) {
6770 return result;
6771 }
6772 // NOTE: Performance optimization - shortcut if there are no relative path segments in
6773 // the non-root portion of the path
6774 var aRest = a.substring(aRoot.length);
6775 var bRest = b.substring(bRoot.length);
6776 if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6777 return componentComparer(aRest, bRest);
6778 }
6779 // The path contains a relative path segment. Normalize the paths and perform a slower component
6780 // by component comparison.
6781 var aComponents = reducePathComponents(getPathComponents(a));
6782 var bComponents = reducePathComponents(getPathComponents(b));
6783 var sharedLength = Math.min(aComponents.length, bComponents.length);
6784 for (var i = 1; i < sharedLength; i++) {
6785 var result_2 = componentComparer(aComponents[i], bComponents[i]);
6786 if (result_2 !== 0 /* EqualTo */) {
6787 return result_2;
6788 }
6789 }
6790 return ts.compareValues(aComponents.length, bComponents.length);
6791 }
6792 /**
6793 * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6794 */
6795 function comparePathsCaseSensitive(a, b) {
6796 return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6797 }
6798 ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6799 /**
6800 * Performs a case-insensitive comparison of two paths.
6801 */
6802 function comparePathsCaseInsensitive(a, b) {
6803 return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6804 }
6805 ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6806 function comparePaths(a, b, currentDirectory, ignoreCase) {
6807 if (typeof currentDirectory === "string") {
6808 a = combinePaths(currentDirectory, a);
6809 b = combinePaths(currentDirectory, b);
6810 }
6811 else if (typeof currentDirectory === "boolean") {
6812 ignoreCase = currentDirectory;
6813 }
6814 return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6815 }
6816 ts.comparePaths = comparePaths;
6817 function containsPath(parent, child, currentDirectory, ignoreCase) {
6818 if (typeof currentDirectory === "string") {
6819 parent = combinePaths(currentDirectory, parent);
6820 child = combinePaths(currentDirectory, child);
6821 }
6822 else if (typeof currentDirectory === "boolean") {
6823 ignoreCase = currentDirectory;
6824 }
6825 if (parent === undefined || child === undefined)
6826 return false;
6827 if (parent === child)
6828 return true;
6829 var parentComponents = reducePathComponents(getPathComponents(parent));
6830 var childComponents = reducePathComponents(getPathComponents(child));
6831 if (childComponents.length < parentComponents.length) {
6832 return false;
6833 }
6834 var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6835 for (var i = 0; i < parentComponents.length; i++) {
6836 var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6837 if (!equalityComparer(parentComponents[i], childComponents[i])) {
6838 return false;
6839 }
6840 }
6841 return true;
6842 }
6843 ts.containsPath = containsPath;
6844 /**
6845 * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6846 * Comparison is case-sensitive between the canonical paths.
6847 *
6848 * @deprecated Use `containsPath` if possible.
6849 */
6850 function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6851 var canonicalFileName = getCanonicalFileName(fileName);
6852 var canonicalDirectoryName = getCanonicalFileName(directoryName);
6853 return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6854 }
6855 ts.startsWithDirectory = startsWithDirectory;
6856 //// Relative Paths
6857 function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6858 var fromComponents = reducePathComponents(getPathComponents(from));
6859 var toComponents = reducePathComponents(getPathComponents(to));
6860 var start;
6861 for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6862 var fromComponent = getCanonicalFileName(fromComponents[start]);
6863 var toComponent = getCanonicalFileName(toComponents[start]);
6864 var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6865 if (!comparer(fromComponent, toComponent))
6866 break;
6867 }
6868 if (start === 0) {
6869 return toComponents;
6870 }
6871 var components = toComponents.slice(start);
6872 var relative = [];
6873 for (; start < fromComponents.length; start++) {
6874 relative.push("..");
6875 }
6876 return __spreadArrays([""], relative, components);
6877 }
6878 ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6879 function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6880 ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6881 var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6882 var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6883 var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6884 return getPathFromPathComponents(pathComponents);
6885 }
6886 ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6887 function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6888 return !isRootedDiskPath(absoluteOrRelativePath)
6889 ? absoluteOrRelativePath
6890 : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6891 }
6892 ts.convertToRelativePath = convertToRelativePath;
6893 function getRelativePathFromFile(from, to, getCanonicalFileName) {
6894 return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6895 }
6896 ts.getRelativePathFromFile = getRelativePathFromFile;
6897 function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6898 var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6899 var firstComponent = pathComponents[0];
6900 if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6901 var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6902 pathComponents[0] = prefix + firstComponent;
6903 }
6904 return getPathFromPathComponents(pathComponents);
6905 }
6906 ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6907 function forEachAncestorDirectory(directory, callback) {
6908 while (true) {
6909 var result = callback(directory);
6910 if (result !== undefined) {
6911 return result;
6912 }
6913 var parentPath = getDirectoryPath(directory);
6914 if (parentPath === directory) {
6915 return undefined;
6916 }
6917 directory = parentPath;
6918 }
6919 }
6920 ts.forEachAncestorDirectory = forEachAncestorDirectory;
6921 function isNodeModulesDirectory(dirPath) {
6922 return ts.endsWith(dirPath, "/node_modules");
6923 }
6924 ts.isNodeModulesDirectory = isNodeModulesDirectory;
6925})(ts || (ts = {}));
6926// <auto-generated />
6927// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6928/* @internal */
6929var ts;
6930(function (ts) {
6931 function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) {
6932 return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
6933 }
6934 ts.Diagnostics = {
6935 Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6936 Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6937 _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6938 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."),
6939 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."),
6940 Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6941 Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6942 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."),
6943 Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6944 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."),
6945 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."),
6946 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."),
6947 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."),
6948 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."),
6949 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."),
6950 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."),
6951 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."),
6952 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."),
6953 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."),
6954 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'."),
6955 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."),
6956 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."),
6957 Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6958 _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6959 _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6960 _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
6961 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."),
6962 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."),
6963 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."),
6964 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."),
6965 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."),
6966 _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."),
6967 _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."),
6968 _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6969 _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."),
6970 _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."),
6971 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."),
6972 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."),
6973 A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6974 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."),
6975 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."),
6976 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."),
6977 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."),
6978 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."),
6979 A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6980 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."),
6981 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."),
6982 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."),
6983 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."),
6984 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."),
6985 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."),
6986 Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6987 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."),
6988 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."),
6989 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}>'?"),
6990 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."),
6991 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."),
6992 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."),
6993 _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."),
6994 _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."),
6995 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."),
6996 Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6997 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}'."),
6998 _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."),
6999 _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."),
7000 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."),
7001 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."),
7002 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."),
7003 An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
7004 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."),
7005 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."),
7006 _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
7007 Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
7008 Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
7009 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."),
7010 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."),
7011 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."),
7012 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."),
7013 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."),
7014 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."),
7015 Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
7016 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."),
7017 Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
7018 Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
7019 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."),
7020 Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
7021 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."),
7022 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."),
7023 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."),
7024 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."),
7025 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."),
7026 An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
7027 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."),
7028 Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
7029 Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
7030 Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
7031 Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
7032 Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
7033 Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
7034 Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
7035 case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
7036 Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
7037 Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
7038 Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
7039 Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
7040 Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
7041 Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
7042 Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
7043 Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
7044 Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
7045 String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
7046 Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
7047 or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
7048 Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
7049 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."),
7050 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'."),
7051 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."),
7052 const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
7053 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."),
7054 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."),
7055 Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
7056 Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
7057 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."),
7058 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."),
7059 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."),
7060 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."),
7061 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."),
7062 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."),
7063 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."),
7064 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."),
7065 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."),
7066 extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
7067 extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
7068 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."),
7069 implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
7070 Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
7071 Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
7072 Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
7073 Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
7074 Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
7075 Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
7076 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."),
7077 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."),
7078 Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
7079 Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
7080 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."),
7081 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."),
7082 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."),
7083 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."),
7084 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."),
7085 An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
7086 Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
7087 An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
7088 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."),
7089 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."),
7090 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."),
7091 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."),
7092 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."),
7093 Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
7094 Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
7095 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."),
7096 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."),
7097 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'."),
7098 Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
7099 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."),
7100 All_files_must_be_modules_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "All_files_must_be_modules_when_the_isolatedModules_flag_is_provided_1208", "All files must be modules when the '--isolatedModules' flag is provided."),
7101 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."),
7102 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."),
7103 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."),
7104 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."),
7105 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."),
7106 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."),
7107 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."),
7108 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'."),
7109 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."),
7110 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."),
7111 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."),
7112 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."),
7113 _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
7114 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."),
7115 Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
7116 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}'."),
7117 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}'."),
7118 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."),
7119 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."),
7120 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."),
7121 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."),
7122 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."),
7123 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."),
7124 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."),
7125 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."),
7126 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'."),
7127 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'."),
7128 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."),
7129 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."),
7130 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."),
7131 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."),
7132 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."),
7133 _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."),
7134 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."),
7135 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."),
7136 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."),
7137 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."),
7138 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."),
7139 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."),
7140 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'."),
7141 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."),
7142 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."),
7143 _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."),
7144 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."),
7145 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."),
7146 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."),
7147 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."),
7148 Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation: diag(1258, ts.DiagnosticCategory.Error, "Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation_1258", "Definite assignment assertions can only be used along with a type annotation."),
7149 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"),
7150 Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
7151 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."),
7152 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."),
7153 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."),
7154 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."),
7155 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."),
7156 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."),
7157 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."),
7158 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."),
7159 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."),
7160 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."),
7161 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."),
7162 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."),
7163 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."),
7164 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."),
7165 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."),
7166 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'."),
7167 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."),
7168 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."),
7169 Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
7170 String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
7171 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."),
7172 _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}()'?"),
7173 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'."),
7174 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'."),
7175 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'."),
7176 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."),
7177 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."),
7178 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."),
7179 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."),
7180 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."),
7181 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."),
7182 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."),
7183 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}')'?"),
7184 Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
7185 The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'esnext' or 'system'."),
7186 A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
7187 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"),
7188 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."),
7189 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."),
7190 Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
7191 use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
7192 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."),
7193 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."),
7194 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."),
7195 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."),
7196 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."),
7197 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."),
7198 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'?"),
7199 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 '}'."),
7200 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."),
7201 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."),
7202 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?"),
7203 _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'."),
7204 _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'."),
7205 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."),
7206 Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
7207 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"),
7208 Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
7209 Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
7210 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"),
7211 Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
7212 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'."),
7213 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'."),
7214 Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
7215 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"),
7216 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."),
7217 _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
7218 _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
7219 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."),
7220 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'."),
7221 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'."),
7222 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;`?"),
7223 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;`?"),
7224 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'."),
7225 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."),
7226 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."),
7227 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."),
7228 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."),
7229 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."),
7230 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."),
7231 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."),
7232 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),
7233 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),
7234 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),
7235 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),
7236 Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
7237 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."),
7238 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."),
7239 Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
7240 Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
7241 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}'."),
7242 File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
7243 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."),
7244 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."),
7245 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."),
7246 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."),
7247 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."),
7248 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."),
7249 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."),
7250 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)."),
7251 Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
7252 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."),
7253 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)."),
7254 Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
7255 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."),
7256 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}'."),
7257 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}'."),
7258 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}'."),
7259 Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
7260 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}'."),
7261 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}'."),
7262 Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
7263 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}'."),
7264 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."),
7265 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}'."),
7266 Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
7267 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."),
7268 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."),
7269 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."),
7270 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."),
7271 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."),
7272 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."),
7273 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."),
7274 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."),
7275 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}'."),
7276 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."),
7277 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}'."),
7278 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'."),
7279 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}'."),
7280 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}'."),
7281 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}'."),
7282 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."),
7283 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."),
7284 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'?"),
7285 This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7286 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."),
7287 This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7288 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."),
7289 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}'."),
7290 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."),
7291 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."),
7292 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."),
7293 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."),
7294 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."),
7295 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."),
7296 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'."),
7297 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."),
7298 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."),
7299 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."),
7300 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."),
7301 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}'."),
7302 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'."),
7303 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."),
7304 Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7305 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."),
7306 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."),
7307 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."),
7308 Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7309 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."),
7310 Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7311 Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7312 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."),
7313 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."),
7314 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."),
7315 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."),
7316 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."),
7317 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."),
7318 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."),
7319 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."),
7320 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."),
7321 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."),
7322 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."),
7323 Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7324 Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7325 Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7326 Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7327 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."),
7328 Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7329 Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7330 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."),
7331 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."),
7332 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."),
7333 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}'."),
7334 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."),
7335 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."),
7336 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."),
7337 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."),
7338 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."),
7339 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}'."),
7340 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."),
7341 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'."),
7342 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."),
7343 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}'."),
7344 Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7345 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."),
7346 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'."),
7347 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}'."),
7348 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}'."),
7349 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}'."),
7350 Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7351 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}'."),
7352 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}'."),
7353 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}'."),
7354 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}'."),
7355 Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7356 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."),
7357 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."),
7358 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."),
7359 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."),
7360 Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7361 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."),
7362 Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7363 Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7364 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."),
7365 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."),
7366 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."),
7367 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."),
7368 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."),
7369 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."),
7370 Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7371 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."),
7372 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}'."),
7373 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."),
7374 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}'."),
7375 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}'."),
7376 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}'."),
7377 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."),
7378 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}'."),
7379 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."),
7380 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."),
7381 Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7382 Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7383 Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7384 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."),
7385 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."),
7386 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."),
7387 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}'."),
7388 Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7389 Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7390 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."),
7391 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."),
7392 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}'."),
7393 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."),
7394 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."),
7395 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."),
7396 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'."),
7397 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."),
7398 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."),
7399 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."),
7400 Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7401 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'."),
7402 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."),
7403 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'."),
7404 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."),
7405 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."),
7406 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."),
7407 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."),
7408 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."),
7409 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."),
7410 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'."),
7411 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}'."),
7412 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."),
7413 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}'."),
7414 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."),
7415 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}'."),
7416 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."),
7417 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."),
7418 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."),
7419 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."),
7420 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."),
7421 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."),
7422 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}'."),
7423 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."),
7424 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."),
7425 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."),
7426 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."),
7427 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 *'."),
7428 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."),
7429 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."),
7430 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."),
7431 _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."),
7432 Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7433 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."),
7434 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."),
7435 _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."),
7436 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."),
7437 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."),
7438 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."),
7439 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."),
7440 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."),
7441 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."),
7442 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."),
7443 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."),
7444 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}'."),
7445 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."),
7446 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."),
7447 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."),
7448 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."),
7449 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."),
7450 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."),
7451 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."),
7452 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."),
7453 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."),
7454 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."),
7455 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."),
7456 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."),
7457 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."),
7458 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."),
7459 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."),
7460 Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7461 Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7462 Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7463 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."),
7464 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."),
7465 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}'."),
7466 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}'."),
7467 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."),
7468 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."),
7469 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."),
7470 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."),
7471 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."),
7472 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."),
7473 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."),
7474 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[]'."),
7475 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."),
7476 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."),
7477 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."),
7478 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}'?"),
7479 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}'?"),
7480 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."),
7481 Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7482 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}."),
7483 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."),
7484 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."),
7485 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}."),
7486 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}'."),
7487 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?"),
7488 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}'?"),
7489 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."),
7490 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."),
7491 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."),
7492 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."),
7493 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."),
7494 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."),
7495 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."),
7496 Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7497 Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7498 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."),
7499 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."),
7500 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."),
7501 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}'"),
7502 Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7503 Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7504 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
7505 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
7506 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
7507 Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
7508 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'."),
7509 _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."),
7510 Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7511 JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7512 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."),
7513 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."),
7514 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."),
7515 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
7516 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
7517 Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
7518 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."),
7519 _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."),
7520 _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."),
7521 _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."),
7522 _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."),
7523 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."),
7524 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."),
7525 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."),
7526 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}'."),
7527 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."),
7528 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."),
7529 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."),
7530 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."),
7531 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."),
7532 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."),
7533 _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."),
7534 _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."),
7535 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."),
7536 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?"),
7537 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?"),
7538 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}'."),
7539 _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."),
7540 _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."),
7541 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}."),
7542 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}."),
7543 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."),
7544 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."),
7545 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."),
7546 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."),
7547 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."),
7548 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."),
7549 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}'."),
7550 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."),
7551 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."),
7552 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."),
7553 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}'."),
7554 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."),
7555 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."),
7556 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."),
7557 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}'?"),
7558 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}'?"),
7559 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."),
7560 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."),
7561 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."),
7562 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."),
7563 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."),
7564 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."),
7565 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."),
7566 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."),
7567 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."),
7568 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."),
7569 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."),
7570 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."),
7571 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."),
7572 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."),
7573 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}'."),
7574 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'."),
7575 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."),
7576 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."),
7577 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."),
7578 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."),
7579 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}'."),
7580 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."),
7581 _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."),
7582 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."),
7583 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}'."),
7584 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'?"),
7585 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."),
7586 _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."),
7587 _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."),
7588 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}'."),
7589 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),
7590 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?"),
7591 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."),
7592 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."),
7593 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}'."),
7594 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."),
7595 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."),
7596 _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."),
7597 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."),
7598 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."),
7599 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."),
7600 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."),
7601 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."),
7602 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."),
7603 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."),
7604 _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."),
7605 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."),
7606 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."),
7607 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}\"]'?"),
7608 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."),
7609 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."),
7610 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."),
7611 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}'."),
7612 Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7613 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."),
7614 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?"),
7615 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'."),
7616 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'."),
7617 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'."),
7618 Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
7619 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}."),
7620 Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7621 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}'?"),
7622 _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7623 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."),
7624 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."),
7625 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(...)'."),
7626 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"),
7627 Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7628 Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7629 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}'?"),
7630 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}'."),
7631 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."),
7632 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."),
7633 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}"),
7634 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."),
7635 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}'."),
7636 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."),
7637 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."),
7638 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."),
7639 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."),
7640 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."),
7641 _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}'."),
7642 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."),
7643 _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}'?"),
7644 The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7645 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."),
7646 The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7647 Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7648 super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7649 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."),
7650 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."),
7651 Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7652 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."),
7653 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."),
7654 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."),
7655 Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7656 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."),
7657 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}'."),
7658 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}'."),
7659 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}'."),
7660 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}'."),
7661 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."),
7662 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."),
7663 No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7664 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."),
7665 The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7666 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."),
7667 Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7668 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?"),
7669 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."),
7670 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."),
7671 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."),
7672 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."),
7673 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."),
7674 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."),
7675 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."),
7676 _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7677 _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."),
7678 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."),
7679 This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7680 _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."),
7681 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."),
7682 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."),
7683 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."),
7684 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."),
7685 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."),
7686 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?"),
7687 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}'."),
7688 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}'."),
7689 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}'."),
7690 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}'."),
7691 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}'."),
7692 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}'."),
7693 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}'."),
7694 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}'."),
7695 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}'."),
7696 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}'."),
7697 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}'."),
7698 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}'."),
7699 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}'."),
7700 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."),
7701 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}'."),
7702 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}'."),
7703 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."),
7704 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}'."),
7705 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}'."),
7706 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."),
7707 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}'."),
7708 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}'."),
7709 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}'."),
7710 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}'."),
7711 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}'."),
7712 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}'."),
7713 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}'."),
7714 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}'."),
7715 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."),
7716 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}'."),
7717 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}'."),
7718 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."),
7719 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}'."),
7720 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}'."),
7721 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}'."),
7722 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}'."),
7723 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}'."),
7724 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}'."),
7725 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}'."),
7726 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}'."),
7727 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."),
7728 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}'."),
7729 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}'."),
7730 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."),
7731 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}'."),
7732 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}'."),
7733 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}'."),
7734 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}'."),
7735 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."),
7736 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}'."),
7737 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}'."),
7738 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."),
7739 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}'."),
7740 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}'."),
7741 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}'."),
7742 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}'."),
7743 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}'."),
7744 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}'."),
7745 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."),
7746 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}'."),
7747 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}'."),
7748 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."),
7749 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}'."),
7750 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}'."),
7751 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}'."),
7752 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}'."),
7753 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."),
7754 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}'."),
7755 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}'."),
7756 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}'."),
7757 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}'."),
7758 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}'."),
7759 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."),
7760 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}'."),
7761 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}'."),
7762 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."),
7763 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."),
7764 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}'."),
7765 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}'."),
7766 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."),
7767 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}'."),
7768 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}'."),
7769 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}'."),
7770 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}'."),
7771 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}'."),
7772 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}'."),
7773 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."),
7774 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}'."),
7775 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}'."),
7776 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."),
7777 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."),
7778 Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7779 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."),
7780 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."),
7781 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}'."),
7782 Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7783 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}."),
7784 Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7785 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}."),
7786 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}'?"),
7787 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}."),
7788 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."),
7789 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."),
7790 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'."),
7791 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."),
7792 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}'."),
7793 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}'."),
7794 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}'."),
7795 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."),
7796 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."),
7797 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}'."),
7798 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}'."),
7799 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."),
7800 Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
7801 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."),
7802 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."),
7803 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."),
7804 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}'."),
7805 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}'."),
7806 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."),
7807 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."),
7808 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."),
7809 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}'."),
7810 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."),
7811 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'."),
7812 Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7813 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}."),
7814 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."),
7815 _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}'."),
7816 _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."),
7817 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}'?"),
7818 Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7819 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}'?"),
7820 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}."),
7821 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}."),
7822 _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}'."),
7823 Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7824 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."),
7825 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."),
7826 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."),
7827 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."),
7828 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."),
7829 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."),
7830 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."),
7831 Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7832 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."),
7833 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."),
7834 Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7835 Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7836 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."),
7837 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."),
7838 Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7839 Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7840 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."),
7841 Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7842 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."),
7843 Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7844 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'."),
7845 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'."),
7846 Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7847 Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7848 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'."),
7849 Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7850 options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7851 file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7852 Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7853 Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7854 Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7855 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."),
7856 Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7857 File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7858 KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7859 FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7860 VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7861 LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7862 DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7863 STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7864 FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7865 Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7866 Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7867 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}'."),
7868 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}."),
7869 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}'."),
7870 Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7871 Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7872 Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7873 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."),
7874 File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7875 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}."),
7876 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."),
7877 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."),
7878 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."),
7879 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."),
7880 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)."),
7881 NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7882 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."),
7883 Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7884 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."),
7885 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."),
7886 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)."),
7887 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."),
7888 Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7889 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."),
7890 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)."),
7891 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."),
7892 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."),
7893 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."),
7894 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."),
7895 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."),
7896 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."),
7897 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'."),
7898 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."),
7899 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}."),
7900 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."),
7901 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"),
7902 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."),
7903 Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7904 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}'."),
7905 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}'."),
7906 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}'. ========"),
7907 Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7908 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}'."),
7909 Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7910 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}'."),
7911 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}'."),
7912 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}'."),
7913 File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7914 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."),
7915 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}'."),
7916 Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7917 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."),
7918 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}'."),
7919 Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7920 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."),
7921 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}'."),
7922 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}'."),
7923 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}'."),
7924 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}'."),
7925 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}'."),
7926 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}'."),
7927 Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7928 Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7929 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."),
7930 Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7931 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'?"),
7932 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."),
7933 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}'. ========"),
7934 Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7935 Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7936 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}. ========"),
7937 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. ========"),
7938 Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7939 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."),
7940 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. ========"),
7941 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."),
7942 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}'."),
7943 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."),
7944 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}'. ========"),
7945 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. ========"),
7946 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}'."),
7947 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'."),
7948 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."),
7949 _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),
7950 Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7951 Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7952 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."),
7953 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}'."),
7954 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),
7955 Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7956 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}'."),
7957 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."),
7958 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."),
7959 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}'."),
7960 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."),
7961 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'."),
7962 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}'."),
7963 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."),
7964 Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7965 Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7966 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."),
7967 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."),
7968 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')."),
7969 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."),
7970 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."),
7971 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')"),
7972 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."),
7973 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)."),
7974 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."),
7975 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."),
7976 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."),
7977 Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7978 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."),
7979 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."),
7980 Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7981 Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7982 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'."),
7983 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."),
7984 Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7985 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"),
7986 Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7987 Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7988 Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7989 Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7990 Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7991 Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7992 Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7993 Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7994 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'."),
7995 Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7996 List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7997 Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7998 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."),
7999 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."),
8000 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."),
8001 Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
8002 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."),
8003 Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
8004 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."),
8005 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."),
8006 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),
8007 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."),
8008 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."),
8009 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)."),
8010 _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),
8011 Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
8012 All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
8013 All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
8014 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}"),
8015 Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
8016 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}"),
8017 _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
8018 and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
8019 All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
8020 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."),
8021 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}'."),
8022 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}'."),
8023 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."),
8024 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."),
8025 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."),
8026 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?"),
8027 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?"),
8028 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."),
8029 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}'."),
8030 Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
8031 Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
8032 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}'. ========"),
8033 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}. ========"),
8034 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."),
8035 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."),
8036 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."),
8037 Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
8038 Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
8039 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'."),
8040 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'."),
8041 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'."),
8042 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."),
8043 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}'."),
8044 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."),
8045 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}."),
8046 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."),
8047 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."),
8048 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 '()'?"),
8049 Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
8050 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."),
8051 Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
8052 Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
8053 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."),
8054 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}'."),
8055 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."),
8056 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."),
8057 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"),
8058 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"),
8059 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."),
8060 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}'"),
8061 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}'"),
8062 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"),
8063 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"),
8064 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"),
8065 Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
8066 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}"),
8067 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}'"),
8068 Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
8069 Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
8070 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"),
8071 Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
8072 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"),
8073 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"),
8074 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"),
8075 Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
8076 Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
8077 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')"),
8078 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"),
8079 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."),
8080 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."),
8081 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}'..."),
8082 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"),
8083 Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
8084 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}'"),
8085 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}'"),
8086 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}'"),
8087 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}'"),
8088 Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
8089 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."),
8090 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"),
8091 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}'"),
8092 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"),
8093 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"),
8094 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."),
8095 _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
8096 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}'"),
8097 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."),
8098 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."),
8099 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."),
8100 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?"),
8101 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."),
8102 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."),
8103 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."),
8104 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."),
8105 _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."),
8106 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."),
8107 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."),
8108 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."),
8109 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'."),
8110 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."),
8111 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."),
8112 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."),
8113 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."),
8114 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."),
8115 _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."),
8116 _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."),
8117 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."),
8118 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."),
8119 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."),
8120 Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
8121 Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
8122 Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
8123 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."),
8124 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."),
8125 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."),
8126 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."),
8127 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."),
8128 Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
8129 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}'."),
8130 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'."),
8131 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."),
8132 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."),
8133 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}`"),
8134 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'."),
8135 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."),
8136 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."),
8137 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."),
8138 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."),
8139 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."),
8140 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."),
8141 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."),
8142 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."),
8143 _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."),
8144 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}'?"),
8145 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}'?"),
8146 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}'."),
8147 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}'."),
8148 _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."),
8149 You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
8150 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."),
8151 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."),
8152 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."),
8153 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."),
8154 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."),
8155 _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."),
8156 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."),
8157 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."),
8158 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."),
8159 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."),
8160 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."),
8161 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."),
8162 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."),
8163 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}'."),
8164 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}'."),
8165 Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
8166 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."),
8167 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."),
8168 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."),
8169 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."),
8170 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."),
8171 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."),
8172 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."),
8173 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."),
8174 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."),
8175 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."),
8176 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."),
8177 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."),
8178 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}'."),
8179 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."),
8180 The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
8181 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."),
8182 class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
8183 Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
8184 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."),
8185 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."),
8186 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'."),
8187 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."),
8188 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}'."),
8189 JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
8190 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."),
8191 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'."),
8192 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."),
8193 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."),
8194 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."),
8195 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."),
8196 Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
8197 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."),
8198 _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}'?"),
8199 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."),
8200 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."),
8201 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."),
8202 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."),
8203 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."),
8204 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}'?"),
8205 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}"),
8206 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."),
8207 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."),
8208 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}'."),
8209 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."),
8210 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."),
8211 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."),
8212 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."),
8213 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."),
8214 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."),
8215 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."),
8216 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."),
8217 Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
8218 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"),
8219 Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
8220 Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
8221 Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
8222 Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
8223 Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
8224 Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
8225 Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
8226 Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
8227 Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
8228 Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
8229 Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
8230 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}\""),
8231 Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
8232 Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
8233 Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
8234 Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
8235 Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
8236 Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
8237 Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
8238 Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
8239 Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
8240 Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
8241 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}'"),
8242 Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
8243 Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
8244 Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
8245 Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
8246 Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
8247 Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
8248 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}\""),
8249 Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
8250 Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
8251 Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
8252 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"),
8253 Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
8254 Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
8255 Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
8256 Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
8257 Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
8258 Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
8259 Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
8260 Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
8261 Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
8262 Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
8263 Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
8264 Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
8265 Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
8266 Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
8267 Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
8268 Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
8269 Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
8270 Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
8271 Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
8272 Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
8273 Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
8274 Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
8275 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}'"),
8276 Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
8277 Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
8278 Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
8279 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"),
8280 Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
8281 Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
8282 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"),
8283 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"),
8284 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"),
8285 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)"),
8286 Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
8287 Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
8288 Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
8289 Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
8290 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"),
8291 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"),
8292 Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
8293 Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
8294 Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
8295 Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
8296 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"),
8297 Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
8298 Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
8299 Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
8300 Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
8301 Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
8302 Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
8303 Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8304 Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8305 Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8306 Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8307 Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8308 Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8309 Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8310 Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8311 Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8312 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"),
8313 Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8314 Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8315 Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8316 Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8317 Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8318 Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8319 Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8320 Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8321 Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8322 Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8323 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"),
8324 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"),
8325 Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8326 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"),
8327 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"),
8328 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"),
8329 Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8330 Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8331 Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8332 Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8333 Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8334 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"),
8335 Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8336 Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8337 Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8338 Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8339 Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8340 Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8341 Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8342 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"),
8343 Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8344 Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8345 Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8346 Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8347 Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8348 Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8349 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'"),
8350 Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8351 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"),
8352 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}'"),
8353 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}'"),
8354 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"),
8355 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"),
8356 Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8357 Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8358 Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8359 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"),
8360 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"),
8361 Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8362 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"),
8363 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"),
8364 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"),
8365 Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8366 Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
8367 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"),
8368 Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8369 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"),
8370 Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8371 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"),
8372 Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
8373 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"),
8374 Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
8375 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"),
8376 Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
8377 Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
8378 Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
8379 Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
8380 Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
8381 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"),
8382 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"),
8383 Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
8384 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"),
8385 Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
8386 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"),
8387 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"),
8388 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"),
8389 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"),
8390 Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
8391 Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
8392 Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
8393 Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
8394 Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
8395 Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
8396 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"),
8397 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."),
8398 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'."),
8399 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?"),
8400 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"),
8401 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."),
8402 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."),
8403 constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8404 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."),
8405 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."),
8406 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}'."),
8407 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."),
8408 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"),
8409 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"),
8410 _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"),
8411 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."),
8412 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."),
8413 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."),
8414 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."),
8415 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."),
8416 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."),
8417 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."),
8418 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."),
8419 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."),
8420 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."),
8421 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."),
8422 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'."),
8423 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."),
8424 };
8425})(ts || (ts = {}));
8426var ts;
8427(function (ts) {
8428 var _a;
8429 /* @internal */
8430 function tokenIsIdentifierOrKeyword(token) {
8431 return token >= 78 /* Identifier */;
8432 }
8433 ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8434 /* @internal */
8435 function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8436 return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8437 }
8438 ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8439 var textToKeywordObj = (_a = {
8440 abstract: 125 /* AbstractKeyword */,
8441 any: 128 /* AnyKeyword */,
8442 as: 126 /* AsKeyword */,
8443 asserts: 127 /* AssertsKeyword */,
8444 bigint: 154 /* BigIntKeyword */,
8445 boolean: 131 /* BooleanKeyword */,
8446 break: 80 /* BreakKeyword */,
8447 case: 81 /* CaseKeyword */,
8448 catch: 82 /* CatchKeyword */,
8449 class: 83 /* ClassKeyword */,
8450 continue: 85 /* ContinueKeyword */,
8451 const: 84 /* ConstKeyword */
8452 },
8453 _a["" + "constructor"] = 132 /* ConstructorKeyword */,
8454 _a.debugger = 86 /* DebuggerKeyword */,
8455 _a.declare = 133 /* DeclareKeyword */,
8456 _a.default = 87 /* DefaultKeyword */,
8457 _a.delete = 88 /* DeleteKeyword */,
8458 _a.do = 89 /* DoKeyword */,
8459 _a.else = 90 /* ElseKeyword */,
8460 _a.enum = 91 /* EnumKeyword */,
8461 _a.export = 92 /* ExportKeyword */,
8462 _a.extends = 93 /* ExtendsKeyword */,
8463 _a.false = 94 /* FalseKeyword */,
8464 _a.finally = 95 /* FinallyKeyword */,
8465 _a.for = 96 /* ForKeyword */,
8466 _a.from = 152 /* FromKeyword */,
8467 _a.function = 97 /* FunctionKeyword */,
8468 _a.get = 134 /* GetKeyword */,
8469 _a.if = 98 /* IfKeyword */,
8470 _a.implements = 116 /* ImplementsKeyword */,
8471 _a.import = 99 /* ImportKeyword */,
8472 _a.in = 100 /* InKeyword */,
8473 _a.infer = 135 /* InferKeyword */,
8474 _a.instanceof = 101 /* InstanceOfKeyword */,
8475 _a.interface = 117 /* InterfaceKeyword */,
8476 _a.is = 136 /* IsKeyword */,
8477 _a.keyof = 137 /* KeyOfKeyword */,
8478 _a.let = 118 /* LetKeyword */,
8479 _a.module = 138 /* ModuleKeyword */,
8480 _a.namespace = 139 /* NamespaceKeyword */,
8481 _a.never = 140 /* NeverKeyword */,
8482 _a.new = 102 /* NewKeyword */,
8483 _a.null = 103 /* NullKeyword */,
8484 _a.number = 143 /* NumberKeyword */,
8485 _a.object = 144 /* ObjectKeyword */,
8486 _a.package = 119 /* PackageKeyword */,
8487 _a.private = 120 /* PrivateKeyword */,
8488 _a.protected = 121 /* ProtectedKeyword */,
8489 _a.public = 122 /* PublicKeyword */,
8490 _a.readonly = 141 /* ReadonlyKeyword */,
8491 _a.require = 142 /* RequireKeyword */,
8492 _a.global = 153 /* GlobalKeyword */,
8493 _a.return = 104 /* ReturnKeyword */,
8494 _a.set = 145 /* SetKeyword */,
8495 _a.static = 123 /* StaticKeyword */,
8496 _a.string = 146 /* StringKeyword */,
8497 _a.super = 105 /* SuperKeyword */,
8498 _a.switch = 106 /* SwitchKeyword */,
8499 _a.symbol = 147 /* SymbolKeyword */,
8500 _a.this = 107 /* ThisKeyword */,
8501 _a.throw = 108 /* ThrowKeyword */,
8502 _a.true = 109 /* TrueKeyword */,
8503 _a.try = 110 /* TryKeyword */,
8504 _a.type = 148 /* TypeKeyword */,
8505 _a.typeof = 111 /* TypeOfKeyword */,
8506 _a.undefined = 149 /* UndefinedKeyword */,
8507 _a.unique = 150 /* UniqueKeyword */,
8508 _a.unknown = 151 /* UnknownKeyword */,
8509 _a.var = 112 /* VarKeyword */,
8510 _a.void = 113 /* VoidKeyword */,
8511 _a.while = 114 /* WhileKeyword */,
8512 _a.with = 115 /* WithKeyword */,
8513 _a.yield = 124 /* YieldKeyword */,
8514 _a.async = 129 /* AsyncKeyword */,
8515 _a.await = 130 /* AwaitKeyword */,
8516 _a.of = 155 /* OfKeyword */,
8517 _a);
8518 var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj));
8519 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 */ })));
8520 /*
8521 As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8522 IdentifierStart ::
8523 Can contain Unicode 3.0.0 categories:
8524 Uppercase letter (Lu),
8525 Lowercase letter (Ll),
8526 Titlecase letter (Lt),
8527 Modifier letter (Lm),
8528 Other letter (Lo), or
8529 Letter number (Nl).
8530 IdentifierPart :: =
8531 Can contain IdentifierStart + Unicode 3.0.0 categories:
8532 Non-spacing mark (Mn),
8533 Combining spacing mark (Mc),
8534 Decimal number (Nd), or
8535 Connector punctuation (Pc).
8536
8537 Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8538 http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8539 */
8540 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,];
8541 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,];
8542 /*
8543 As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8544 IdentifierStart ::
8545 Can contain Unicode 6.2 categories:
8546 Uppercase letter (Lu),
8547 Lowercase letter (Ll),
8548 Titlecase letter (Lt),
8549 Modifier letter (Lm),
8550 Other letter (Lo), or
8551 Letter number (Nl).
8552 IdentifierPart ::
8553 Can contain IdentifierStart + Unicode 6.2 categories:
8554 Non-spacing mark (Mn),
8555 Combining spacing mark (Mc),
8556 Decimal number (Nd),
8557 Connector punctuation (Pc),
8558 <ZWNJ>, or
8559 <ZWJ>.
8560
8561 Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8562 http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8563 */
8564 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,];
8565 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,];
8566 /**
8567 * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8568 * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8569 * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8570 * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8571 */
8572 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];
8573 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];
8574 /**
8575 * Test for whether a single line comment's text contains a directive.
8576 */
8577 var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8578 /**
8579 * Test for whether a multi-line comment's last line contains a directive.
8580 */
8581 var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8582 function lookupInUnicodeMap(code, map) {
8583 // Bail out quickly if it couldn't possibly be in the map.
8584 if (code < map[0]) {
8585 return false;
8586 }
8587 // Perform binary search in one of the Unicode range maps
8588 var lo = 0;
8589 var hi = map.length;
8590 var mid;
8591 while (lo + 1 < hi) {
8592 mid = lo + (hi - lo) / 2;
8593 // mid has to be even to catch a range's beginning
8594 mid -= mid % 2;
8595 if (map[mid] <= code && code <= map[mid + 1]) {
8596 return true;
8597 }
8598 if (code < map[mid]) {
8599 hi = mid;
8600 }
8601 else {
8602 lo = mid + 2;
8603 }
8604 }
8605 return false;
8606 }
8607 /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8608 return languageVersion >= 2 /* ES2015 */ ?
8609 lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8610 languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8611 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8612 }
8613 ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8614 function isUnicodeIdentifierPart(code, languageVersion) {
8615 return languageVersion >= 2 /* ES2015 */ ?
8616 lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8617 languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8618 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8619 }
8620 function makeReverseMap(source) {
8621 var result = [];
8622 source.forEach(function (value, name) {
8623 result[value] = name;
8624 });
8625 return result;
8626 }
8627 var tokenStrings = makeReverseMap(textToToken);
8628 function tokenToString(t) {
8629 return tokenStrings[t];
8630 }
8631 ts.tokenToString = tokenToString;
8632 /* @internal */
8633 function stringToToken(s) {
8634 return textToToken.get(s);
8635 }
8636 ts.stringToToken = stringToToken;
8637 /* @internal */
8638 function computeLineStarts(text) {
8639 var result = new Array();
8640 var pos = 0;
8641 var lineStart = 0;
8642 while (pos < text.length) {
8643 var ch = text.charCodeAt(pos);
8644 pos++;
8645 switch (ch) {
8646 case 13 /* carriageReturn */:
8647 if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8648 pos++;
8649 }
8650 // falls through
8651 case 10 /* lineFeed */:
8652 result.push(lineStart);
8653 lineStart = pos;
8654 break;
8655 default:
8656 if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8657 result.push(lineStart);
8658 lineStart = pos;
8659 }
8660 break;
8661 }
8662 }
8663 result.push(lineStart);
8664 return result;
8665 }
8666 ts.computeLineStarts = computeLineStarts;
8667 function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8668 return sourceFile.getPositionOfLineAndCharacter ?
8669 sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8670 computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8671 }
8672 ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8673 /* @internal */
8674 function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8675 if (line < 0 || line >= lineStarts.length) {
8676 if (allowEdits) {
8677 // Clamp line to nearest allowable value
8678 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8679 }
8680 else {
8681 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8682 }
8683 }
8684 var res = lineStarts[line] + character;
8685 if (allowEdits) {
8686 // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8687 // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8688 // apply them to the computed position to improve accuracy
8689 return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8690 }
8691 if (line < lineStarts.length - 1) {
8692 ts.Debug.assert(res < lineStarts[line + 1]);
8693 }
8694 else if (debugText !== undefined) {
8695 ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8696 }
8697 return res;
8698 }
8699 ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8700 /* @internal */
8701 function getLineStarts(sourceFile) {
8702 return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8703 }
8704 ts.getLineStarts = getLineStarts;
8705 /* @internal */
8706 function computeLineAndCharacterOfPosition(lineStarts, position) {
8707 var lineNumber = computeLineOfPosition(lineStarts, position);
8708 return {
8709 line: lineNumber,
8710 character: position - lineStarts[lineNumber]
8711 };
8712 }
8713 ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8714 /**
8715 * @internal
8716 * We assume the first line starts at position 0 and 'position' is non-negative.
8717 */
8718 function computeLineOfPosition(lineStarts, position, lowerBound) {
8719 var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8720 if (lineNumber < 0) {
8721 // If the actual position was not found,
8722 // the binary search returns the 2's-complement of the next line start
8723 // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8724 // then the search will return -2.
8725 //
8726 // We want the index of the previous line start, so we subtract 1.
8727 // Review 2's-complement if this is confusing.
8728 lineNumber = ~lineNumber - 1;
8729 ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8730 }
8731 return lineNumber;
8732 }
8733 ts.computeLineOfPosition = computeLineOfPosition;
8734 /** @internal */
8735 function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8736 if (pos1 === pos2)
8737 return 0;
8738 var lineStarts = getLineStarts(sourceFile);
8739 var lower = Math.min(pos1, pos2);
8740 var isNegative = lower === pos2;
8741 var upper = isNegative ? pos1 : pos2;
8742 var lowerLine = computeLineOfPosition(lineStarts, lower);
8743 var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8744 return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8745 }
8746 ts.getLinesBetweenPositions = getLinesBetweenPositions;
8747 function getLineAndCharacterOfPosition(sourceFile, position) {
8748 return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8749 }
8750 ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8751 function isWhiteSpaceLike(ch) {
8752 return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8753 }
8754 ts.isWhiteSpaceLike = isWhiteSpaceLike;
8755 /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8756 function isWhiteSpaceSingleLine(ch) {
8757 // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8758 // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8759 return ch === 32 /* space */ ||
8760 ch === 9 /* tab */ ||
8761 ch === 11 /* verticalTab */ ||
8762 ch === 12 /* formFeed */ ||
8763 ch === 160 /* nonBreakingSpace */ ||
8764 ch === 133 /* nextLine */ ||
8765 ch === 5760 /* ogham */ ||
8766 ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8767 ch === 8239 /* narrowNoBreakSpace */ ||
8768 ch === 8287 /* mathematicalSpace */ ||
8769 ch === 12288 /* ideographicSpace */ ||
8770 ch === 65279 /* byteOrderMark */;
8771 }
8772 ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8773 function isLineBreak(ch) {
8774 // ES5 7.3:
8775 // The ECMAScript line terminator characters are listed in Table 3.
8776 // Table 3: Line Terminator Characters
8777 // Code Unit Value Name Formal Name
8778 // \u000A Line Feed <LF>
8779 // \u000D Carriage Return <CR>
8780 // \u2028 Line separator <LS>
8781 // \u2029 Paragraph separator <PS>
8782 // Only the characters in Table 3 are treated as line terminators. Other new line or line
8783 // breaking characters are treated as white space but not as line terminators.
8784 return ch === 10 /* lineFeed */ ||
8785 ch === 13 /* carriageReturn */ ||
8786 ch === 8232 /* lineSeparator */ ||
8787 ch === 8233 /* paragraphSeparator */;
8788 }
8789 ts.isLineBreak = isLineBreak;
8790 function isDigit(ch) {
8791 return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8792 }
8793 function isHexDigit(ch) {
8794 return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8795 }
8796 function isCodePoint(code) {
8797 return code <= 0x10FFFF;
8798 }
8799 /* @internal */
8800 function isOctalDigit(ch) {
8801 return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8802 }
8803 ts.isOctalDigit = isOctalDigit;
8804 function couldStartTrivia(text, pos) {
8805 // Keep in sync with skipTrivia
8806 var ch = text.charCodeAt(pos);
8807 switch (ch) {
8808 case 13 /* carriageReturn */:
8809 case 10 /* lineFeed */:
8810 case 9 /* tab */:
8811 case 11 /* verticalTab */:
8812 case 12 /* formFeed */:
8813 case 32 /* space */:
8814 case 47 /* slash */:
8815 // starts of normal trivia
8816 // falls through
8817 case 60 /* lessThan */:
8818 case 124 /* bar */:
8819 case 61 /* equals */:
8820 case 62 /* greaterThan */:
8821 // Starts of conflict marker trivia
8822 return true;
8823 case 35 /* hash */:
8824 // Only if its the beginning can we have #! trivia
8825 return pos === 0;
8826 default:
8827 return ch > 127 /* maxAsciiCharacter */;
8828 }
8829 }
8830 ts.couldStartTrivia = couldStartTrivia;
8831 /* @internal */
8832 function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8833 if (stopAtComments === void 0) { stopAtComments = false; }
8834 if (ts.positionIsSynthesized(pos)) {
8835 return pos;
8836 }
8837 // Keep in sync with couldStartTrivia
8838 while (true) {
8839 var ch = text.charCodeAt(pos);
8840 switch (ch) {
8841 case 13 /* carriageReturn */:
8842 if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8843 pos++;
8844 }
8845 // falls through
8846 case 10 /* lineFeed */:
8847 pos++;
8848 if (stopAfterLineBreak) {
8849 return pos;
8850 }
8851 continue;
8852 case 9 /* tab */:
8853 case 11 /* verticalTab */:
8854 case 12 /* formFeed */:
8855 case 32 /* space */:
8856 pos++;
8857 continue;
8858 case 47 /* slash */:
8859 if (stopAtComments) {
8860 break;
8861 }
8862 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8863 pos += 2;
8864 while (pos < text.length) {
8865 if (isLineBreak(text.charCodeAt(pos))) {
8866 break;
8867 }
8868 pos++;
8869 }
8870 continue;
8871 }
8872 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8873 pos += 2;
8874 while (pos < text.length) {
8875 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8876 pos += 2;
8877 break;
8878 }
8879 pos++;
8880 }
8881 continue;
8882 }
8883 break;
8884 case 60 /* lessThan */:
8885 case 124 /* bar */:
8886 case 61 /* equals */:
8887 case 62 /* greaterThan */:
8888 if (isConflictMarkerTrivia(text, pos)) {
8889 pos = scanConflictMarkerTrivia(text, pos);
8890 continue;
8891 }
8892 break;
8893 case 35 /* hash */:
8894 if (pos === 0 && isShebangTrivia(text, pos)) {
8895 pos = scanShebangTrivia(text, pos);
8896 continue;
8897 }
8898 break;
8899 default:
8900 if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8901 pos++;
8902 continue;
8903 }
8904 break;
8905 }
8906 return pos;
8907 }
8908 }
8909 ts.skipTrivia = skipTrivia;
8910 // All conflict markers consist of the same character repeated seven times. If it is
8911 // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8912 var mergeConflictMarkerLength = "<<<<<<<".length;
8913 function isConflictMarkerTrivia(text, pos) {
8914 ts.Debug.assert(pos >= 0);
8915 // Conflict markers must be at the start of a line.
8916 if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8917 var ch = text.charCodeAt(pos);
8918 if ((pos + mergeConflictMarkerLength) < text.length) {
8919 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8920 if (text.charCodeAt(pos + i) !== ch) {
8921 return false;
8922 }
8923 }
8924 return ch === 61 /* equals */ ||
8925 text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8926 }
8927 }
8928 return false;
8929 }
8930 function scanConflictMarkerTrivia(text, pos, error) {
8931 if (error) {
8932 error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8933 }
8934 var ch = text.charCodeAt(pos);
8935 var len = text.length;
8936 if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8937 while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8938 pos++;
8939 }
8940 }
8941 else {
8942 ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8943 // Consume everything from the start of a ||||||| or ======= marker to the start
8944 // of the next ======= or >>>>>>> marker.
8945 while (pos < len) {
8946 var currentChar = text.charCodeAt(pos);
8947 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8948 break;
8949 }
8950 pos++;
8951 }
8952 }
8953 return pos;
8954 }
8955 var shebangTriviaRegex = /^#!.*/;
8956 /*@internal*/
8957 function isShebangTrivia(text, pos) {
8958 // Shebangs check must only be done at the start of the file
8959 ts.Debug.assert(pos === 0);
8960 return shebangTriviaRegex.test(text);
8961 }
8962 ts.isShebangTrivia = isShebangTrivia;
8963 /*@internal*/
8964 function scanShebangTrivia(text, pos) {
8965 var shebang = shebangTriviaRegex.exec(text)[0];
8966 pos = pos + shebang.length;
8967 return pos;
8968 }
8969 ts.scanShebangTrivia = scanShebangTrivia;
8970 /**
8971 * Invokes a callback for each comment range following the provided position.
8972 *
8973 * Single-line comment ranges include the leading double-slash characters but not the ending
8974 * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8975 * asterisk-slash characters.
8976 *
8977 * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8978 * to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8979 * @param text The source text to scan.
8980 * @param pos The position at which to start scanning.
8981 * @param trailing If false, whitespace is skipped until the first line break and comments
8982 * between that location and the next token are returned. If true, comments occurring
8983 * between the given position and the next line break are returned.
8984 * @param cb The callback to execute as each comment range is encountered.
8985 * @param state A state value to pass to each iteration of the callback.
8986 * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8987 * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8988 * return value of the callback.
8989 */
8990 function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8991 var pendingPos;
8992 var pendingEnd;
8993 var pendingKind;
8994 var pendingHasTrailingNewLine;
8995 var hasPendingCommentRange = false;
8996 var collecting = trailing;
8997 var accumulator = initial;
8998 if (pos === 0) {
8999 collecting = true;
9000 var shebang = getShebang(text);
9001 if (shebang) {
9002 pos = shebang.length;
9003 }
9004 }
9005 scan: while (pos >= 0 && pos < text.length) {
9006 var ch = text.charCodeAt(pos);
9007 switch (ch) {
9008 case 13 /* carriageReturn */:
9009 if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9010 pos++;
9011 }
9012 // falls through
9013 case 10 /* lineFeed */:
9014 pos++;
9015 if (trailing) {
9016 break scan;
9017 }
9018 collecting = true;
9019 if (hasPendingCommentRange) {
9020 pendingHasTrailingNewLine = true;
9021 }
9022 continue;
9023 case 9 /* tab */:
9024 case 11 /* verticalTab */:
9025 case 12 /* formFeed */:
9026 case 32 /* space */:
9027 pos++;
9028 continue;
9029 case 47 /* slash */:
9030 var nextChar = text.charCodeAt(pos + 1);
9031 var hasTrailingNewLine = false;
9032 if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
9033 var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
9034 var startPos = pos;
9035 pos += 2;
9036 if (nextChar === 47 /* slash */) {
9037 while (pos < text.length) {
9038 if (isLineBreak(text.charCodeAt(pos))) {
9039 hasTrailingNewLine = true;
9040 break;
9041 }
9042 pos++;
9043 }
9044 }
9045 else {
9046 while (pos < text.length) {
9047 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9048 pos += 2;
9049 break;
9050 }
9051 pos++;
9052 }
9053 }
9054 if (collecting) {
9055 if (hasPendingCommentRange) {
9056 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9057 if (!reduce && accumulator) {
9058 // If we are not reducing and we have a truthy result, return it.
9059 return accumulator;
9060 }
9061 }
9062 pendingPos = startPos;
9063 pendingEnd = pos;
9064 pendingKind = kind;
9065 pendingHasTrailingNewLine = hasTrailingNewLine;
9066 hasPendingCommentRange = true;
9067 }
9068 continue;
9069 }
9070 break scan;
9071 default:
9072 if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9073 if (hasPendingCommentRange && isLineBreak(ch)) {
9074 pendingHasTrailingNewLine = true;
9075 }
9076 pos++;
9077 continue;
9078 }
9079 break scan;
9080 }
9081 }
9082 if (hasPendingCommentRange) {
9083 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9084 }
9085 return accumulator;
9086 }
9087 function forEachLeadingCommentRange(text, pos, cb, state) {
9088 return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
9089 }
9090 ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
9091 function forEachTrailingCommentRange(text, pos, cb, state) {
9092 return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
9093 }
9094 ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
9095 function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
9096 return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
9097 }
9098 ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
9099 function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
9100 return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
9101 }
9102 ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
9103 function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
9104 if (!comments) {
9105 comments = [];
9106 }
9107 comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
9108 return comments;
9109 }
9110 function getLeadingCommentRanges(text, pos) {
9111 return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9112 }
9113 ts.getLeadingCommentRanges = getLeadingCommentRanges;
9114 function getTrailingCommentRanges(text, pos) {
9115 return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9116 }
9117 ts.getTrailingCommentRanges = getTrailingCommentRanges;
9118 /** Optionally, get the shebang */
9119 function getShebang(text) {
9120 var match = shebangTriviaRegex.exec(text);
9121 if (match) {
9122 return match[0];
9123 }
9124 }
9125 ts.getShebang = getShebang;
9126 function isIdentifierStart(ch, languageVersion) {
9127 return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9128 ch === 36 /* $ */ || ch === 95 /* _ */ ||
9129 ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
9130 }
9131 ts.isIdentifierStart = isIdentifierStart;
9132 function isIdentifierPart(ch, languageVersion, identifierVariant) {
9133 return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9134 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
9135 // "-" and ":" are valid in JSX Identifiers
9136 (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
9137 ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
9138 }
9139 ts.isIdentifierPart = isIdentifierPart;
9140 /* @internal */
9141 function isIdentifierText(name, languageVersion, identifierVariant) {
9142 var ch = codePointAt(name, 0);
9143 if (!isIdentifierStart(ch, languageVersion)) {
9144 return false;
9145 }
9146 for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
9147 if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
9148 return false;
9149 }
9150 }
9151 return true;
9152 }
9153 ts.isIdentifierText = isIdentifierText;
9154 // Creates a scanner over a (possibly unspecified) range of a piece of text.
9155 function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
9156 if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
9157 var text = textInitial;
9158 // Current position (end position of text of current token)
9159 var pos;
9160 // end of text
9161 var end;
9162 // Start position of whitespace before current token
9163 var startPos;
9164 // Start position of text of current token
9165 var tokenPos;
9166 var token;
9167 var tokenValue;
9168 var tokenFlags;
9169 var commentDirectives;
9170 var inJSDocType = 0;
9171 setText(text, start, length);
9172 var scanner = {
9173 getStartPos: function () { return startPos; },
9174 getTextPos: function () { return pos; },
9175 getToken: function () { return token; },
9176 getTokenPos: function () { return tokenPos; },
9177 getTokenText: function () { return text.substring(tokenPos, pos); },
9178 getTokenValue: function () { return tokenValue; },
9179 hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
9180 hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
9181 hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
9182 hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
9183 isIdentifier: function () { return token === 78 /* Identifier */ || token > 115 /* LastReservedWord */; },
9184 isReservedWord: function () { return token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */; },
9185 isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
9186 getCommentDirectives: function () { return commentDirectives; },
9187 getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
9188 getTokenFlags: function () { return tokenFlags; },
9189 reScanGreaterToken: reScanGreaterToken,
9190 reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
9191 reScanSlashToken: reScanSlashToken,
9192 reScanTemplateToken: reScanTemplateToken,
9193 reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
9194 scanJsxIdentifier: scanJsxIdentifier,
9195 scanJsxAttributeValue: scanJsxAttributeValue,
9196 reScanJsxAttributeValue: reScanJsxAttributeValue,
9197 reScanJsxToken: reScanJsxToken,
9198 reScanLessThanToken: reScanLessThanToken,
9199 reScanQuestionToken: reScanQuestionToken,
9200 scanJsxToken: scanJsxToken,
9201 scanJsDocToken: scanJsDocToken,
9202 scan: scan,
9203 getText: getText,
9204 clearCommentDirectives: clearCommentDirectives,
9205 setText: setText,
9206 setScriptTarget: setScriptTarget,
9207 setLanguageVariant: setLanguageVariant,
9208 setOnError: setOnError,
9209 setTextPos: setTextPos,
9210 setInJSDocType: setInJSDocType,
9211 tryScan: tryScan,
9212 lookAhead: lookAhead,
9213 scanRange: scanRange,
9214 };
9215 if (ts.Debug.isDebugging) {
9216 Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
9217 get: function () {
9218 var text = scanner.getText();
9219 return text.slice(0, scanner.getStartPos()) + "║" + text.slice(scanner.getStartPos());
9220 },
9221 });
9222 }
9223 return scanner;
9224 function error(message, errPos, length) {
9225 if (errPos === void 0) { errPos = pos; }
9226 if (onError) {
9227 var oldPos = pos;
9228 pos = errPos;
9229 onError(message, length || 0);
9230 pos = oldPos;
9231 }
9232 }
9233 function scanNumberFragment() {
9234 var start = pos;
9235 var allowSeparator = false;
9236 var isPreviousTokenSeparator = false;
9237 var result = "";
9238 while (true) {
9239 var ch = text.charCodeAt(pos);
9240 if (ch === 95 /* _ */) {
9241 tokenFlags |= 512 /* ContainsSeparator */;
9242 if (allowSeparator) {
9243 allowSeparator = false;
9244 isPreviousTokenSeparator = true;
9245 result += text.substring(start, pos);
9246 }
9247 else if (isPreviousTokenSeparator) {
9248 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9249 }
9250 else {
9251 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9252 }
9253 pos++;
9254 start = pos;
9255 continue;
9256 }
9257 if (isDigit(ch)) {
9258 allowSeparator = true;
9259 isPreviousTokenSeparator = false;
9260 pos++;
9261 continue;
9262 }
9263 break;
9264 }
9265 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9266 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9267 }
9268 return result + text.substring(start, pos);
9269 }
9270 function scanNumber() {
9271 var start = pos;
9272 var mainFragment = scanNumberFragment();
9273 var decimalFragment;
9274 var scientificFragment;
9275 if (text.charCodeAt(pos) === 46 /* dot */) {
9276 pos++;
9277 decimalFragment = scanNumberFragment();
9278 }
9279 var end = pos;
9280 if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
9281 pos++;
9282 tokenFlags |= 16 /* Scientific */;
9283 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
9284 pos++;
9285 var preNumericPart = pos;
9286 var finalFragment = scanNumberFragment();
9287 if (!finalFragment) {
9288 error(ts.Diagnostics.Digit_expected);
9289 }
9290 else {
9291 scientificFragment = text.substring(end, preNumericPart) + finalFragment;
9292 end = pos;
9293 }
9294 }
9295 var result;
9296 if (tokenFlags & 512 /* ContainsSeparator */) {
9297 result = mainFragment;
9298 if (decimalFragment) {
9299 result += "." + decimalFragment;
9300 }
9301 if (scientificFragment) {
9302 result += scientificFragment;
9303 }
9304 }
9305 else {
9306 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
9307 }
9308 if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
9309 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
9310 return {
9311 type: 8 /* NumericLiteral */,
9312 value: "" + +result // if value is not an integer, it can be safely coerced to a number
9313 };
9314 }
9315 else {
9316 tokenValue = result;
9317 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
9318 checkForIdentifierStartAfterNumericLiteral(start);
9319 return { type: type, value: tokenValue };
9320 }
9321 }
9322 function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
9323 if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
9324 return;
9325 }
9326 var identifierStart = pos;
9327 var length = scanIdentifierParts().length;
9328 if (length === 1 && text[identifierStart] === "n") {
9329 if (isScientific) {
9330 error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
9331 }
9332 else {
9333 error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
9334 }
9335 }
9336 else {
9337 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9338 pos = identifierStart;
9339 }
9340 }
9341 function scanOctalDigits() {
9342 var start = pos;
9343 while (isOctalDigit(text.charCodeAt(pos))) {
9344 pos++;
9345 }
9346 return +(text.substring(start, pos));
9347 }
9348 /**
9349 * Scans the given number of hexadecimal digits in the text,
9350 * returning -1 if the given number is unavailable.
9351 */
9352 function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9353 var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9354 return valueString ? parseInt(valueString, 16) : -1;
9355 }
9356 /**
9357 * Scans as many hexadecimal digits as are available in the text,
9358 * returning "" if the given number of digits was unavailable.
9359 */
9360 function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9361 return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9362 }
9363 function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9364 var valueChars = [];
9365 var allowSeparator = false;
9366 var isPreviousTokenSeparator = false;
9367 while (valueChars.length < minCount || scanAsManyAsPossible) {
9368 var ch = text.charCodeAt(pos);
9369 if (canHaveSeparators && ch === 95 /* _ */) {
9370 tokenFlags |= 512 /* ContainsSeparator */;
9371 if (allowSeparator) {
9372 allowSeparator = false;
9373 isPreviousTokenSeparator = true;
9374 }
9375 else if (isPreviousTokenSeparator) {
9376 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9377 }
9378 else {
9379 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9380 }
9381 pos++;
9382 continue;
9383 }
9384 allowSeparator = canHaveSeparators;
9385 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9386 ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9387 }
9388 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9389 (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9390 break;
9391 }
9392 valueChars.push(ch);
9393 pos++;
9394 isPreviousTokenSeparator = false;
9395 }
9396 if (valueChars.length < minCount) {
9397 valueChars = [];
9398 }
9399 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9400 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9401 }
9402 return String.fromCharCode.apply(String, valueChars);
9403 }
9404 function scanString(jsxAttributeString) {
9405 if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9406 var quote = text.charCodeAt(pos);
9407 pos++;
9408 var result = "";
9409 var start = pos;
9410 while (true) {
9411 if (pos >= end) {
9412 result += text.substring(start, pos);
9413 tokenFlags |= 4 /* Unterminated */;
9414 error(ts.Diagnostics.Unterminated_string_literal);
9415 break;
9416 }
9417 var ch = text.charCodeAt(pos);
9418 if (ch === quote) {
9419 result += text.substring(start, pos);
9420 pos++;
9421 break;
9422 }
9423 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9424 result += text.substring(start, pos);
9425 result += scanEscapeSequence();
9426 start = pos;
9427 continue;
9428 }
9429 if (isLineBreak(ch) && !jsxAttributeString) {
9430 result += text.substring(start, pos);
9431 tokenFlags |= 4 /* Unterminated */;
9432 error(ts.Diagnostics.Unterminated_string_literal);
9433 break;
9434 }
9435 pos++;
9436 }
9437 return result;
9438 }
9439 /**
9440 * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9441 * a literal component of a TemplateExpression.
9442 */
9443 function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9444 var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9445 pos++;
9446 var start = pos;
9447 var contents = "";
9448 var resultingToken;
9449 while (true) {
9450 if (pos >= end) {
9451 contents += text.substring(start, pos);
9452 tokenFlags |= 4 /* Unterminated */;
9453 error(ts.Diagnostics.Unterminated_template_literal);
9454 resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9455 break;
9456 }
9457 var currChar = text.charCodeAt(pos);
9458 // '`'
9459 if (currChar === 96 /* backtick */) {
9460 contents += text.substring(start, pos);
9461 pos++;
9462 resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9463 break;
9464 }
9465 // '${'
9466 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9467 contents += text.substring(start, pos);
9468 pos += 2;
9469 resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9470 break;
9471 }
9472 // Escape character
9473 if (currChar === 92 /* backslash */) {
9474 contents += text.substring(start, pos);
9475 contents += scanEscapeSequence(isTaggedTemplate);
9476 start = pos;
9477 continue;
9478 }
9479 // Speculated ECMAScript 6 Spec 11.8.6.1:
9480 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9481 if (currChar === 13 /* carriageReturn */) {
9482 contents += text.substring(start, pos);
9483 pos++;
9484 if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9485 pos++;
9486 }
9487 contents += "\n";
9488 start = pos;
9489 continue;
9490 }
9491 pos++;
9492 }
9493 ts.Debug.assert(resultingToken !== undefined);
9494 tokenValue = contents;
9495 return resultingToken;
9496 }
9497 function scanEscapeSequence(isTaggedTemplate) {
9498 var start = pos;
9499 pos++;
9500 if (pos >= end) {
9501 error(ts.Diagnostics.Unexpected_end_of_text);
9502 return "";
9503 }
9504 var ch = text.charCodeAt(pos);
9505 pos++;
9506 switch (ch) {
9507 case 48 /* _0 */:
9508 // '\01'
9509 if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9510 pos++;
9511 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9512 return text.substring(start, pos);
9513 }
9514 return "\0";
9515 case 98 /* b */:
9516 return "\b";
9517 case 116 /* t */:
9518 return "\t";
9519 case 110 /* n */:
9520 return "\n";
9521 case 118 /* v */:
9522 return "\v";
9523 case 102 /* f */:
9524 return "\f";
9525 case 114 /* r */:
9526 return "\r";
9527 case 39 /* singleQuote */:
9528 return "\'";
9529 case 34 /* doubleQuote */:
9530 return "\"";
9531 case 117 /* u */:
9532 if (isTaggedTemplate) {
9533 // '\u' or '\u0' or '\u00' or '\u000'
9534 for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9535 if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9536 pos = escapePos;
9537 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9538 return text.substring(start, pos);
9539 }
9540 }
9541 }
9542 // '\u{DDDDDDDD}'
9543 if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9544 pos++;
9545 // '\u{'
9546 if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9547 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9548 return text.substring(start, pos);
9549 }
9550 if (isTaggedTemplate) {
9551 var savePos = pos;
9552 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9553 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9554 // '\u{Not Code Point' or '\u{CodePoint'
9555 if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9556 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9557 return text.substring(start, pos);
9558 }
9559 else {
9560 pos = savePos;
9561 }
9562 }
9563 tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9564 return scanExtendedUnicodeEscape();
9565 }
9566 tokenFlags |= 1024 /* UnicodeEscape */;
9567 // '\uDDDD'
9568 return scanHexadecimalEscape(/*numDigits*/ 4);
9569 case 120 /* x */:
9570 if (isTaggedTemplate) {
9571 if (!isHexDigit(text.charCodeAt(pos))) {
9572 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9573 return text.substring(start, pos);
9574 }
9575 else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9576 pos++;
9577 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9578 return text.substring(start, pos);
9579 }
9580 }
9581 // '\xDD'
9582 return scanHexadecimalEscape(/*numDigits*/ 2);
9583 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9584 // the line terminator is interpreted to be "the empty code unit sequence".
9585 case 13 /* carriageReturn */:
9586 if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9587 pos++;
9588 }
9589 // falls through
9590 case 10 /* lineFeed */:
9591 case 8232 /* lineSeparator */:
9592 case 8233 /* paragraphSeparator */:
9593 return "";
9594 default:
9595 return String.fromCharCode(ch);
9596 }
9597 }
9598 function scanHexadecimalEscape(numDigits) {
9599 var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9600 if (escapedValue >= 0) {
9601 return String.fromCharCode(escapedValue);
9602 }
9603 else {
9604 error(ts.Diagnostics.Hexadecimal_digit_expected);
9605 return "";
9606 }
9607 }
9608 function scanExtendedUnicodeEscape() {
9609 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9610 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9611 var isInvalidExtendedEscape = false;
9612 // Validate the value of the digit
9613 if (escapedValue < 0) {
9614 error(ts.Diagnostics.Hexadecimal_digit_expected);
9615 isInvalidExtendedEscape = true;
9616 }
9617 else if (escapedValue > 0x10FFFF) {
9618 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9619 isInvalidExtendedEscape = true;
9620 }
9621 if (pos >= end) {
9622 error(ts.Diagnostics.Unexpected_end_of_text);
9623 isInvalidExtendedEscape = true;
9624 }
9625 else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9626 // Only swallow the following character up if it's a '}'.
9627 pos++;
9628 }
9629 else {
9630 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9631 isInvalidExtendedEscape = true;
9632 }
9633 if (isInvalidExtendedEscape) {
9634 return "";
9635 }
9636 return utf16EncodeAsString(escapedValue);
9637 }
9638 // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9639 // and return code point value if valid Unicode escape is found. Otherwise return -1.
9640 function peekUnicodeEscape() {
9641 if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9642 var start_1 = pos;
9643 pos += 2;
9644 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9645 pos = start_1;
9646 return value;
9647 }
9648 return -1;
9649 }
9650 function peekExtendedUnicodeEscape() {
9651 if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9652 var start_2 = pos;
9653 pos += 3;
9654 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9655 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9656 pos = start_2;
9657 return escapedValue;
9658 }
9659 return -1;
9660 }
9661 function scanIdentifierParts() {
9662 var result = "";
9663 var start = pos;
9664 while (pos < end) {
9665 var ch = codePointAt(text, pos);
9666 if (isIdentifierPart(ch, languageVersion)) {
9667 pos += charSize(ch);
9668 }
9669 else if (ch === 92 /* backslash */) {
9670 ch = peekExtendedUnicodeEscape();
9671 if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9672 pos += 3;
9673 tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9674 result += scanExtendedUnicodeEscape();
9675 start = pos;
9676 continue;
9677 }
9678 ch = peekUnicodeEscape();
9679 if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9680 break;
9681 }
9682 tokenFlags |= 1024 /* UnicodeEscape */;
9683 result += text.substring(start, pos);
9684 result += utf16EncodeAsString(ch);
9685 // Valid Unicode escape is always six characters
9686 pos += 6;
9687 start = pos;
9688 }
9689 else {
9690 break;
9691 }
9692 }
9693 result += text.substring(start, pos);
9694 return result;
9695 }
9696 function getIdentifierToken() {
9697 // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9698 var len = tokenValue.length;
9699 if (len >= 2 && len <= 11) {
9700 var ch = tokenValue.charCodeAt(0);
9701 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9702 var keyword = textToKeyword.get(tokenValue);
9703 if (keyword !== undefined) {
9704 return token = keyword;
9705 }
9706 }
9707 }
9708 return token = 78 /* Identifier */;
9709 }
9710 function scanBinaryOrOctalDigits(base) {
9711 var value = "";
9712 // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9713 // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9714 var separatorAllowed = false;
9715 var isPreviousTokenSeparator = false;
9716 while (true) {
9717 var ch = text.charCodeAt(pos);
9718 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9719 if (ch === 95 /* _ */) {
9720 tokenFlags |= 512 /* ContainsSeparator */;
9721 if (separatorAllowed) {
9722 separatorAllowed = false;
9723 isPreviousTokenSeparator = true;
9724 }
9725 else if (isPreviousTokenSeparator) {
9726 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9727 }
9728 else {
9729 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9730 }
9731 pos++;
9732 continue;
9733 }
9734 separatorAllowed = true;
9735 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9736 break;
9737 }
9738 value += text[pos];
9739 pos++;
9740 isPreviousTokenSeparator = false;
9741 }
9742 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9743 // Literal ends with underscore - not allowed
9744 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9745 }
9746 return value;
9747 }
9748 function checkBigIntSuffix() {
9749 if (text.charCodeAt(pos) === 110 /* n */) {
9750 tokenValue += "n";
9751 // Use base 10 instead of base 2 or base 8 for shorter literals
9752 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9753 tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9754 }
9755 pos++;
9756 return 9 /* BigIntLiteral */;
9757 }
9758 else { // not a bigint, so can convert to number in simplified form
9759 // Number() may not support 0b or 0o, so use parseInt() instead
9760 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9761 ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9762 : tokenFlags & 256 /* OctalSpecifier */
9763 ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9764 : +tokenValue;
9765 tokenValue = "" + numericValue;
9766 return 8 /* NumericLiteral */;
9767 }
9768 }
9769 function scan() {
9770 var _a;
9771 startPos = pos;
9772 tokenFlags = 0 /* None */;
9773 var asteriskSeen = false;
9774 while (true) {
9775 tokenPos = pos;
9776 if (pos >= end) {
9777 return token = 1 /* EndOfFileToken */;
9778 }
9779 var ch = codePointAt(text, pos);
9780 // Special handling for shebang
9781 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9782 pos = scanShebangTrivia(text, pos);
9783 if (skipTrivia) {
9784 continue;
9785 }
9786 else {
9787 return token = 6 /* ShebangTrivia */;
9788 }
9789 }
9790 switch (ch) {
9791 case 10 /* lineFeed */:
9792 case 13 /* carriageReturn */:
9793 tokenFlags |= 1 /* PrecedingLineBreak */;
9794 if (skipTrivia) {
9795 pos++;
9796 continue;
9797 }
9798 else {
9799 if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9800 // consume both CR and LF
9801 pos += 2;
9802 }
9803 else {
9804 pos++;
9805 }
9806 return token = 4 /* NewLineTrivia */;
9807 }
9808 case 9 /* tab */:
9809 case 11 /* verticalTab */:
9810 case 12 /* formFeed */:
9811 case 32 /* space */:
9812 case 160 /* nonBreakingSpace */:
9813 case 5760 /* ogham */:
9814 case 8192 /* enQuad */:
9815 case 8193 /* emQuad */:
9816 case 8194 /* enSpace */:
9817 case 8195 /* emSpace */:
9818 case 8196 /* threePerEmSpace */:
9819 case 8197 /* fourPerEmSpace */:
9820 case 8198 /* sixPerEmSpace */:
9821 case 8199 /* figureSpace */:
9822 case 8200 /* punctuationSpace */:
9823 case 8201 /* thinSpace */:
9824 case 8202 /* hairSpace */:
9825 case 8203 /* zeroWidthSpace */:
9826 case 8239 /* narrowNoBreakSpace */:
9827 case 8287 /* mathematicalSpace */:
9828 case 12288 /* ideographicSpace */:
9829 case 65279 /* byteOrderMark */:
9830 if (skipTrivia) {
9831 pos++;
9832 continue;
9833 }
9834 else {
9835 while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9836 pos++;
9837 }
9838 return token = 5 /* WhitespaceTrivia */;
9839 }
9840 case 33 /* exclamation */:
9841 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9842 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9843 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9844 }
9845 return pos += 2, token = 35 /* ExclamationEqualsToken */;
9846 }
9847 pos++;
9848 return token = 53 /* ExclamationToken */;
9849 case 34 /* doubleQuote */:
9850 case 39 /* singleQuote */:
9851 tokenValue = scanString();
9852 return token = 10 /* StringLiteral */;
9853 case 96 /* backtick */:
9854 return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9855 case 37 /* percent */:
9856 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9857 return pos += 2, token = 68 /* PercentEqualsToken */;
9858 }
9859 pos++;
9860 return token = 44 /* PercentToken */;
9861 case 38 /* ampersand */:
9862 if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9863 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9864 return pos += 3, token = 75 /* AmpersandAmpersandEqualsToken */;
9865 }
9866 return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9867 }
9868 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9869 return pos += 2, token = 72 /* AmpersandEqualsToken */;
9870 }
9871 pos++;
9872 return token = 50 /* AmpersandToken */;
9873 case 40 /* openParen */:
9874 pos++;
9875 return token = 20 /* OpenParenToken */;
9876 case 41 /* closeParen */:
9877 pos++;
9878 return token = 21 /* CloseParenToken */;
9879 case 42 /* asterisk */:
9880 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9881 return pos += 2, token = 65 /* AsteriskEqualsToken */;
9882 }
9883 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9884 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9885 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9886 }
9887 return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9888 }
9889 pos++;
9890 if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9891 // decoration at the start of a JSDoc comment line
9892 asteriskSeen = true;
9893 continue;
9894 }
9895 return token = 41 /* AsteriskToken */;
9896 case 43 /* plus */:
9897 if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9898 return pos += 2, token = 45 /* PlusPlusToken */;
9899 }
9900 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9901 return pos += 2, token = 63 /* PlusEqualsToken */;
9902 }
9903 pos++;
9904 return token = 39 /* PlusToken */;
9905 case 44 /* comma */:
9906 pos++;
9907 return token = 27 /* CommaToken */;
9908 case 45 /* minus */:
9909 if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9910 return pos += 2, token = 46 /* MinusMinusToken */;
9911 }
9912 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9913 return pos += 2, token = 64 /* MinusEqualsToken */;
9914 }
9915 pos++;
9916 return token = 40 /* MinusToken */;
9917 case 46 /* dot */:
9918 if (isDigit(text.charCodeAt(pos + 1))) {
9919 tokenValue = scanNumber().value;
9920 return token = 8 /* NumericLiteral */;
9921 }
9922 if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9923 return pos += 3, token = 25 /* DotDotDotToken */;
9924 }
9925 pos++;
9926 return token = 24 /* DotToken */;
9927 case 47 /* slash */:
9928 // Single-line comment
9929 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9930 pos += 2;
9931 while (pos < end) {
9932 if (isLineBreak(text.charCodeAt(pos))) {
9933 break;
9934 }
9935 pos++;
9936 }
9937 commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9938 if (skipTrivia) {
9939 continue;
9940 }
9941 else {
9942 return token = 2 /* SingleLineCommentTrivia */;
9943 }
9944 }
9945 // Multi-line comment
9946 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9947 pos += 2;
9948 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9949 tokenFlags |= 2 /* PrecedingJSDocComment */;
9950 }
9951 var commentClosed = false;
9952 var lastLineStart = tokenPos;
9953 while (pos < end) {
9954 var ch_1 = text.charCodeAt(pos);
9955 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9956 pos += 2;
9957 commentClosed = true;
9958 break;
9959 }
9960 pos++;
9961 if (isLineBreak(ch_1)) {
9962 lastLineStart = pos;
9963 tokenFlags |= 1 /* PrecedingLineBreak */;
9964 }
9965 }
9966 commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9967 if (!commentClosed) {
9968 error(ts.Diagnostics.Asterisk_Slash_expected);
9969 }
9970 if (skipTrivia) {
9971 continue;
9972 }
9973 else {
9974 if (!commentClosed) {
9975 tokenFlags |= 4 /* Unterminated */;
9976 }
9977 return token = 3 /* MultiLineCommentTrivia */;
9978 }
9979 }
9980 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9981 return pos += 2, token = 67 /* SlashEqualsToken */;
9982 }
9983 pos++;
9984 return token = 43 /* SlashToken */;
9985 case 48 /* _0 */:
9986 if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9987 pos += 2;
9988 tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9989 if (!tokenValue) {
9990 error(ts.Diagnostics.Hexadecimal_digit_expected);
9991 tokenValue = "0";
9992 }
9993 tokenValue = "0x" + tokenValue;
9994 tokenFlags |= 64 /* HexSpecifier */;
9995 return token = checkBigIntSuffix();
9996 }
9997 else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9998 pos += 2;
9999 tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
10000 if (!tokenValue) {
10001 error(ts.Diagnostics.Binary_digit_expected);
10002 tokenValue = "0";
10003 }
10004 tokenValue = "0b" + tokenValue;
10005 tokenFlags |= 128 /* BinarySpecifier */;
10006 return token = checkBigIntSuffix();
10007 }
10008 else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
10009 pos += 2;
10010 tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
10011 if (!tokenValue) {
10012 error(ts.Diagnostics.Octal_digit_expected);
10013 tokenValue = "0";
10014 }
10015 tokenValue = "0o" + tokenValue;
10016 tokenFlags |= 256 /* OctalSpecifier */;
10017 return token = checkBigIntSuffix();
10018 }
10019 // Try to parse as an octal
10020 if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
10021 tokenValue = "" + scanOctalDigits();
10022 tokenFlags |= 32 /* Octal */;
10023 return token = 8 /* NumericLiteral */;
10024 }
10025 // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
10026 // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
10027 // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
10028 // falls through
10029 case 49 /* _1 */:
10030 case 50 /* _2 */:
10031 case 51 /* _3 */:
10032 case 52 /* _4 */:
10033 case 53 /* _5 */:
10034 case 54 /* _6 */:
10035 case 55 /* _7 */:
10036 case 56 /* _8 */:
10037 case 57 /* _9 */:
10038 (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
10039 return token;
10040 case 58 /* colon */:
10041 pos++;
10042 return token = 58 /* ColonToken */;
10043 case 59 /* semicolon */:
10044 pos++;
10045 return token = 26 /* SemicolonToken */;
10046 case 60 /* lessThan */:
10047 if (isConflictMarkerTrivia(text, pos)) {
10048 pos = scanConflictMarkerTrivia(text, pos, error);
10049 if (skipTrivia) {
10050 continue;
10051 }
10052 else {
10053 return token = 7 /* ConflictMarkerTrivia */;
10054 }
10055 }
10056 if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
10057 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10058 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
10059 }
10060 return pos += 2, token = 47 /* LessThanLessThanToken */;
10061 }
10062 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10063 return pos += 2, token = 32 /* LessThanEqualsToken */;
10064 }
10065 if (languageVariant === 1 /* JSX */ &&
10066 text.charCodeAt(pos + 1) === 47 /* slash */ &&
10067 text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
10068 return pos += 2, token = 30 /* LessThanSlashToken */;
10069 }
10070 pos++;
10071 return token = 29 /* LessThanToken */;
10072 case 61 /* equals */:
10073 if (isConflictMarkerTrivia(text, pos)) {
10074 pos = scanConflictMarkerTrivia(text, pos, error);
10075 if (skipTrivia) {
10076 continue;
10077 }
10078 else {
10079 return token = 7 /* ConflictMarkerTrivia */;
10080 }
10081 }
10082 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10083 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10084 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
10085 }
10086 return pos += 2, token = 34 /* EqualsEqualsToken */;
10087 }
10088 if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10089 return pos += 2, token = 38 /* EqualsGreaterThanToken */;
10090 }
10091 pos++;
10092 return token = 62 /* EqualsToken */;
10093 case 62 /* greaterThan */:
10094 if (isConflictMarkerTrivia(text, pos)) {
10095 pos = scanConflictMarkerTrivia(text, pos, error);
10096 if (skipTrivia) {
10097 continue;
10098 }
10099 else {
10100 return token = 7 /* ConflictMarkerTrivia */;
10101 }
10102 }
10103 pos++;
10104 return token = 31 /* GreaterThanToken */;
10105 case 63 /* question */:
10106 if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
10107 return pos += 2, token = 28 /* QuestionDotToken */;
10108 }
10109 if (text.charCodeAt(pos + 1) === 63 /* question */) {
10110 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10111 return pos += 3, token = 76 /* QuestionQuestionEqualsToken */;
10112 }
10113 return pos += 2, token = 60 /* QuestionQuestionToken */;
10114 }
10115 pos++;
10116 return token = 57 /* QuestionToken */;
10117 case 91 /* openBracket */:
10118 pos++;
10119 return token = 22 /* OpenBracketToken */;
10120 case 93 /* closeBracket */:
10121 pos++;
10122 return token = 23 /* CloseBracketToken */;
10123 case 94 /* caret */:
10124 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10125 return pos += 2, token = 77 /* CaretEqualsToken */;
10126 }
10127 pos++;
10128 return token = 52 /* CaretToken */;
10129 case 123 /* openBrace */:
10130 pos++;
10131 return token = 18 /* OpenBraceToken */;
10132 case 124 /* bar */:
10133 if (isConflictMarkerTrivia(text, pos)) {
10134 pos = scanConflictMarkerTrivia(text, pos, error);
10135 if (skipTrivia) {
10136 continue;
10137 }
10138 else {
10139 return token = 7 /* ConflictMarkerTrivia */;
10140 }
10141 }
10142 if (text.charCodeAt(pos + 1) === 124 /* bar */) {
10143 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10144 return pos += 3, token = 74 /* BarBarEqualsToken */;
10145 }
10146 return pos += 2, token = 56 /* BarBarToken */;
10147 }
10148 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10149 return pos += 2, token = 73 /* BarEqualsToken */;
10150 }
10151 pos++;
10152 return token = 51 /* BarToken */;
10153 case 125 /* closeBrace */:
10154 pos++;
10155 return token = 19 /* CloseBraceToken */;
10156 case 126 /* tilde */:
10157 pos++;
10158 return token = 54 /* TildeToken */;
10159 case 64 /* at */:
10160 pos++;
10161 return token = 59 /* AtToken */;
10162 case 92 /* backslash */:
10163 var extendedCookedChar = peekExtendedUnicodeEscape();
10164 if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10165 pos += 3;
10166 tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10167 tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10168 return token = getIdentifierToken();
10169 }
10170 var cookedChar = peekUnicodeEscape();
10171 if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10172 pos += 6;
10173 tokenFlags |= 1024 /* UnicodeEscape */;
10174 tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10175 return token = getIdentifierToken();
10176 }
10177 error(ts.Diagnostics.Invalid_character);
10178 pos++;
10179 return token = 0 /* Unknown */;
10180 case 35 /* hash */:
10181 if (pos !== 0 && text[pos + 1] === "!") {
10182 error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
10183 pos++;
10184 return token = 0 /* Unknown */;
10185 }
10186 pos++;
10187 if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
10188 pos++;
10189 while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
10190 pos++;
10191 tokenValue = text.substring(tokenPos, pos);
10192 if (ch === 92 /* backslash */) {
10193 tokenValue += scanIdentifierParts();
10194 }
10195 }
10196 else {
10197 tokenValue = "#";
10198 error(ts.Diagnostics.Invalid_character);
10199 }
10200 return token = 79 /* PrivateIdentifier */;
10201 default:
10202 if (isIdentifierStart(ch, languageVersion)) {
10203 pos += charSize(ch);
10204 while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
10205 pos += charSize(ch);
10206 tokenValue = text.substring(tokenPos, pos);
10207 if (ch === 92 /* backslash */) {
10208 tokenValue += scanIdentifierParts();
10209 }
10210 return token = getIdentifierToken();
10211 }
10212 else if (isWhiteSpaceSingleLine(ch)) {
10213 pos += charSize(ch);
10214 continue;
10215 }
10216 else if (isLineBreak(ch)) {
10217 tokenFlags |= 1 /* PrecedingLineBreak */;
10218 pos += charSize(ch);
10219 continue;
10220 }
10221 error(ts.Diagnostics.Invalid_character);
10222 pos += charSize(ch);
10223 return token = 0 /* Unknown */;
10224 }
10225 }
10226 }
10227 function reScanGreaterToken() {
10228 if (token === 31 /* GreaterThanToken */) {
10229 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
10230 if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10231 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10232 return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
10233 }
10234 return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
10235 }
10236 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10237 return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
10238 }
10239 pos++;
10240 return token = 48 /* GreaterThanGreaterThanToken */;
10241 }
10242 if (text.charCodeAt(pos) === 61 /* equals */) {
10243 pos++;
10244 return token = 33 /* GreaterThanEqualsToken */;
10245 }
10246 }
10247 return token;
10248 }
10249 function reScanAsteriskEqualsToken() {
10250 ts.Debug.assert(token === 65 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
10251 pos = tokenPos + 1;
10252 return token = 62 /* EqualsToken */;
10253 }
10254 function reScanSlashToken() {
10255 if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
10256 var p = tokenPos + 1;
10257 var inEscape = false;
10258 var inCharacterClass = false;
10259 while (true) {
10260 // If we reach the end of a file, or hit a newline, then this is an unterminated
10261 // regex. Report error and return what we have so far.
10262 if (p >= end) {
10263 tokenFlags |= 4 /* Unterminated */;
10264 error(ts.Diagnostics.Unterminated_regular_expression_literal);
10265 break;
10266 }
10267 var ch = text.charCodeAt(p);
10268 if (isLineBreak(ch)) {
10269 tokenFlags |= 4 /* Unterminated */;
10270 error(ts.Diagnostics.Unterminated_regular_expression_literal);
10271 break;
10272 }
10273 if (inEscape) {
10274 // Parsing an escape character;
10275 // reset the flag and just advance to the next char.
10276 inEscape = false;
10277 }
10278 else if (ch === 47 /* slash */ && !inCharacterClass) {
10279 // A slash within a character class is permissible,
10280 // but in general it signals the end of the regexp literal.
10281 p++;
10282 break;
10283 }
10284 else if (ch === 91 /* openBracket */) {
10285 inCharacterClass = true;
10286 }
10287 else if (ch === 92 /* backslash */) {
10288 inEscape = true;
10289 }
10290 else if (ch === 93 /* closeBracket */) {
10291 inCharacterClass = false;
10292 }
10293 p++;
10294 }
10295 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
10296 p++;
10297 }
10298 pos = p;
10299 tokenValue = text.substring(tokenPos, pos);
10300 token = 13 /* RegularExpressionLiteral */;
10301 }
10302 return token;
10303 }
10304 function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
10305 var type = getDirectiveFromComment(text, commentDirectiveRegEx);
10306 if (type === undefined) {
10307 return commentDirectives;
10308 }
10309 return ts.append(commentDirectives, {
10310 range: { pos: lineStart, end: pos },
10311 type: type,
10312 });
10313 }
10314 function getDirectiveFromComment(text, commentDirectiveRegEx) {
10315 var match = commentDirectiveRegEx.exec(text);
10316 if (!match) {
10317 return undefined;
10318 }
10319 switch (match[1]) {
10320 case "ts-expect-error":
10321 return 0 /* ExpectError */;
10322 case "ts-ignore":
10323 return 1 /* Ignore */;
10324 }
10325 return undefined;
10326 }
10327 /**
10328 * Unconditionally back up and scan a template expression portion.
10329 */
10330 function reScanTemplateToken(isTaggedTemplate) {
10331 ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
10332 pos = tokenPos;
10333 return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
10334 }
10335 function reScanTemplateHeadOrNoSubstitutionTemplate() {
10336 pos = tokenPos;
10337 return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
10338 }
10339 function reScanJsxToken() {
10340 pos = tokenPos = startPos;
10341 return token = scanJsxToken();
10342 }
10343 function reScanLessThanToken() {
10344 if (token === 47 /* LessThanLessThanToken */) {
10345 pos = tokenPos + 1;
10346 return token = 29 /* LessThanToken */;
10347 }
10348 return token;
10349 }
10350 function reScanQuestionToken() {
10351 ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10352 pos = tokenPos + 1;
10353 return token = 57 /* QuestionToken */;
10354 }
10355 function scanJsxToken() {
10356 startPos = tokenPos = pos;
10357 if (pos >= end) {
10358 return token = 1 /* EndOfFileToken */;
10359 }
10360 var char = text.charCodeAt(pos);
10361 if (char === 60 /* lessThan */) {
10362 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10363 pos += 2;
10364 return token = 30 /* LessThanSlashToken */;
10365 }
10366 pos++;
10367 return token = 29 /* LessThanToken */;
10368 }
10369 if (char === 123 /* openBrace */) {
10370 pos++;
10371 return token = 18 /* OpenBraceToken */;
10372 }
10373 // First non-whitespace character on this line.
10374 var firstNonWhitespace = 0;
10375 var lastNonWhitespace = -1;
10376 // These initial values are special because the first line is:
10377 // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10378 while (pos < end) {
10379 // We want to keep track of the last non-whitespace (but including
10380 // newlines character for hitting the end of the JSX Text region)
10381 if (!isWhiteSpaceSingleLine(char)) {
10382 lastNonWhitespace = pos;
10383 }
10384 char = text.charCodeAt(pos);
10385 if (char === 123 /* openBrace */) {
10386 break;
10387 }
10388 if (char === 60 /* lessThan */) {
10389 if (isConflictMarkerTrivia(text, pos)) {
10390 pos = scanConflictMarkerTrivia(text, pos, error);
10391 return token = 7 /* ConflictMarkerTrivia */;
10392 }
10393 break;
10394 }
10395 if (char === 62 /* greaterThan */) {
10396 error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10397 }
10398 if (char === 125 /* closeBrace */) {
10399 error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10400 }
10401 if (lastNonWhitespace > 0)
10402 lastNonWhitespace++;
10403 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10404 // i.e (- : whitespace)
10405 // <div>----
10406 // </div> becomes <div></div>
10407 //
10408 // <div>----</div> becomes <div>----</div>
10409 if (isLineBreak(char) && firstNonWhitespace === 0) {
10410 firstNonWhitespace = -1;
10411 }
10412 else if (!isWhiteSpaceLike(char)) {
10413 firstNonWhitespace = pos;
10414 }
10415 pos++;
10416 }
10417 var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10418 tokenValue = text.substring(startPos, endPosition);
10419 return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10420 }
10421 // Scans a JSX identifier; these differ from normal identifiers in that
10422 // they allow dashes
10423 function scanJsxIdentifier() {
10424 if (tokenIsIdentifierOrKeyword(token)) {
10425 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10426 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10427 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10428 while (pos < end) {
10429 var ch = text.charCodeAt(pos);
10430 if (ch === 45 /* minus */) {
10431 tokenValue += "-";
10432 pos++;
10433 continue;
10434 }
10435 var oldPos = pos;
10436 tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10437 if (pos === oldPos) {
10438 break;
10439 }
10440 }
10441 }
10442 return token;
10443 }
10444 function scanJsxAttributeValue() {
10445 startPos = pos;
10446 switch (text.charCodeAt(pos)) {
10447 case 34 /* doubleQuote */:
10448 case 39 /* singleQuote */:
10449 tokenValue = scanString(/*jsxAttributeString*/ true);
10450 return token = 10 /* StringLiteral */;
10451 default:
10452 // If this scans anything other than `{`, it's a parse error.
10453 return scan();
10454 }
10455 }
10456 function reScanJsxAttributeValue() {
10457 pos = tokenPos = startPos;
10458 return scanJsxAttributeValue();
10459 }
10460 function scanJsDocToken() {
10461 startPos = tokenPos = pos;
10462 tokenFlags = 0 /* None */;
10463 if (pos >= end) {
10464 return token = 1 /* EndOfFileToken */;
10465 }
10466 var ch = codePointAt(text, pos);
10467 pos += charSize(ch);
10468 switch (ch) {
10469 case 9 /* tab */:
10470 case 11 /* verticalTab */:
10471 case 12 /* formFeed */:
10472 case 32 /* space */:
10473 while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10474 pos++;
10475 }
10476 return token = 5 /* WhitespaceTrivia */;
10477 case 64 /* at */:
10478 return token = 59 /* AtToken */;
10479 case 13 /* carriageReturn */:
10480 if (text.charCodeAt(pos) === 10 /* lineFeed */) {
10481 pos++;
10482 }
10483 // falls through
10484 case 10 /* lineFeed */:
10485 tokenFlags |= 1 /* PrecedingLineBreak */;
10486 return token = 4 /* NewLineTrivia */;
10487 case 42 /* asterisk */:
10488 return token = 41 /* AsteriskToken */;
10489 case 123 /* openBrace */:
10490 return token = 18 /* OpenBraceToken */;
10491 case 125 /* closeBrace */:
10492 return token = 19 /* CloseBraceToken */;
10493 case 91 /* openBracket */:
10494 return token = 22 /* OpenBracketToken */;
10495 case 93 /* closeBracket */:
10496 return token = 23 /* CloseBracketToken */;
10497 case 60 /* lessThan */:
10498 return token = 29 /* LessThanToken */;
10499 case 62 /* greaterThan */:
10500 return token = 31 /* GreaterThanToken */;
10501 case 61 /* equals */:
10502 return token = 62 /* EqualsToken */;
10503 case 44 /* comma */:
10504 return token = 27 /* CommaToken */;
10505 case 46 /* dot */:
10506 return token = 24 /* DotToken */;
10507 case 96 /* backtick */:
10508 return token = 61 /* BacktickToken */;
10509 case 92 /* backslash */:
10510 pos--;
10511 var extendedCookedChar = peekExtendedUnicodeEscape();
10512 if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10513 pos += 3;
10514 tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10515 tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10516 return token = getIdentifierToken();
10517 }
10518 var cookedChar = peekUnicodeEscape();
10519 if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10520 pos += 6;
10521 tokenFlags |= 1024 /* UnicodeEscape */;
10522 tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10523 return token = getIdentifierToken();
10524 }
10525 pos++;
10526 return token = 0 /* Unknown */;
10527 }
10528 if (isIdentifierStart(ch, languageVersion)) {
10529 var char = ch;
10530 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10531 pos += charSize(char);
10532 tokenValue = text.substring(tokenPos, pos);
10533 if (char === 92 /* backslash */) {
10534 tokenValue += scanIdentifierParts();
10535 }
10536 return token = getIdentifierToken();
10537 }
10538 else {
10539 return token = 0 /* Unknown */;
10540 }
10541 }
10542 function speculationHelper(callback, isLookahead) {
10543 var savePos = pos;
10544 var saveStartPos = startPos;
10545 var saveTokenPos = tokenPos;
10546 var saveToken = token;
10547 var saveTokenValue = tokenValue;
10548 var saveTokenFlags = tokenFlags;
10549 var result = callback();
10550 // If our callback returned something 'falsy' or we're just looking ahead,
10551 // then unconditionally restore us to where we were.
10552 if (!result || isLookahead) {
10553 pos = savePos;
10554 startPos = saveStartPos;
10555 tokenPos = saveTokenPos;
10556 token = saveToken;
10557 tokenValue = saveTokenValue;
10558 tokenFlags = saveTokenFlags;
10559 }
10560 return result;
10561 }
10562 function scanRange(start, length, callback) {
10563 var saveEnd = end;
10564 var savePos = pos;
10565 var saveStartPos = startPos;
10566 var saveTokenPos = tokenPos;
10567 var saveToken = token;
10568 var saveTokenValue = tokenValue;
10569 var saveTokenFlags = tokenFlags;
10570 var saveErrorExpectations = commentDirectives;
10571 setText(text, start, length);
10572 var result = callback();
10573 end = saveEnd;
10574 pos = savePos;
10575 startPos = saveStartPos;
10576 tokenPos = saveTokenPos;
10577 token = saveToken;
10578 tokenValue = saveTokenValue;
10579 tokenFlags = saveTokenFlags;
10580 commentDirectives = saveErrorExpectations;
10581 return result;
10582 }
10583 function lookAhead(callback) {
10584 return speculationHelper(callback, /*isLookahead*/ true);
10585 }
10586 function tryScan(callback) {
10587 return speculationHelper(callback, /*isLookahead*/ false);
10588 }
10589 function getText() {
10590 return text;
10591 }
10592 function clearCommentDirectives() {
10593 commentDirectives = undefined;
10594 }
10595 function setText(newText, start, length) {
10596 text = newText || "";
10597 end = length === undefined ? text.length : start + length;
10598 setTextPos(start || 0);
10599 }
10600 function setOnError(errorCallback) {
10601 onError = errorCallback;
10602 }
10603 function setScriptTarget(scriptTarget) {
10604 languageVersion = scriptTarget;
10605 }
10606 function setLanguageVariant(variant) {
10607 languageVariant = variant;
10608 }
10609 function setTextPos(textPos) {
10610 ts.Debug.assert(textPos >= 0);
10611 pos = textPos;
10612 startPos = textPos;
10613 tokenPos = textPos;
10614 token = 0 /* Unknown */;
10615 tokenValue = undefined;
10616 tokenFlags = 0 /* None */;
10617 }
10618 function setInJSDocType(inType) {
10619 inJSDocType += inType ? 1 : -1;
10620 }
10621 }
10622 ts.createScanner = createScanner;
10623 /* @internal */
10624 var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10625 // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10626 var size = str.length;
10627 // Account for out-of-bounds indices:
10628 if (i < 0 || i >= size) {
10629 return undefined; // String.codePointAt returns `undefined` for OOB indexes
10630 }
10631 // Get the first code unit
10632 var first = str.charCodeAt(i);
10633 // check if it’s the start of a surrogate pair
10634 if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10635 var second = str.charCodeAt(i + 1);
10636 if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10637 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10638 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10639 }
10640 }
10641 return first;
10642 };
10643 /* @internal */
10644 function charSize(ch) {
10645 if (ch >= 0x10000) {
10646 return 2;
10647 }
10648 return 1;
10649 }
10650 // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10651 function utf16EncodeAsStringFallback(codePoint) {
10652 ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10653 if (codePoint <= 65535) {
10654 return String.fromCharCode(codePoint);
10655 }
10656 var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10657 var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10658 return String.fromCharCode(codeUnit1, codeUnit2);
10659 }
10660 var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10661 /* @internal */
10662 function utf16EncodeAsString(codePoint) {
10663 return utf16EncodeAsStringWorker(codePoint);
10664 }
10665 ts.utf16EncodeAsString = utf16EncodeAsString;
10666})(ts || (ts = {}));
10667var ts;
10668(function (ts) {
10669 function isExternalModuleNameRelative(moduleName) {
10670 // TypeScript 1.0 spec (April 2014): 11.2.1
10671 // An external module name is "relative" if the first term is "." or "..".
10672 // 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.
10673 return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10674 }
10675 ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10676 function sortAndDeduplicateDiagnostics(diagnostics) {
10677 return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10678 }
10679 ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10680 function getDefaultLibFileName(options) {
10681 switch (options.target) {
10682 case 99 /* ESNext */:
10683 return "lib.esnext.full.d.ts";
10684 case 7 /* ES2020 */:
10685 return "lib.es2020.full.d.ts";
10686 case 6 /* ES2019 */:
10687 return "lib.es2019.full.d.ts";
10688 case 5 /* ES2018 */:
10689 return "lib.es2018.full.d.ts";
10690 case 4 /* ES2017 */:
10691 return "lib.es2017.full.d.ts";
10692 case 3 /* ES2016 */:
10693 return "lib.es2016.full.d.ts";
10694 case 2 /* ES2015 */:
10695 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10696 default:
10697 return "lib.d.ts";
10698 }
10699 }
10700 ts.getDefaultLibFileName = getDefaultLibFileName;
10701 function textSpanEnd(span) {
10702 return span.start + span.length;
10703 }
10704 ts.textSpanEnd = textSpanEnd;
10705 function textSpanIsEmpty(span) {
10706 return span.length === 0;
10707 }
10708 ts.textSpanIsEmpty = textSpanIsEmpty;
10709 function textSpanContainsPosition(span, position) {
10710 return position >= span.start && position < textSpanEnd(span);
10711 }
10712 ts.textSpanContainsPosition = textSpanContainsPosition;
10713 /* @internal */
10714 function textRangeContainsPositionInclusive(span, position) {
10715 return position >= span.pos && position <= span.end;
10716 }
10717 ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10718 // Returns true if 'span' contains 'other'.
10719 function textSpanContainsTextSpan(span, other) {
10720 return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10721 }
10722 ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10723 function textSpanOverlapsWith(span, other) {
10724 return textSpanOverlap(span, other) !== undefined;
10725 }
10726 ts.textSpanOverlapsWith = textSpanOverlapsWith;
10727 function textSpanOverlap(span1, span2) {
10728 var overlap = textSpanIntersection(span1, span2);
10729 return overlap && overlap.length === 0 ? undefined : overlap;
10730 }
10731 ts.textSpanOverlap = textSpanOverlap;
10732 function textSpanIntersectsWithTextSpan(span, other) {
10733 return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10734 }
10735 ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10736 function textSpanIntersectsWith(span, start, length) {
10737 return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10738 }
10739 ts.textSpanIntersectsWith = textSpanIntersectsWith;
10740 function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10741 var end1 = start1 + length1;
10742 var end2 = start2 + length2;
10743 return start2 <= end1 && end2 >= start1;
10744 }
10745 ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10746 function textSpanIntersectsWithPosition(span, position) {
10747 return position <= textSpanEnd(span) && position >= span.start;
10748 }
10749 ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10750 function textSpanIntersection(span1, span2) {
10751 var start = Math.max(span1.start, span2.start);
10752 var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10753 return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10754 }
10755 ts.textSpanIntersection = textSpanIntersection;
10756 function createTextSpan(start, length) {
10757 if (start < 0) {
10758 throw new Error("start < 0");
10759 }
10760 if (length < 0) {
10761 throw new Error("length < 0");
10762 }
10763 return { start: start, length: length };
10764 }
10765 ts.createTextSpan = createTextSpan;
10766 function createTextSpanFromBounds(start, end) {
10767 return createTextSpan(start, end - start);
10768 }
10769 ts.createTextSpanFromBounds = createTextSpanFromBounds;
10770 function textChangeRangeNewSpan(range) {
10771 return createTextSpan(range.span.start, range.newLength);
10772 }
10773 ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10774 function textChangeRangeIsUnchanged(range) {
10775 return textSpanIsEmpty(range.span) && range.newLength === 0;
10776 }
10777 ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10778 function createTextChangeRange(span, newLength) {
10779 if (newLength < 0) {
10780 throw new Error("newLength < 0");
10781 }
10782 return { span: span, newLength: newLength };
10783 }
10784 ts.createTextChangeRange = createTextChangeRange;
10785 ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10786 /**
10787 * Called to merge all the changes that occurred across several versions of a script snapshot
10788 * into a single change. i.e. if a user keeps making successive edits to a script we will
10789 * have a text change from V1 to V2, V2 to V3, ..., Vn.
10790 *
10791 * This function will then merge those changes into a single change range valid between V1 and
10792 * Vn.
10793 */
10794 function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10795 if (changes.length === 0) {
10796 return ts.unchangedTextChangeRange;
10797 }
10798 if (changes.length === 1) {
10799 return changes[0];
10800 }
10801 // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10802 // as it makes things much easier to reason about.
10803 var change0 = changes[0];
10804 var oldStartN = change0.span.start;
10805 var oldEndN = textSpanEnd(change0.span);
10806 var newEndN = oldStartN + change0.newLength;
10807 for (var i = 1; i < changes.length; i++) {
10808 var nextChange = changes[i];
10809 // Consider the following case:
10810 // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
10811 // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
10812 // i.e. the span starting at 30 with length 30 is increased to length 40.
10813 //
10814 // 0 10 20 30 40 50 60 70 80 90 100
10815 // -------------------------------------------------------------------------------------------------------
10816 // | /
10817 // | /----
10818 // T1 | /----
10819 // | /----
10820 // | /----
10821 // -------------------------------------------------------------------------------------------------------
10822 // | \
10823 // | \
10824 // T2 | \
10825 // | \
10826 // | \
10827 // -------------------------------------------------------------------------------------------------------
10828 //
10829 // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
10830 // it's just the min of the old and new starts. i.e.:
10831 //
10832 // 0 10 20 30 40 50 60 70 80 90 100
10833 // ------------------------------------------------------------*------------------------------------------
10834 // | /
10835 // | /----
10836 // T1 | /----
10837 // | /----
10838 // | /----
10839 // ----------------------------------------$-------------------$------------------------------------------
10840 // . | \
10841 // . | \
10842 // T2 . | \
10843 // . | \
10844 // . | \
10845 // ----------------------------------------------------------------------*--------------------------------
10846 //
10847 // (Note the dots represent the newly inferred start.
10848 // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
10849 // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10850 // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
10851 // means:
10852 //
10853 // 0 10 20 30 40 50 60 70 80 90 100
10854 // --------------------------------------------------------------------------------*----------------------
10855 // | /
10856 // | /----
10857 // T1 | /----
10858 // | /----
10859 // | /----
10860 // ------------------------------------------------------------$------------------------------------------
10861 // . | \
10862 // . | \
10863 // T2 . | \
10864 // . | \
10865 // . | \
10866 // ----------------------------------------------------------------------*--------------------------------
10867 //
10868 // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10869 // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
10870 // that's the same as if we started at char 80 instead of 60.
10871 //
10872 // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
10873 // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10874 // first.
10875 //
10876 // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10877 // semantics: { { start: 10, length: 70 }, newLength: 60 }
10878 //
10879 // The math then works out as follows.
10880 // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10881 // final result like so:
10882 //
10883 // {
10884 // oldStart3: Min(oldStart1, oldStart2),
10885 // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10886 // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10887 // }
10888 var oldStart1 = oldStartN;
10889 var oldEnd1 = oldEndN;
10890 var newEnd1 = newEndN;
10891 var oldStart2 = nextChange.span.start;
10892 var oldEnd2 = textSpanEnd(nextChange.span);
10893 var newEnd2 = oldStart2 + nextChange.newLength;
10894 oldStartN = Math.min(oldStart1, oldStart2);
10895 oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10896 newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10897 }
10898 return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10899 }
10900 ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10901 function getTypeParameterOwner(d) {
10902 if (d && d.kind === 158 /* TypeParameter */) {
10903 for (var current = d; current; current = current.parent) {
10904 if (isFunctionLike(current) || isClassLike(current) || current.kind === 250 /* InterfaceDeclaration */) {
10905 return current;
10906 }
10907 }
10908 }
10909 }
10910 ts.getTypeParameterOwner = getTypeParameterOwner;
10911 function isParameterPropertyDeclaration(node, parent) {
10912 return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 165 /* Constructor */;
10913 }
10914 ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10915 function isEmptyBindingPattern(node) {
10916 if (isBindingPattern(node)) {
10917 return ts.every(node.elements, isEmptyBindingElement);
10918 }
10919 return false;
10920 }
10921 ts.isEmptyBindingPattern = isEmptyBindingPattern;
10922 function isEmptyBindingElement(node) {
10923 if (ts.isOmittedExpression(node)) {
10924 return true;
10925 }
10926 return isEmptyBindingPattern(node.name);
10927 }
10928 ts.isEmptyBindingElement = isEmptyBindingElement;
10929 function walkUpBindingElementsAndPatterns(binding) {
10930 var node = binding.parent;
10931 while (ts.isBindingElement(node.parent)) {
10932 node = node.parent.parent;
10933 }
10934 return node.parent;
10935 }
10936 ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10937 function getCombinedFlags(node, getFlags) {
10938 if (ts.isBindingElement(node)) {
10939 node = walkUpBindingElementsAndPatterns(node);
10940 }
10941 var flags = getFlags(node);
10942 if (node.kind === 246 /* VariableDeclaration */) {
10943 node = node.parent;
10944 }
10945 if (node && node.kind === 247 /* VariableDeclarationList */) {
10946 flags |= getFlags(node);
10947 node = node.parent;
10948 }
10949 if (node && node.kind === 229 /* VariableStatement */) {
10950 flags |= getFlags(node);
10951 }
10952 return flags;
10953 }
10954 function getCombinedModifierFlags(node) {
10955 return getCombinedFlags(node, ts.getEffectiveModifierFlags);
10956 }
10957 ts.getCombinedModifierFlags = getCombinedModifierFlags;
10958 /* @internal */
10959 function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
10960 return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
10961 }
10962 ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
10963 // Returns the node flags for this node and all relevant parent nodes. This is done so that
10964 // nodes like variable declarations and binding elements can returned a view of their flags
10965 // that includes the modifiers from their container. i.e. flags like export/declare aren't
10966 // stored on the variable declaration directly, but on the containing variable statement
10967 // (if it has one). Similarly, flags for let/const are store on the variable declaration
10968 // list. By calling this function, all those flags are combined so that the client can treat
10969 // the node as if it actually had those flags.
10970 function getCombinedNodeFlags(node) {
10971 return getCombinedFlags(node, function (n) { return n.flags; });
10972 }
10973 ts.getCombinedNodeFlags = getCombinedNodeFlags;
10974 /**
10975 * Checks to see if the locale is in the appropriate format,
10976 * and if it is, attempts to set the appropriate language.
10977 */
10978 function validateLocaleAndSetLanguage(locale, sys, errors) {
10979 var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10980 if (!matchResult) {
10981 if (errors) {
10982 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10983 }
10984 return;
10985 }
10986 var language = matchResult[1];
10987 var territory = matchResult[3];
10988 // First try the entire locale, then fall back to just language if that's all we have.
10989 // Either ways do not fail, and fallback to the English diagnostic strings.
10990 if (!trySetLanguageAndTerritory(language, territory, errors)) {
10991 trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10992 }
10993 // Set the UI locale for string collation
10994 ts.setUILocale(locale);
10995 function trySetLanguageAndTerritory(language, territory, errors) {
10996 var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10997 var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10998 var filePath = ts.combinePaths(containingDirectoryPath, language);
10999 if (territory) {
11000 filePath = filePath + "-" + territory;
11001 }
11002 filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
11003 if (!sys.fileExists(filePath)) {
11004 return false;
11005 }
11006 // TODO: Add codePage support for readFile?
11007 var fileContents = "";
11008 try {
11009 fileContents = sys.readFile(filePath);
11010 }
11011 catch (e) {
11012 if (errors) {
11013 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
11014 }
11015 return false;
11016 }
11017 try {
11018 // this is a global mutation (or live binding update)!
11019 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
11020 }
11021 catch (_a) {
11022 if (errors) {
11023 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
11024 }
11025 return false;
11026 }
11027 return true;
11028 }
11029 }
11030 ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
11031 function getOriginalNode(node, nodeTest) {
11032 if (node) {
11033 while (node.original !== undefined) {
11034 node = node.original;
11035 }
11036 }
11037 return !nodeTest || nodeTest(node) ? node : undefined;
11038 }
11039 ts.getOriginalNode = getOriginalNode;
11040 /**
11041 * Gets a value indicating whether a node originated in the parse tree.
11042 *
11043 * @param node The node to test.
11044 */
11045 function isParseTreeNode(node) {
11046 return (node.flags & 8 /* Synthesized */) === 0;
11047 }
11048 ts.isParseTreeNode = isParseTreeNode;
11049 function getParseTreeNode(node, nodeTest) {
11050 if (node === undefined || isParseTreeNode(node)) {
11051 return node;
11052 }
11053 node = node.original;
11054 while (node) {
11055 if (isParseTreeNode(node)) {
11056 return !nodeTest || nodeTest(node) ? node : undefined;
11057 }
11058 node = node.original;
11059 }
11060 }
11061 ts.getParseTreeNode = getParseTreeNode;
11062 /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
11063 function escapeLeadingUnderscores(identifier) {
11064 return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
11065 }
11066 ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
11067 /**
11068 * Remove extra underscore from escaped identifier text content.
11069 *
11070 * @param identifier The escaped identifier text.
11071 * @returns The unescaped identifier text.
11072 */
11073 function unescapeLeadingUnderscores(identifier) {
11074 var id = identifier;
11075 return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
11076 }
11077 ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
11078 function idText(identifierOrPrivateName) {
11079 return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
11080 }
11081 ts.idText = idText;
11082 function symbolName(symbol) {
11083 if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
11084 return idText(symbol.valueDeclaration.name);
11085 }
11086 return unescapeLeadingUnderscores(symbol.escapedName);
11087 }
11088 ts.symbolName = symbolName;
11089 /**
11090 * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
11091 * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
11092 * will be merged with)
11093 */
11094 function nameForNamelessJSDocTypedef(declaration) {
11095 var hostNode = declaration.parent.parent;
11096 if (!hostNode) {
11097 return undefined;
11098 }
11099 // Covers classes, functions - any named declaration host node
11100 if (isDeclaration(hostNode)) {
11101 return getDeclarationIdentifier(hostNode);
11102 }
11103 // Covers remaining cases (returning undefined if none match).
11104 switch (hostNode.kind) {
11105 case 229 /* VariableStatement */:
11106 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
11107 return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
11108 }
11109 break;
11110 case 230 /* ExpressionStatement */:
11111 var expr = hostNode.expression;
11112 if (expr.kind === 213 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
11113 expr = expr.left;
11114 }
11115 switch (expr.kind) {
11116 case 198 /* PropertyAccessExpression */:
11117 return expr.name;
11118 case 199 /* ElementAccessExpression */:
11119 var arg = expr.argumentExpression;
11120 if (ts.isIdentifier(arg)) {
11121 return arg;
11122 }
11123 }
11124 break;
11125 case 204 /* ParenthesizedExpression */: {
11126 return getDeclarationIdentifier(hostNode.expression);
11127 }
11128 case 242 /* LabeledStatement */: {
11129 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
11130 return getDeclarationIdentifier(hostNode.statement);
11131 }
11132 break;
11133 }
11134 }
11135 }
11136 function getDeclarationIdentifier(node) {
11137 var name = getNameOfDeclaration(node);
11138 return name && ts.isIdentifier(name) ? name : undefined;
11139 }
11140 /** @internal */
11141 function nodeHasName(statement, name) {
11142 if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
11143 return true;
11144 }
11145 if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
11146 return true;
11147 }
11148 return false;
11149 }
11150 ts.nodeHasName = nodeHasName;
11151 function getNameOfJSDocTypedef(declaration) {
11152 return declaration.name || nameForNamelessJSDocTypedef(declaration);
11153 }
11154 ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
11155 /** @internal */
11156 function isNamedDeclaration(node) {
11157 return !!node.name; // A 'name' property should always be a DeclarationName.
11158 }
11159 ts.isNamedDeclaration = isNamedDeclaration;
11160 /** @internal */
11161 function getNonAssignedNameOfDeclaration(declaration) {
11162 switch (declaration.kind) {
11163 case 78 /* Identifier */:
11164 return declaration;
11165 case 328 /* JSDocPropertyTag */:
11166 case 322 /* JSDocParameterTag */: {
11167 var name = declaration.name;
11168 if (name.kind === 156 /* QualifiedName */) {
11169 return name.right;
11170 }
11171 break;
11172 }
11173 case 200 /* CallExpression */:
11174 case 213 /* BinaryExpression */: {
11175 var expr_1 = declaration;
11176 switch (ts.getAssignmentDeclarationKind(expr_1)) {
11177 case 1 /* ExportsProperty */:
11178 case 4 /* ThisProperty */:
11179 case 5 /* Property */:
11180 case 3 /* PrototypeProperty */:
11181 return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
11182 case 7 /* ObjectDefinePropertyValue */:
11183 case 8 /* ObjectDefinePropertyExports */:
11184 case 9 /* ObjectDefinePrototypeProperty */:
11185 return expr_1.arguments[1];
11186 default:
11187 return undefined;
11188 }
11189 }
11190 case 327 /* JSDocTypedefTag */:
11191 return getNameOfJSDocTypedef(declaration);
11192 case 321 /* JSDocEnumTag */:
11193 return nameForNamelessJSDocTypedef(declaration);
11194 case 263 /* ExportAssignment */: {
11195 var expression = declaration.expression;
11196 return ts.isIdentifier(expression) ? expression : undefined;
11197 }
11198 case 199 /* ElementAccessExpression */:
11199 var expr = declaration;
11200 if (ts.isBindableStaticElementAccessExpression(expr)) {
11201 return expr.argumentExpression;
11202 }
11203 }
11204 return declaration.name;
11205 }
11206 ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
11207 function getNameOfDeclaration(declaration) {
11208 if (declaration === undefined)
11209 return undefined;
11210 return getNonAssignedNameOfDeclaration(declaration) ||
11211 (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
11212 }
11213 ts.getNameOfDeclaration = getNameOfDeclaration;
11214 /*@internal*/
11215 function getAssignedName(node) {
11216 if (!node.parent) {
11217 return undefined;
11218 }
11219 else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
11220 return node.parent.name;
11221 }
11222 else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
11223 if (ts.isIdentifier(node.parent.left)) {
11224 return node.parent.left;
11225 }
11226 else if (ts.isAccessExpression(node.parent.left)) {
11227 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
11228 }
11229 }
11230 else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
11231 return node.parent.name;
11232 }
11233 }
11234 ts.getAssignedName = getAssignedName;
11235 function getJSDocParameterTagsWorker(param, noCache) {
11236 if (param.name) {
11237 if (ts.isIdentifier(param.name)) {
11238 var name_1 = param.name.escapedText;
11239 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
11240 }
11241 else {
11242 var i = param.parent.parameters.indexOf(param);
11243 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
11244 var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
11245 if (i < paramTags.length) {
11246 return [paramTags[i]];
11247 }
11248 }
11249 }
11250 // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
11251 return ts.emptyArray;
11252 }
11253 /**
11254 * Gets the JSDoc parameter tags for the node if present.
11255 *
11256 * @remarks Returns any JSDoc param tag whose name matches the provided
11257 * parameter, whether a param tag on a containing function
11258 * expression, or a param tag on a variable declaration whose
11259 * initializer is the containing function. The tags closest to the
11260 * node are returned first, so in the previous example, the param
11261 * tag on the containing function expression would be first.
11262 *
11263 * For binding patterns, parameter tags are matched by position.
11264 */
11265 function getJSDocParameterTags(param) {
11266 return getJSDocParameterTagsWorker(param, /*noCache*/ false);
11267 }
11268 ts.getJSDocParameterTags = getJSDocParameterTags;
11269 /* @internal */
11270 function getJSDocParameterTagsNoCache(param) {
11271 return getJSDocParameterTagsWorker(param, /*noCache*/ true);
11272 }
11273 ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
11274 function getJSDocTypeParameterTagsWorker(param, noCache) {
11275 var name = param.name.escapedText;
11276 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
11277 return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
11278 });
11279 }
11280 /**
11281 * Gets the JSDoc type parameter tags for the node if present.
11282 *
11283 * @remarks Returns any JSDoc template tag whose names match the provided
11284 * parameter, whether a template tag on a containing function
11285 * expression, or a template tag on a variable declaration whose
11286 * initializer is the containing function. The tags closest to the
11287 * node are returned first, so in the previous example, the template
11288 * tag on the containing function expression would be first.
11289 */
11290 function getJSDocTypeParameterTags(param) {
11291 return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
11292 }
11293 ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
11294 /* @internal */
11295 function getJSDocTypeParameterTagsNoCache(param) {
11296 return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
11297 }
11298 ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
11299 /**
11300 * Return true if the node has JSDoc parameter tags.
11301 *
11302 * @remarks Includes parameter tags that are not directly on the node,
11303 * for example on a variable declaration whose initializer is a function expression.
11304 */
11305 function hasJSDocParameterTags(node) {
11306 return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
11307 }
11308 ts.hasJSDocParameterTags = hasJSDocParameterTags;
11309 /** Gets the JSDoc augments tag for the node if present */
11310 function getJSDocAugmentsTag(node) {
11311 return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
11312 }
11313 ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
11314 /** Gets the JSDoc implements tags for the node if present */
11315 function getJSDocImplementsTags(node) {
11316 return getAllJSDocTags(node, ts.isJSDocImplementsTag);
11317 }
11318 ts.getJSDocImplementsTags = getJSDocImplementsTags;
11319 /** Gets the JSDoc class tag for the node if present */
11320 function getJSDocClassTag(node) {
11321 return getFirstJSDocTag(node, ts.isJSDocClassTag);
11322 }
11323 ts.getJSDocClassTag = getJSDocClassTag;
11324 /** Gets the JSDoc public tag for the node if present */
11325 function getJSDocPublicTag(node) {
11326 return getFirstJSDocTag(node, ts.isJSDocPublicTag);
11327 }
11328 ts.getJSDocPublicTag = getJSDocPublicTag;
11329 /*@internal*/
11330 function getJSDocPublicTagNoCache(node) {
11331 return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
11332 }
11333 ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
11334 /** Gets the JSDoc private tag for the node if present */
11335 function getJSDocPrivateTag(node) {
11336 return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
11337 }
11338 ts.getJSDocPrivateTag = getJSDocPrivateTag;
11339 /*@internal*/
11340 function getJSDocPrivateTagNoCache(node) {
11341 return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
11342 }
11343 ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
11344 /** Gets the JSDoc protected tag for the node if present */
11345 function getJSDocProtectedTag(node) {
11346 return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
11347 }
11348 ts.getJSDocProtectedTag = getJSDocProtectedTag;
11349 /*@internal*/
11350 function getJSDocProtectedTagNoCache(node) {
11351 return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
11352 }
11353 ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
11354 /** Gets the JSDoc protected tag for the node if present */
11355 function getJSDocReadonlyTag(node) {
11356 return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
11357 }
11358 ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
11359 /*@internal*/
11360 function getJSDocReadonlyTagNoCache(node) {
11361 return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
11362 }
11363 ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
11364 /** Gets the JSDoc deprecated tag for the node if present */
11365 function getJSDocDeprecatedTag(node) {
11366 return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
11367 }
11368 ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
11369 /*@internal */
11370 function getJSDocDeprecatedTagNoCache(node) {
11371 return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
11372 }
11373 ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
11374 /** Gets the JSDoc enum tag for the node if present */
11375 function getJSDocEnumTag(node) {
11376 return getFirstJSDocTag(node, ts.isJSDocEnumTag);
11377 }
11378 ts.getJSDocEnumTag = getJSDocEnumTag;
11379 /** Gets the JSDoc this tag for the node if present */
11380 function getJSDocThisTag(node) {
11381 return getFirstJSDocTag(node, ts.isJSDocThisTag);
11382 }
11383 ts.getJSDocThisTag = getJSDocThisTag;
11384 /** Gets the JSDoc return tag for the node if present */
11385 function getJSDocReturnTag(node) {
11386 return getFirstJSDocTag(node, ts.isJSDocReturnTag);
11387 }
11388 ts.getJSDocReturnTag = getJSDocReturnTag;
11389 /** Gets the JSDoc template tag for the node if present */
11390 function getJSDocTemplateTag(node) {
11391 return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
11392 }
11393 ts.getJSDocTemplateTag = getJSDocTemplateTag;
11394 /** Gets the JSDoc type tag for the node if present and valid */
11395 function getJSDocTypeTag(node) {
11396 // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
11397 var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
11398 if (tag && tag.typeExpression && tag.typeExpression.type) {
11399 return tag;
11400 }
11401 return undefined;
11402 }
11403 ts.getJSDocTypeTag = getJSDocTypeTag;
11404 /**
11405 * Gets the type node for the node if provided via JSDoc.
11406 *
11407 * @remarks The search includes any JSDoc param tag that relates
11408 * to the provided parameter, for example a type tag on the
11409 * parameter itself, or a param tag on a containing function
11410 * expression, or a param tag on a variable declaration whose
11411 * initializer is the containing function. The tags closest to the
11412 * node are examined first, so in the previous example, the type
11413 * tag directly on the node would be returned.
11414 */
11415 function getJSDocType(node) {
11416 var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
11417 if (!tag && ts.isParameter(node)) {
11418 tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11419 }
11420 return tag && tag.typeExpression && tag.typeExpression.type;
11421 }
11422 ts.getJSDocType = getJSDocType;
11423 /**
11424 * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11425 *
11426 * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11427 * gets the type from inside the braces, after the fat arrow, etc.
11428 */
11429 function getJSDocReturnType(node) {
11430 var returnTag = getJSDocReturnTag(node);
11431 if (returnTag && returnTag.typeExpression) {
11432 return returnTag.typeExpression.type;
11433 }
11434 var typeTag = getJSDocTypeTag(node);
11435 if (typeTag && typeTag.typeExpression) {
11436 var type = typeTag.typeExpression.type;
11437 if (ts.isTypeLiteralNode(type)) {
11438 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
11439 return sig && sig.type;
11440 }
11441 if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
11442 return type.type;
11443 }
11444 }
11445 }
11446 ts.getJSDocReturnType = getJSDocReturnType;
11447 function getJSDocTagsWorker(node, noCache) {
11448 var tags = node.jsDocCache;
11449 // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11450 if (tags === undefined || noCache) {
11451 var comments = ts.getJSDocCommentsAndTags(node, noCache);
11452 ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11453 tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
11454 if (!noCache) {
11455 node.jsDocCache = tags;
11456 }
11457 }
11458 return tags;
11459 }
11460 /** Get all JSDoc tags related to a node, including those on parent nodes. */
11461 function getJSDocTags(node) {
11462 return getJSDocTagsWorker(node, /*noCache*/ false);
11463 }
11464 ts.getJSDocTags = getJSDocTags;
11465 /* @internal */
11466 function getJSDocTagsNoCache(node) {
11467 return getJSDocTagsWorker(node, /*noCache*/ true);
11468 }
11469 ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
11470 /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11471 function getFirstJSDocTag(node, predicate, noCache) {
11472 return ts.find(getJSDocTagsWorker(node, noCache), predicate);
11473 }
11474 /** Gets all JSDoc tags that match a specified predicate */
11475 function getAllJSDocTags(node, predicate) {
11476 return getJSDocTags(node).filter(predicate);
11477 }
11478 ts.getAllJSDocTags = getAllJSDocTags;
11479 /** Gets all JSDoc tags of a specified kind */
11480 function getAllJSDocTagsOfKind(node, kind) {
11481 return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11482 }
11483 ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11484 /**
11485 * Gets the effective type parameters. If the node was parsed in a
11486 * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11487 */
11488 function getEffectiveTypeParameterDeclarations(node) {
11489 if (ts.isJSDocSignature(node)) {
11490 return ts.emptyArray;
11491 }
11492 if (ts.isJSDocTypeAlias(node)) {
11493 ts.Debug.assert(node.parent.kind === 307 /* JSDocComment */);
11494 return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11495 }
11496 if (node.typeParameters) {
11497 return node.typeParameters;
11498 }
11499 if (ts.isInJSFile(node)) {
11500 var decls = ts.getJSDocTypeParameterDeclarations(node);
11501 if (decls.length) {
11502 return decls;
11503 }
11504 var typeTag = getJSDocType(node);
11505 if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11506 return typeTag.typeParameters;
11507 }
11508 }
11509 return ts.emptyArray;
11510 }
11511 ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11512 function getEffectiveConstraintOfTypeParameter(node) {
11513 return node.constraint ? node.constraint :
11514 ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11515 undefined;
11516 }
11517 ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11518 // #region
11519 function isIdentifierOrPrivateIdentifier(node) {
11520 return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */;
11521 }
11522 ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11523 /* @internal */
11524 function isGetOrSetAccessorDeclaration(node) {
11525 return node.kind === 167 /* SetAccessor */ || node.kind === 166 /* GetAccessor */;
11526 }
11527 ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11528 function isPropertyAccessChain(node) {
11529 return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11530 }
11531 ts.isPropertyAccessChain = isPropertyAccessChain;
11532 function isElementAccessChain(node) {
11533 return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11534 }
11535 ts.isElementAccessChain = isElementAccessChain;
11536 function isCallChain(node) {
11537 return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11538 }
11539 ts.isCallChain = isCallChain;
11540 function isOptionalChain(node) {
11541 var kind = node.kind;
11542 return !!(node.flags & 32 /* OptionalChain */) &&
11543 (kind === 198 /* PropertyAccessExpression */
11544 || kind === 199 /* ElementAccessExpression */
11545 || kind === 200 /* CallExpression */
11546 || kind === 222 /* NonNullExpression */);
11547 }
11548 ts.isOptionalChain = isOptionalChain;
11549 /* @internal */
11550 function isOptionalChainRoot(node) {
11551 return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
11552 }
11553 ts.isOptionalChainRoot = isOptionalChainRoot;
11554 /**
11555 * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11556 */
11557 /* @internal */
11558 function isExpressionOfOptionalChainRoot(node) {
11559 return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11560 }
11561 ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11562 /**
11563 * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11564 *
11565 * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11566 * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11567 * 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)
11568 * 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
11569 * the end of the chain starting at `c?.`)
11570 * 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
11571 * the end of the chain starting at `a?.`)
11572 */
11573 /* @internal */
11574 function isOutermostOptionalChain(node) {
11575 return !isOptionalChain(node.parent) // cases 1, 2, and 3
11576 || isOptionalChainRoot(node.parent) // case 4
11577 || node !== node.parent.expression; // case 5
11578 }
11579 ts.isOutermostOptionalChain = isOutermostOptionalChain;
11580 function isNullishCoalesce(node) {
11581 return node.kind === 213 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11582 }
11583 ts.isNullishCoalesce = isNullishCoalesce;
11584 function isConstTypeReference(node) {
11585 return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
11586 node.typeName.escapedText === "const" && !node.typeArguments;
11587 }
11588 ts.isConstTypeReference = isConstTypeReference;
11589 function skipPartiallyEmittedExpressions(node) {
11590 return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11591 }
11592 ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11593 function isNonNullChain(node) {
11594 return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11595 }
11596 ts.isNonNullChain = isNonNullChain;
11597 function isBreakOrContinueStatement(node) {
11598 return node.kind === 238 /* BreakStatement */ || node.kind === 237 /* ContinueStatement */;
11599 }
11600 ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11601 function isNamedExportBindings(node) {
11602 return node.kind === 266 /* NamespaceExport */ || node.kind === 265 /* NamedExports */;
11603 }
11604 ts.isNamedExportBindings = isNamedExportBindings;
11605 function isUnparsedTextLike(node) {
11606 switch (node.kind) {
11607 case 291 /* UnparsedText */:
11608 case 292 /* UnparsedInternalText */:
11609 return true;
11610 default:
11611 return false;
11612 }
11613 }
11614 ts.isUnparsedTextLike = isUnparsedTextLike;
11615 function isUnparsedNode(node) {
11616 return isUnparsedTextLike(node) ||
11617 node.kind === 289 /* UnparsedPrologue */ ||
11618 node.kind === 293 /* UnparsedSyntheticReference */;
11619 }
11620 ts.isUnparsedNode = isUnparsedNode;
11621 function isJSDocPropertyLikeTag(node) {
11622 return node.kind === 328 /* JSDocPropertyTag */ || node.kind === 322 /* JSDocParameterTag */;
11623 }
11624 ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11625 // #endregion
11626 // #region
11627 // Node tests
11628 //
11629 // All node tests in the following list should *not* reference parent pointers so that
11630 // they may be used with transformations.
11631 /* @internal */
11632 function isNode(node) {
11633 return isNodeKind(node.kind);
11634 }
11635 ts.isNode = isNode;
11636 /* @internal */
11637 function isNodeKind(kind) {
11638 return kind >= 156 /* FirstNode */;
11639 }
11640 ts.isNodeKind = isNodeKind;
11641 /**
11642 * True if node is of some token syntax kind.
11643 * For example, this is true for an IfKeyword but not for an IfStatement.
11644 * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11645 */
11646 function isToken(n) {
11647 return n.kind >= 0 /* FirstToken */ && n.kind <= 155 /* LastToken */;
11648 }
11649 ts.isToken = isToken;
11650 // Node Arrays
11651 /* @internal */
11652 function isNodeArray(array) {
11653 return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11654 }
11655 ts.isNodeArray = isNodeArray;
11656 // Literals
11657 /* @internal */
11658 function isLiteralKind(kind) {
11659 return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11660 }
11661 ts.isLiteralKind = isLiteralKind;
11662 function isLiteralExpression(node) {
11663 return isLiteralKind(node.kind);
11664 }
11665 ts.isLiteralExpression = isLiteralExpression;
11666 // Pseudo-literals
11667 /* @internal */
11668 function isTemplateLiteralKind(kind) {
11669 return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11670 }
11671 ts.isTemplateLiteralKind = isTemplateLiteralKind;
11672 function isTemplateLiteralToken(node) {
11673 return isTemplateLiteralKind(node.kind);
11674 }
11675 ts.isTemplateLiteralToken = isTemplateLiteralToken;
11676 function isTemplateMiddleOrTemplateTail(node) {
11677 var kind = node.kind;
11678 return kind === 16 /* TemplateMiddle */
11679 || kind === 17 /* TemplateTail */;
11680 }
11681 ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11682 function isImportOrExportSpecifier(node) {
11683 return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
11684 }
11685 ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11686 function isTypeOnlyImportOrExportDeclaration(node) {
11687 switch (node.kind) {
11688 case 262 /* ImportSpecifier */:
11689 case 267 /* ExportSpecifier */:
11690 return node.parent.parent.isTypeOnly;
11691 case 260 /* NamespaceImport */:
11692 return node.parent.isTypeOnly;
11693 case 259 /* ImportClause */:
11694 return node.isTypeOnly;
11695 default:
11696 return false;
11697 }
11698 }
11699 ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
11700 function isStringTextContainingNode(node) {
11701 return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
11702 }
11703 ts.isStringTextContainingNode = isStringTextContainingNode;
11704 // Identifiers
11705 /* @internal */
11706 function isGeneratedIdentifier(node) {
11707 return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
11708 }
11709 ts.isGeneratedIdentifier = isGeneratedIdentifier;
11710 // Private Identifiers
11711 /*@internal*/
11712 function isPrivateIdentifierPropertyDeclaration(node) {
11713 return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name);
11714 }
11715 ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
11716 /*@internal*/
11717 function isPrivateIdentifierPropertyAccessExpression(node) {
11718 return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
11719 }
11720 ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
11721 // Keywords
11722 /* @internal */
11723 function isModifierKind(token) {
11724 switch (token) {
11725 case 125 /* AbstractKeyword */:
11726 case 129 /* AsyncKeyword */:
11727 case 84 /* ConstKeyword */:
11728 case 133 /* DeclareKeyword */:
11729 case 87 /* DefaultKeyword */:
11730 case 92 /* ExportKeyword */:
11731 case 122 /* PublicKeyword */:
11732 case 120 /* PrivateKeyword */:
11733 case 121 /* ProtectedKeyword */:
11734 case 141 /* ReadonlyKeyword */:
11735 case 123 /* StaticKeyword */:
11736 return true;
11737 }
11738 return false;
11739 }
11740 ts.isModifierKind = isModifierKind;
11741 /* @internal */
11742 function isParameterPropertyModifier(kind) {
11743 return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
11744 }
11745 ts.isParameterPropertyModifier = isParameterPropertyModifier;
11746 /* @internal */
11747 function isClassMemberModifier(idToken) {
11748 return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */;
11749 }
11750 ts.isClassMemberModifier = isClassMemberModifier;
11751 function isModifier(node) {
11752 return isModifierKind(node.kind);
11753 }
11754 ts.isModifier = isModifier;
11755 function isEntityName(node) {
11756 var kind = node.kind;
11757 return kind === 156 /* QualifiedName */
11758 || kind === 78 /* Identifier */;
11759 }
11760 ts.isEntityName = isEntityName;
11761 function isPropertyName(node) {
11762 var kind = node.kind;
11763 return kind === 78 /* Identifier */
11764 || kind === 79 /* PrivateIdentifier */
11765 || kind === 10 /* StringLiteral */
11766 || kind === 8 /* NumericLiteral */
11767 || kind === 157 /* ComputedPropertyName */;
11768 }
11769 ts.isPropertyName = isPropertyName;
11770 function isBindingName(node) {
11771 var kind = node.kind;
11772 return kind === 78 /* Identifier */
11773 || kind === 193 /* ObjectBindingPattern */
11774 || kind === 194 /* ArrayBindingPattern */;
11775 }
11776 ts.isBindingName = isBindingName;
11777 // Functions
11778 function isFunctionLike(node) {
11779 return node && isFunctionLikeKind(node.kind);
11780 }
11781 ts.isFunctionLike = isFunctionLike;
11782 /* @internal */
11783 function isFunctionLikeDeclaration(node) {
11784 return node && isFunctionLikeDeclarationKind(node.kind);
11785 }
11786 ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
11787 function isFunctionLikeDeclarationKind(kind) {
11788 switch (kind) {
11789 case 248 /* FunctionDeclaration */:
11790 case 164 /* MethodDeclaration */:
11791 case 165 /* Constructor */:
11792 case 166 /* GetAccessor */:
11793 case 167 /* SetAccessor */:
11794 case 205 /* FunctionExpression */:
11795 case 206 /* ArrowFunction */:
11796 return true;
11797 default:
11798 return false;
11799 }
11800 }
11801 /* @internal */
11802 function isFunctionLikeKind(kind) {
11803 switch (kind) {
11804 case 163 /* MethodSignature */:
11805 case 168 /* CallSignature */:
11806 case 309 /* JSDocSignature */:
11807 case 169 /* ConstructSignature */:
11808 case 170 /* IndexSignature */:
11809 case 173 /* FunctionType */:
11810 case 304 /* JSDocFunctionType */:
11811 case 174 /* ConstructorType */:
11812 return true;
11813 default:
11814 return isFunctionLikeDeclarationKind(kind);
11815 }
11816 }
11817 ts.isFunctionLikeKind = isFunctionLikeKind;
11818 /* @internal */
11819 function isFunctionOrModuleBlock(node) {
11820 return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
11821 }
11822 ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
11823 // Classes
11824 function isClassElement(node) {
11825 var kind = node.kind;
11826 return kind === 165 /* Constructor */
11827 || kind === 162 /* PropertyDeclaration */
11828 || kind === 164 /* MethodDeclaration */
11829 || kind === 166 /* GetAccessor */
11830 || kind === 167 /* SetAccessor */
11831 || kind === 170 /* IndexSignature */
11832 || kind === 226 /* SemicolonClassElement */;
11833 }
11834 ts.isClassElement = isClassElement;
11835 function isClassLike(node) {
11836 return node && (node.kind === 249 /* ClassDeclaration */ || node.kind === 218 /* ClassExpression */);
11837 }
11838 ts.isClassLike = isClassLike;
11839 function isAccessor(node) {
11840 return node && (node.kind === 166 /* GetAccessor */ || node.kind === 167 /* SetAccessor */);
11841 }
11842 ts.isAccessor = isAccessor;
11843 /* @internal */
11844 function isMethodOrAccessor(node) {
11845 switch (node.kind) {
11846 case 164 /* MethodDeclaration */:
11847 case 166 /* GetAccessor */:
11848 case 167 /* SetAccessor */:
11849 return true;
11850 default:
11851 return false;
11852 }
11853 }
11854 ts.isMethodOrAccessor = isMethodOrAccessor;
11855 // Type members
11856 function isTypeElement(node) {
11857 var kind = node.kind;
11858 return kind === 169 /* ConstructSignature */
11859 || kind === 168 /* CallSignature */
11860 || kind === 161 /* PropertySignature */
11861 || kind === 163 /* MethodSignature */
11862 || kind === 170 /* IndexSignature */;
11863 }
11864 ts.isTypeElement = isTypeElement;
11865 function isClassOrTypeElement(node) {
11866 return isTypeElement(node) || isClassElement(node);
11867 }
11868 ts.isClassOrTypeElement = isClassOrTypeElement;
11869 function isObjectLiteralElementLike(node) {
11870 var kind = node.kind;
11871 return kind === 285 /* PropertyAssignment */
11872 || kind === 286 /* ShorthandPropertyAssignment */
11873 || kind === 287 /* SpreadAssignment */
11874 || kind === 164 /* MethodDeclaration */
11875 || kind === 166 /* GetAccessor */
11876 || kind === 167 /* SetAccessor */;
11877 }
11878 ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
11879 // Type
11880 /**
11881 * Node test that determines whether a node is a valid type node.
11882 * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
11883 * of a TypeNode.
11884 */
11885 function isTypeNode(node) {
11886 return ts.isTypeNodeKind(node.kind);
11887 }
11888 ts.isTypeNode = isTypeNode;
11889 function isFunctionOrConstructorTypeNode(node) {
11890 switch (node.kind) {
11891 case 173 /* FunctionType */:
11892 case 174 /* ConstructorType */:
11893 return true;
11894 }
11895 return false;
11896 }
11897 ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
11898 // Binding patterns
11899 /* @internal */
11900 function isBindingPattern(node) {
11901 if (node) {
11902 var kind = node.kind;
11903 return kind === 194 /* ArrayBindingPattern */
11904 || kind === 193 /* ObjectBindingPattern */;
11905 }
11906 return false;
11907 }
11908 ts.isBindingPattern = isBindingPattern;
11909 /* @internal */
11910 function isAssignmentPattern(node) {
11911 var kind = node.kind;
11912 return kind === 196 /* ArrayLiteralExpression */
11913 || kind === 197 /* ObjectLiteralExpression */;
11914 }
11915 ts.isAssignmentPattern = isAssignmentPattern;
11916 /* @internal */
11917 function isArrayBindingElement(node) {
11918 var kind = node.kind;
11919 return kind === 195 /* BindingElement */
11920 || kind === 219 /* OmittedExpression */;
11921 }
11922 ts.isArrayBindingElement = isArrayBindingElement;
11923 /**
11924 * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
11925 */
11926 /* @internal */
11927 function isDeclarationBindingElement(bindingElement) {
11928 switch (bindingElement.kind) {
11929 case 246 /* VariableDeclaration */:
11930 case 159 /* Parameter */:
11931 case 195 /* BindingElement */:
11932 return true;
11933 }
11934 return false;
11935 }
11936 ts.isDeclarationBindingElement = isDeclarationBindingElement;
11937 /**
11938 * Determines whether a node is a BindingOrAssignmentPattern
11939 */
11940 /* @internal */
11941 function isBindingOrAssignmentPattern(node) {
11942 return isObjectBindingOrAssignmentPattern(node)
11943 || isArrayBindingOrAssignmentPattern(node);
11944 }
11945 ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
11946 /**
11947 * Determines whether a node is an ObjectBindingOrAssignmentPattern
11948 */
11949 /* @internal */
11950 function isObjectBindingOrAssignmentPattern(node) {
11951 switch (node.kind) {
11952 case 193 /* ObjectBindingPattern */:
11953 case 197 /* ObjectLiteralExpression */:
11954 return true;
11955 }
11956 return false;
11957 }
11958 ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
11959 /**
11960 * Determines whether a node is an ArrayBindingOrAssignmentPattern
11961 */
11962 /* @internal */
11963 function isArrayBindingOrAssignmentPattern(node) {
11964 switch (node.kind) {
11965 case 194 /* ArrayBindingPattern */:
11966 case 196 /* ArrayLiteralExpression */:
11967 return true;
11968 }
11969 return false;
11970 }
11971 ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
11972 /* @internal */
11973 function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
11974 var kind = node.kind;
11975 return kind === 198 /* PropertyAccessExpression */
11976 || kind === 156 /* QualifiedName */
11977 || kind === 192 /* ImportType */;
11978 }
11979 ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
11980 // Expression
11981 function isPropertyAccessOrQualifiedName(node) {
11982 var kind = node.kind;
11983 return kind === 198 /* PropertyAccessExpression */
11984 || kind === 156 /* QualifiedName */;
11985 }
11986 ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
11987 function isCallLikeExpression(node) {
11988 switch (node.kind) {
11989 case 272 /* JsxOpeningElement */:
11990 case 271 /* JsxSelfClosingElement */:
11991 case 200 /* CallExpression */:
11992 case 201 /* NewExpression */:
11993 case 202 /* TaggedTemplateExpression */:
11994 case 160 /* Decorator */:
11995 return true;
11996 default:
11997 return false;
11998 }
11999 }
12000 ts.isCallLikeExpression = isCallLikeExpression;
12001 function isCallOrNewExpression(node) {
12002 return node.kind === 200 /* CallExpression */ || node.kind === 201 /* NewExpression */;
12003 }
12004 ts.isCallOrNewExpression = isCallOrNewExpression;
12005 function isTemplateLiteral(node) {
12006 var kind = node.kind;
12007 return kind === 215 /* TemplateExpression */
12008 || kind === 14 /* NoSubstitutionTemplateLiteral */;
12009 }
12010 ts.isTemplateLiteral = isTemplateLiteral;
12011 /* @internal */
12012 function isLeftHandSideExpression(node) {
12013 return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12014 }
12015 ts.isLeftHandSideExpression = isLeftHandSideExpression;
12016 function isLeftHandSideExpressionKind(kind) {
12017 switch (kind) {
12018 case 198 /* PropertyAccessExpression */:
12019 case 199 /* ElementAccessExpression */:
12020 case 201 /* NewExpression */:
12021 case 200 /* CallExpression */:
12022 case 270 /* JsxElement */:
12023 case 271 /* JsxSelfClosingElement */:
12024 case 274 /* JsxFragment */:
12025 case 202 /* TaggedTemplateExpression */:
12026 case 196 /* ArrayLiteralExpression */:
12027 case 204 /* ParenthesizedExpression */:
12028 case 197 /* ObjectLiteralExpression */:
12029 case 218 /* ClassExpression */:
12030 case 205 /* FunctionExpression */:
12031 case 78 /* Identifier */:
12032 case 13 /* RegularExpressionLiteral */:
12033 case 8 /* NumericLiteral */:
12034 case 9 /* BigIntLiteral */:
12035 case 10 /* StringLiteral */:
12036 case 14 /* NoSubstitutionTemplateLiteral */:
12037 case 215 /* TemplateExpression */:
12038 case 94 /* FalseKeyword */:
12039 case 103 /* NullKeyword */:
12040 case 107 /* ThisKeyword */:
12041 case 109 /* TrueKeyword */:
12042 case 105 /* SuperKeyword */:
12043 case 222 /* NonNullExpression */:
12044 case 223 /* MetaProperty */:
12045 case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12046 return true;
12047 default:
12048 return false;
12049 }
12050 }
12051 /* @internal */
12052 function isUnaryExpression(node) {
12053 return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12054 }
12055 ts.isUnaryExpression = isUnaryExpression;
12056 function isUnaryExpressionKind(kind) {
12057 switch (kind) {
12058 case 211 /* PrefixUnaryExpression */:
12059 case 212 /* PostfixUnaryExpression */:
12060 case 207 /* DeleteExpression */:
12061 case 208 /* TypeOfExpression */:
12062 case 209 /* VoidExpression */:
12063 case 210 /* AwaitExpression */:
12064 case 203 /* TypeAssertionExpression */:
12065 return true;
12066 default:
12067 return isLeftHandSideExpressionKind(kind);
12068 }
12069 }
12070 /* @internal */
12071 function isUnaryExpressionWithWrite(expr) {
12072 switch (expr.kind) {
12073 case 212 /* PostfixUnaryExpression */:
12074 return true;
12075 case 211 /* PrefixUnaryExpression */:
12076 return expr.operator === 45 /* PlusPlusToken */ ||
12077 expr.operator === 46 /* MinusMinusToken */;
12078 default:
12079 return false;
12080 }
12081 }
12082 ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12083 /* @internal */
12084 /**
12085 * Determines whether a node is an expression based only on its kind.
12086 * Use `isExpressionNode` if not in transforms.
12087 */
12088 function isExpression(node) {
12089 return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12090 }
12091 ts.isExpression = isExpression;
12092 function isExpressionKind(kind) {
12093 switch (kind) {
12094 case 214 /* ConditionalExpression */:
12095 case 216 /* YieldExpression */:
12096 case 206 /* ArrowFunction */:
12097 case 213 /* BinaryExpression */:
12098 case 217 /* SpreadElement */:
12099 case 221 /* AsExpression */:
12100 case 219 /* OmittedExpression */:
12101 case 332 /* CommaListExpression */:
12102 case 331 /* PartiallyEmittedExpression */:
12103 return true;
12104 default:
12105 return isUnaryExpressionKind(kind);
12106 }
12107 }
12108 function isAssertionExpression(node) {
12109 var kind = node.kind;
12110 return kind === 203 /* TypeAssertionExpression */
12111 || kind === 221 /* AsExpression */;
12112 }
12113 ts.isAssertionExpression = isAssertionExpression;
12114 /* @internal */
12115 function isNotEmittedOrPartiallyEmittedNode(node) {
12116 return ts.isNotEmittedStatement(node)
12117 || ts.isPartiallyEmittedExpression(node);
12118 }
12119 ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12120 function isIterationStatement(node, lookInLabeledStatements) {
12121 switch (node.kind) {
12122 case 234 /* ForStatement */:
12123 case 235 /* ForInStatement */:
12124 case 236 /* ForOfStatement */:
12125 case 232 /* DoStatement */:
12126 case 233 /* WhileStatement */:
12127 return true;
12128 case 242 /* LabeledStatement */:
12129 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12130 }
12131 return false;
12132 }
12133 ts.isIterationStatement = isIterationStatement;
12134 /* @internal */
12135 function isScopeMarker(node) {
12136 return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
12137 }
12138 ts.isScopeMarker = isScopeMarker;
12139 /* @internal */
12140 function hasScopeMarker(statements) {
12141 return ts.some(statements, isScopeMarker);
12142 }
12143 ts.hasScopeMarker = hasScopeMarker;
12144 /* @internal */
12145 function needsScopeMarker(result) {
12146 return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12147 }
12148 ts.needsScopeMarker = needsScopeMarker;
12149 /* @internal */
12150 function isExternalModuleIndicator(result) {
12151 // Exported top-level member indicates moduleness
12152 return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
12153 }
12154 ts.isExternalModuleIndicator = isExternalModuleIndicator;
12155 /* @internal */
12156 function isForInOrOfStatement(node) {
12157 return node.kind === 235 /* ForInStatement */ || node.kind === 236 /* ForOfStatement */;
12158 }
12159 ts.isForInOrOfStatement = isForInOrOfStatement;
12160 // Element
12161 /* @internal */
12162 function isConciseBody(node) {
12163 return ts.isBlock(node)
12164 || isExpression(node);
12165 }
12166 ts.isConciseBody = isConciseBody;
12167 /* @internal */
12168 function isFunctionBody(node) {
12169 return ts.isBlock(node);
12170 }
12171 ts.isFunctionBody = isFunctionBody;
12172 /* @internal */
12173 function isForInitializer(node) {
12174 return ts.isVariableDeclarationList(node)
12175 || isExpression(node);
12176 }
12177 ts.isForInitializer = isForInitializer;
12178 /* @internal */
12179 function isModuleBody(node) {
12180 var kind = node.kind;
12181 return kind === 254 /* ModuleBlock */
12182 || kind === 253 /* ModuleDeclaration */
12183 || kind === 78 /* Identifier */;
12184 }
12185 ts.isModuleBody = isModuleBody;
12186 /* @internal */
12187 function isNamespaceBody(node) {
12188 var kind = node.kind;
12189 return kind === 254 /* ModuleBlock */
12190 || kind === 253 /* ModuleDeclaration */;
12191 }
12192 ts.isNamespaceBody = isNamespaceBody;
12193 /* @internal */
12194 function isJSDocNamespaceBody(node) {
12195 var kind = node.kind;
12196 return kind === 78 /* Identifier */
12197 || kind === 253 /* ModuleDeclaration */;
12198 }
12199 ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12200 /* @internal */
12201 function isNamedImportBindings(node) {
12202 var kind = node.kind;
12203 return kind === 261 /* NamedImports */
12204 || kind === 260 /* NamespaceImport */;
12205 }
12206 ts.isNamedImportBindings = isNamedImportBindings;
12207 /* @internal */
12208 function isModuleOrEnumDeclaration(node) {
12209 return node.kind === 253 /* ModuleDeclaration */ || node.kind === 252 /* EnumDeclaration */;
12210 }
12211 ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12212 function isDeclarationKind(kind) {
12213 return kind === 206 /* ArrowFunction */
12214 || kind === 195 /* BindingElement */
12215 || kind === 249 /* ClassDeclaration */
12216 || kind === 218 /* ClassExpression */
12217 || kind === 165 /* Constructor */
12218 || kind === 252 /* EnumDeclaration */
12219 || kind === 288 /* EnumMember */
12220 || kind === 267 /* ExportSpecifier */
12221 || kind === 248 /* FunctionDeclaration */
12222 || kind === 205 /* FunctionExpression */
12223 || kind === 166 /* GetAccessor */
12224 || kind === 259 /* ImportClause */
12225 || kind === 257 /* ImportEqualsDeclaration */
12226 || kind === 262 /* ImportSpecifier */
12227 || kind === 250 /* InterfaceDeclaration */
12228 || kind === 277 /* JsxAttribute */
12229 || kind === 164 /* MethodDeclaration */
12230 || kind === 163 /* MethodSignature */
12231 || kind === 253 /* ModuleDeclaration */
12232 || kind === 256 /* NamespaceExportDeclaration */
12233 || kind === 260 /* NamespaceImport */
12234 || kind === 266 /* NamespaceExport */
12235 || kind === 159 /* Parameter */
12236 || kind === 285 /* PropertyAssignment */
12237 || kind === 162 /* PropertyDeclaration */
12238 || kind === 161 /* PropertySignature */
12239 || kind === 167 /* SetAccessor */
12240 || kind === 286 /* ShorthandPropertyAssignment */
12241 || kind === 251 /* TypeAliasDeclaration */
12242 || kind === 158 /* TypeParameter */
12243 || kind === 246 /* VariableDeclaration */
12244 || kind === 327 /* JSDocTypedefTag */
12245 || kind === 320 /* JSDocCallbackTag */
12246 || kind === 328 /* JSDocPropertyTag */;
12247 }
12248 function isDeclarationStatementKind(kind) {
12249 return kind === 248 /* FunctionDeclaration */
12250 || kind === 268 /* MissingDeclaration */
12251 || kind === 249 /* ClassDeclaration */
12252 || kind === 250 /* InterfaceDeclaration */
12253 || kind === 251 /* TypeAliasDeclaration */
12254 || kind === 252 /* EnumDeclaration */
12255 || kind === 253 /* ModuleDeclaration */
12256 || kind === 258 /* ImportDeclaration */
12257 || kind === 257 /* ImportEqualsDeclaration */
12258 || kind === 264 /* ExportDeclaration */
12259 || kind === 263 /* ExportAssignment */
12260 || kind === 256 /* NamespaceExportDeclaration */;
12261 }
12262 function isStatementKindButNotDeclarationKind(kind) {
12263 return kind === 238 /* BreakStatement */
12264 || kind === 237 /* ContinueStatement */
12265 || kind === 245 /* DebuggerStatement */
12266 || kind === 232 /* DoStatement */
12267 || kind === 230 /* ExpressionStatement */
12268 || kind === 228 /* EmptyStatement */
12269 || kind === 235 /* ForInStatement */
12270 || kind === 236 /* ForOfStatement */
12271 || kind === 234 /* ForStatement */
12272 || kind === 231 /* IfStatement */
12273 || kind === 242 /* LabeledStatement */
12274 || kind === 239 /* ReturnStatement */
12275 || kind === 241 /* SwitchStatement */
12276 || kind === 243 /* ThrowStatement */
12277 || kind === 244 /* TryStatement */
12278 || kind === 229 /* VariableStatement */
12279 || kind === 233 /* WhileStatement */
12280 || kind === 240 /* WithStatement */
12281 || kind === 330 /* NotEmittedStatement */
12282 || kind === 334 /* EndOfDeclarationMarker */
12283 || kind === 333 /* MergeDeclarationMarker */;
12284 }
12285 /* @internal */
12286 function isDeclaration(node) {
12287 if (node.kind === 158 /* TypeParameter */) {
12288 return (node.parent && node.parent.kind !== 326 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12289 }
12290 return isDeclarationKind(node.kind);
12291 }
12292 ts.isDeclaration = isDeclaration;
12293 /* @internal */
12294 function isDeclarationStatement(node) {
12295 return isDeclarationStatementKind(node.kind);
12296 }
12297 ts.isDeclarationStatement = isDeclarationStatement;
12298 /**
12299 * Determines whether the node is a statement that is not also a declaration
12300 */
12301 /* @internal */
12302 function isStatementButNotDeclaration(node) {
12303 return isStatementKindButNotDeclarationKind(node.kind);
12304 }
12305 ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12306 /* @internal */
12307 function isStatement(node) {
12308 var kind = node.kind;
12309 return isStatementKindButNotDeclarationKind(kind)
12310 || isDeclarationStatementKind(kind)
12311 || isBlockStatement(node);
12312 }
12313 ts.isStatement = isStatement;
12314 function isBlockStatement(node) {
12315 if (node.kind !== 227 /* Block */)
12316 return false;
12317 if (node.parent !== undefined) {
12318 if (node.parent.kind === 244 /* TryStatement */ || node.parent.kind === 284 /* CatchClause */) {
12319 return false;
12320 }
12321 }
12322 return !ts.isFunctionBlock(node);
12323 }
12324 /**
12325 * NOTE: This is similar to `isStatement` but does not access parent pointers.
12326 */
12327 /* @internal */
12328 function isStatementOrBlock(node) {
12329 var kind = node.kind;
12330 return isStatementKindButNotDeclarationKind(kind)
12331 || isDeclarationStatementKind(kind)
12332 || kind === 227 /* Block */;
12333 }
12334 ts.isStatementOrBlock = isStatementOrBlock;
12335 // Module references
12336 /* @internal */
12337 function isModuleReference(node) {
12338 var kind = node.kind;
12339 return kind === 269 /* ExternalModuleReference */
12340 || kind === 156 /* QualifiedName */
12341 || kind === 78 /* Identifier */;
12342 }
12343 ts.isModuleReference = isModuleReference;
12344 // JSX
12345 /* @internal */
12346 function isJsxTagNameExpression(node) {
12347 var kind = node.kind;
12348 return kind === 107 /* ThisKeyword */
12349 || kind === 78 /* Identifier */
12350 || kind === 198 /* PropertyAccessExpression */;
12351 }
12352 ts.isJsxTagNameExpression = isJsxTagNameExpression;
12353 /* @internal */
12354 function isJsxChild(node) {
12355 var kind = node.kind;
12356 return kind === 270 /* JsxElement */
12357 || kind === 280 /* JsxExpression */
12358 || kind === 271 /* JsxSelfClosingElement */
12359 || kind === 11 /* JsxText */
12360 || kind === 274 /* JsxFragment */;
12361 }
12362 ts.isJsxChild = isJsxChild;
12363 /* @internal */
12364 function isJsxAttributeLike(node) {
12365 var kind = node.kind;
12366 return kind === 277 /* JsxAttribute */
12367 || kind === 279 /* JsxSpreadAttribute */;
12368 }
12369 ts.isJsxAttributeLike = isJsxAttributeLike;
12370 /* @internal */
12371 function isStringLiteralOrJsxExpression(node) {
12372 var kind = node.kind;
12373 return kind === 10 /* StringLiteral */
12374 || kind === 280 /* JsxExpression */;
12375 }
12376 ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12377 function isJsxOpeningLikeElement(node) {
12378 var kind = node.kind;
12379 return kind === 272 /* JsxOpeningElement */
12380 || kind === 271 /* JsxSelfClosingElement */;
12381 }
12382 ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12383 // Clauses
12384 function isCaseOrDefaultClause(node) {
12385 var kind = node.kind;
12386 return kind === 281 /* CaseClause */
12387 || kind === 282 /* DefaultClause */;
12388 }
12389 ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12390 // JSDoc
12391 /** True if node is of some JSDoc syntax kind. */
12392 /* @internal */
12393 function isJSDocNode(node) {
12394 return node.kind >= 298 /* FirstJSDocNode */ && node.kind <= 328 /* LastJSDocNode */;
12395 }
12396 ts.isJSDocNode = isJSDocNode;
12397 /** True if node is of a kind that may contain comment text. */
12398 function isJSDocCommentContainingNode(node) {
12399 return node.kind === 307 /* JSDocComment */ || node.kind === 306 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
12400 }
12401 ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12402 // TODO: determine what this does before making it public.
12403 /* @internal */
12404 function isJSDocTag(node) {
12405 return node.kind >= 310 /* FirstJSDocTagNode */ && node.kind <= 328 /* LastJSDocTagNode */;
12406 }
12407 ts.isJSDocTag = isJSDocTag;
12408 function isSetAccessor(node) {
12409 return node.kind === 167 /* SetAccessor */;
12410 }
12411 ts.isSetAccessor = isSetAccessor;
12412 function isGetAccessor(node) {
12413 return node.kind === 166 /* GetAccessor */;
12414 }
12415 ts.isGetAccessor = isGetAccessor;
12416 /** True if has jsdoc nodes attached to it. */
12417 /* @internal */
12418 // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12419 function hasJSDocNodes(node) {
12420 var jsDoc = node.jsDoc;
12421 return !!jsDoc && jsDoc.length > 0;
12422 }
12423 ts.hasJSDocNodes = hasJSDocNodes;
12424 /** True if has type node attached to it. */
12425 /* @internal */
12426 function hasType(node) {
12427 return !!node.type;
12428 }
12429 ts.hasType = hasType;
12430 /** True if has initializer node attached to it. */
12431 /* @internal */
12432 function hasInitializer(node) {
12433 return !!node.initializer;
12434 }
12435 ts.hasInitializer = hasInitializer;
12436 /** True if has initializer node attached to it. */
12437 function hasOnlyExpressionInitializer(node) {
12438 switch (node.kind) {
12439 case 246 /* VariableDeclaration */:
12440 case 159 /* Parameter */:
12441 case 195 /* BindingElement */:
12442 case 161 /* PropertySignature */:
12443 case 162 /* PropertyDeclaration */:
12444 case 285 /* PropertyAssignment */:
12445 case 288 /* EnumMember */:
12446 return true;
12447 default:
12448 return false;
12449 }
12450 }
12451 ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12452 function isObjectLiteralElement(node) {
12453 return node.kind === 277 /* JsxAttribute */ || node.kind === 279 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12454 }
12455 ts.isObjectLiteralElement = isObjectLiteralElement;
12456 /* @internal */
12457 function isTypeReferenceType(node) {
12458 return node.kind === 172 /* TypeReference */ || node.kind === 220 /* ExpressionWithTypeArguments */;
12459 }
12460 ts.isTypeReferenceType = isTypeReferenceType;
12461 var MAX_SMI_X86 = 1073741823;
12462 /* @internal */
12463 function guessIndentation(lines) {
12464 var indentation = MAX_SMI_X86;
12465 for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12466 var line = lines_1[_i];
12467 if (!line.length) {
12468 continue;
12469 }
12470 var i = 0;
12471 for (; i < line.length && i < indentation; i++) {
12472 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12473 break;
12474 }
12475 }
12476 if (i < indentation) {
12477 indentation = i;
12478 }
12479 if (indentation === 0) {
12480 return 0;
12481 }
12482 }
12483 return indentation === MAX_SMI_X86 ? undefined : indentation;
12484 }
12485 ts.guessIndentation = guessIndentation;
12486 function isStringLiteralLike(node) {
12487 return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12488 }
12489 ts.isStringLiteralLike = isStringLiteralLike;
12490 // #endregion
12491})(ts || (ts = {}));
12492/* @internal */
12493var ts;
12494(function (ts) {
12495 ts.resolvingEmptyArray = [];
12496 ts.externalHelpersModuleNameText = "tslib";
12497 ts.defaultMaximumTruncationLength = 160;
12498 ts.noTruncationMaximumTruncationLength = 1000000;
12499 function getDeclarationOfKind(symbol, kind) {
12500 var declarations = symbol.declarations;
12501 if (declarations) {
12502 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12503 var declaration = declarations_1[_i];
12504 if (declaration.kind === kind) {
12505 return declaration;
12506 }
12507 }
12508 }
12509 return undefined;
12510 }
12511 ts.getDeclarationOfKind = getDeclarationOfKind;
12512 /**
12513 * Create a new escaped identifier map.
12514 * @deprecated Use `new Map<__String, T>()` instead.
12515 */
12516 function createUnderscoreEscapedMap() {
12517 return new ts.Map();
12518 }
12519 ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12520 /**
12521 * @deprecated Use `!!map?.size` instead
12522 */
12523 function hasEntries(map) {
12524 return !!map && !!map.size;
12525 }
12526 ts.hasEntries = hasEntries;
12527 function createSymbolTable(symbols) {
12528 var result = new ts.Map();
12529 if (symbols) {
12530 for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12531 var symbol = symbols_1[_i];
12532 result.set(symbol.escapedName, symbol);
12533 }
12534 }
12535 return result;
12536 }
12537 ts.createSymbolTable = createSymbolTable;
12538 function isTransientSymbol(symbol) {
12539 return (symbol.flags & 33554432 /* Transient */) !== 0;
12540 }
12541 ts.isTransientSymbol = isTransientSymbol;
12542 var stringWriter = createSingleLineStringWriter();
12543 function createSingleLineStringWriter() {
12544 var str = "";
12545 var writeText = function (text) { return str += text; };
12546 return {
12547 getText: function () { return str; },
12548 write: writeText,
12549 rawWrite: writeText,
12550 writeKeyword: writeText,
12551 writeOperator: writeText,
12552 writePunctuation: writeText,
12553 writeSpace: writeText,
12554 writeStringLiteral: writeText,
12555 writeLiteral: writeText,
12556 writeParameter: writeText,
12557 writeProperty: writeText,
12558 writeSymbol: function (s, _) { return writeText(s); },
12559 writeTrailingSemicolon: writeText,
12560 writeComment: writeText,
12561 getTextPos: function () { return str.length; },
12562 getLine: function () { return 0; },
12563 getColumn: function () { return 0; },
12564 getIndent: function () { return 0; },
12565 isAtStartOfLine: function () { return false; },
12566 hasTrailingComment: function () { return false; },
12567 hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12568 // Completely ignore indentation for string writers. And map newlines to
12569 // a single space.
12570 writeLine: function () { return str += " "; },
12571 increaseIndent: ts.noop,
12572 decreaseIndent: ts.noop,
12573 clear: function () { return str = ""; },
12574 trackSymbol: ts.noop,
12575 reportInaccessibleThisError: ts.noop,
12576 reportInaccessibleUniqueSymbolError: ts.noop,
12577 reportPrivateInBaseOfClassExpression: ts.noop,
12578 };
12579 }
12580 function changesAffectModuleResolution(oldOptions, newOptions) {
12581 return oldOptions.configFilePath !== newOptions.configFilePath ||
12582 optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12583 }
12584 ts.changesAffectModuleResolution = changesAffectModuleResolution;
12585 function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12586 return ts.moduleResolutionOptionDeclarations.some(function (o) {
12587 return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12588 });
12589 }
12590 ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12591 function findAncestor(node, callback) {
12592 while (node) {
12593 var result = callback(node);
12594 if (result === "quit") {
12595 return undefined;
12596 }
12597 else if (result) {
12598 return node;
12599 }
12600 node = node.parent;
12601 }
12602 return undefined;
12603 }
12604 ts.findAncestor = findAncestor;
12605 function forEachAncestor(node, callback) {
12606 while (true) {
12607 var res = callback(node);
12608 if (res === "quit")
12609 return undefined;
12610 if (res !== undefined)
12611 return res;
12612 if (ts.isSourceFile(node))
12613 return undefined;
12614 node = node.parent;
12615 }
12616 }
12617 ts.forEachAncestor = forEachAncestor;
12618 /**
12619 * Calls `callback` for each entry in the map, returning the first truthy result.
12620 * Use `map.forEach` instead for normal iteration.
12621 */
12622 function forEachEntry(map, callback) {
12623 var iterator = map.entries();
12624 for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12625 var _a = iterResult.value, key = _a[0], value = _a[1];
12626 var result = callback(value, key);
12627 if (result) {
12628 return result;
12629 }
12630 }
12631 return undefined;
12632 }
12633 ts.forEachEntry = forEachEntry;
12634 /** `forEachEntry` for just keys. */
12635 function forEachKey(map, callback) {
12636 var iterator = map.keys();
12637 for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12638 var result = callback(iterResult.value);
12639 if (result) {
12640 return result;
12641 }
12642 }
12643 return undefined;
12644 }
12645 ts.forEachKey = forEachKey;
12646 /** Copy entries from `source` to `target`. */
12647 function copyEntries(source, target) {
12648 source.forEach(function (value, key) {
12649 target.set(key, value);
12650 });
12651 }
12652 ts.copyEntries = copyEntries;
12653 function usingSingleLineStringWriter(action) {
12654 var oldString = stringWriter.getText();
12655 try {
12656 action(stringWriter);
12657 return stringWriter.getText();
12658 }
12659 finally {
12660 stringWriter.clear();
12661 stringWriter.writeKeyword(oldString);
12662 }
12663 }
12664 ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12665 function getFullWidth(node) {
12666 return node.end - node.pos;
12667 }
12668 ts.getFullWidth = getFullWidth;
12669 function getResolvedModule(sourceFile, moduleNameText) {
12670 return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12671 }
12672 ts.getResolvedModule = getResolvedModule;
12673 function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12674 if (!sourceFile.resolvedModules) {
12675 sourceFile.resolvedModules = new ts.Map();
12676 }
12677 sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12678 }
12679 ts.setResolvedModule = setResolvedModule;
12680 function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12681 if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12682 sourceFile.resolvedTypeReferenceDirectiveNames = new ts.Map();
12683 }
12684 sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12685 }
12686 ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12687 function projectReferenceIsEqualTo(oldRef, newRef) {
12688 return oldRef.path === newRef.path &&
12689 !oldRef.prepend === !newRef.prepend &&
12690 !oldRef.circular === !newRef.circular;
12691 }
12692 ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12693 function moduleResolutionIsEqualTo(oldResolution, newResolution) {
12694 return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
12695 oldResolution.extension === newResolution.extension &&
12696 oldResolution.resolvedFileName === newResolution.resolvedFileName &&
12697 oldResolution.originalPath === newResolution.originalPath &&
12698 packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
12699 }
12700 ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
12701 function packageIdIsEqual(a, b) {
12702 return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
12703 }
12704 function packageIdToString(_a) {
12705 var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
12706 var fullName = subModuleName ? name + "/" + subModuleName : name;
12707 return fullName + "@" + version;
12708 }
12709 ts.packageIdToString = packageIdToString;
12710 function typeDirectiveIsEqualTo(oldResolution, newResolution) {
12711 return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
12712 }
12713 ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
12714 function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
12715 ts.Debug.assert(names.length === newResolutions.length);
12716 for (var i = 0; i < names.length; i++) {
12717 var newResolution = newResolutions[i];
12718 var oldResolution = oldResolutions && oldResolutions.get(names[i]);
12719 var changed = oldResolution
12720 ? !newResolution || !comparer(oldResolution, newResolution)
12721 : newResolution;
12722 if (changed) {
12723 return true;
12724 }
12725 }
12726 return false;
12727 }
12728 ts.hasChangesInResolutions = hasChangesInResolutions;
12729 // Returns true if this node contains a parse error anywhere underneath it.
12730 function containsParseError(node) {
12731 aggregateChildData(node);
12732 return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
12733 }
12734 ts.containsParseError = containsParseError;
12735 function aggregateChildData(node) {
12736 if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
12737 // A node is considered to contain a parse error if:
12738 // a) the parser explicitly marked that it had an error
12739 // b) any of it's children reported that it had an error.
12740 var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
12741 ts.forEachChild(node, containsParseError);
12742 // If so, mark ourselves accordingly.
12743 if (thisNodeOrAnySubNodesHasError) {
12744 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
12745 }
12746 // Also mark that we've propagated the child information to this node. This way we can
12747 // always consult the bit directly on this node without needing to check its children
12748 // again.
12749 node.flags |= 524288 /* HasAggregatedChildData */;
12750 }
12751 }
12752 function getSourceFileOfNode(node) {
12753 while (node && node.kind !== 294 /* SourceFile */) {
12754 node = node.parent;
12755 }
12756 return node;
12757 }
12758 ts.getSourceFileOfNode = getSourceFileOfNode;
12759 function isStatementWithLocals(node) {
12760 switch (node.kind) {
12761 case 227 /* Block */:
12762 case 255 /* CaseBlock */:
12763 case 234 /* ForStatement */:
12764 case 235 /* ForInStatement */:
12765 case 236 /* ForOfStatement */:
12766 return true;
12767 }
12768 return false;
12769 }
12770 ts.isStatementWithLocals = isStatementWithLocals;
12771 function getStartPositionOfLine(line, sourceFile) {
12772 ts.Debug.assert(line >= 0);
12773 return ts.getLineStarts(sourceFile)[line];
12774 }
12775 ts.getStartPositionOfLine = getStartPositionOfLine;
12776 // This is a useful function for debugging purposes.
12777 function nodePosToString(node) {
12778 var file = getSourceFileOfNode(node);
12779 var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
12780 return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
12781 }
12782 ts.nodePosToString = nodePosToString;
12783 function getEndLinePosition(line, sourceFile) {
12784 ts.Debug.assert(line >= 0);
12785 var lineStarts = ts.getLineStarts(sourceFile);
12786 var lineIndex = line;
12787 var sourceText = sourceFile.text;
12788 if (lineIndex + 1 === lineStarts.length) {
12789 // last line - return EOF
12790 return sourceText.length - 1;
12791 }
12792 else {
12793 // current line start
12794 var start = lineStarts[lineIndex];
12795 // take the start position of the next line - 1 = it should be some line break
12796 var pos = lineStarts[lineIndex + 1] - 1;
12797 ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
12798 // walk backwards skipping line breaks, stop the the beginning of current line.
12799 // i.e:
12800 // <some text>
12801 // $ <- end of line for this position should match the start position
12802 while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
12803 pos--;
12804 }
12805 return pos;
12806 }
12807 }
12808 ts.getEndLinePosition = getEndLinePosition;
12809 /**
12810 * Returns a value indicating whether a name is unique globally or within the current file.
12811 * 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`.
12812 */
12813 function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
12814 return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
12815 }
12816 ts.isFileLevelUniqueName = isFileLevelUniqueName;
12817 // Returns true if this node is missing from the actual source code. A 'missing' node is different
12818 // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
12819 // in the tree), it is definitely missing. However, a node may be defined, but still be
12820 // missing. This happens whenever the parser knows it needs to parse something, but can't
12821 // get anything in the source code that it expects at that location. For example:
12822 //
12823 // let a: ;
12824 //
12825 // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
12826 // code). So the parser will attempt to parse out a type, and will create an actual node.
12827 // However, this node will be 'missing' in the sense that no actual source-code/tokens are
12828 // contained within it.
12829 function nodeIsMissing(node) {
12830 if (node === undefined) {
12831 return true;
12832 }
12833 return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
12834 }
12835 ts.nodeIsMissing = nodeIsMissing;
12836 function nodeIsPresent(node) {
12837 return !nodeIsMissing(node);
12838 }
12839 ts.nodeIsPresent = nodeIsPresent;
12840 function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
12841 if (from === undefined || from.length === 0)
12842 return to;
12843 var statementIndex = 0;
12844 // skip all prologue directives to insert at the correct position
12845 for (; statementIndex < to.length; ++statementIndex) {
12846 if (!isPrologueDirective(to[statementIndex])) {
12847 break;
12848 }
12849 }
12850 to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
12851 return to;
12852 }
12853 function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
12854 if (statement === undefined)
12855 return to;
12856 var statementIndex = 0;
12857 // skip all prologue directives to insert at the correct position
12858 for (; statementIndex < to.length; ++statementIndex) {
12859 if (!isPrologueDirective(to[statementIndex])) {
12860 break;
12861 }
12862 }
12863 to.splice(statementIndex, 0, statement);
12864 return to;
12865 }
12866 function isAnyPrologueDirective(node) {
12867 return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
12868 }
12869 /**
12870 * Prepends statements to an array while taking care of prologue directives.
12871 */
12872 function insertStatementsAfterStandardPrologue(to, from) {
12873 return insertStatementsAfterPrologue(to, from, isPrologueDirective);
12874 }
12875 ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
12876 function insertStatementsAfterCustomPrologue(to, from) {
12877 return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
12878 }
12879 ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
12880 /**
12881 * Prepends statements to an array while taking care of prologue directives.
12882 */
12883 function insertStatementAfterStandardPrologue(to, statement) {
12884 return insertStatementAfterPrologue(to, statement, isPrologueDirective);
12885 }
12886 ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
12887 function insertStatementAfterCustomPrologue(to, statement) {
12888 return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
12889 }
12890 ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
12891 /**
12892 * Determine if the given comment is a triple-slash
12893 *
12894 * @return true if the comment is a triple-slash comment else false
12895 */
12896 function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
12897 // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
12898 // so that we don't end up computing comment string and doing match for all // comments
12899 if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
12900 commentPos + 2 < commentEnd &&
12901 text.charCodeAt(commentPos + 2) === 47 /* slash */) {
12902 var textSubStr = text.substring(commentPos, commentEnd);
12903 return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
12904 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
12905 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
12906 textSubStr.match(defaultLibReferenceRegEx) ?
12907 true : false;
12908 }
12909 return false;
12910 }
12911 ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
12912 function isPinnedComment(text, start) {
12913 return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
12914 text.charCodeAt(start + 2) === 33 /* exclamation */;
12915 }
12916 ts.isPinnedComment = isPinnedComment;
12917 function createCommentDirectivesMap(sourceFile, commentDirectives) {
12918 var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
12919 "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
12920 commentDirective,
12921 ]); }));
12922 var usedLines = new ts.Map();
12923 return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
12924 function getUnusedExpectations() {
12925 return ts.arrayFrom(directivesByLine.entries())
12926 .filter(function (_a) {
12927 var line = _a[0], directive = _a[1];
12928 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
12929 })
12930 .map(function (_a) {
12931 var _ = _a[0], directive = _a[1];
12932 return directive;
12933 });
12934 }
12935 function markUsed(line) {
12936 if (!directivesByLine.has("" + line)) {
12937 return false;
12938 }
12939 usedLines.set("" + line, true);
12940 return true;
12941 }
12942 }
12943 ts.createCommentDirectivesMap = createCommentDirectivesMap;
12944 function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
12945 // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
12946 // want to skip trivia because this will launch us forward to the next token.
12947 if (nodeIsMissing(node)) {
12948 return node.pos;
12949 }
12950 if (ts.isJSDocNode(node) || node.kind === 11 /* JsxText */) {
12951 // JsxText cannot actually contain comments, even though the scanner will think it sees comments
12952 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
12953 }
12954 if (includeJsDoc && ts.hasJSDocNodes(node)) {
12955 return getTokenPosOfNode(node.jsDoc[0], sourceFile);
12956 }
12957 // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
12958 // the syntax list itself considers them as normal trivia. Therefore if we simply skip
12959 // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
12960 // first child to determine the actual position of its first token.
12961 if (node.kind === 329 /* SyntaxList */ && node._children.length > 0) {
12962 return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
12963 }
12964 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
12965 }
12966 ts.getTokenPosOfNode = getTokenPosOfNode;
12967 function getNonDecoratorTokenPosOfNode(node, sourceFile) {
12968 if (nodeIsMissing(node) || !node.decorators) {
12969 return getTokenPosOfNode(node, sourceFile);
12970 }
12971 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
12972 }
12973 ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
12974 function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
12975 if (includeTrivia === void 0) { includeTrivia = false; }
12976 return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
12977 }
12978 ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
12979 function isJSDocTypeExpressionOrChild(node) {
12980 return !!findAncestor(node, ts.isJSDocTypeExpression);
12981 }
12982 function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
12983 if (includeTrivia === void 0) { includeTrivia = false; }
12984 if (nodeIsMissing(node)) {
12985 return "";
12986 }
12987 var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
12988 if (isJSDocTypeExpressionOrChild(node)) {
12989 // strip space + asterisk at line start
12990 text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
12991 }
12992 return text;
12993 }
12994 ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
12995 function getTextOfNode(node, includeTrivia) {
12996 if (includeTrivia === void 0) { includeTrivia = false; }
12997 return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
12998 }
12999 ts.getTextOfNode = getTextOfNode;
13000 function getPos(range) {
13001 return range.pos;
13002 }
13003 /**
13004 * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13005 * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13006 */
13007 function indexOfNode(nodeArray, node) {
13008 return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13009 }
13010 ts.indexOfNode = indexOfNode;
13011 /**
13012 * Gets flags that control emit behavior of a node.
13013 */
13014 function getEmitFlags(node) {
13015 var emitNode = node.emitNode;
13016 return emitNode && emitNode.flags || 0;
13017 }
13018 ts.getEmitFlags = getEmitFlags;
13019 function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13020 // If we don't need to downlevel and we can reach the original source text using
13021 // the node's parent reference, then simply get the text as it was originally written.
13022 if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13023 ts.isBigIntLiteral(node))) {
13024 return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13025 }
13026 // If we can't reach the original source text, use the canonical form if it's a number,
13027 // or a (possibly escaped) quoted form of the original text if it's string-like.
13028 switch (node.kind) {
13029 case 10 /* StringLiteral */: {
13030 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13031 neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13032 escapeNonAsciiString;
13033 if (node.singleQuote) {
13034 return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13035 }
13036 else {
13037 return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13038 }
13039 }
13040 case 14 /* NoSubstitutionTemplateLiteral */:
13041 case 15 /* TemplateHead */:
13042 case 16 /* TemplateMiddle */:
13043 case 17 /* TemplateTail */: {
13044 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13045 // had to include a backslash: `not \${a} substitution`.
13046 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13047 escapeNonAsciiString;
13048 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13049 switch (node.kind) {
13050 case 14 /* NoSubstitutionTemplateLiteral */:
13051 return "`" + rawText + "`";
13052 case 15 /* TemplateHead */:
13053 return "`" + rawText + "${";
13054 case 16 /* TemplateMiddle */:
13055 return "}" + rawText + "${";
13056 case 17 /* TemplateTail */:
13057 return "}" + rawText + "`";
13058 }
13059 break;
13060 }
13061 case 8 /* NumericLiteral */:
13062 case 9 /* BigIntLiteral */:
13063 case 13 /* RegularExpressionLiteral */:
13064 return node.text;
13065 }
13066 return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13067 }
13068 ts.getLiteralText = getLiteralText;
13069 function getTextOfConstantValue(value) {
13070 return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13071 }
13072 ts.getTextOfConstantValue = getTextOfConstantValue;
13073 // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13074 // all non-alphanumeric characters with underscores
13075 function makeIdentifierFromModuleName(moduleName) {
13076 return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13077 }
13078 ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13079 function isBlockOrCatchScoped(declaration) {
13080 return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13081 isCatchClauseVariableDeclarationOrBindingElement(declaration);
13082 }
13083 ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13084 function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13085 var node = getRootDeclaration(declaration);
13086 return node.kind === 246 /* VariableDeclaration */ && node.parent.kind === 284 /* CatchClause */;
13087 }
13088 ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13089 function isAmbientModule(node) {
13090 return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13091 }
13092 ts.isAmbientModule = isAmbientModule;
13093 function isModuleWithStringLiteralName(node) {
13094 return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13095 }
13096 ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13097 function isNonGlobalAmbientModule(node) {
13098 return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13099 }
13100 ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13101 /**
13102 * An effective module (namespace) declaration is either
13103 * 1. An actual declaration: namespace X { ... }
13104 * 2. A Javascript declaration, which is:
13105 * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13106 */
13107 function isEffectiveModuleDeclaration(node) {
13108 return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13109 }
13110 ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13111 /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13112 function isShorthandAmbientModuleSymbol(moduleSymbol) {
13113 return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13114 }
13115 ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13116 function isShorthandAmbientModule(node) {
13117 // The only kind of module that can be missing a body is a shorthand ambient module.
13118 return node && node.kind === 253 /* ModuleDeclaration */ && (!node.body);
13119 }
13120 function isBlockScopedContainerTopLevel(node) {
13121 return node.kind === 294 /* SourceFile */ ||
13122 node.kind === 253 /* ModuleDeclaration */ ||
13123 ts.isFunctionLike(node);
13124 }
13125 ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13126 function isGlobalScopeAugmentation(module) {
13127 return !!(module.flags & 1024 /* GlobalAugmentation */);
13128 }
13129 ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13130 function isExternalModuleAugmentation(node) {
13131 return isAmbientModule(node) && isModuleAugmentationExternal(node);
13132 }
13133 ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13134 function isModuleAugmentationExternal(node) {
13135 // external module augmentation is a ambient module declaration that is either:
13136 // - defined in the top level scope and source file is an external module
13137 // - defined inside ambient module declaration located in the top level scope and source file not an external module
13138 switch (node.parent.kind) {
13139 case 294 /* SourceFile */:
13140 return ts.isExternalModule(node.parent);
13141 case 254 /* ModuleBlock */:
13142 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13143 }
13144 return false;
13145 }
13146 ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13147 function getNonAugmentationDeclaration(symbol) {
13148 return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13149 }
13150 ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13151 function isEffectiveExternalModule(node, compilerOptions) {
13152 return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13153 }
13154 ts.isEffectiveExternalModule = isEffectiveExternalModule;
13155 /**
13156 * Returns whether the source file will be treated as if it were in strict mode at runtime.
13157 */
13158 function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13159 // We can only verify strict mode for JS/TS files
13160 switch (node.scriptKind) {
13161 case 1 /* JS */:
13162 case 3 /* TS */:
13163 case 2 /* JSX */:
13164 case 4 /* TSX */:
13165 break;
13166 default:
13167 return false;
13168 }
13169 // Strict mode does not matter for declaration files.
13170 if (node.isDeclarationFile) {
13171 return false;
13172 }
13173 // If `alwaysStrict` is set, then treat the file as strict.
13174 if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13175 return true;
13176 }
13177 // Starting with a "use strict" directive indicates the file is strict.
13178 if (ts.startsWithUseStrict(node.statements)) {
13179 return true;
13180 }
13181 if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13182 // ECMAScript Modules are always strict.
13183 if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13184 return true;
13185 }
13186 // Other modules are strict unless otherwise specified.
13187 return !compilerOptions.noImplicitUseStrict;
13188 }
13189 return false;
13190 }
13191 ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13192 function isBlockScope(node, parentNode) {
13193 switch (node.kind) {
13194 case 294 /* SourceFile */:
13195 case 255 /* CaseBlock */:
13196 case 284 /* CatchClause */:
13197 case 253 /* ModuleDeclaration */:
13198 case 234 /* ForStatement */:
13199 case 235 /* ForInStatement */:
13200 case 236 /* ForOfStatement */:
13201 case 165 /* Constructor */:
13202 case 164 /* MethodDeclaration */:
13203 case 166 /* GetAccessor */:
13204 case 167 /* SetAccessor */:
13205 case 248 /* FunctionDeclaration */:
13206 case 205 /* FunctionExpression */:
13207 case 206 /* ArrowFunction */:
13208 return true;
13209 case 227 /* Block */:
13210 // function block is not considered block-scope container
13211 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13212 return !ts.isFunctionLike(parentNode);
13213 }
13214 return false;
13215 }
13216 ts.isBlockScope = isBlockScope;
13217 function isDeclarationWithTypeParameters(node) {
13218 switch (node.kind) {
13219 case 320 /* JSDocCallbackTag */:
13220 case 327 /* JSDocTypedefTag */:
13221 case 309 /* JSDocSignature */:
13222 return true;
13223 default:
13224 ts.assertType(node);
13225 return isDeclarationWithTypeParameterChildren(node);
13226 }
13227 }
13228 ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13229 function isDeclarationWithTypeParameterChildren(node) {
13230 switch (node.kind) {
13231 case 168 /* CallSignature */:
13232 case 169 /* ConstructSignature */:
13233 case 163 /* MethodSignature */:
13234 case 170 /* IndexSignature */:
13235 case 173 /* FunctionType */:
13236 case 174 /* ConstructorType */:
13237 case 304 /* JSDocFunctionType */:
13238 case 249 /* ClassDeclaration */:
13239 case 218 /* ClassExpression */:
13240 case 250 /* InterfaceDeclaration */:
13241 case 251 /* TypeAliasDeclaration */:
13242 case 326 /* JSDocTemplateTag */:
13243 case 248 /* FunctionDeclaration */:
13244 case 164 /* MethodDeclaration */:
13245 case 165 /* Constructor */:
13246 case 166 /* GetAccessor */:
13247 case 167 /* SetAccessor */:
13248 case 205 /* FunctionExpression */:
13249 case 206 /* ArrowFunction */:
13250 return true;
13251 default:
13252 ts.assertType(node);
13253 return false;
13254 }
13255 }
13256 ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13257 function isAnyImportSyntax(node) {
13258 switch (node.kind) {
13259 case 258 /* ImportDeclaration */:
13260 case 257 /* ImportEqualsDeclaration */:
13261 return true;
13262 default:
13263 return false;
13264 }
13265 }
13266 ts.isAnyImportSyntax = isAnyImportSyntax;
13267 function isLateVisibilityPaintedStatement(node) {
13268 switch (node.kind) {
13269 case 258 /* ImportDeclaration */:
13270 case 257 /* ImportEqualsDeclaration */:
13271 case 229 /* VariableStatement */:
13272 case 249 /* ClassDeclaration */:
13273 case 248 /* FunctionDeclaration */:
13274 case 253 /* ModuleDeclaration */:
13275 case 251 /* TypeAliasDeclaration */:
13276 case 250 /* InterfaceDeclaration */:
13277 case 252 /* EnumDeclaration */:
13278 return true;
13279 default:
13280 return false;
13281 }
13282 }
13283 ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13284 function isAnyImportOrReExport(node) {
13285 return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13286 }
13287 ts.isAnyImportOrReExport = isAnyImportOrReExport;
13288 // Gets the nearest enclosing block scope container that has the provided node
13289 // as a descendant, that is not the provided node.
13290 function getEnclosingBlockScopeContainer(node) {
13291 return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13292 }
13293 ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13294 // Return display name of an identifier
13295 // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13296 // text of the expression in the computed property.
13297 function declarationNameToString(name) {
13298 return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13299 }
13300 ts.declarationNameToString = declarationNameToString;
13301 function getNameFromIndexInfo(info) {
13302 return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13303 }
13304 ts.getNameFromIndexInfo = getNameFromIndexInfo;
13305 function isComputedNonLiteralName(name) {
13306 return name.kind === 157 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13307 }
13308 ts.isComputedNonLiteralName = isComputedNonLiteralName;
13309 function getTextOfPropertyName(name) {
13310 switch (name.kind) {
13311 case 78 /* Identifier */:
13312 case 79 /* PrivateIdentifier */:
13313 return name.escapedText;
13314 case 10 /* StringLiteral */:
13315 case 8 /* NumericLiteral */:
13316 case 14 /* NoSubstitutionTemplateLiteral */:
13317 return ts.escapeLeadingUnderscores(name.text);
13318 case 157 /* ComputedPropertyName */:
13319 if (isStringOrNumericLiteralLike(name.expression))
13320 return ts.escapeLeadingUnderscores(name.expression.text);
13321 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13322 default:
13323 return ts.Debug.assertNever(name);
13324 }
13325 }
13326 ts.getTextOfPropertyName = getTextOfPropertyName;
13327 function entityNameToString(name) {
13328 switch (name.kind) {
13329 case 107 /* ThisKeyword */:
13330 return "this";
13331 case 79 /* PrivateIdentifier */:
13332 case 78 /* Identifier */:
13333 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13334 case 156 /* QualifiedName */:
13335 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13336 case 198 /* PropertyAccessExpression */:
13337 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13338 return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13339 }
13340 else {
13341 return ts.Debug.assertNever(name.name);
13342 }
13343 default:
13344 return ts.Debug.assertNever(name);
13345 }
13346 }
13347 ts.entityNameToString = entityNameToString;
13348 function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13349 var sourceFile = getSourceFileOfNode(node);
13350 return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13351 }
13352 ts.createDiagnosticForNode = createDiagnosticForNode;
13353 function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13354 var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13355 return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13356 }
13357 ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13358 function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13359 var span = getErrorSpanForNode(sourceFile, node);
13360 return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13361 }
13362 ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13363 function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13364 var sourceFile = getSourceFileOfNode(node);
13365 var span = getErrorSpanForNode(sourceFile, node);
13366 return {
13367 file: sourceFile,
13368 start: span.start,
13369 length: span.length,
13370 code: messageChain.code,
13371 category: messageChain.category,
13372 messageText: messageChain.next ? messageChain : messageChain.messageText,
13373 relatedInformation: relatedInformation
13374 };
13375 }
13376 ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13377 function createDiagnosticForRange(sourceFile, range, message) {
13378 return {
13379 file: sourceFile,
13380 start: range.pos,
13381 length: range.end - range.pos,
13382 code: message.code,
13383 category: message.category,
13384 messageText: message.message,
13385 };
13386 }
13387 ts.createDiagnosticForRange = createDiagnosticForRange;
13388 function getSpanOfTokenAtPosition(sourceFile, pos) {
13389 var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13390 scanner.scan();
13391 var start = scanner.getTokenPos();
13392 return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13393 }
13394 ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13395 function getErrorSpanForArrowFunction(sourceFile, node) {
13396 var pos = ts.skipTrivia(sourceFile.text, node.pos);
13397 if (node.body && node.body.kind === 227 /* Block */) {
13398 var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13399 var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13400 if (startLine < endLine) {
13401 // The arrow function spans multiple lines,
13402 // make the error span be the first line, inclusive.
13403 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13404 }
13405 }
13406 return ts.createTextSpanFromBounds(pos, node.end);
13407 }
13408 function getErrorSpanForNode(sourceFile, node) {
13409 var errorNode = node;
13410 switch (node.kind) {
13411 case 294 /* SourceFile */:
13412 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13413 if (pos_1 === sourceFile.text.length) {
13414 // file is empty - return span for the beginning of the file
13415 return ts.createTextSpan(0, 0);
13416 }
13417 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13418 // This list is a work in progress. Add missing node kinds to improve their error
13419 // spans.
13420 case 246 /* VariableDeclaration */:
13421 case 195 /* BindingElement */:
13422 case 249 /* ClassDeclaration */:
13423 case 218 /* ClassExpression */:
13424 case 250 /* InterfaceDeclaration */:
13425 case 253 /* ModuleDeclaration */:
13426 case 252 /* EnumDeclaration */:
13427 case 288 /* EnumMember */:
13428 case 248 /* FunctionDeclaration */:
13429 case 205 /* FunctionExpression */:
13430 case 164 /* MethodDeclaration */:
13431 case 166 /* GetAccessor */:
13432 case 167 /* SetAccessor */:
13433 case 251 /* TypeAliasDeclaration */:
13434 case 162 /* PropertyDeclaration */:
13435 case 161 /* PropertySignature */:
13436 errorNode = node.name;
13437 break;
13438 case 206 /* ArrowFunction */:
13439 return getErrorSpanForArrowFunction(sourceFile, node);
13440 case 281 /* CaseClause */:
13441 case 282 /* DefaultClause */:
13442 var start = ts.skipTrivia(sourceFile.text, node.pos);
13443 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13444 return ts.createTextSpanFromBounds(start, end);
13445 }
13446 if (errorNode === undefined) {
13447 // If we don't have a better node, then just set the error on the first token of
13448 // construct.
13449 return getSpanOfTokenAtPosition(sourceFile, node.pos);
13450 }
13451 ts.Debug.assert(!ts.isJSDoc(errorNode));
13452 var isMissing = nodeIsMissing(errorNode);
13453 var pos = isMissing || ts.isJsxText(node)
13454 ? errorNode.pos
13455 : ts.skipTrivia(sourceFile.text, errorNode.pos);
13456 // These asserts should all be satisfied for a properly constructed `errorNode`.
13457 if (isMissing) {
13458 ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13459 ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13460 }
13461 else {
13462 ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13463 ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13464 }
13465 return ts.createTextSpanFromBounds(pos, errorNode.end);
13466 }
13467 ts.getErrorSpanForNode = getErrorSpanForNode;
13468 function isExternalOrCommonJsModule(file) {
13469 return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13470 }
13471 ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13472 function isJsonSourceFile(file) {
13473 return file.scriptKind === 6 /* JSON */;
13474 }
13475 ts.isJsonSourceFile = isJsonSourceFile;
13476 function isEnumConst(node) {
13477 return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13478 }
13479 ts.isEnumConst = isEnumConst;
13480 function isDeclarationReadonly(declaration) {
13481 return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13482 }
13483 ts.isDeclarationReadonly = isDeclarationReadonly;
13484 function isVarConst(node) {
13485 return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13486 }
13487 ts.isVarConst = isVarConst;
13488 function isLet(node) {
13489 return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13490 }
13491 ts.isLet = isLet;
13492 function isSuperCall(n) {
13493 return n.kind === 200 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */;
13494 }
13495 ts.isSuperCall = isSuperCall;
13496 function isImportCall(n) {
13497 return n.kind === 200 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */;
13498 }
13499 ts.isImportCall = isImportCall;
13500 function isImportMeta(n) {
13501 return ts.isMetaProperty(n)
13502 && n.keywordToken === 99 /* ImportKeyword */
13503 && n.name.escapedText === "meta";
13504 }
13505 ts.isImportMeta = isImportMeta;
13506 function isLiteralImportTypeNode(n) {
13507 return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13508 }
13509 ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13510 function isPrologueDirective(node) {
13511 return node.kind === 230 /* ExpressionStatement */
13512 && node.expression.kind === 10 /* StringLiteral */;
13513 }
13514 ts.isPrologueDirective = isPrologueDirective;
13515 function isCustomPrologue(node) {
13516 return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13517 }
13518 ts.isCustomPrologue = isCustomPrologue;
13519 function isHoistedFunction(node) {
13520 return isCustomPrologue(node)
13521 && ts.isFunctionDeclaration(node);
13522 }
13523 ts.isHoistedFunction = isHoistedFunction;
13524 function isHoistedVariable(node) {
13525 return ts.isIdentifier(node.name)
13526 && !node.initializer;
13527 }
13528 function isHoistedVariableStatement(node) {
13529 return isCustomPrologue(node)
13530 && ts.isVariableStatement(node)
13531 && ts.every(node.declarationList.declarations, isHoistedVariable);
13532 }
13533 ts.isHoistedVariableStatement = isHoistedVariableStatement;
13534 function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13535 return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13536 }
13537 ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13538 function getJSDocCommentRanges(node, text) {
13539 var commentRanges = (node.kind === 159 /* Parameter */ ||
13540 node.kind === 158 /* TypeParameter */ ||
13541 node.kind === 205 /* FunctionExpression */ ||
13542 node.kind === 206 /* ArrowFunction */ ||
13543 node.kind === 204 /* ParenthesizedExpression */) ?
13544 ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13545 ts.getLeadingCommentRanges(text, node.pos);
13546 // True if the comment starts with '/**' but not if it is '/**/'
13547 return ts.filter(commentRanges, function (comment) {
13548 return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13549 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13550 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13551 });
13552 }
13553 ts.getJSDocCommentRanges = getJSDocCommentRanges;
13554 ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13555 var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13556 ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13557 var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13558 function isPartOfTypeNode(node) {
13559 if (171 /* FirstTypeNode */ <= node.kind && node.kind <= 192 /* LastTypeNode */) {
13560 return true;
13561 }
13562 switch (node.kind) {
13563 case 128 /* AnyKeyword */:
13564 case 151 /* UnknownKeyword */:
13565 case 143 /* NumberKeyword */:
13566 case 154 /* BigIntKeyword */:
13567 case 146 /* StringKeyword */:
13568 case 131 /* BooleanKeyword */:
13569 case 147 /* SymbolKeyword */:
13570 case 144 /* ObjectKeyword */:
13571 case 149 /* UndefinedKeyword */:
13572 case 140 /* NeverKeyword */:
13573 return true;
13574 case 113 /* VoidKeyword */:
13575 return node.parent.kind !== 209 /* VoidExpression */;
13576 case 220 /* ExpressionWithTypeArguments */:
13577 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13578 case 158 /* TypeParameter */:
13579 return node.parent.kind === 189 /* MappedType */ || node.parent.kind === 184 /* InferType */;
13580 // Identifiers and qualified names may be type nodes, depending on their context. Climb
13581 // above them to find the lowest container
13582 case 78 /* Identifier */:
13583 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13584 if (node.parent.kind === 156 /* QualifiedName */ && node.parent.right === node) {
13585 node = node.parent;
13586 }
13587 else if (node.parent.kind === 198 /* PropertyAccessExpression */ && node.parent.name === node) {
13588 node = node.parent;
13589 }
13590 // At this point, node is either a qualified name or an identifier
13591 ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 156 /* QualifiedName */ || node.kind === 198 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
13592 // falls through
13593 case 156 /* QualifiedName */:
13594 case 198 /* PropertyAccessExpression */:
13595 case 107 /* ThisKeyword */: {
13596 var parent = node.parent;
13597 if (parent.kind === 175 /* TypeQuery */) {
13598 return false;
13599 }
13600 if (parent.kind === 192 /* ImportType */) {
13601 return !parent.isTypeOf;
13602 }
13603 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13604 //
13605 // let a: A.B.C;
13606 //
13607 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13608 // Only C and A.B.C are type nodes.
13609 if (171 /* FirstTypeNode */ <= parent.kind && parent.kind <= 192 /* LastTypeNode */) {
13610 return true;
13611 }
13612 switch (parent.kind) {
13613 case 220 /* ExpressionWithTypeArguments */:
13614 return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13615 case 158 /* TypeParameter */:
13616 return node === parent.constraint;
13617 case 326 /* JSDocTemplateTag */:
13618 return node === parent.constraint;
13619 case 162 /* PropertyDeclaration */:
13620 case 161 /* PropertySignature */:
13621 case 159 /* Parameter */:
13622 case 246 /* VariableDeclaration */:
13623 return node === parent.type;
13624 case 248 /* FunctionDeclaration */:
13625 case 205 /* FunctionExpression */:
13626 case 206 /* ArrowFunction */:
13627 case 165 /* Constructor */:
13628 case 164 /* MethodDeclaration */:
13629 case 163 /* MethodSignature */:
13630 case 166 /* GetAccessor */:
13631 case 167 /* SetAccessor */:
13632 return node === parent.type;
13633 case 168 /* CallSignature */:
13634 case 169 /* ConstructSignature */:
13635 case 170 /* IndexSignature */:
13636 return node === parent.type;
13637 case 203 /* TypeAssertionExpression */:
13638 return node === parent.type;
13639 case 200 /* CallExpression */:
13640 case 201 /* NewExpression */:
13641 return ts.contains(parent.typeArguments, node);
13642 case 202 /* TaggedTemplateExpression */:
13643 // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13644 return false;
13645 }
13646 }
13647 }
13648 return false;
13649 }
13650 ts.isPartOfTypeNode = isPartOfTypeNode;
13651 function isChildOfNodeWithKind(node, kind) {
13652 while (node) {
13653 if (node.kind === kind) {
13654 return true;
13655 }
13656 node = node.parent;
13657 }
13658 return false;
13659 }
13660 ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13661 // Warning: This has the same semantics as the forEach family of functions,
13662 // in that traversal terminates in the event that 'visitor' supplies a truthy value.
13663 function forEachReturnStatement(body, visitor) {
13664 return traverse(body);
13665 function traverse(node) {
13666 switch (node.kind) {
13667 case 239 /* ReturnStatement */:
13668 return visitor(node);
13669 case 255 /* CaseBlock */:
13670 case 227 /* Block */:
13671 case 231 /* IfStatement */:
13672 case 232 /* DoStatement */:
13673 case 233 /* WhileStatement */:
13674 case 234 /* ForStatement */:
13675 case 235 /* ForInStatement */:
13676 case 236 /* ForOfStatement */:
13677 case 240 /* WithStatement */:
13678 case 241 /* SwitchStatement */:
13679 case 281 /* CaseClause */:
13680 case 282 /* DefaultClause */:
13681 case 242 /* LabeledStatement */:
13682 case 244 /* TryStatement */:
13683 case 284 /* CatchClause */:
13684 return ts.forEachChild(node, traverse);
13685 }
13686 }
13687 }
13688 ts.forEachReturnStatement = forEachReturnStatement;
13689 function forEachYieldExpression(body, visitor) {
13690 return traverse(body);
13691 function traverse(node) {
13692 switch (node.kind) {
13693 case 216 /* YieldExpression */:
13694 visitor(node);
13695 var operand = node.expression;
13696 if (operand) {
13697 traverse(operand);
13698 }
13699 return;
13700 case 252 /* EnumDeclaration */:
13701 case 250 /* InterfaceDeclaration */:
13702 case 253 /* ModuleDeclaration */:
13703 case 251 /* TypeAliasDeclaration */:
13704 // These are not allowed inside a generator now, but eventually they may be allowed
13705 // as local types. Regardless, skip them to avoid the work.
13706 return;
13707 default:
13708 if (ts.isFunctionLike(node)) {
13709 if (node.name && node.name.kind === 157 /* ComputedPropertyName */) {
13710 // Note that we will not include methods/accessors of a class because they would require
13711 // first descending into the class. This is by design.
13712 traverse(node.name.expression);
13713 return;
13714 }
13715 }
13716 else if (!isPartOfTypeNode(node)) {
13717 // This is the general case, which should include mostly expressions and statements.
13718 // Also includes NodeArrays.
13719 ts.forEachChild(node, traverse);
13720 }
13721 }
13722 }
13723 }
13724 ts.forEachYieldExpression = forEachYieldExpression;
13725 /**
13726 * Gets the most likely element type for a TypeNode. This is not an exhaustive test
13727 * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
13728 *
13729 * @param node The type node.
13730 */
13731 function getRestParameterElementType(node) {
13732 if (node && node.kind === 177 /* ArrayType */) {
13733 return node.elementType;
13734 }
13735 else if (node && node.kind === 172 /* TypeReference */) {
13736 return ts.singleOrUndefined(node.typeArguments);
13737 }
13738 else {
13739 return undefined;
13740 }
13741 }
13742 ts.getRestParameterElementType = getRestParameterElementType;
13743 function getMembersOfDeclaration(node) {
13744 switch (node.kind) {
13745 case 250 /* InterfaceDeclaration */:
13746 case 249 /* ClassDeclaration */:
13747 case 218 /* ClassExpression */:
13748 case 176 /* TypeLiteral */:
13749 return node.members;
13750 case 197 /* ObjectLiteralExpression */:
13751 return node.properties;
13752 }
13753 }
13754 ts.getMembersOfDeclaration = getMembersOfDeclaration;
13755 function isVariableLike(node) {
13756 if (node) {
13757 switch (node.kind) {
13758 case 195 /* BindingElement */:
13759 case 288 /* EnumMember */:
13760 case 159 /* Parameter */:
13761 case 285 /* PropertyAssignment */:
13762 case 162 /* PropertyDeclaration */:
13763 case 161 /* PropertySignature */:
13764 case 286 /* ShorthandPropertyAssignment */:
13765 case 246 /* VariableDeclaration */:
13766 return true;
13767 }
13768 }
13769 return false;
13770 }
13771 ts.isVariableLike = isVariableLike;
13772 function isVariableLikeOrAccessor(node) {
13773 return isVariableLike(node) || ts.isAccessor(node);
13774 }
13775 ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
13776 function isVariableDeclarationInVariableStatement(node) {
13777 return node.parent.kind === 247 /* VariableDeclarationList */
13778 && node.parent.parent.kind === 229 /* VariableStatement */;
13779 }
13780 ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
13781 function isValidESSymbolDeclaration(node) {
13782 return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
13783 ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
13784 ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
13785 }
13786 ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
13787 function introducesArgumentsExoticObject(node) {
13788 switch (node.kind) {
13789 case 164 /* MethodDeclaration */:
13790 case 163 /* MethodSignature */:
13791 case 165 /* Constructor */:
13792 case 166 /* GetAccessor */:
13793 case 167 /* SetAccessor */:
13794 case 248 /* FunctionDeclaration */:
13795 case 205 /* FunctionExpression */:
13796 return true;
13797 }
13798 return false;
13799 }
13800 ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
13801 function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
13802 while (true) {
13803 if (beforeUnwrapLabelCallback) {
13804 beforeUnwrapLabelCallback(node);
13805 }
13806 if (node.statement.kind !== 242 /* LabeledStatement */) {
13807 return node.statement;
13808 }
13809 node = node.statement;
13810 }
13811 }
13812 ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
13813 function isFunctionBlock(node) {
13814 return node && node.kind === 227 /* Block */ && ts.isFunctionLike(node.parent);
13815 }
13816 ts.isFunctionBlock = isFunctionBlock;
13817 function isObjectLiteralMethod(node) {
13818 return node && node.kind === 164 /* MethodDeclaration */ && node.parent.kind === 197 /* ObjectLiteralExpression */;
13819 }
13820 ts.isObjectLiteralMethod = isObjectLiteralMethod;
13821 function isObjectLiteralOrClassExpressionMethod(node) {
13822 return node.kind === 164 /* MethodDeclaration */ &&
13823 (node.parent.kind === 197 /* ObjectLiteralExpression */ ||
13824 node.parent.kind === 218 /* ClassExpression */);
13825 }
13826 ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
13827 function isIdentifierTypePredicate(predicate) {
13828 return predicate && predicate.kind === 1 /* Identifier */;
13829 }
13830 ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
13831 function isThisTypePredicate(predicate) {
13832 return predicate && predicate.kind === 0 /* This */;
13833 }
13834 ts.isThisTypePredicate = isThisTypePredicate;
13835 function getPropertyAssignment(objectLiteral, key, key2) {
13836 return objectLiteral.properties.filter(function (property) {
13837 if (property.kind === 285 /* PropertyAssignment */) {
13838 var propName = getTextOfPropertyName(property.name);
13839 return key === propName || (!!key2 && key2 === propName);
13840 }
13841 return false;
13842 });
13843 }
13844 ts.getPropertyAssignment = getPropertyAssignment;
13845 function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
13846 if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
13847 var expression = tsConfigSourceFile.statements[0].expression;
13848 return ts.tryCast(expression, ts.isObjectLiteralExpression);
13849 }
13850 }
13851 ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
13852 function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
13853 return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
13854 return ts.isArrayLiteralExpression(property.initializer) ?
13855 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
13856 undefined;
13857 });
13858 }
13859 ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
13860 function getTsConfigPropArray(tsConfigSourceFile, propKey) {
13861 var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
13862 return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
13863 }
13864 ts.getTsConfigPropArray = getTsConfigPropArray;
13865 function getContainingFunction(node) {
13866 return findAncestor(node.parent, ts.isFunctionLike);
13867 }
13868 ts.getContainingFunction = getContainingFunction;
13869 function getContainingFunctionDeclaration(node) {
13870 return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
13871 }
13872 ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
13873 function getContainingClass(node) {
13874 return findAncestor(node.parent, ts.isClassLike);
13875 }
13876 ts.getContainingClass = getContainingClass;
13877 function getThisContainer(node, includeArrowFunctions) {
13878 ts.Debug.assert(node.kind !== 294 /* SourceFile */);
13879 while (true) {
13880 node = node.parent;
13881 if (!node) {
13882 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
13883 }
13884 switch (node.kind) {
13885 case 157 /* ComputedPropertyName */:
13886 // If the grandparent node is an object literal (as opposed to a class),
13887 // then the computed property is not a 'this' container.
13888 // A computed property name in a class needs to be a this container
13889 // so that we can error on it.
13890 if (ts.isClassLike(node.parent.parent)) {
13891 return node;
13892 }
13893 // If this is a computed property, then the parent should not
13894 // make it a this container. The parent might be a property
13895 // in an object literal, like a method or accessor. But in order for
13896 // such a parent to be a this container, the reference must be in
13897 // the *body* of the container.
13898 node = node.parent;
13899 break;
13900 case 160 /* Decorator */:
13901 // Decorators are always applied outside of the body of a class or method.
13902 if (node.parent.kind === 159 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
13903 // If the decorator's parent is a Parameter, we resolve the this container from
13904 // the grandparent class declaration.
13905 node = node.parent.parent;
13906 }
13907 else if (ts.isClassElement(node.parent)) {
13908 // If the decorator's parent is a class element, we resolve the 'this' container
13909 // from the parent class declaration.
13910 node = node.parent;
13911 }
13912 break;
13913 case 206 /* ArrowFunction */:
13914 if (!includeArrowFunctions) {
13915 continue;
13916 }
13917 // falls through
13918 case 248 /* FunctionDeclaration */:
13919 case 205 /* FunctionExpression */:
13920 case 253 /* ModuleDeclaration */:
13921 case 162 /* PropertyDeclaration */:
13922 case 161 /* PropertySignature */:
13923 case 164 /* MethodDeclaration */:
13924 case 163 /* MethodSignature */:
13925 case 165 /* Constructor */:
13926 case 166 /* GetAccessor */:
13927 case 167 /* SetAccessor */:
13928 case 168 /* CallSignature */:
13929 case 169 /* ConstructSignature */:
13930 case 170 /* IndexSignature */:
13931 case 252 /* EnumDeclaration */:
13932 case 294 /* SourceFile */:
13933 return node;
13934 }
13935 }
13936 }
13937 ts.getThisContainer = getThisContainer;
13938 function isInTopLevelContext(node) {
13939 // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
13940 if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
13941 node = node.parent;
13942 }
13943 var container = getThisContainer(node, /*includeArrowFunctions*/ true);
13944 return ts.isSourceFile(container);
13945 }
13946 ts.isInTopLevelContext = isInTopLevelContext;
13947 function getNewTargetContainer(node) {
13948 var container = getThisContainer(node, /*includeArrowFunctions*/ false);
13949 if (container) {
13950 switch (container.kind) {
13951 case 165 /* Constructor */:
13952 case 248 /* FunctionDeclaration */:
13953 case 205 /* FunctionExpression */:
13954 return container;
13955 }
13956 }
13957 return undefined;
13958 }
13959 ts.getNewTargetContainer = getNewTargetContainer;
13960 /**
13961 * Given an super call/property node, returns the closest node where
13962 * - a super call/property access is legal in the node and not legal in the parent node the node.
13963 * i.e. super call is legal in constructor but not legal in the class body.
13964 * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
13965 * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
13966 * i.e. super property access is illegal in function declaration but can be legal in the statement list
13967 */
13968 function getSuperContainer(node, stopOnFunctions) {
13969 while (true) {
13970 node = node.parent;
13971 if (!node) {
13972 return node;
13973 }
13974 switch (node.kind) {
13975 case 157 /* ComputedPropertyName */:
13976 node = node.parent;
13977 break;
13978 case 248 /* FunctionDeclaration */:
13979 case 205 /* FunctionExpression */:
13980 case 206 /* ArrowFunction */:
13981 if (!stopOnFunctions) {
13982 continue;
13983 }
13984 // falls through
13985 case 162 /* PropertyDeclaration */:
13986 case 161 /* PropertySignature */:
13987 case 164 /* MethodDeclaration */:
13988 case 163 /* MethodSignature */:
13989 case 165 /* Constructor */:
13990 case 166 /* GetAccessor */:
13991 case 167 /* SetAccessor */:
13992 return node;
13993 case 160 /* Decorator */:
13994 // Decorators are always applied outside of the body of a class or method.
13995 if (node.parent.kind === 159 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
13996 // If the decorator's parent is a Parameter, we resolve the this container from
13997 // the grandparent class declaration.
13998 node = node.parent.parent;
13999 }
14000 else if (ts.isClassElement(node.parent)) {
14001 // If the decorator's parent is a class element, we resolve the 'this' container
14002 // from the parent class declaration.
14003 node = node.parent;
14004 }
14005 break;
14006 }
14007 }
14008 }
14009 ts.getSuperContainer = getSuperContainer;
14010 function getImmediatelyInvokedFunctionExpression(func) {
14011 if (func.kind === 205 /* FunctionExpression */ || func.kind === 206 /* ArrowFunction */) {
14012 var prev = func;
14013 var parent = func.parent;
14014 while (parent.kind === 204 /* ParenthesizedExpression */) {
14015 prev = parent;
14016 parent = parent.parent;
14017 }
14018 if (parent.kind === 200 /* CallExpression */ && parent.expression === prev) {
14019 return parent;
14020 }
14021 }
14022 }
14023 ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14024 function isSuperOrSuperProperty(node) {
14025 return node.kind === 105 /* SuperKeyword */
14026 || isSuperProperty(node);
14027 }
14028 ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14029 /**
14030 * Determines whether a node is a property or element access expression for `super`.
14031 */
14032 function isSuperProperty(node) {
14033 var kind = node.kind;
14034 return (kind === 198 /* PropertyAccessExpression */ || kind === 199 /* ElementAccessExpression */)
14035 && node.expression.kind === 105 /* SuperKeyword */;
14036 }
14037 ts.isSuperProperty = isSuperProperty;
14038 /**
14039 * Determines whether a node is a property or element access expression for `this`.
14040 */
14041 function isThisProperty(node) {
14042 var kind = node.kind;
14043 return (kind === 198 /* PropertyAccessExpression */ || kind === 199 /* ElementAccessExpression */)
14044 && node.expression.kind === 107 /* ThisKeyword */;
14045 }
14046 ts.isThisProperty = isThisProperty;
14047 function getEntityNameFromTypeNode(node) {
14048 switch (node.kind) {
14049 case 172 /* TypeReference */:
14050 return node.typeName;
14051 case 220 /* ExpressionWithTypeArguments */:
14052 return isEntityNameExpression(node.expression)
14053 ? node.expression
14054 : undefined;
14055 // 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.
14056 case 78 /* Identifier */:
14057 case 156 /* QualifiedName */:
14058 return node;
14059 }
14060 return undefined;
14061 }
14062 ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14063 function getInvokedExpression(node) {
14064 switch (node.kind) {
14065 case 202 /* TaggedTemplateExpression */:
14066 return node.tag;
14067 case 272 /* JsxOpeningElement */:
14068 case 271 /* JsxSelfClosingElement */:
14069 return node.tagName;
14070 default:
14071 return node.expression;
14072 }
14073 }
14074 ts.getInvokedExpression = getInvokedExpression;
14075 function nodeCanBeDecorated(node, parent, grandparent) {
14076 // private names cannot be used with decorators yet
14077 if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14078 return false;
14079 }
14080 switch (node.kind) {
14081 case 249 /* ClassDeclaration */:
14082 // classes are valid targets
14083 return true;
14084 case 162 /* PropertyDeclaration */:
14085 // property declarations are valid if their parent is a class declaration.
14086 return parent.kind === 249 /* ClassDeclaration */;
14087 case 166 /* GetAccessor */:
14088 case 167 /* SetAccessor */:
14089 case 164 /* MethodDeclaration */:
14090 // if this method has a body and its parent is a class declaration, this is a valid target.
14091 return node.body !== undefined
14092 && parent.kind === 249 /* ClassDeclaration */;
14093 case 159 /* Parameter */:
14094 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14095 return parent.body !== undefined
14096 && (parent.kind === 165 /* Constructor */
14097 || parent.kind === 164 /* MethodDeclaration */
14098 || parent.kind === 167 /* SetAccessor */)
14099 && grandparent.kind === 249 /* ClassDeclaration */;
14100 }
14101 return false;
14102 }
14103 ts.nodeCanBeDecorated = nodeCanBeDecorated;
14104 function nodeIsDecorated(node, parent, grandparent) {
14105 return node.decorators !== undefined
14106 && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14107 }
14108 ts.nodeIsDecorated = nodeIsDecorated;
14109 function nodeOrChildIsDecorated(node, parent, grandparent) {
14110 return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14111 }
14112 ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14113 function childIsDecorated(node, parent) {
14114 switch (node.kind) {
14115 case 249 /* ClassDeclaration */:
14116 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14117 case 164 /* MethodDeclaration */:
14118 case 167 /* SetAccessor */:
14119 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14120 default:
14121 return false;
14122 }
14123 }
14124 ts.childIsDecorated = childIsDecorated;
14125 function isJSXTagName(node) {
14126 var parent = node.parent;
14127 if (parent.kind === 272 /* JsxOpeningElement */ ||
14128 parent.kind === 271 /* JsxSelfClosingElement */ ||
14129 parent.kind === 273 /* JsxClosingElement */) {
14130 return parent.tagName === node;
14131 }
14132 return false;
14133 }
14134 ts.isJSXTagName = isJSXTagName;
14135 function isExpressionNode(node) {
14136 switch (node.kind) {
14137 case 105 /* SuperKeyword */:
14138 case 103 /* NullKeyword */:
14139 case 109 /* TrueKeyword */:
14140 case 94 /* FalseKeyword */:
14141 case 13 /* RegularExpressionLiteral */:
14142 case 196 /* ArrayLiteralExpression */:
14143 case 197 /* ObjectLiteralExpression */:
14144 case 198 /* PropertyAccessExpression */:
14145 case 199 /* ElementAccessExpression */:
14146 case 200 /* CallExpression */:
14147 case 201 /* NewExpression */:
14148 case 202 /* TaggedTemplateExpression */:
14149 case 221 /* AsExpression */:
14150 case 203 /* TypeAssertionExpression */:
14151 case 222 /* NonNullExpression */:
14152 case 204 /* ParenthesizedExpression */:
14153 case 205 /* FunctionExpression */:
14154 case 218 /* ClassExpression */:
14155 case 206 /* ArrowFunction */:
14156 case 209 /* VoidExpression */:
14157 case 207 /* DeleteExpression */:
14158 case 208 /* TypeOfExpression */:
14159 case 211 /* PrefixUnaryExpression */:
14160 case 212 /* PostfixUnaryExpression */:
14161 case 213 /* BinaryExpression */:
14162 case 214 /* ConditionalExpression */:
14163 case 217 /* SpreadElement */:
14164 case 215 /* TemplateExpression */:
14165 case 219 /* OmittedExpression */:
14166 case 270 /* JsxElement */:
14167 case 271 /* JsxSelfClosingElement */:
14168 case 274 /* JsxFragment */:
14169 case 216 /* YieldExpression */:
14170 case 210 /* AwaitExpression */:
14171 case 223 /* MetaProperty */:
14172 return true;
14173 case 156 /* QualifiedName */:
14174 while (node.parent.kind === 156 /* QualifiedName */) {
14175 node = node.parent;
14176 }
14177 return node.parent.kind === 175 /* TypeQuery */ || isJSXTagName(node);
14178 case 78 /* Identifier */:
14179 if (node.parent.kind === 175 /* TypeQuery */ || isJSXTagName(node)) {
14180 return true;
14181 }
14182 // falls through
14183 case 8 /* NumericLiteral */:
14184 case 9 /* BigIntLiteral */:
14185 case 10 /* StringLiteral */:
14186 case 14 /* NoSubstitutionTemplateLiteral */:
14187 case 107 /* ThisKeyword */:
14188 return isInExpressionContext(node);
14189 default:
14190 return false;
14191 }
14192 }
14193 ts.isExpressionNode = isExpressionNode;
14194 function isInExpressionContext(node) {
14195 var parent = node.parent;
14196 switch (parent.kind) {
14197 case 246 /* VariableDeclaration */:
14198 case 159 /* Parameter */:
14199 case 162 /* PropertyDeclaration */:
14200 case 161 /* PropertySignature */:
14201 case 288 /* EnumMember */:
14202 case 285 /* PropertyAssignment */:
14203 case 195 /* BindingElement */:
14204 return parent.initializer === node;
14205 case 230 /* ExpressionStatement */:
14206 case 231 /* IfStatement */:
14207 case 232 /* DoStatement */:
14208 case 233 /* WhileStatement */:
14209 case 239 /* ReturnStatement */:
14210 case 240 /* WithStatement */:
14211 case 241 /* SwitchStatement */:
14212 case 281 /* CaseClause */:
14213 case 243 /* ThrowStatement */:
14214 return parent.expression === node;
14215 case 234 /* ForStatement */:
14216 var forStatement = parent;
14217 return (forStatement.initializer === node && forStatement.initializer.kind !== 247 /* VariableDeclarationList */) ||
14218 forStatement.condition === node ||
14219 forStatement.incrementor === node;
14220 case 235 /* ForInStatement */:
14221 case 236 /* ForOfStatement */:
14222 var forInStatement = parent;
14223 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 247 /* VariableDeclarationList */) ||
14224 forInStatement.expression === node;
14225 case 203 /* TypeAssertionExpression */:
14226 case 221 /* AsExpression */:
14227 return node === parent.expression;
14228 case 225 /* TemplateSpan */:
14229 return node === parent.expression;
14230 case 157 /* ComputedPropertyName */:
14231 return node === parent.expression;
14232 case 160 /* Decorator */:
14233 case 280 /* JsxExpression */:
14234 case 279 /* JsxSpreadAttribute */:
14235 case 287 /* SpreadAssignment */:
14236 return true;
14237 case 220 /* ExpressionWithTypeArguments */:
14238 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14239 case 286 /* ShorthandPropertyAssignment */:
14240 return parent.objectAssignmentInitializer === node;
14241 default:
14242 return isExpressionNode(parent);
14243 }
14244 }
14245 ts.isInExpressionContext = isInExpressionContext;
14246 function isPartOfTypeQuery(node) {
14247 while (node.kind === 156 /* QualifiedName */ || node.kind === 78 /* Identifier */) {
14248 node = node.parent;
14249 }
14250 return node.kind === 175 /* TypeQuery */;
14251 }
14252 ts.isPartOfTypeQuery = isPartOfTypeQuery;
14253 function isExternalModuleImportEqualsDeclaration(node) {
14254 return node.kind === 257 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 269 /* ExternalModuleReference */;
14255 }
14256 ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14257 function getExternalModuleImportEqualsDeclarationExpression(node) {
14258 ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14259 return node.moduleReference.expression;
14260 }
14261 ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14262 function isInternalModuleImportEqualsDeclaration(node) {
14263 return node.kind === 257 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 269 /* ExternalModuleReference */;
14264 }
14265 ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14266 function isSourceFileJS(file) {
14267 return isInJSFile(file);
14268 }
14269 ts.isSourceFileJS = isSourceFileJS;
14270 function isSourceFileNotJS(file) {
14271 return !isInJSFile(file);
14272 }
14273 ts.isSourceFileNotJS = isSourceFileNotJS;
14274 function isInJSFile(node) {
14275 return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14276 }
14277 ts.isInJSFile = isInJSFile;
14278 function isInJsonFile(node) {
14279 return !!node && !!(node.flags & 33554432 /* JsonFile */);
14280 }
14281 ts.isInJsonFile = isInJsonFile;
14282 function isSourceFileNotJson(file) {
14283 return !isJsonSourceFile(file);
14284 }
14285 ts.isSourceFileNotJson = isSourceFileNotJson;
14286 function isInJSDoc(node) {
14287 return !!node && !!(node.flags & 4194304 /* JSDoc */);
14288 }
14289 ts.isInJSDoc = isInJSDoc;
14290 function isJSDocIndexSignature(node) {
14291 return ts.isTypeReferenceNode(node) &&
14292 ts.isIdentifier(node.typeName) &&
14293 node.typeName.escapedText === "Object" &&
14294 node.typeArguments && node.typeArguments.length === 2 &&
14295 (node.typeArguments[0].kind === 146 /* StringKeyword */ || node.typeArguments[0].kind === 143 /* NumberKeyword */);
14296 }
14297 ts.isJSDocIndexSignature = isJSDocIndexSignature;
14298 function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14299 if (callExpression.kind !== 200 /* CallExpression */) {
14300 return false;
14301 }
14302 var _a = callExpression, expression = _a.expression, args = _a.arguments;
14303 if (expression.kind !== 78 /* Identifier */ || expression.escapedText !== "require") {
14304 return false;
14305 }
14306 if (args.length !== 1) {
14307 return false;
14308 }
14309 var arg = args[0];
14310 return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14311 }
14312 ts.isRequireCall = isRequireCall;
14313 function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14314 return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14315 }
14316 ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14317 function isRequireVariableStatement(node, requireStringLiteralLikeArgument) {
14318 if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14319 return ts.isVariableStatement(node)
14320 && node.declarationList.declarations.length > 0
14321 && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14322 }
14323 ts.isRequireVariableStatement = isRequireVariableStatement;
14324 function isSingleOrDoubleQuote(charCode) {
14325 return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14326 }
14327 ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14328 function isStringDoubleQuoted(str, sourceFile) {
14329 return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14330 }
14331 ts.isStringDoubleQuoted = isStringDoubleQuoted;
14332 function getDeclarationOfExpando(node) {
14333 if (!node.parent) {
14334 return undefined;
14335 }
14336 var name;
14337 var decl;
14338 if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14339 if (!isInJSFile(node) && !isVarConst(node.parent)) {
14340 return undefined;
14341 }
14342 name = node.parent.name;
14343 decl = node.parent;
14344 }
14345 else if (ts.isBinaryExpression(node.parent)) {
14346 var parentNode = node.parent;
14347 var parentNodeOperator = node.parent.operatorToken.kind;
14348 if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14349 name = parentNode.left;
14350 decl = name;
14351 }
14352 else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14353 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14354 name = parentNode.parent.name;
14355 decl = parentNode.parent;
14356 }
14357 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14358 name = parentNode.parent.left;
14359 decl = name;
14360 }
14361 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14362 return undefined;
14363 }
14364 }
14365 }
14366 if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14367 return undefined;
14368 }
14369 return decl;
14370 }
14371 ts.getDeclarationOfExpando = getDeclarationOfExpando;
14372 function isAssignmentDeclaration(decl) {
14373 return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14374 }
14375 ts.isAssignmentDeclaration = isAssignmentDeclaration;
14376 /** Get the initializer, taking into account defaulted Javascript initializers */
14377 function getEffectiveInitializer(node) {
14378 if (isInJSFile(node) && node.initializer &&
14379 ts.isBinaryExpression(node.initializer) &&
14380 (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14381 node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14382 return node.initializer.right;
14383 }
14384 return node.initializer;
14385 }
14386 ts.getEffectiveInitializer = getEffectiveInitializer;
14387 /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14388 function getDeclaredExpandoInitializer(node) {
14389 var init = getEffectiveInitializer(node);
14390 return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14391 }
14392 ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14393 function hasExpandoValueProperty(node, isPrototypeAssignment) {
14394 return ts.forEach(node.properties, function (p) {
14395 return ts.isPropertyAssignment(p) &&
14396 ts.isIdentifier(p.name) &&
14397 p.name.escapedText === "value" &&
14398 p.initializer &&
14399 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14400 });
14401 }
14402 /**
14403 * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14404 * We treat the right hand side of assignments with container-like initializers as declarations.
14405 */
14406 function getAssignedExpandoInitializer(node) {
14407 if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14408 var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14409 return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14410 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14411 }
14412 if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14413 var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14414 if (result) {
14415 return result;
14416 }
14417 }
14418 }
14419 ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14420 /**
14421 * Recognized expando initializers are:
14422 * 1. (function() {})() -- IIFEs
14423 * 2. function() { } -- Function expressions
14424 * 3. class { } -- Class expressions
14425 * 4. {} -- Empty object literals
14426 * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14427 *
14428 * This function returns the provided initializer, or undefined if it is not valid.
14429 */
14430 function getExpandoInitializer(initializer, isPrototypeAssignment) {
14431 if (ts.isCallExpression(initializer)) {
14432 var e = skipParentheses(initializer.expression);
14433 return e.kind === 205 /* FunctionExpression */ || e.kind === 206 /* ArrowFunction */ ? initializer : undefined;
14434 }
14435 if (initializer.kind === 205 /* FunctionExpression */ ||
14436 initializer.kind === 218 /* ClassExpression */ ||
14437 initializer.kind === 206 /* ArrowFunction */) {
14438 return initializer;
14439 }
14440 if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14441 return initializer;
14442 }
14443 }
14444 ts.getExpandoInitializer = getExpandoInitializer;
14445 /**
14446 * A defaulted expando initializer matches the pattern
14447 * `Lhs = Lhs || ExpandoInitializer`
14448 * or `var Lhs = Lhs || ExpandoInitializer`
14449 *
14450 * The second Lhs is required to be the same as the first except that it may be prefixed with
14451 * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14452 */
14453 function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14454 var e = ts.isBinaryExpression(initializer)
14455 && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14456 && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14457 if (e && isSameEntityName(name, initializer.left)) {
14458 return e;
14459 }
14460 }
14461 function isDefaultedExpandoInitializer(node) {
14462 var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14463 ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14464 undefined;
14465 return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14466 }
14467 ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14468 /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14469 function getNameOfExpando(node) {
14470 if (ts.isBinaryExpression(node.parent)) {
14471 var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14472 if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14473 return parent.left;
14474 }
14475 }
14476 else if (ts.isVariableDeclaration(node.parent)) {
14477 return node.parent.name;
14478 }
14479 }
14480 ts.getNameOfExpando = getNameOfExpando;
14481 /**
14482 * Is the 'declared' name the same as the one in the initializer?
14483 * @return true for identical entity names, as well as ones where the initializer is prefixed with
14484 * 'window', 'self' or 'global'. For example:
14485 *
14486 * var my = my || {}
14487 * var min = window.min || {}
14488 * my.app = self.my.app || class { }
14489 */
14490 function isSameEntityName(name, initializer) {
14491 if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14492 return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
14493 }
14494 if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14495 (initializer.expression.kind === 107 /* ThisKeyword */ ||
14496 ts.isIdentifier(initializer.expression) &&
14497 (initializer.expression.escapedText === "window" ||
14498 initializer.expression.escapedText === "self" ||
14499 initializer.expression.escapedText === "global"))) {
14500 var nameOrArgument = getNameOrArgument(initializer);
14501 if (ts.isPrivateIdentifier(nameOrArgument)) {
14502 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14503 }
14504 return isSameEntityName(name, nameOrArgument);
14505 }
14506 if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14507 return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14508 && isSameEntityName(name.expression, initializer.expression);
14509 }
14510 return false;
14511 }
14512 function getRightMostAssignedExpression(node) {
14513 while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14514 node = node.right;
14515 }
14516 return node;
14517 }
14518 ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14519 function isExportsIdentifier(node) {
14520 return ts.isIdentifier(node) && node.escapedText === "exports";
14521 }
14522 ts.isExportsIdentifier = isExportsIdentifier;
14523 function isModuleIdentifier(node) {
14524 return ts.isIdentifier(node) && node.escapedText === "module";
14525 }
14526 ts.isModuleIdentifier = isModuleIdentifier;
14527 function isModuleExportsAccessExpression(node) {
14528 return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14529 && isModuleIdentifier(node.expression)
14530 && getElementOrPropertyAccessName(node) === "exports";
14531 }
14532 ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14533 /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14534 /// assignments we treat as special in the binder
14535 function getAssignmentDeclarationKind(expr) {
14536 var special = getAssignmentDeclarationKindWorker(expr);
14537 return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14538 }
14539 ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14540 function isBindableObjectDefinePropertyCall(expr) {
14541 return ts.length(expr.arguments) === 3 &&
14542 ts.isPropertyAccessExpression(expr.expression) &&
14543 ts.isIdentifier(expr.expression.expression) &&
14544 ts.idText(expr.expression.expression) === "Object" &&
14545 ts.idText(expr.expression.name) === "defineProperty" &&
14546 isStringOrNumericLiteralLike(expr.arguments[1]) &&
14547 isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14548 }
14549 ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14550 /** x.y OR x[0] */
14551 function isLiteralLikeAccess(node) {
14552 return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14553 }
14554 ts.isLiteralLikeAccess = isLiteralLikeAccess;
14555 /** x[0] OR x['a'] OR x[Symbol.y] */
14556 function isLiteralLikeElementAccess(node) {
14557 return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14558 isWellKnownSymbolSyntactically(node.argumentExpression));
14559 }
14560 ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14561 /** Any series of property and element accesses. */
14562 function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14563 return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14564 || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14565 }
14566 ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14567 /** Any series of property and element accesses, ending in a literal element access */
14568 function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14569 return isLiteralLikeElementAccess(node)
14570 && ((!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */) ||
14571 isEntityNameExpression(node.expression) ||
14572 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14573 }
14574 ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14575 function isBindableStaticNameExpression(node, excludeThisKeyword) {
14576 return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14577 }
14578 ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14579 function getNameOrArgument(expr) {
14580 if (ts.isPropertyAccessExpression(expr)) {
14581 return expr.name;
14582 }
14583 return expr.argumentExpression;
14584 }
14585 ts.getNameOrArgument = getNameOrArgument;
14586 function getAssignmentDeclarationKindWorker(expr) {
14587 if (ts.isCallExpression(expr)) {
14588 if (!isBindableObjectDefinePropertyCall(expr)) {
14589 return 0 /* None */;
14590 }
14591 var entityName = expr.arguments[0];
14592 if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14593 return 8 /* ObjectDefinePropertyExports */;
14594 }
14595 if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14596 return 9 /* ObjectDefinePrototypeProperty */;
14597 }
14598 return 7 /* ObjectDefinePropertyValue */;
14599 }
14600 if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
14601 return 0 /* None */;
14602 }
14603 if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14604 // F.prototype = { ... }
14605 return 6 /* Prototype */;
14606 }
14607 return getAssignmentDeclarationPropertyAccessKind(expr.left);
14608 }
14609 function isVoidZero(node) {
14610 return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
14611 }
14612 /**
14613 * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14614 * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14615 */
14616 /* @internal */
14617 function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14618 if (ts.isPropertyAccessExpression(node)) {
14619 return node.name;
14620 }
14621 var arg = skipParentheses(node.argumentExpression);
14622 if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14623 return arg;
14624 }
14625 return node;
14626 }
14627 ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14628 function getElementOrPropertyAccessName(node) {
14629 var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14630 if (name) {
14631 if (ts.isIdentifier(name)) {
14632 return name.escapedText;
14633 }
14634 if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14635 return ts.escapeLeadingUnderscores(name.text);
14636 }
14637 }
14638 if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14639 return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14640 }
14641 return undefined;
14642 }
14643 ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14644 function getAssignmentDeclarationPropertyAccessKind(lhs) {
14645 if (lhs.expression.kind === 107 /* ThisKeyword */) {
14646 return 4 /* ThisProperty */;
14647 }
14648 else if (isModuleExportsAccessExpression(lhs)) {
14649 // module.exports = expr
14650 return 2 /* ModuleExports */;
14651 }
14652 else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14653 if (isPrototypeAccess(lhs.expression)) {
14654 // F.G....prototype.x = expr
14655 return 3 /* PrototypeProperty */;
14656 }
14657 var nextToLast = lhs;
14658 while (!ts.isIdentifier(nextToLast.expression)) {
14659 nextToLast = nextToLast.expression;
14660 }
14661 var id = nextToLast.expression;
14662 if ((id.escapedText === "exports" ||
14663 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14664 // ExportsProperty does not support binding with computed names
14665 isBindableStaticAccessExpression(lhs)) {
14666 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14667 return 1 /* ExportsProperty */;
14668 }
14669 if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14670 // F.G...x = expr
14671 return 5 /* Property */;
14672 }
14673 }
14674 return 0 /* None */;
14675 }
14676 ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14677 function getInitializerOfBinaryExpression(expr) {
14678 while (ts.isBinaryExpression(expr.right)) {
14679 expr = expr.right;
14680 }
14681 return expr.right;
14682 }
14683 ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14684 function isPrototypePropertyAssignment(node) {
14685 return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14686 }
14687 ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14688 function isSpecialPropertyDeclaration(expr) {
14689 return isInJSFile(expr) &&
14690 expr.parent && expr.parent.kind === 230 /* ExpressionStatement */ &&
14691 (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14692 !!ts.getJSDocTypeTag(expr.parent);
14693 }
14694 ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14695 function setValueDeclaration(symbol, node) {
14696 var valueDeclaration = symbol.valueDeclaration;
14697 if (!valueDeclaration ||
14698 !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14699 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14700 (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14701 // other kinds of value declarations take precedence over modules and assignment declarations
14702 symbol.valueDeclaration = node;
14703 }
14704 }
14705 ts.setValueDeclaration = setValueDeclaration;
14706 function isFunctionSymbol(symbol) {
14707 if (!symbol || !symbol.valueDeclaration) {
14708 return false;
14709 }
14710 var decl = symbol.valueDeclaration;
14711 return decl.kind === 248 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
14712 }
14713 ts.isFunctionSymbol = isFunctionSymbol;
14714 function importFromModuleSpecifier(node) {
14715 return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
14716 }
14717 ts.importFromModuleSpecifier = importFromModuleSpecifier;
14718 function tryGetImportFromModuleSpecifier(node) {
14719 switch (node.parent.kind) {
14720 case 258 /* ImportDeclaration */:
14721 case 264 /* ExportDeclaration */:
14722 return node.parent;
14723 case 269 /* ExternalModuleReference */:
14724 return node.parent.parent;
14725 case 200 /* CallExpression */:
14726 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
14727 case 190 /* LiteralType */:
14728 ts.Debug.assert(ts.isStringLiteral(node));
14729 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
14730 default:
14731 return undefined;
14732 }
14733 }
14734 ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
14735 function getExternalModuleName(node) {
14736 switch (node.kind) {
14737 case 258 /* ImportDeclaration */:
14738 case 264 /* ExportDeclaration */:
14739 return node.moduleSpecifier;
14740 case 257 /* ImportEqualsDeclaration */:
14741 return node.moduleReference.kind === 269 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
14742 case 192 /* ImportType */:
14743 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
14744 default:
14745 return ts.Debug.assertNever(node);
14746 }
14747 }
14748 ts.getExternalModuleName = getExternalModuleName;
14749 function getNamespaceDeclarationNode(node) {
14750 switch (node.kind) {
14751 case 258 /* ImportDeclaration */:
14752 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
14753 case 257 /* ImportEqualsDeclaration */:
14754 return node;
14755 case 264 /* ExportDeclaration */:
14756 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
14757 default:
14758 return ts.Debug.assertNever(node);
14759 }
14760 }
14761 ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
14762 function isDefaultImport(node) {
14763 return node.kind === 258 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
14764 }
14765 ts.isDefaultImport = isDefaultImport;
14766 function forEachImportClauseDeclaration(node, action) {
14767 if (node.name) {
14768 var result = action(node);
14769 if (result)
14770 return result;
14771 }
14772 if (node.namedBindings) {
14773 var result = ts.isNamespaceImport(node.namedBindings)
14774 ? action(node.namedBindings)
14775 : ts.forEach(node.namedBindings.elements, action);
14776 if (result)
14777 return result;
14778 }
14779 }
14780 ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
14781 function hasQuestionToken(node) {
14782 if (node) {
14783 switch (node.kind) {
14784 case 159 /* Parameter */:
14785 case 164 /* MethodDeclaration */:
14786 case 163 /* MethodSignature */:
14787 case 286 /* ShorthandPropertyAssignment */:
14788 case 285 /* PropertyAssignment */:
14789 case 162 /* PropertyDeclaration */:
14790 case 161 /* PropertySignature */:
14791 return node.questionToken !== undefined;
14792 }
14793 }
14794 return false;
14795 }
14796 ts.hasQuestionToken = hasQuestionToken;
14797 function isJSDocConstructSignature(node) {
14798 var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
14799 var name = ts.tryCast(param && param.name, ts.isIdentifier);
14800 return !!name && name.escapedText === "new";
14801 }
14802 ts.isJSDocConstructSignature = isJSDocConstructSignature;
14803 function isJSDocTypeAlias(node) {
14804 return node.kind === 327 /* JSDocTypedefTag */ || node.kind === 320 /* JSDocCallbackTag */ || node.kind === 321 /* JSDocEnumTag */;
14805 }
14806 ts.isJSDocTypeAlias = isJSDocTypeAlias;
14807 function isTypeAlias(node) {
14808 return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
14809 }
14810 ts.isTypeAlias = isTypeAlias;
14811 function getSourceOfAssignment(node) {
14812 return ts.isExpressionStatement(node) &&
14813 ts.isBinaryExpression(node.expression) &&
14814 node.expression.operatorToken.kind === 62 /* EqualsToken */
14815 ? getRightMostAssignedExpression(node.expression)
14816 : undefined;
14817 }
14818 function getSourceOfDefaultedAssignment(node) {
14819 return ts.isExpressionStatement(node) &&
14820 ts.isBinaryExpression(node.expression) &&
14821 getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
14822 ts.isBinaryExpression(node.expression.right) &&
14823 (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
14824 ? node.expression.right.right
14825 : undefined;
14826 }
14827 function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
14828 switch (node.kind) {
14829 case 229 /* VariableStatement */:
14830 var v = getSingleVariableOfVariableStatement(node);
14831 return v && v.initializer;
14832 case 162 /* PropertyDeclaration */:
14833 return node.initializer;
14834 case 285 /* PropertyAssignment */:
14835 return node.initializer;
14836 }
14837 }
14838 ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
14839 function getSingleVariableOfVariableStatement(node) {
14840 return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
14841 }
14842 ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
14843 function getNestedModuleDeclaration(node) {
14844 return ts.isModuleDeclaration(node) &&
14845 node.body &&
14846 node.body.kind === 253 /* ModuleDeclaration */
14847 ? node.body
14848 : undefined;
14849 }
14850 function getJSDocCommentsAndTags(hostNode, noCache) {
14851 var result;
14852 // Pull parameter comments from declaring function as well
14853 if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
14854 result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
14855 }
14856 var node = hostNode;
14857 while (node && node.parent) {
14858 if (ts.hasJSDocNodes(node)) {
14859 result = ts.append(result, ts.last(node.jsDoc));
14860 }
14861 if (node.kind === 159 /* Parameter */) {
14862 result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
14863 break;
14864 }
14865 if (node.kind === 158 /* TypeParameter */) {
14866 result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
14867 break;
14868 }
14869 node = getNextJSDocCommentLocation(node);
14870 }
14871 return result || ts.emptyArray;
14872 }
14873 ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
14874 function getNextJSDocCommentLocation(node) {
14875 var parent = node.parent;
14876 if (parent.kind === 285 /* PropertyAssignment */ ||
14877 parent.kind === 263 /* ExportAssignment */ ||
14878 parent.kind === 162 /* PropertyDeclaration */ ||
14879 parent.kind === 230 /* ExpressionStatement */ && node.kind === 198 /* PropertyAccessExpression */ ||
14880 getNestedModuleDeclaration(parent) ||
14881 ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
14882 return parent;
14883 }
14884 // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
14885 // /**
14886 // * @param {number} name
14887 // * @returns {number}
14888 // */
14889 // var x = function(name) { return name.length; }
14890 else if (parent.parent &&
14891 (getSingleVariableOfVariableStatement(parent.parent) === node ||
14892 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
14893 return parent.parent;
14894 }
14895 else if (parent.parent && parent.parent.parent &&
14896 (getSingleVariableOfVariableStatement(parent.parent.parent) ||
14897 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
14898 getSourceOfDefaultedAssignment(parent.parent.parent))) {
14899 return parent.parent.parent;
14900 }
14901 }
14902 /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
14903 function getParameterSymbolFromJSDoc(node) {
14904 if (node.symbol) {
14905 return node.symbol;
14906 }
14907 if (!ts.isIdentifier(node.name)) {
14908 return undefined;
14909 }
14910 var name = node.name.escapedText;
14911 var decl = getHostSignatureFromJSDoc(node);
14912 if (!decl) {
14913 return undefined;
14914 }
14915 var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 78 /* Identifier */ && p.name.escapedText === name; });
14916 return parameter && parameter.symbol;
14917 }
14918 ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
14919 function getHostSignatureFromJSDoc(node) {
14920 var host = getEffectiveJSDocHost(node);
14921 return host && ts.isFunctionLike(host) ? host : undefined;
14922 }
14923 ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
14924 function getEffectiveJSDocHost(node) {
14925 var host = getJSDocHost(node);
14926 var decl = getSourceOfDefaultedAssignment(host) ||
14927 getSourceOfAssignment(host) ||
14928 getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
14929 getSingleVariableOfVariableStatement(host) ||
14930 getNestedModuleDeclaration(host) ||
14931 host;
14932 return decl;
14933 }
14934 ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
14935 /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
14936 function getJSDocHost(node) {
14937 return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
14938 }
14939 ts.getJSDocHost = getJSDocHost;
14940 function getTypeParameterFromJsDoc(node) {
14941 var name = node.name.escapedText;
14942 var typeParameters = node.parent.parent.parent.typeParameters;
14943 return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
14944 }
14945 ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
14946 function hasRestParameter(s) {
14947 var last = ts.lastOrUndefined(s.parameters);
14948 return !!last && isRestParameter(last);
14949 }
14950 ts.hasRestParameter = hasRestParameter;
14951 function isRestParameter(node) {
14952 var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
14953 return node.dotDotDotToken !== undefined || !!type && type.kind === 305 /* JSDocVariadicType */;
14954 }
14955 ts.isRestParameter = isRestParameter;
14956 function hasTypeArguments(node) {
14957 return !!node.typeArguments;
14958 }
14959 ts.hasTypeArguments = hasTypeArguments;
14960 var AssignmentKind;
14961 (function (AssignmentKind) {
14962 AssignmentKind[AssignmentKind["None"] = 0] = "None";
14963 AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
14964 AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
14965 })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
14966 function getAssignmentTargetKind(node) {
14967 var parent = node.parent;
14968 while (true) {
14969 switch (parent.kind) {
14970 case 213 /* BinaryExpression */:
14971 var binaryOperator = parent.operatorToken.kind;
14972 return isAssignmentOperator(binaryOperator) && parent.left === node ?
14973 binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
14974 0 /* None */;
14975 case 211 /* PrefixUnaryExpression */:
14976 case 212 /* PostfixUnaryExpression */:
14977 var unaryOperator = parent.operator;
14978 return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
14979 case 235 /* ForInStatement */:
14980 case 236 /* ForOfStatement */:
14981 return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
14982 case 204 /* ParenthesizedExpression */:
14983 case 196 /* ArrayLiteralExpression */:
14984 case 217 /* SpreadElement */:
14985 case 222 /* NonNullExpression */:
14986 node = parent;
14987 break;
14988 case 286 /* ShorthandPropertyAssignment */:
14989 if (parent.name !== node) {
14990 return 0 /* None */;
14991 }
14992 node = parent.parent;
14993 break;
14994 case 285 /* PropertyAssignment */:
14995 if (parent.name === node) {
14996 return 0 /* None */;
14997 }
14998 node = parent.parent;
14999 break;
15000 default:
15001 return 0 /* None */;
15002 }
15003 parent = node.parent;
15004 }
15005 }
15006 ts.getAssignmentTargetKind = getAssignmentTargetKind;
15007 // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15008 // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15009 // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15010 // (Note that `p` is not a target in the above examples, only `a`.)
15011 function isAssignmentTarget(node) {
15012 return getAssignmentTargetKind(node) !== 0 /* None */;
15013 }
15014 ts.isAssignmentTarget = isAssignmentTarget;
15015 /**
15016 * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15017 * the same `var` declaration scope as the node's parent.
15018 */
15019 function isNodeWithPossibleHoistedDeclaration(node) {
15020 switch (node.kind) {
15021 case 227 /* Block */:
15022 case 229 /* VariableStatement */:
15023 case 240 /* WithStatement */:
15024 case 231 /* IfStatement */:
15025 case 241 /* SwitchStatement */:
15026 case 255 /* CaseBlock */:
15027 case 281 /* CaseClause */:
15028 case 282 /* DefaultClause */:
15029 case 242 /* LabeledStatement */:
15030 case 234 /* ForStatement */:
15031 case 235 /* ForInStatement */:
15032 case 236 /* ForOfStatement */:
15033 case 232 /* DoStatement */:
15034 case 233 /* WhileStatement */:
15035 case 244 /* TryStatement */:
15036 case 284 /* CatchClause */:
15037 return true;
15038 }
15039 return false;
15040 }
15041 ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15042 function isValueSignatureDeclaration(node) {
15043 return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15044 }
15045 ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15046 function walkUp(node, kind) {
15047 while (node && node.kind === kind) {
15048 node = node.parent;
15049 }
15050 return node;
15051 }
15052 function walkUpParenthesizedTypes(node) {
15053 return walkUp(node, 185 /* ParenthesizedType */);
15054 }
15055 ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15056 function walkUpParenthesizedExpressions(node) {
15057 return walkUp(node, 204 /* ParenthesizedExpression */);
15058 }
15059 ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15060 function skipParentheses(node) {
15061 return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15062 }
15063 ts.skipParentheses = skipParentheses;
15064 function skipParenthesesUp(node) {
15065 while (node.kind === 204 /* ParenthesizedExpression */) {
15066 node = node.parent;
15067 }
15068 return node;
15069 }
15070 // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15071 function isDeleteTarget(node) {
15072 if (node.kind !== 198 /* PropertyAccessExpression */ && node.kind !== 199 /* ElementAccessExpression */) {
15073 return false;
15074 }
15075 node = walkUpParenthesizedExpressions(node.parent);
15076 return node && node.kind === 207 /* DeleteExpression */;
15077 }
15078 ts.isDeleteTarget = isDeleteTarget;
15079 function isNodeDescendantOf(node, ancestor) {
15080 while (node) {
15081 if (node === ancestor)
15082 return true;
15083 node = node.parent;
15084 }
15085 return false;
15086 }
15087 ts.isNodeDescendantOf = isNodeDescendantOf;
15088 // True if `name` is the name of a declaration node
15089 function isDeclarationName(name) {
15090 return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15091 }
15092 ts.isDeclarationName = isDeclarationName;
15093 // See GH#16030
15094 function getDeclarationFromName(name) {
15095 var parent = name.parent;
15096 switch (name.kind) {
15097 case 10 /* StringLiteral */:
15098 case 14 /* NoSubstitutionTemplateLiteral */:
15099 case 8 /* NumericLiteral */:
15100 if (ts.isComputedPropertyName(parent))
15101 return parent.parent;
15102 // falls through
15103 case 78 /* Identifier */:
15104 if (ts.isDeclaration(parent)) {
15105 return parent.name === name ? parent : undefined;
15106 }
15107 else if (ts.isQualifiedName(parent)) {
15108 var tag = parent.parent;
15109 return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15110 }
15111 else {
15112 var binExp = parent.parent;
15113 return ts.isBinaryExpression(binExp) &&
15114 getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15115 (binExp.left.symbol || binExp.symbol) &&
15116 ts.getNameOfDeclaration(binExp) === name
15117 ? binExp
15118 : undefined;
15119 }
15120 case 79 /* PrivateIdentifier */:
15121 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15122 default:
15123 return undefined;
15124 }
15125 }
15126 ts.getDeclarationFromName = getDeclarationFromName;
15127 function isLiteralComputedPropertyDeclarationName(node) {
15128 return isStringOrNumericLiteralLike(node) &&
15129 node.parent.kind === 157 /* ComputedPropertyName */ &&
15130 ts.isDeclaration(node.parent.parent);
15131 }
15132 ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15133 // Return true if the given identifier is classified as an IdentifierName
15134 function isIdentifierName(node) {
15135 var parent = node.parent;
15136 switch (parent.kind) {
15137 case 162 /* PropertyDeclaration */:
15138 case 161 /* PropertySignature */:
15139 case 164 /* MethodDeclaration */:
15140 case 163 /* MethodSignature */:
15141 case 166 /* GetAccessor */:
15142 case 167 /* SetAccessor */:
15143 case 288 /* EnumMember */:
15144 case 285 /* PropertyAssignment */:
15145 case 198 /* PropertyAccessExpression */:
15146 // Name in member declaration or property name in property access
15147 return parent.name === node;
15148 case 156 /* QualifiedName */:
15149 // Name on right hand side of dot in a type query or type reference
15150 return parent.right === node;
15151 case 195 /* BindingElement */:
15152 case 262 /* ImportSpecifier */:
15153 // Property name in binding element or import specifier
15154 return parent.propertyName === node;
15155 case 267 /* ExportSpecifier */:
15156 case 277 /* JsxAttribute */:
15157 // Any name in an export specifier or JSX Attribute
15158 return true;
15159 }
15160 return false;
15161 }
15162 ts.isIdentifierName = isIdentifierName;
15163 // An alias symbol is created by one of the following declarations:
15164 // import <symbol> = ...
15165 // import <symbol> from ...
15166 // import * as <symbol> from ...
15167 // import { x as <symbol> } from ...
15168 // export { x as <symbol> } from ...
15169 // export * as ns <symbol> from ...
15170 // export = <EntityNameExpression>
15171 // export default <EntityNameExpression>
15172 // module.exports = <EntityNameExpression>
15173 // {<Identifier>}
15174 // {name: <EntityNameExpression>}
15175 function isAliasSymbolDeclaration(node) {
15176 return node.kind === 257 /* ImportEqualsDeclaration */ ||
15177 node.kind === 256 /* NamespaceExportDeclaration */ ||
15178 node.kind === 259 /* ImportClause */ && !!node.name ||
15179 node.kind === 260 /* NamespaceImport */ ||
15180 node.kind === 266 /* NamespaceExport */ ||
15181 node.kind === 262 /* ImportSpecifier */ ||
15182 node.kind === 267 /* ExportSpecifier */ ||
15183 node.kind === 263 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15184 ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15185 ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15186 node.kind === 286 /* ShorthandPropertyAssignment */ ||
15187 node.kind === 285 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15188 }
15189 ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15190 function getAliasDeclarationFromName(node) {
15191 switch (node.parent.kind) {
15192 case 259 /* ImportClause */:
15193 case 262 /* ImportSpecifier */:
15194 case 260 /* NamespaceImport */:
15195 case 267 /* ExportSpecifier */:
15196 case 263 /* ExportAssignment */:
15197 case 257 /* ImportEqualsDeclaration */:
15198 return node.parent;
15199 case 156 /* QualifiedName */:
15200 do {
15201 node = node.parent;
15202 } while (node.parent.kind === 156 /* QualifiedName */);
15203 return getAliasDeclarationFromName(node);
15204 }
15205 }
15206 ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15207 function isAliasableExpression(e) {
15208 return isEntityNameExpression(e) || ts.isClassExpression(e);
15209 }
15210 ts.isAliasableExpression = isAliasableExpression;
15211 function exportAssignmentIsAlias(node) {
15212 var e = getExportAssignmentExpression(node);
15213 return isAliasableExpression(e);
15214 }
15215 ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15216 function getExportAssignmentExpression(node) {
15217 return ts.isExportAssignment(node) ? node.expression : node.right;
15218 }
15219 ts.getExportAssignmentExpression = getExportAssignmentExpression;
15220 function getPropertyAssignmentAliasLikeExpression(node) {
15221 return node.kind === 286 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 285 /* PropertyAssignment */ ? node.initializer :
15222 node.parent.right;
15223 }
15224 ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15225 function getEffectiveBaseTypeNode(node) {
15226 var baseType = getClassExtendsHeritageElement(node);
15227 if (baseType && isInJSFile(node)) {
15228 // Prefer an @augments tag because it may have type parameters.
15229 var tag = ts.getJSDocAugmentsTag(node);
15230 if (tag) {
15231 return tag.class;
15232 }
15233 }
15234 return baseType;
15235 }
15236 ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15237 function getClassExtendsHeritageElement(node) {
15238 var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15239 return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15240 }
15241 ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15242 function getEffectiveImplementsTypeNodes(node) {
15243 if (isInJSFile(node)) {
15244 return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15245 }
15246 else {
15247 var heritageClause = getHeritageClause(node.heritageClauses, 116 /* ImplementsKeyword */);
15248 return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15249 }
15250 }
15251 ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15252 /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15253 function getAllSuperTypeNodes(node) {
15254 return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15255 ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15256 ts.emptyArray;
15257 }
15258 ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15259 function getInterfaceBaseTypeNodes(node) {
15260 var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15261 return heritageClause ? heritageClause.types : undefined;
15262 }
15263 ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15264 function getHeritageClause(clauses, kind) {
15265 if (clauses) {
15266 for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15267 var clause = clauses_1[_i];
15268 if (clause.token === kind) {
15269 return clause;
15270 }
15271 }
15272 }
15273 return undefined;
15274 }
15275 ts.getHeritageClause = getHeritageClause;
15276 function getAncestor(node, kind) {
15277 while (node) {
15278 if (node.kind === kind) {
15279 return node;
15280 }
15281 node = node.parent;
15282 }
15283 return undefined;
15284 }
15285 ts.getAncestor = getAncestor;
15286 function isKeyword(token) {
15287 return 80 /* FirstKeyword */ <= token && token <= 155 /* LastKeyword */;
15288 }
15289 ts.isKeyword = isKeyword;
15290 function isContextualKeyword(token) {
15291 return 125 /* FirstContextualKeyword */ <= token && token <= 155 /* LastContextualKeyword */;
15292 }
15293 ts.isContextualKeyword = isContextualKeyword;
15294 function isNonContextualKeyword(token) {
15295 return isKeyword(token) && !isContextualKeyword(token);
15296 }
15297 ts.isNonContextualKeyword = isNonContextualKeyword;
15298 function isFutureReservedKeyword(token) {
15299 return 116 /* FirstFutureReservedWord */ <= token && token <= 124 /* LastFutureReservedWord */;
15300 }
15301 ts.isFutureReservedKeyword = isFutureReservedKeyword;
15302 function isStringANonContextualKeyword(name) {
15303 var token = ts.stringToToken(name);
15304 return token !== undefined && isNonContextualKeyword(token);
15305 }
15306 ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15307 function isStringAKeyword(name) {
15308 var token = ts.stringToToken(name);
15309 return token !== undefined && isKeyword(token);
15310 }
15311 ts.isStringAKeyword = isStringAKeyword;
15312 function isIdentifierANonContextualKeyword(_a) {
15313 var originalKeywordKind = _a.originalKeywordKind;
15314 return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15315 }
15316 ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15317 function isTrivia(token) {
15318 return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15319 }
15320 ts.isTrivia = isTrivia;
15321 var FunctionFlags;
15322 (function (FunctionFlags) {
15323 FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15324 FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15325 FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15326 FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15327 FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15328 })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15329 function getFunctionFlags(node) {
15330 if (!node) {
15331 return 4 /* Invalid */;
15332 }
15333 var flags = 0 /* Normal */;
15334 switch (node.kind) {
15335 case 248 /* FunctionDeclaration */:
15336 case 205 /* FunctionExpression */:
15337 case 164 /* MethodDeclaration */:
15338 if (node.asteriskToken) {
15339 flags |= 1 /* Generator */;
15340 }
15341 // falls through
15342 case 206 /* ArrowFunction */:
15343 if (hasSyntacticModifier(node, 256 /* Async */)) {
15344 flags |= 2 /* Async */;
15345 }
15346 break;
15347 }
15348 if (!node.body) {
15349 flags |= 4 /* Invalid */;
15350 }
15351 return flags;
15352 }
15353 ts.getFunctionFlags = getFunctionFlags;
15354 function isAsyncFunction(node) {
15355 switch (node.kind) {
15356 case 248 /* FunctionDeclaration */:
15357 case 205 /* FunctionExpression */:
15358 case 206 /* ArrowFunction */:
15359 case 164 /* MethodDeclaration */:
15360 return node.body !== undefined
15361 && node.asteriskToken === undefined
15362 && hasSyntacticModifier(node, 256 /* Async */);
15363 }
15364 return false;
15365 }
15366 ts.isAsyncFunction = isAsyncFunction;
15367 function isStringOrNumericLiteralLike(node) {
15368 return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15369 }
15370 ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15371 function isSignedNumericLiteral(node) {
15372 return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15373 }
15374 ts.isSignedNumericLiteral = isSignedNumericLiteral;
15375 /**
15376 * A declaration has a dynamic name if all of the following are true:
15377 * 1. The declaration has a computed property name.
15378 * 2. The computed name is *not* expressed as a StringLiteral.
15379 * 3. The computed name is *not* expressed as a NumericLiteral.
15380 * 4. The computed name is *not* expressed as a PlusToken or MinusToken
15381 * immediately followed by a NumericLiteral.
15382 * 5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15383 * is a property of the Symbol constructor that denotes a built-in
15384 * Symbol.
15385 */
15386 function hasDynamicName(declaration) {
15387 var name = ts.getNameOfDeclaration(declaration);
15388 return !!name && isDynamicName(name);
15389 }
15390 ts.hasDynamicName = hasDynamicName;
15391 function isDynamicName(name) {
15392 if (!(name.kind === 157 /* ComputedPropertyName */ || name.kind === 199 /* ElementAccessExpression */)) {
15393 return false;
15394 }
15395 var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15396 return !isStringOrNumericLiteralLike(expr) &&
15397 !isSignedNumericLiteral(expr) &&
15398 !isWellKnownSymbolSyntactically(expr);
15399 }
15400 ts.isDynamicName = isDynamicName;
15401 /**
15402 * Checks if the expression is of the form:
15403 * Symbol.name
15404 * where Symbol is literally the word "Symbol", and name is any identifierName
15405 */
15406 function isWellKnownSymbolSyntactically(node) {
15407 return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15408 }
15409 ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15410 function getPropertyNameForPropertyNameNode(name) {
15411 switch (name.kind) {
15412 case 78 /* Identifier */:
15413 case 79 /* PrivateIdentifier */:
15414 return name.escapedText;
15415 case 10 /* StringLiteral */:
15416 case 8 /* NumericLiteral */:
15417 return ts.escapeLeadingUnderscores(name.text);
15418 case 157 /* ComputedPropertyName */:
15419 var nameExpression = name.expression;
15420 if (isWellKnownSymbolSyntactically(nameExpression)) {
15421 return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15422 }
15423 else if (isStringOrNumericLiteralLike(nameExpression)) {
15424 return ts.escapeLeadingUnderscores(nameExpression.text);
15425 }
15426 else if (isSignedNumericLiteral(nameExpression)) {
15427 if (nameExpression.operator === 40 /* MinusToken */) {
15428 return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
15429 }
15430 return nameExpression.operand.text;
15431 }
15432 return undefined;
15433 default:
15434 return ts.Debug.assertNever(name);
15435 }
15436 }
15437 ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15438 function isPropertyNameLiteral(node) {
15439 switch (node.kind) {
15440 case 78 /* Identifier */:
15441 case 10 /* StringLiteral */:
15442 case 14 /* NoSubstitutionTemplateLiteral */:
15443 case 8 /* NumericLiteral */:
15444 return true;
15445 default:
15446 return false;
15447 }
15448 }
15449 ts.isPropertyNameLiteral = isPropertyNameLiteral;
15450 function getTextOfIdentifierOrLiteral(node) {
15451 return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15452 }
15453 ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15454 function getEscapedTextOfIdentifierOrLiteral(node) {
15455 return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15456 }
15457 ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15458 function getPropertyNameForUniqueESSymbol(symbol) {
15459 return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15460 }
15461 ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15462 function getPropertyNameForKnownSymbolName(symbolName) {
15463 return "__@" + symbolName;
15464 }
15465 ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15466 function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15467 return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15468 }
15469 ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15470 function isKnownSymbol(symbol) {
15471 return ts.startsWith(symbol.escapedName, "__@");
15472 }
15473 ts.isKnownSymbol = isKnownSymbol;
15474 /**
15475 * Includes the word "Symbol" with unicode escapes
15476 */
15477 function isESSymbolIdentifier(node) {
15478 return node.kind === 78 /* Identifier */ && node.escapedText === "Symbol";
15479 }
15480 ts.isESSymbolIdentifier = isESSymbolIdentifier;
15481 function isPushOrUnshiftIdentifier(node) {
15482 return node.escapedText === "push" || node.escapedText === "unshift";
15483 }
15484 ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15485 function isParameterDeclaration(node) {
15486 var root = getRootDeclaration(node);
15487 return root.kind === 159 /* Parameter */;
15488 }
15489 ts.isParameterDeclaration = isParameterDeclaration;
15490 function getRootDeclaration(node) {
15491 while (node.kind === 195 /* BindingElement */) {
15492 node = node.parent.parent;
15493 }
15494 return node;
15495 }
15496 ts.getRootDeclaration = getRootDeclaration;
15497 function nodeStartsNewLexicalEnvironment(node) {
15498 var kind = node.kind;
15499 return kind === 165 /* Constructor */
15500 || kind === 205 /* FunctionExpression */
15501 || kind === 248 /* FunctionDeclaration */
15502 || kind === 206 /* ArrowFunction */
15503 || kind === 164 /* MethodDeclaration */
15504 || kind === 166 /* GetAccessor */
15505 || kind === 167 /* SetAccessor */
15506 || kind === 253 /* ModuleDeclaration */
15507 || kind === 294 /* SourceFile */;
15508 }
15509 ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15510 function nodeIsSynthesized(range) {
15511 return positionIsSynthesized(range.pos)
15512 || positionIsSynthesized(range.end);
15513 }
15514 ts.nodeIsSynthesized = nodeIsSynthesized;
15515 function getOriginalSourceFile(sourceFile) {
15516 return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15517 }
15518 ts.getOriginalSourceFile = getOriginalSourceFile;
15519 var Associativity;
15520 (function (Associativity) {
15521 Associativity[Associativity["Left"] = 0] = "Left";
15522 Associativity[Associativity["Right"] = 1] = "Right";
15523 })(Associativity = ts.Associativity || (ts.Associativity = {}));
15524 function getExpressionAssociativity(expression) {
15525 var operator = getOperator(expression);
15526 var hasArguments = expression.kind === 201 /* NewExpression */ && expression.arguments !== undefined;
15527 return getOperatorAssociativity(expression.kind, operator, hasArguments);
15528 }
15529 ts.getExpressionAssociativity = getExpressionAssociativity;
15530 function getOperatorAssociativity(kind, operator, hasArguments) {
15531 switch (kind) {
15532 case 201 /* NewExpression */:
15533 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15534 case 211 /* PrefixUnaryExpression */:
15535 case 208 /* TypeOfExpression */:
15536 case 209 /* VoidExpression */:
15537 case 207 /* DeleteExpression */:
15538 case 210 /* AwaitExpression */:
15539 case 214 /* ConditionalExpression */:
15540 case 216 /* YieldExpression */:
15541 return 1 /* Right */;
15542 case 213 /* BinaryExpression */:
15543 switch (operator) {
15544 case 42 /* AsteriskAsteriskToken */:
15545 case 62 /* EqualsToken */:
15546 case 63 /* PlusEqualsToken */:
15547 case 64 /* MinusEqualsToken */:
15548 case 66 /* AsteriskAsteriskEqualsToken */:
15549 case 65 /* AsteriskEqualsToken */:
15550 case 67 /* SlashEqualsToken */:
15551 case 68 /* PercentEqualsToken */:
15552 case 69 /* LessThanLessThanEqualsToken */:
15553 case 70 /* GreaterThanGreaterThanEqualsToken */:
15554 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15555 case 72 /* AmpersandEqualsToken */:
15556 case 77 /* CaretEqualsToken */:
15557 case 73 /* BarEqualsToken */:
15558 case 74 /* BarBarEqualsToken */:
15559 case 75 /* AmpersandAmpersandEqualsToken */:
15560 case 76 /* QuestionQuestionEqualsToken */:
15561 return 1 /* Right */;
15562 }
15563 }
15564 return 0 /* Left */;
15565 }
15566 ts.getOperatorAssociativity = getOperatorAssociativity;
15567 function getExpressionPrecedence(expression) {
15568 var operator = getOperator(expression);
15569 var hasArguments = expression.kind === 201 /* NewExpression */ && expression.arguments !== undefined;
15570 return getOperatorPrecedence(expression.kind, operator, hasArguments);
15571 }
15572 ts.getExpressionPrecedence = getExpressionPrecedence;
15573 function getOperator(expression) {
15574 if (expression.kind === 213 /* BinaryExpression */) {
15575 return expression.operatorToken.kind;
15576 }
15577 else if (expression.kind === 211 /* PrefixUnaryExpression */ || expression.kind === 212 /* PostfixUnaryExpression */) {
15578 return expression.operator;
15579 }
15580 else {
15581 return expression.kind;
15582 }
15583 }
15584 ts.getOperator = getOperator;
15585 var OperatorPrecedence;
15586 (function (OperatorPrecedence) {
15587 // Expression:
15588 // AssignmentExpression
15589 // Expression `,` AssignmentExpression
15590 OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
15591 // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
15592 // SpreadElement:
15593 // `...` AssignmentExpression
15594 OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
15595 // AssignmentExpression:
15596 // ConditionalExpression
15597 // YieldExpression
15598 // ArrowFunction
15599 // AsyncArrowFunction
15600 // LeftHandSideExpression `=` AssignmentExpression
15601 // LeftHandSideExpression AssignmentOperator AssignmentExpression
15602 //
15603 // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
15604 // of the parenthesizer rules.
15605 // AssignmentExpression: YieldExpression
15606 // YieldExpression:
15607 // `yield`
15608 // `yield` AssignmentExpression
15609 // `yield` `*` AssignmentExpression
15610 OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
15611 // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
15612 // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
15613 // AssignmentOperator: one of
15614 // `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
15615 OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
15616 // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
15617 // the same precedence.
15618 // AssignmentExpression: ConditionalExpression
15619 // ConditionalExpression:
15620 // ShortCircuitExpression
15621 // ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
15622 // ShortCircuitExpression:
15623 // LogicalORExpression
15624 // CoalesceExpression
15625 OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
15626 // CoalesceExpression:
15627 // CoalesceExpressionHead `??` BitwiseORExpression
15628 // CoalesceExpressionHead:
15629 // CoalesceExpression
15630 // BitwiseORExpression
15631 OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
15632 // LogicalORExpression:
15633 // LogicalANDExpression
15634 // LogicalORExpression `||` LogicalANDExpression
15635 OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
15636 // LogicalANDExpression:
15637 // BitwiseORExpression
15638 // LogicalANDExprerssion `&&` BitwiseORExpression
15639 OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
15640 // BitwiseORExpression:
15641 // BitwiseXORExpression
15642 // BitwiseORExpression `^` BitwiseXORExpression
15643 OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
15644 // BitwiseXORExpression:
15645 // BitwiseANDExpression
15646 // BitwiseXORExpression `^` BitwiseANDExpression
15647 OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
15648 // BitwiseANDExpression:
15649 // EqualityExpression
15650 // BitwiseANDExpression `^` EqualityExpression
15651 OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
15652 // EqualityExpression:
15653 // RelationalExpression
15654 // EqualityExpression `==` RelationalExpression
15655 // EqualityExpression `!=` RelationalExpression
15656 // EqualityExpression `===` RelationalExpression
15657 // EqualityExpression `!==` RelationalExpression
15658 OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
15659 // RelationalExpression:
15660 // ShiftExpression
15661 // RelationalExpression `<` ShiftExpression
15662 // RelationalExpression `>` ShiftExpression
15663 // RelationalExpression `<=` ShiftExpression
15664 // RelationalExpression `>=` ShiftExpression
15665 // RelationalExpression `instanceof` ShiftExpression
15666 // RelationalExpression `in` ShiftExpression
15667 // [+TypeScript] RelationalExpression `as` Type
15668 OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
15669 // ShiftExpression:
15670 // AdditiveExpression
15671 // ShiftExpression `<<` AdditiveExpression
15672 // ShiftExpression `>>` AdditiveExpression
15673 // ShiftExpression `>>>` AdditiveExpression
15674 OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
15675 // AdditiveExpression:
15676 // MultiplicativeExpression
15677 // AdditiveExpression `+` MultiplicativeExpression
15678 // AdditiveExpression `-` MultiplicativeExpression
15679 OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
15680 // MultiplicativeExpression:
15681 // ExponentiationExpression
15682 // MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
15683 // MultiplicativeOperator: one of `*`, `/`, `%`
15684 OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
15685 // ExponentiationExpression:
15686 // UnaryExpression
15687 // UpdateExpression `**` ExponentiationExpression
15688 OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
15689 // UnaryExpression:
15690 // UpdateExpression
15691 // `delete` UnaryExpression
15692 // `void` UnaryExpression
15693 // `typeof` UnaryExpression
15694 // `+` UnaryExpression
15695 // `-` UnaryExpression
15696 // `~` UnaryExpression
15697 // `!` UnaryExpression
15698 // AwaitExpression
15699 // UpdateExpression: // TODO: Do we need to investigate the precedence here?
15700 // `++` UnaryExpression
15701 // `--` UnaryExpression
15702 OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
15703 // UpdateExpression:
15704 // LeftHandSideExpression
15705 // LeftHandSideExpression `++`
15706 // LeftHandSideExpression `--`
15707 OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
15708 // LeftHandSideExpression:
15709 // NewExpression
15710 // CallExpression
15711 // NewExpression:
15712 // MemberExpression
15713 // `new` NewExpression
15714 OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
15715 // CallExpression:
15716 // CoverCallExpressionAndAsyncArrowHead
15717 // SuperCall
15718 // ImportCall
15719 // CallExpression Arguments
15720 // CallExpression `[` Expression `]`
15721 // CallExpression `.` IdentifierName
15722 // CallExpression TemplateLiteral
15723 // MemberExpression:
15724 // PrimaryExpression
15725 // MemberExpression `[` Expression `]`
15726 // MemberExpression `.` IdentifierName
15727 // MemberExpression TemplateLiteral
15728 // SuperProperty
15729 // MetaProperty
15730 // `new` MemberExpression Arguments
15731 OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
15732 // TODO: JSXElement?
15733 // PrimaryExpression:
15734 // `this`
15735 // IdentifierReference
15736 // Literal
15737 // ArrayLiteral
15738 // ObjectLiteral
15739 // FunctionExpression
15740 // ClassExpression
15741 // GeneratorExpression
15742 // AsyncFunctionExpression
15743 // AsyncGeneratorExpression
15744 // RegularExpressionLiteral
15745 // TemplateLiteral
15746 // CoverParenthesizedExpressionAndArrowParameterList
15747 OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
15748 OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
15749 OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
15750 // -1 is lower than all other precedences. Returning it will cause binary expression
15751 // parsing to stop.
15752 OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
15753 })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
15754 function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15755 switch (nodeKind) {
15756 case 332 /* CommaListExpression */:
15757 return 0 /* Comma */;
15758 case 217 /* SpreadElement */:
15759 return 1 /* Spread */;
15760 case 216 /* YieldExpression */:
15761 return 2 /* Yield */;
15762 case 214 /* ConditionalExpression */:
15763 return 4 /* Conditional */;
15764 case 213 /* BinaryExpression */:
15765 switch (operatorKind) {
15766 case 27 /* CommaToken */:
15767 return 0 /* Comma */;
15768 case 62 /* EqualsToken */:
15769 case 63 /* PlusEqualsToken */:
15770 case 64 /* MinusEqualsToken */:
15771 case 66 /* AsteriskAsteriskEqualsToken */:
15772 case 65 /* AsteriskEqualsToken */:
15773 case 67 /* SlashEqualsToken */:
15774 case 68 /* PercentEqualsToken */:
15775 case 69 /* LessThanLessThanEqualsToken */:
15776 case 70 /* GreaterThanGreaterThanEqualsToken */:
15777 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15778 case 72 /* AmpersandEqualsToken */:
15779 case 77 /* CaretEqualsToken */:
15780 case 73 /* BarEqualsToken */:
15781 case 74 /* BarBarEqualsToken */:
15782 case 75 /* AmpersandAmpersandEqualsToken */:
15783 case 76 /* QuestionQuestionEqualsToken */:
15784 return 3 /* Assignment */;
15785 default:
15786 return getBinaryOperatorPrecedence(operatorKind);
15787 }
15788 // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
15789 // TODO: We are missing `TypeAssertionExpression`
15790 case 211 /* PrefixUnaryExpression */:
15791 case 208 /* TypeOfExpression */:
15792 case 209 /* VoidExpression */:
15793 case 207 /* DeleteExpression */:
15794 case 210 /* AwaitExpression */:
15795 return 16 /* Unary */;
15796 case 212 /* PostfixUnaryExpression */:
15797 return 17 /* Update */;
15798 case 200 /* CallExpression */:
15799 return 18 /* LeftHandSide */;
15800 case 201 /* NewExpression */:
15801 return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
15802 case 202 /* TaggedTemplateExpression */:
15803 case 198 /* PropertyAccessExpression */:
15804 case 199 /* ElementAccessExpression */:
15805 return 19 /* Member */;
15806 case 107 /* ThisKeyword */:
15807 case 105 /* SuperKeyword */:
15808 case 78 /* Identifier */:
15809 case 103 /* NullKeyword */:
15810 case 109 /* TrueKeyword */:
15811 case 94 /* FalseKeyword */:
15812 case 8 /* NumericLiteral */:
15813 case 9 /* BigIntLiteral */:
15814 case 10 /* StringLiteral */:
15815 case 196 /* ArrayLiteralExpression */:
15816 case 197 /* ObjectLiteralExpression */:
15817 case 205 /* FunctionExpression */:
15818 case 206 /* ArrowFunction */:
15819 case 218 /* ClassExpression */:
15820 case 13 /* RegularExpressionLiteral */:
15821 case 14 /* NoSubstitutionTemplateLiteral */:
15822 case 215 /* TemplateExpression */:
15823 case 204 /* ParenthesizedExpression */:
15824 case 219 /* OmittedExpression */:
15825 case 270 /* JsxElement */:
15826 case 271 /* JsxSelfClosingElement */:
15827 case 274 /* JsxFragment */:
15828 return 20 /* Primary */;
15829 default:
15830 return -1 /* Invalid */;
15831 }
15832 }
15833 ts.getOperatorPrecedence = getOperatorPrecedence;
15834 function getBinaryOperatorPrecedence(kind) {
15835 switch (kind) {
15836 case 60 /* QuestionQuestionToken */:
15837 return 4 /* Coalesce */;
15838 case 56 /* BarBarToken */:
15839 return 5 /* LogicalOR */;
15840 case 55 /* AmpersandAmpersandToken */:
15841 return 6 /* LogicalAND */;
15842 case 51 /* BarToken */:
15843 return 7 /* BitwiseOR */;
15844 case 52 /* CaretToken */:
15845 return 8 /* BitwiseXOR */;
15846 case 50 /* AmpersandToken */:
15847 return 9 /* BitwiseAND */;
15848 case 34 /* EqualsEqualsToken */:
15849 case 35 /* ExclamationEqualsToken */:
15850 case 36 /* EqualsEqualsEqualsToken */:
15851 case 37 /* ExclamationEqualsEqualsToken */:
15852 return 10 /* Equality */;
15853 case 29 /* LessThanToken */:
15854 case 31 /* GreaterThanToken */:
15855 case 32 /* LessThanEqualsToken */:
15856 case 33 /* GreaterThanEqualsToken */:
15857 case 101 /* InstanceOfKeyword */:
15858 case 100 /* InKeyword */:
15859 case 126 /* AsKeyword */:
15860 return 11 /* Relational */;
15861 case 47 /* LessThanLessThanToken */:
15862 case 48 /* GreaterThanGreaterThanToken */:
15863 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15864 return 12 /* Shift */;
15865 case 39 /* PlusToken */:
15866 case 40 /* MinusToken */:
15867 return 13 /* Additive */;
15868 case 41 /* AsteriskToken */:
15869 case 43 /* SlashToken */:
15870 case 44 /* PercentToken */:
15871 return 14 /* Multiplicative */;
15872 case 42 /* AsteriskAsteriskToken */:
15873 return 15 /* Exponentiation */;
15874 }
15875 // -1 is lower than all other precedences. Returning it will cause binary expression
15876 // parsing to stop.
15877 return -1;
15878 }
15879 ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15880 function createDiagnosticCollection() {
15881 var nonFileDiagnostics = []; // See GH#19873
15882 var filesWithDiagnostics = [];
15883 var fileDiagnostics = new ts.Map();
15884 var hasReadNonFileDiagnostics = false;
15885 return {
15886 add: add,
15887 lookup: lookup,
15888 getGlobalDiagnostics: getGlobalDiagnostics,
15889 getDiagnostics: getDiagnostics,
15890 reattachFileDiagnostics: reattachFileDiagnostics
15891 };
15892 function reattachFileDiagnostics(newFile) {
15893 ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
15894 }
15895 function lookup(diagnostic) {
15896 var diagnostics;
15897 if (diagnostic.file) {
15898 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
15899 }
15900 else {
15901 diagnostics = nonFileDiagnostics;
15902 }
15903 if (!diagnostics) {
15904 return undefined;
15905 }
15906 var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
15907 if (result >= 0) {
15908 return diagnostics[result];
15909 }
15910 return undefined;
15911 }
15912 function add(diagnostic) {
15913 var diagnostics;
15914 if (diagnostic.file) {
15915 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
15916 if (!diagnostics) {
15917 diagnostics = []; // See GH#19873
15918 fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
15919 ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
15920 }
15921 }
15922 else {
15923 // If we've already read the non-file diagnostics, do not modify the existing array.
15924 if (hasReadNonFileDiagnostics) {
15925 hasReadNonFileDiagnostics = false;
15926 nonFileDiagnostics = nonFileDiagnostics.slice();
15927 }
15928 diagnostics = nonFileDiagnostics;
15929 }
15930 ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
15931 }
15932 function getGlobalDiagnostics() {
15933 hasReadNonFileDiagnostics = true;
15934 return nonFileDiagnostics;
15935 }
15936 function getDiagnostics(fileName) {
15937 if (fileName) {
15938 return fileDiagnostics.get(fileName) || [];
15939 }
15940 var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
15941 if (!nonFileDiagnostics.length) {
15942 return fileDiags;
15943 }
15944 fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
15945 return fileDiags;
15946 }
15947 }
15948 ts.createDiagnosticCollection = createDiagnosticCollection;
15949 var templateSubstitutionRegExp = /\$\{/g;
15950 function escapeTemplateSubstitution(str) {
15951 return str.replace(templateSubstitutionRegExp, "\\${");
15952 }
15953 /** @internal */
15954 function hasInvalidEscape(template) {
15955 return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
15956 ? template.templateFlags
15957 : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
15958 }
15959 ts.hasInvalidEscape = hasInvalidEscape;
15960 // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
15961 // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
15962 // the language service. These characters should be escaped when printing, and if any characters are added,
15963 // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
15964 // There is no reason for this other than that JSON.stringify does not handle it either.
15965 var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
15966 var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
15967 // Template strings should be preserved as much as possible
15968 var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
15969 var escapedCharsMap = new ts.Map(ts.getEntries({
15970 "\t": "\\t",
15971 "\v": "\\v",
15972 "\f": "\\f",
15973 "\b": "\\b",
15974 "\r": "\\r",
15975 "\n": "\\n",
15976 "\\": "\\\\",
15977 "\"": "\\\"",
15978 "\'": "\\\'",
15979 "\`": "\\\`",
15980 "\u2028": "\\u2028",
15981 "\u2029": "\\u2029",
15982 "\u0085": "\\u0085" // nextLine
15983 }));
15984 function encodeUtf16EscapeSequence(charCode) {
15985 var hexCharCode = charCode.toString(16).toUpperCase();
15986 var paddedHexCode = ("0000" + hexCharCode).slice(-4);
15987 return "\\u" + paddedHexCode;
15988 }
15989 function getReplacement(c, offset, input) {
15990 if (c.charCodeAt(0) === 0 /* nullCharacter */) {
15991 var lookAhead = input.charCodeAt(offset + c.length);
15992 if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
15993 // 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)
15994 return "\\x00";
15995 }
15996 // Otherwise, keep printing a literal \0 for the null character
15997 return "\\0";
15998 }
15999 return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16000 }
16001 /**
16002 * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16003 * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16004 * Note that this doesn't actually wrap the input in double quotes.
16005 */
16006 function escapeString(s, quoteChar) {
16007 var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16008 quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16009 doubleQuoteEscapedCharsRegExp;
16010 return s.replace(escapedCharsRegExp, getReplacement);
16011 }
16012 ts.escapeString = escapeString;
16013 var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16014 function escapeNonAsciiString(s, quoteChar) {
16015 s = escapeString(s, quoteChar);
16016 // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16017 // Otherwise just return the original string.
16018 return nonAsciiCharacters.test(s) ?
16019 s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16020 s;
16021 }
16022 ts.escapeNonAsciiString = escapeNonAsciiString;
16023 // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16024 // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16025 // the language service. These characters should be escaped when printing, and if any characters are added,
16026 // the map below must be updated.
16027 var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16028 var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16029 var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
16030 "\"": "&quot;",
16031 "\'": "&apos;"
16032 }));
16033 function encodeJsxCharacterEntity(charCode) {
16034 var hexCharCode = charCode.toString(16).toUpperCase();
16035 return "&#x" + hexCharCode + ";";
16036 }
16037 function getJsxAttributeStringReplacement(c) {
16038 if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16039 return "&#0;";
16040 }
16041 return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16042 }
16043 function escapeJsxAttributeString(s, quoteChar) {
16044 var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16045 jsxDoubleQuoteEscapedCharsRegExp;
16046 return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16047 }
16048 ts.escapeJsxAttributeString = escapeJsxAttributeString;
16049 /**
16050 * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16051 *
16052 * @return non-quoted string
16053 */
16054 function stripQuotes(name) {
16055 var length = name.length;
16056 if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16057 return name.substring(1, length - 1);
16058 }
16059 return name;
16060 }
16061 ts.stripQuotes = stripQuotes;
16062 function isQuoteOrBacktick(charCode) {
16063 return charCode === 39 /* singleQuote */ ||
16064 charCode === 34 /* doubleQuote */ ||
16065 charCode === 96 /* backtick */;
16066 }
16067 function isIntrinsicJsxName(name) {
16068 var ch = name.charCodeAt(0);
16069 return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16070 }
16071 ts.isIntrinsicJsxName = isIntrinsicJsxName;
16072 var indentStrings = ["", " "];
16073 function getIndentString(level) {
16074 if (indentStrings[level] === undefined) {
16075 indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16076 }
16077 return indentStrings[level];
16078 }
16079 ts.getIndentString = getIndentString;
16080 function getIndentSize() {
16081 return indentStrings[1].length;
16082 }
16083 ts.getIndentSize = getIndentSize;
16084 function createTextWriter(newLine) {
16085 var output;
16086 var indent;
16087 var lineStart;
16088 var lineCount;
16089 var linePos;
16090 var hasTrailingComment = false;
16091 function updateLineCountAndPosFor(s) {
16092 var lineStartsOfS = ts.computeLineStarts(s);
16093 if (lineStartsOfS.length > 1) {
16094 lineCount = lineCount + lineStartsOfS.length - 1;
16095 linePos = output.length - s.length + ts.last(lineStartsOfS);
16096 lineStart = (linePos - output.length) === 0;
16097 }
16098 else {
16099 lineStart = false;
16100 }
16101 }
16102 function writeText(s) {
16103 if (s && s.length) {
16104 if (lineStart) {
16105 s = getIndentString(indent) + s;
16106 lineStart = false;
16107 }
16108 output += s;
16109 updateLineCountAndPosFor(s);
16110 }
16111 }
16112 function write(s) {
16113 if (s)
16114 hasTrailingComment = false;
16115 writeText(s);
16116 }
16117 function writeComment(s) {
16118 if (s)
16119 hasTrailingComment = true;
16120 writeText(s);
16121 }
16122 function reset() {
16123 output = "";
16124 indent = 0;
16125 lineStart = true;
16126 lineCount = 0;
16127 linePos = 0;
16128 hasTrailingComment = false;
16129 }
16130 function rawWrite(s) {
16131 if (s !== undefined) {
16132 output += s;
16133 updateLineCountAndPosFor(s);
16134 hasTrailingComment = false;
16135 }
16136 }
16137 function writeLiteral(s) {
16138 if (s && s.length) {
16139 write(s);
16140 }
16141 }
16142 function writeLine(force) {
16143 if (!lineStart || force) {
16144 output += newLine;
16145 lineCount++;
16146 linePos = output.length;
16147 lineStart = true;
16148 hasTrailingComment = false;
16149 }
16150 }
16151 function getTextPosWithWriteLine() {
16152 return lineStart ? output.length : (output.length + newLine.length);
16153 }
16154 reset();
16155 return {
16156 write: write,
16157 rawWrite: rawWrite,
16158 writeLiteral: writeLiteral,
16159 writeLine: writeLine,
16160 increaseIndent: function () { indent++; },
16161 decreaseIndent: function () { indent--; },
16162 getIndent: function () { return indent; },
16163 getTextPos: function () { return output.length; },
16164 getLine: function () { return lineCount; },
16165 getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16166 getText: function () { return output; },
16167 isAtStartOfLine: function () { return lineStart; },
16168 hasTrailingComment: function () { return hasTrailingComment; },
16169 hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16170 clear: reset,
16171 reportInaccessibleThisError: ts.noop,
16172 reportPrivateInBaseOfClassExpression: ts.noop,
16173 reportInaccessibleUniqueSymbolError: ts.noop,
16174 trackSymbol: ts.noop,
16175 writeKeyword: write,
16176 writeOperator: write,
16177 writeParameter: write,
16178 writeProperty: write,
16179 writePunctuation: write,
16180 writeSpace: write,
16181 writeStringLiteral: write,
16182 writeSymbol: function (s, _) { return write(s); },
16183 writeTrailingSemicolon: write,
16184 writeComment: writeComment,
16185 getTextPosWithWriteLine: getTextPosWithWriteLine
16186 };
16187 }
16188 ts.createTextWriter = createTextWriter;
16189 function getTrailingSemicolonDeferringWriter(writer) {
16190 var pendingTrailingSemicolon = false;
16191 function commitPendingTrailingSemicolon() {
16192 if (pendingTrailingSemicolon) {
16193 writer.writeTrailingSemicolon(";");
16194 pendingTrailingSemicolon = false;
16195 }
16196 }
16197 return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16198 pendingTrailingSemicolon = true;
16199 },
16200 writeLiteral: function (s) {
16201 commitPendingTrailingSemicolon();
16202 writer.writeLiteral(s);
16203 },
16204 writeStringLiteral: function (s) {
16205 commitPendingTrailingSemicolon();
16206 writer.writeStringLiteral(s);
16207 },
16208 writeSymbol: function (s, sym) {
16209 commitPendingTrailingSemicolon();
16210 writer.writeSymbol(s, sym);
16211 },
16212 writePunctuation: function (s) {
16213 commitPendingTrailingSemicolon();
16214 writer.writePunctuation(s);
16215 },
16216 writeKeyword: function (s) {
16217 commitPendingTrailingSemicolon();
16218 writer.writeKeyword(s);
16219 },
16220 writeOperator: function (s) {
16221 commitPendingTrailingSemicolon();
16222 writer.writeOperator(s);
16223 },
16224 writeParameter: function (s) {
16225 commitPendingTrailingSemicolon();
16226 writer.writeParameter(s);
16227 },
16228 writeSpace: function (s) {
16229 commitPendingTrailingSemicolon();
16230 writer.writeSpace(s);
16231 },
16232 writeProperty: function (s) {
16233 commitPendingTrailingSemicolon();
16234 writer.writeProperty(s);
16235 },
16236 writeComment: function (s) {
16237 commitPendingTrailingSemicolon();
16238 writer.writeComment(s);
16239 },
16240 writeLine: function () {
16241 commitPendingTrailingSemicolon();
16242 writer.writeLine();
16243 },
16244 increaseIndent: function () {
16245 commitPendingTrailingSemicolon();
16246 writer.increaseIndent();
16247 },
16248 decreaseIndent: function () {
16249 commitPendingTrailingSemicolon();
16250 writer.decreaseIndent();
16251 } });
16252 }
16253 ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16254 function hostUsesCaseSensitiveFileNames(host) {
16255 return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16256 }
16257 ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16258 function hostGetCanonicalFileName(host) {
16259 return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16260 }
16261 ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16262 function getResolvedExternalModuleName(host, file, referenceFile) {
16263 return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16264 }
16265 ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16266 function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16267 var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16268 if (!file || file.isDeclarationFile) {
16269 return undefined;
16270 }
16271 return getResolvedExternalModuleName(host, file);
16272 }
16273 ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16274 /**
16275 * Resolves a local path to a path which is absolute to the base of the emit
16276 */
16277 function getExternalModuleNameFromPath(host, fileName, referencePath) {
16278 var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16279 var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16280 var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16281 var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16282 var extensionless = removeFileExtension(relativePath);
16283 return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16284 }
16285 ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16286 function getOwnEmitOutputFilePath(fileName, host, extension) {
16287 var compilerOptions = host.getCompilerOptions();
16288 var emitOutputFilePathWithoutExtension;
16289 if (compilerOptions.outDir) {
16290 emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16291 }
16292 else {
16293 emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16294 }
16295 return emitOutputFilePathWithoutExtension + extension;
16296 }
16297 ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16298 function getDeclarationEmitOutputFilePath(fileName, host) {
16299 return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16300 }
16301 ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16302 function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16303 var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16304 var path = outputDir
16305 ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16306 : fileName;
16307 return removeFileExtension(path) + ".d.ts" /* Dts */;
16308 }
16309 ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16310 function outFile(options) {
16311 return options.outFile || options.out;
16312 }
16313 ts.outFile = outFile;
16314 /**
16315 * Gets the source files that are expected to have an emit output.
16316 *
16317 * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16318 * transformations.
16319 *
16320 * @param host An EmitHost.
16321 * @param targetSourceFile An optional target source file to emit.
16322 */
16323 function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16324 var options = host.getCompilerOptions();
16325 if (outFile(options)) {
16326 var moduleKind = getEmitModuleKind(options);
16327 var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16328 // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16329 return ts.filter(host.getSourceFiles(), function (sourceFile) {
16330 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16331 sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16332 });
16333 }
16334 else {
16335 var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16336 return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16337 }
16338 }
16339 ts.getSourceFilesToEmit = getSourceFilesToEmit;
16340 /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16341 function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16342 var options = host.getCompilerOptions();
16343 return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16344 !sourceFile.isDeclarationFile &&
16345 !host.isSourceFileFromExternalLibrary(sourceFile) &&
16346 !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16347 (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16348 }
16349 ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16350 function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16351 return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16352 }
16353 ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16354 function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16355 var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16356 var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16357 sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16358 return ts.combinePaths(newDirPath, sourceFilePath);
16359 }
16360 ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16361 function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16362 host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16363 diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16364 }, sourceFiles);
16365 }
16366 ts.writeFile = writeFile;
16367 function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16368 if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16369 var parentDirectory = ts.getDirectoryPath(directoryPath);
16370 ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16371 createDirectory(directoryPath);
16372 }
16373 }
16374 function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16375 // PERF: Checking for directory existence is expensive. Instead, assume the directory exists
16376 // and fall back to creating it if the file write fails.
16377 try {
16378 writeFile(path, data, writeByteOrderMark);
16379 }
16380 catch (_a) {
16381 ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16382 writeFile(path, data, writeByteOrderMark);
16383 }
16384 }
16385 ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16386 function getLineOfLocalPosition(sourceFile, pos) {
16387 var lineStarts = ts.getLineStarts(sourceFile);
16388 return ts.computeLineOfPosition(lineStarts, pos);
16389 }
16390 ts.getLineOfLocalPosition = getLineOfLocalPosition;
16391 function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16392 return ts.computeLineOfPosition(lineMap, pos);
16393 }
16394 ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16395 function getFirstConstructorWithBody(node) {
16396 return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16397 }
16398 ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16399 function getSetAccessorValueParameter(accessor) {
16400 if (accessor && accessor.parameters.length > 0) {
16401 var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16402 return accessor.parameters[hasThis ? 1 : 0];
16403 }
16404 }
16405 ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16406 /** Get the type annotation for the value parameter. */
16407 function getSetAccessorTypeAnnotationNode(accessor) {
16408 var parameter = getSetAccessorValueParameter(accessor);
16409 return parameter && parameter.type;
16410 }
16411 ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16412 function getThisParameter(signature) {
16413 // callback tags do not currently support this parameters
16414 if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16415 var thisParameter = signature.parameters[0];
16416 if (parameterIsThisKeyword(thisParameter)) {
16417 return thisParameter;
16418 }
16419 }
16420 }
16421 ts.getThisParameter = getThisParameter;
16422 function parameterIsThisKeyword(parameter) {
16423 return isThisIdentifier(parameter.name);
16424 }
16425 ts.parameterIsThisKeyword = parameterIsThisKeyword;
16426 function isThisIdentifier(node) {
16427 return !!node && node.kind === 78 /* Identifier */ && identifierIsThisKeyword(node);
16428 }
16429 ts.isThisIdentifier = isThisIdentifier;
16430 function identifierIsThisKeyword(id) {
16431 return id.originalKeywordKind === 107 /* ThisKeyword */;
16432 }
16433 ts.identifierIsThisKeyword = identifierIsThisKeyword;
16434 function getAllAccessorDeclarations(declarations, accessor) {
16435 // TODO: GH#18217
16436 var firstAccessor;
16437 var secondAccessor;
16438 var getAccessor;
16439 var setAccessor;
16440 if (hasDynamicName(accessor)) {
16441 firstAccessor = accessor;
16442 if (accessor.kind === 166 /* GetAccessor */) {
16443 getAccessor = accessor;
16444 }
16445 else if (accessor.kind === 167 /* SetAccessor */) {
16446 setAccessor = accessor;
16447 }
16448 else {
16449 ts.Debug.fail("Accessor has wrong kind");
16450 }
16451 }
16452 else {
16453 ts.forEach(declarations, function (member) {
16454 if (ts.isAccessor(member)
16455 && hasSyntacticModifier(member, 32 /* Static */) === hasSyntacticModifier(accessor, 32 /* Static */)) {
16456 var memberName = getPropertyNameForPropertyNameNode(member.name);
16457 var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16458 if (memberName === accessorName) {
16459 if (!firstAccessor) {
16460 firstAccessor = member;
16461 }
16462 else if (!secondAccessor) {
16463 secondAccessor = member;
16464 }
16465 if (member.kind === 166 /* GetAccessor */ && !getAccessor) {
16466 getAccessor = member;
16467 }
16468 if (member.kind === 167 /* SetAccessor */ && !setAccessor) {
16469 setAccessor = member;
16470 }
16471 }
16472 }
16473 });
16474 }
16475 return {
16476 firstAccessor: firstAccessor,
16477 secondAccessor: secondAccessor,
16478 getAccessor: getAccessor,
16479 setAccessor: setAccessor
16480 };
16481 }
16482 ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16483 /**
16484 * Gets the effective type annotation of a variable, parameter, or property. If the node was
16485 * parsed in a JavaScript file, gets the type annotation from JSDoc. Also gets the type of
16486 * functions only the JSDoc case.
16487 */
16488 function getEffectiveTypeAnnotationNode(node) {
16489 if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16490 return undefined;
16491 var type = node.type;
16492 if (type || !isInJSFile(node))
16493 return type;
16494 return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16495 }
16496 ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16497 function getTypeAnnotationNode(node) {
16498 return node.type;
16499 }
16500 ts.getTypeAnnotationNode = getTypeAnnotationNode;
16501 /**
16502 * Gets the effective return type annotation of a signature. If the node was parsed in a
16503 * JavaScript file, gets the return type annotation from JSDoc.
16504 */
16505 function getEffectiveReturnTypeNode(node) {
16506 return ts.isJSDocSignature(node) ?
16507 node.type && node.type.typeExpression && node.type.typeExpression.type :
16508 node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16509 }
16510 ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16511 function getJSDocTypeParameterDeclarations(node) {
16512 return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16513 }
16514 ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16515 /** template tags are only available when a typedef isn't already using them */
16516 function isNonTypeAliasTemplate(tag) {
16517 return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 307 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16518 }
16519 /**
16520 * Gets the effective type annotation of the value parameter of a set accessor. If the node
16521 * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16522 */
16523 function getEffectiveSetAccessorTypeAnnotationNode(node) {
16524 var parameter = getSetAccessorValueParameter(node);
16525 return parameter && getEffectiveTypeAnnotationNode(parameter);
16526 }
16527 ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16528 function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16529 emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16530 }
16531 ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16532 function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16533 // If the leading comments start on different line than the start of node, write new line
16534 if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16535 getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16536 writer.writeLine();
16537 }
16538 }
16539 ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16540 function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16541 // If the leading comments start on different line than the start of node, write new line
16542 if (pos !== commentPos &&
16543 getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16544 writer.writeLine();
16545 }
16546 }
16547 ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16548 function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16549 if (comments && comments.length > 0) {
16550 if (leadingSeparator) {
16551 writer.writeSpace(" ");
16552 }
16553 var emitInterveningSeparator = false;
16554 for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16555 var comment = comments_1[_i];
16556 if (emitInterveningSeparator) {
16557 writer.writeSpace(" ");
16558 emitInterveningSeparator = false;
16559 }
16560 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16561 if (comment.hasTrailingNewLine) {
16562 writer.writeLine();
16563 }
16564 else {
16565 emitInterveningSeparator = true;
16566 }
16567 }
16568 if (emitInterveningSeparator && trailingSeparator) {
16569 writer.writeSpace(" ");
16570 }
16571 }
16572 }
16573 ts.emitComments = emitComments;
16574 /**
16575 * Detached comment is a comment at the top of file or function body that is separated from
16576 * the next statement by space.
16577 */
16578 function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16579 var leadingComments;
16580 var currentDetachedCommentInfo;
16581 if (removeComments) {
16582 // removeComments is true, only reserve pinned comment at the top of file
16583 // For example:
16584 // /*! Pinned Comment */
16585 //
16586 // var x = 10;
16587 if (node.pos === 0) {
16588 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16589 }
16590 }
16591 else {
16592 // removeComments is false, just get detached as normal and bypass the process to filter comment
16593 leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16594 }
16595 if (leadingComments) {
16596 var detachedComments = [];
16597 var lastComment = void 0;
16598 for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16599 var comment = leadingComments_1[_i];
16600 if (lastComment) {
16601 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16602 var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16603 if (commentLine >= lastCommentLine + 2) {
16604 // There was a blank line between the last comment and this comment. This
16605 // comment is not part of the copyright comments. Return what we have so
16606 // far.
16607 break;
16608 }
16609 }
16610 detachedComments.push(comment);
16611 lastComment = comment;
16612 }
16613 if (detachedComments.length) {
16614 // All comments look like they could have been part of the copyright header. Make
16615 // sure there is at least one blank line between it and the node. If not, it's not
16616 // a copyright header.
16617 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16618 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16619 if (nodeLine >= lastCommentLine + 2) {
16620 // Valid detachedComments
16621 emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16622 emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16623 currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16624 }
16625 }
16626 }
16627 return currentDetachedCommentInfo;
16628 function isPinnedCommentLocal(comment) {
16629 return isPinnedComment(text, comment.pos);
16630 }
16631 }
16632 ts.emitDetachedComments = emitDetachedComments;
16633 function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16634 if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16635 var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16636 var lineCount = lineMap.length;
16637 var firstCommentLineIndent = void 0;
16638 for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16639 var nextLineStart = (currentLine + 1) === lineCount
16640 ? text.length + 1
16641 : lineMap[currentLine + 1];
16642 if (pos !== commentPos) {
16643 // If we are not emitting first line, we need to write the spaces to adjust the alignment
16644 if (firstCommentLineIndent === undefined) {
16645 firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16646 }
16647 // These are number of spaces writer is going to write at current indent
16648 var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16649 // Number of spaces we want to be writing
16650 // eg: Assume writer indent
16651 // module m {
16652 // /* starts at character 9 this is line 1
16653 // * starts at character pos 4 line --1 = 8 - 8 + 3
16654 // More left indented comment */ --2 = 8 - 8 + 2
16655 // class c { }
16656 // }
16657 // module m {
16658 // /* this is line 1 -- Assume current writer indent 8
16659 // * line --3 = 8 - 4 + 5
16660 // More right indented comment */ --4 = 8 - 4 + 11
16661 // class c { }
16662 // }
16663 var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16664 if (spacesToEmit > 0) {
16665 var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16666 var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16667 // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16668 writer.rawWrite(indentSizeSpaceString);
16669 // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16670 while (numberOfSingleSpacesToEmit) {
16671 writer.rawWrite(" ");
16672 numberOfSingleSpacesToEmit--;
16673 }
16674 }
16675 else {
16676 // No spaces to emit write empty string
16677 writer.rawWrite("");
16678 }
16679 }
16680 // Write the comment line text
16681 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16682 pos = nextLineStart;
16683 }
16684 }
16685 else {
16686 // Single line comment of style //....
16687 writer.writeComment(text.substring(commentPos, commentEnd));
16688 }
16689 }
16690 ts.writeCommentRange = writeCommentRange;
16691 function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16692 var end = Math.min(commentEnd, nextLineStart - 1);
16693 var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16694 if (currentLineText) {
16695 // trimmed forward and ending spaces text
16696 writer.writeComment(currentLineText);
16697 if (end !== commentEnd) {
16698 writer.writeLine();
16699 }
16700 }
16701 else {
16702 // Empty string - make sure we write empty line
16703 writer.rawWrite(newLine);
16704 }
16705 }
16706 function calculateIndent(text, pos, end) {
16707 var currentLineIndent = 0;
16708 for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16709 if (text.charCodeAt(pos) === 9 /* tab */) {
16710 // Tabs = TabSize = indent size and go to next tabStop
16711 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16712 }
16713 else {
16714 // Single space
16715 currentLineIndent++;
16716 }
16717 }
16718 return currentLineIndent;
16719 }
16720 function hasEffectiveModifiers(node) {
16721 return getEffectiveModifierFlags(node) !== 0 /* None */;
16722 }
16723 ts.hasEffectiveModifiers = hasEffectiveModifiers;
16724 function hasSyntacticModifiers(node) {
16725 return getSyntacticModifierFlags(node) !== 0 /* None */;
16726 }
16727 ts.hasSyntacticModifiers = hasSyntacticModifiers;
16728 function hasEffectiveModifier(node, flags) {
16729 return !!getSelectedEffectiveModifierFlags(node, flags);
16730 }
16731 ts.hasEffectiveModifier = hasEffectiveModifier;
16732 function hasSyntacticModifier(node, flags) {
16733 return !!getSelectedSyntacticModifierFlags(node, flags);
16734 }
16735 ts.hasSyntacticModifier = hasSyntacticModifier;
16736 function hasStaticModifier(node) {
16737 return hasSyntacticModifier(node, 32 /* Static */);
16738 }
16739 ts.hasStaticModifier = hasStaticModifier;
16740 function hasEffectiveReadonlyModifier(node) {
16741 return hasEffectiveModifier(node, 64 /* Readonly */);
16742 }
16743 ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
16744 function getSelectedEffectiveModifierFlags(node, flags) {
16745 return getEffectiveModifierFlags(node) & flags;
16746 }
16747 ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
16748 function getSelectedSyntacticModifierFlags(node, flags) {
16749 return getSyntacticModifierFlags(node) & flags;
16750 }
16751 ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
16752 function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
16753 if (node.kind >= 0 /* FirstToken */ && node.kind <= 155 /* LastToken */) {
16754 return 0 /* None */;
16755 }
16756 if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
16757 node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
16758 }
16759 if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
16760 node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
16761 }
16762 return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
16763 }
16764 /**
16765 * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
16766 *
16767 * NOTE: This function may use `parent` pointers.
16768 */
16769 function getEffectiveModifierFlags(node) {
16770 return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
16771 }
16772 ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
16773 function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
16774 return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
16775 }
16776 ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
16777 /**
16778 * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
16779 *
16780 * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
16781 */
16782 function getSyntacticModifierFlags(node) {
16783 return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
16784 }
16785 ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
16786 function getJSDocModifierFlagsNoCache(node) {
16787 var flags = 0 /* None */;
16788 if (!!node.parent && !ts.isParameter(node)) {
16789 if (isInJSFile(node)) {
16790 if (ts.getJSDocPublicTagNoCache(node))
16791 flags |= 4 /* Public */;
16792 if (ts.getJSDocPrivateTagNoCache(node))
16793 flags |= 8 /* Private */;
16794 if (ts.getJSDocProtectedTagNoCache(node))
16795 flags |= 16 /* Protected */;
16796 if (ts.getJSDocReadonlyTagNoCache(node))
16797 flags |= 64 /* Readonly */;
16798 }
16799 if (ts.getJSDocDeprecatedTagNoCache(node))
16800 flags |= 8192 /* Deprecated */;
16801 }
16802 return flags;
16803 }
16804 /**
16805 * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
16806 *
16807 * NOTE: This function may use `parent` pointers.
16808 */
16809 function getEffectiveModifierFlagsNoCache(node) {
16810 return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
16811 }
16812 ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
16813 /**
16814 * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
16815 *
16816 * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
16817 */
16818 function getSyntacticModifierFlagsNoCache(node) {
16819 var flags = modifiersToFlags(node.modifiers);
16820 if (node.flags & 4 /* NestedNamespace */ || (node.kind === 78 /* Identifier */ && node.isInJSDocNamespace)) {
16821 flags |= 1 /* Export */;
16822 }
16823 return flags;
16824 }
16825 ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
16826 function modifiersToFlags(modifiers) {
16827 var flags = 0 /* None */;
16828 if (modifiers) {
16829 for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
16830 var modifier = modifiers_1[_i];
16831 flags |= modifierToFlag(modifier.kind);
16832 }
16833 }
16834 return flags;
16835 }
16836 ts.modifiersToFlags = modifiersToFlags;
16837 function modifierToFlag(token) {
16838 switch (token) {
16839 case 123 /* StaticKeyword */: return 32 /* Static */;
16840 case 122 /* PublicKeyword */: return 4 /* Public */;
16841 case 121 /* ProtectedKeyword */: return 16 /* Protected */;
16842 case 120 /* PrivateKeyword */: return 8 /* Private */;
16843 case 125 /* AbstractKeyword */: return 128 /* Abstract */;
16844 case 92 /* ExportKeyword */: return 1 /* Export */;
16845 case 133 /* DeclareKeyword */: return 2 /* Ambient */;
16846 case 84 /* ConstKeyword */: return 2048 /* Const */;
16847 case 87 /* DefaultKeyword */: return 512 /* Default */;
16848 case 129 /* AsyncKeyword */: return 256 /* Async */;
16849 case 141 /* ReadonlyKeyword */: return 64 /* Readonly */;
16850 }
16851 return 0 /* None */;
16852 }
16853 ts.modifierToFlag = modifierToFlag;
16854 function isLogicalOperator(token) {
16855 return token === 56 /* BarBarToken */
16856 || token === 55 /* AmpersandAmpersandToken */
16857 || token === 53 /* ExclamationToken */;
16858 }
16859 ts.isLogicalOperator = isLogicalOperator;
16860 function isLogicalOrCoalescingAssignmentOperator(token) {
16861 return token === 74 /* BarBarEqualsToken */
16862 || token === 75 /* AmpersandAmpersandEqualsToken */
16863 || token === 76 /* QuestionQuestionEqualsToken */;
16864 }
16865 ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
16866 function isLogicalOrCoalescingAssignmentExpression(expr) {
16867 return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
16868 }
16869 ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
16870 function isAssignmentOperator(token) {
16871 return token >= 62 /* FirstAssignment */ && token <= 77 /* LastAssignment */;
16872 }
16873 ts.isAssignmentOperator = isAssignmentOperator;
16874 /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16875 function tryGetClassExtendingExpressionWithTypeArguments(node) {
16876 var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16877 return cls && !cls.isImplements ? cls.class : undefined;
16878 }
16879 ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16880 function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16881 return ts.isExpressionWithTypeArguments(node)
16882 && ts.isHeritageClause(node.parent)
16883 && ts.isClassLike(node.parent.parent)
16884 ? { class: node.parent.parent, isImplements: node.parent.token === 116 /* ImplementsKeyword */ }
16885 : undefined;
16886 }
16887 ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16888 function isAssignmentExpression(node, excludeCompoundAssignment) {
16889 return ts.isBinaryExpression(node)
16890 && (excludeCompoundAssignment
16891 ? node.operatorToken.kind === 62 /* EqualsToken */
16892 : isAssignmentOperator(node.operatorToken.kind))
16893 && ts.isLeftHandSideExpression(node.left);
16894 }
16895 ts.isAssignmentExpression = isAssignmentExpression;
16896 function isDestructuringAssignment(node) {
16897 if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16898 var kind = node.left.kind;
16899 return kind === 197 /* ObjectLiteralExpression */
16900 || kind === 196 /* ArrayLiteralExpression */;
16901 }
16902 return false;
16903 }
16904 ts.isDestructuringAssignment = isDestructuringAssignment;
16905 function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16906 return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16907 }
16908 ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16909 function isEntityNameExpression(node) {
16910 return node.kind === 78 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16911 }
16912 ts.isEntityNameExpression = isEntityNameExpression;
16913 function getFirstIdentifier(node) {
16914 switch (node.kind) {
16915 case 78 /* Identifier */:
16916 return node;
16917 case 156 /* QualifiedName */:
16918 do {
16919 node = node.left;
16920 } while (node.kind !== 78 /* Identifier */);
16921 return node;
16922 case 198 /* PropertyAccessExpression */:
16923 do {
16924 node = node.expression;
16925 } while (node.kind !== 78 /* Identifier */);
16926 return node;
16927 }
16928 }
16929 ts.getFirstIdentifier = getFirstIdentifier;
16930 function isDottedName(node) {
16931 return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ ||
16932 node.kind === 198 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16933 node.kind === 204 /* ParenthesizedExpression */ && isDottedName(node.expression);
16934 }
16935 ts.isDottedName = isDottedName;
16936 function isPropertyAccessEntityNameExpression(node) {
16937 return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16938 }
16939 ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16940 function tryGetPropertyAccessOrIdentifierToString(expr) {
16941 if (ts.isPropertyAccessExpression(expr)) {
16942 var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16943 if (baseStr !== undefined) {
16944 return baseStr + "." + entityNameToString(expr.name);
16945 }
16946 }
16947 else if (ts.isIdentifier(expr)) {
16948 return ts.unescapeLeadingUnderscores(expr.escapedText);
16949 }
16950 return undefined;
16951 }
16952 ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16953 function isPrototypeAccess(node) {
16954 return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16955 }
16956 ts.isPrototypeAccess = isPrototypeAccess;
16957 function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16958 return (node.parent.kind === 156 /* QualifiedName */ && node.parent.right === node) ||
16959 (node.parent.kind === 198 /* PropertyAccessExpression */ && node.parent.name === node);
16960 }
16961 ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
16962 function isEmptyObjectLiteral(expression) {
16963 return expression.kind === 197 /* ObjectLiteralExpression */ &&
16964 expression.properties.length === 0;
16965 }
16966 ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
16967 function isEmptyArrayLiteral(expression) {
16968 return expression.kind === 196 /* ArrayLiteralExpression */ &&
16969 expression.elements.length === 0;
16970 }
16971 ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
16972 function getLocalSymbolForExportDefault(symbol) {
16973 if (!isExportDefaultSymbol(symbol))
16974 return undefined;
16975 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
16976 var decl = _a[_i];
16977 if (decl.localSymbol)
16978 return decl.localSymbol;
16979 }
16980 return undefined;
16981 }
16982 ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
16983 function isExportDefaultSymbol(symbol) {
16984 return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
16985 }
16986 /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
16987 function tryExtractTSExtension(fileName) {
16988 return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
16989 }
16990 ts.tryExtractTSExtension = tryExtractTSExtension;
16991 /**
16992 * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
16993 * representing the UTF-8 encoding of the character, and return the expanded char code list.
16994 */
16995 function getExpandedCharCodes(input) {
16996 var output = [];
16997 var length = input.length;
16998 for (var i = 0; i < length; i++) {
16999 var charCode = input.charCodeAt(i);
17000 // handle utf8
17001 if (charCode < 0x80) {
17002 output.push(charCode);
17003 }
17004 else if (charCode < 0x800) {
17005 output.push((charCode >> 6) | 192);
17006 output.push((charCode & 63) | 128);
17007 }
17008 else if (charCode < 0x10000) {
17009 output.push((charCode >> 12) | 224);
17010 output.push(((charCode >> 6) & 63) | 128);
17011 output.push((charCode & 63) | 128);
17012 }
17013 else if (charCode < 0x20000) {
17014 output.push((charCode >> 18) | 240);
17015 output.push(((charCode >> 12) & 63) | 128);
17016 output.push(((charCode >> 6) & 63) | 128);
17017 output.push((charCode & 63) | 128);
17018 }
17019 else {
17020 ts.Debug.assert(false, "Unexpected code point");
17021 }
17022 }
17023 return output;
17024 }
17025 var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17026 /**
17027 * Converts a string to a base-64 encoded ASCII string.
17028 */
17029 function convertToBase64(input) {
17030 var result = "";
17031 var charCodes = getExpandedCharCodes(input);
17032 var i = 0;
17033 var length = charCodes.length;
17034 var byte1, byte2, byte3, byte4;
17035 while (i < length) {
17036 // Convert every 6-bits in the input 3 character points
17037 // into a base64 digit
17038 byte1 = charCodes[i] >> 2;
17039 byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17040 byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17041 byte4 = charCodes[i + 2] & 63;
17042 // We are out of characters in the input, set the extra
17043 // digits to 64 (padding character).
17044 if (i + 1 >= length) {
17045 byte3 = byte4 = 64;
17046 }
17047 else if (i + 2 >= length) {
17048 byte4 = 64;
17049 }
17050 // Write to the output
17051 result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17052 i += 3;
17053 }
17054 return result;
17055 }
17056 ts.convertToBase64 = convertToBase64;
17057 function getStringFromExpandedCharCodes(codes) {
17058 var output = "";
17059 var i = 0;
17060 var length = codes.length;
17061 while (i < length) {
17062 var charCode = codes[i];
17063 if (charCode < 0x80) {
17064 output += String.fromCharCode(charCode);
17065 i++;
17066 }
17067 else if ((charCode & 192) === 192) {
17068 var value = charCode & 63;
17069 i++;
17070 var nextCode = codes[i];
17071 while ((nextCode & 192) === 128) {
17072 value = (value << 6) | (nextCode & 63);
17073 i++;
17074 nextCode = codes[i];
17075 }
17076 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17077 output += String.fromCharCode(value);
17078 }
17079 else {
17080 // We don't want to kill the process when decoding fails (due to a following char byte not
17081 // following a leading char), so we just print the (bad) value
17082 output += String.fromCharCode(charCode);
17083 i++;
17084 }
17085 }
17086 return output;
17087 }
17088 function base64encode(host, input) {
17089 if (host && host.base64encode) {
17090 return host.base64encode(input);
17091 }
17092 return convertToBase64(input);
17093 }
17094 ts.base64encode = base64encode;
17095 function base64decode(host, input) {
17096 if (host && host.base64decode) {
17097 return host.base64decode(input);
17098 }
17099 var length = input.length;
17100 var expandedCharCodes = [];
17101 var i = 0;
17102 while (i < length) {
17103 // Stop decoding once padding characters are present
17104 if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17105 break;
17106 }
17107 // convert 4 input digits into three characters, ignoring padding characters at the end
17108 var ch1 = base64Digits.indexOf(input[i]);
17109 var ch2 = base64Digits.indexOf(input[i + 1]);
17110 var ch3 = base64Digits.indexOf(input[i + 2]);
17111 var ch4 = base64Digits.indexOf(input[i + 3]);
17112 var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17113 var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17114 var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17115 if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17116 expandedCharCodes.push(code1);
17117 }
17118 else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17119 expandedCharCodes.push(code1, code2);
17120 }
17121 else {
17122 expandedCharCodes.push(code1, code2, code3);
17123 }
17124 i += 4;
17125 }
17126 return getStringFromExpandedCharCodes(expandedCharCodes);
17127 }
17128 ts.base64decode = base64decode;
17129 function readJson(path, host) {
17130 try {
17131 var jsonText = host.readFile(path);
17132 if (!jsonText)
17133 return {};
17134 var result = ts.parseConfigFileTextToJson(path, jsonText);
17135 if (result.error) {
17136 return {};
17137 }
17138 return result.config;
17139 }
17140 catch (e) {
17141 // gracefully handle if readFile fails or returns not JSON
17142 return {};
17143 }
17144 }
17145 ts.readJson = readJson;
17146 function directoryProbablyExists(directoryName, host) {
17147 // if host does not support 'directoryExists' assume that directory will exist
17148 return !host.directoryExists || host.directoryExists(directoryName);
17149 }
17150 ts.directoryProbablyExists = directoryProbablyExists;
17151 var carriageReturnLineFeed = "\r\n";
17152 var lineFeed = "\n";
17153 function getNewLineCharacter(options, getNewLine) {
17154 switch (options.newLine) {
17155 case 0 /* CarriageReturnLineFeed */:
17156 return carriageReturnLineFeed;
17157 case 1 /* LineFeed */:
17158 return lineFeed;
17159 }
17160 return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17161 }
17162 ts.getNewLineCharacter = getNewLineCharacter;
17163 /**
17164 * Creates a new TextRange from the provided pos and end.
17165 *
17166 * @param pos The start position.
17167 * @param end The end position.
17168 */
17169 function createRange(pos, end) {
17170 if (end === void 0) { end = pos; }
17171 ts.Debug.assert(end >= pos || end === -1);
17172 return { pos: pos, end: end };
17173 }
17174 ts.createRange = createRange;
17175 /**
17176 * Creates a new TextRange from a provided range with a new end position.
17177 *
17178 * @param range A TextRange.
17179 * @param end The new end position.
17180 */
17181 function moveRangeEnd(range, end) {
17182 return createRange(range.pos, end);
17183 }
17184 ts.moveRangeEnd = moveRangeEnd;
17185 /**
17186 * Creates a new TextRange from a provided range with a new start position.
17187 *
17188 * @param range A TextRange.
17189 * @param pos The new Start position.
17190 */
17191 function moveRangePos(range, pos) {
17192 return createRange(pos, range.end);
17193 }
17194 ts.moveRangePos = moveRangePos;
17195 /**
17196 * Moves the start position of a range past any decorators.
17197 */
17198 function moveRangePastDecorators(node) {
17199 return node.decorators && node.decorators.length > 0
17200 ? moveRangePos(node, node.decorators.end)
17201 : node;
17202 }
17203 ts.moveRangePastDecorators = moveRangePastDecorators;
17204 /**
17205 * Moves the start position of a range past any decorators or modifiers.
17206 */
17207 function moveRangePastModifiers(node) {
17208 return node.modifiers && node.modifiers.length > 0
17209 ? moveRangePos(node, node.modifiers.end)
17210 : moveRangePastDecorators(node);
17211 }
17212 ts.moveRangePastModifiers = moveRangePastModifiers;
17213 /**
17214 * Determines whether a TextRange has the same start and end positions.
17215 *
17216 * @param range A TextRange.
17217 */
17218 function isCollapsedRange(range) {
17219 return range.pos === range.end;
17220 }
17221 ts.isCollapsedRange = isCollapsedRange;
17222 /**
17223 * Creates a new TextRange for a token at the provides start position.
17224 *
17225 * @param pos The start position.
17226 * @param token The token.
17227 */
17228 function createTokenRange(pos, token) {
17229 return createRange(pos, pos + ts.tokenToString(token).length);
17230 }
17231 ts.createTokenRange = createTokenRange;
17232 function rangeIsOnSingleLine(range, sourceFile) {
17233 return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17234 }
17235 ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17236 function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17237 return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17238 }
17239 ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17240 function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17241 return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17242 }
17243 ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17244 function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17245 return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17246 }
17247 ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17248 function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17249 return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17250 }
17251 ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17252 function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17253 var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17254 return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17255 }
17256 ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17257 function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17258 return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17259 }
17260 ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17261 function isNodeArrayMultiLine(list, sourceFile) {
17262 return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17263 }
17264 ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17265 function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17266 return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17267 }
17268 ts.positionsAreOnSameLine = positionsAreOnSameLine;
17269 function getStartPositionOfRange(range, sourceFile, includeComments) {
17270 return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17271 }
17272 ts.getStartPositionOfRange = getStartPositionOfRange;
17273 function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17274 var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17275 var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17276 return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17277 }
17278 ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17279 function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17280 var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17281 return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17282 }
17283 ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17284 function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17285 if (stopPos === void 0) { stopPos = 0; }
17286 while (pos-- > stopPos) {
17287 if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17288 return pos;
17289 }
17290 }
17291 }
17292 /**
17293 * Determines whether a name was originally the declaration name of an enum or namespace
17294 * declaration.
17295 */
17296 function isDeclarationNameOfEnumOrNamespace(node) {
17297 var parseNode = ts.getParseTreeNode(node);
17298 if (parseNode) {
17299 switch (parseNode.parent.kind) {
17300 case 252 /* EnumDeclaration */:
17301 case 253 /* ModuleDeclaration */:
17302 return parseNode === parseNode.parent.name;
17303 }
17304 }
17305 return false;
17306 }
17307 ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17308 function getInitializedVariables(node) {
17309 return ts.filter(node.declarations, isInitializedVariable);
17310 }
17311 ts.getInitializedVariables = getInitializedVariables;
17312 function isInitializedVariable(node) {
17313 return node.initializer !== undefined;
17314 }
17315 function isWatchSet(options) {
17316 // Firefox has Object.prototype.watch
17317 return options.watch && options.hasOwnProperty("watch");
17318 }
17319 ts.isWatchSet = isWatchSet;
17320 function closeFileWatcher(watcher) {
17321 watcher.close();
17322 }
17323 ts.closeFileWatcher = closeFileWatcher;
17324 function getCheckFlags(symbol) {
17325 return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17326 }
17327 ts.getCheckFlags = getCheckFlags;
17328 function getDeclarationModifierFlagsFromSymbol(s) {
17329 if (s.valueDeclaration) {
17330 var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17331 return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17332 }
17333 if (getCheckFlags(s) & 6 /* Synthetic */) {
17334 var checkFlags = s.checkFlags;
17335 var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17336 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17337 16 /* Protected */;
17338 var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17339 return accessModifier | staticModifier;
17340 }
17341 if (s.flags & 4194304 /* Prototype */) {
17342 return 4 /* Public */ | 32 /* Static */;
17343 }
17344 return 0;
17345 }
17346 ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17347 function skipAlias(symbol, checker) {
17348 return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17349 }
17350 ts.skipAlias = skipAlias;
17351 /** See comment on `declareModuleMember` in `binder.ts`. */
17352 function getCombinedLocalAndExportSymbolFlags(symbol) {
17353 return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17354 }
17355 ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17356 function isWriteOnlyAccess(node) {
17357 return accessKind(node) === 1 /* Write */;
17358 }
17359 ts.isWriteOnlyAccess = isWriteOnlyAccess;
17360 function isWriteAccess(node) {
17361 return accessKind(node) !== 0 /* Read */;
17362 }
17363 ts.isWriteAccess = isWriteAccess;
17364 var AccessKind;
17365 (function (AccessKind) {
17366 /** Only reads from a variable. */
17367 AccessKind[AccessKind["Read"] = 0] = "Read";
17368 /** Only writes to a variable without using the result. E.g.: `x++;`. */
17369 AccessKind[AccessKind["Write"] = 1] = "Write";
17370 /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17371 AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17372 })(AccessKind || (AccessKind = {}));
17373 function accessKind(node) {
17374 var parent = node.parent;
17375 if (!parent)
17376 return 0 /* Read */;
17377 switch (parent.kind) {
17378 case 204 /* ParenthesizedExpression */:
17379 return accessKind(parent);
17380 case 212 /* PostfixUnaryExpression */:
17381 case 211 /* PrefixUnaryExpression */:
17382 var operator = parent.operator;
17383 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17384 case 213 /* BinaryExpression */:
17385 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17386 return left === node && isAssignmentOperator(operatorToken.kind) ?
17387 operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17388 : 0 /* Read */;
17389 case 198 /* PropertyAccessExpression */:
17390 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17391 case 285 /* PropertyAssignment */: {
17392 var parentAccess = accessKind(parent.parent);
17393 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17394 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17395 }
17396 case 286 /* ShorthandPropertyAssignment */:
17397 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17398 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17399 case 196 /* ArrayLiteralExpression */:
17400 return accessKind(parent);
17401 default:
17402 return 0 /* Read */;
17403 }
17404 function writeOrReadWrite() {
17405 // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17406 return parent.parent && skipParenthesesUp(parent.parent).kind === 230 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17407 }
17408 }
17409 function reverseAccessKind(a) {
17410 switch (a) {
17411 case 0 /* Read */:
17412 return 1 /* Write */;
17413 case 1 /* Write */:
17414 return 0 /* Read */;
17415 case 2 /* ReadWrite */:
17416 return 2 /* ReadWrite */;
17417 default:
17418 return ts.Debug.assertNever(a);
17419 }
17420 }
17421 function compareDataObjects(dst, src) {
17422 if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17423 return false;
17424 }
17425 for (var e in dst) {
17426 if (typeof dst[e] === "object") {
17427 if (!compareDataObjects(dst[e], src[e])) {
17428 return false;
17429 }
17430 }
17431 else if (typeof dst[e] !== "function") {
17432 if (dst[e] !== src[e]) {
17433 return false;
17434 }
17435 }
17436 }
17437 return true;
17438 }
17439 ts.compareDataObjects = compareDataObjects;
17440 /**
17441 * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17442 */
17443 function clearMap(map, onDeleteValue) {
17444 // Remove all
17445 map.forEach(onDeleteValue);
17446 map.clear();
17447 }
17448 ts.clearMap = clearMap;
17449 /**
17450 * Mutates the map with newMap such that keys in map will be same as newMap.
17451 */
17452 function mutateMapSkippingNewValues(map, newMap, options) {
17453 var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17454 // Needs update
17455 map.forEach(function (existingValue, key) {
17456 var valueInNewMap = newMap.get(key);
17457 // Not present any more in new map, remove it
17458 if (valueInNewMap === undefined) {
17459 map.delete(key);
17460 onDeleteValue(existingValue, key);
17461 }
17462 // If present notify about existing values
17463 else if (onExistingValue) {
17464 onExistingValue(existingValue, valueInNewMap, key);
17465 }
17466 });
17467 }
17468 ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17469 /**
17470 * Mutates the map with newMap such that keys in map will be same as newMap.
17471 */
17472 function mutateMap(map, newMap, options) {
17473 // Needs update
17474 mutateMapSkippingNewValues(map, newMap, options);
17475 var createNewValue = options.createNewValue;
17476 // Add new values that are not already present
17477 newMap.forEach(function (valueInNewMap, key) {
17478 if (!map.has(key)) {
17479 // New values
17480 map.set(key, createNewValue(key, valueInNewMap));
17481 }
17482 });
17483 }
17484 ts.mutateMap = mutateMap;
17485 // Return true if the given type is the constructor type for an abstract class
17486 function isAbstractConstructorType(type) {
17487 return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17488 }
17489 ts.isAbstractConstructorType = isAbstractConstructorType;
17490 function isAbstractConstructorSymbol(symbol) {
17491 if (symbol.flags & 32 /* Class */) {
17492 var declaration = getClassLikeDeclarationOfSymbol(symbol);
17493 return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
17494 }
17495 return false;
17496 }
17497 ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17498 function getClassLikeDeclarationOfSymbol(symbol) {
17499 return ts.find(symbol.declarations, ts.isClassLike);
17500 }
17501 ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17502 function getObjectFlags(type) {
17503 return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17504 }
17505 ts.getObjectFlags = getObjectFlags;
17506 function typeHasCallOrConstructSignatures(type, checker) {
17507 return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17508 }
17509 ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17510 function forSomeAncestorDirectory(directory, callback) {
17511 return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17512 }
17513 ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17514 function isUMDExportSymbol(symbol) {
17515 return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17516 }
17517 ts.isUMDExportSymbol = isUMDExportSymbol;
17518 function showModuleSpecifier(_a) {
17519 var moduleSpecifier = _a.moduleSpecifier;
17520 return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17521 }
17522 ts.showModuleSpecifier = showModuleSpecifier;
17523 function getLastChild(node) {
17524 var lastChild;
17525 ts.forEachChild(node, function (child) {
17526 if (nodeIsPresent(child))
17527 lastChild = child;
17528 }, function (children) {
17529 // As an optimization, jump straight to the end of the list.
17530 for (var i = children.length - 1; i >= 0; i--) {
17531 if (nodeIsPresent(children[i])) {
17532 lastChild = children[i];
17533 break;
17534 }
17535 }
17536 });
17537 return lastChild;
17538 }
17539 ts.getLastChild = getLastChild;
17540 function addToSeen(seen, key, value) {
17541 if (value === void 0) { value = true; }
17542 key = String(key);
17543 if (seen.has(key)) {
17544 return false;
17545 }
17546 seen.set(key, value);
17547 return true;
17548 }
17549 ts.addToSeen = addToSeen;
17550 function isObjectTypeDeclaration(node) {
17551 return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17552 }
17553 ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17554 function isTypeNodeKind(kind) {
17555 return (kind >= 171 /* FirstTypeNode */ && kind <= 192 /* LastTypeNode */)
17556 || kind === 128 /* AnyKeyword */
17557 || kind === 151 /* UnknownKeyword */
17558 || kind === 143 /* NumberKeyword */
17559 || kind === 154 /* BigIntKeyword */
17560 || kind === 144 /* ObjectKeyword */
17561 || kind === 131 /* BooleanKeyword */
17562 || kind === 146 /* StringKeyword */
17563 || kind === 147 /* SymbolKeyword */
17564 || kind === 113 /* VoidKeyword */
17565 || kind === 149 /* UndefinedKeyword */
17566 || kind === 140 /* NeverKeyword */
17567 || kind === 220 /* ExpressionWithTypeArguments */
17568 || kind === 299 /* JSDocAllType */
17569 || kind === 300 /* JSDocUnknownType */
17570 || kind === 301 /* JSDocNullableType */
17571 || kind === 302 /* JSDocNonNullableType */
17572 || kind === 303 /* JSDocOptionalType */
17573 || kind === 304 /* JSDocFunctionType */
17574 || kind === 305 /* JSDocVariadicType */;
17575 }
17576 ts.isTypeNodeKind = isTypeNodeKind;
17577 function isAccessExpression(node) {
17578 return node.kind === 198 /* PropertyAccessExpression */ || node.kind === 199 /* ElementAccessExpression */;
17579 }
17580 ts.isAccessExpression = isAccessExpression;
17581 function getNameOfAccessExpression(node) {
17582 if (node.kind === 198 /* PropertyAccessExpression */) {
17583 return node.name;
17584 }
17585 ts.Debug.assert(node.kind === 199 /* ElementAccessExpression */);
17586 return node.argumentExpression;
17587 }
17588 ts.getNameOfAccessExpression = getNameOfAccessExpression;
17589 function isBundleFileTextLike(section) {
17590 switch (section.kind) {
17591 case "text" /* Text */:
17592 case "internal" /* Internal */:
17593 return true;
17594 default:
17595 return false;
17596 }
17597 }
17598 ts.isBundleFileTextLike = isBundleFileTextLike;
17599 function isNamedImportsOrExports(node) {
17600 return node.kind === 261 /* NamedImports */ || node.kind === 265 /* NamedExports */;
17601 }
17602 ts.isNamedImportsOrExports = isNamedImportsOrExports;
17603 function getLeftmostExpression(node, stopAtCallExpressions) {
17604 while (true) {
17605 switch (node.kind) {
17606 case 212 /* PostfixUnaryExpression */:
17607 node = node.operand;
17608 continue;
17609 case 213 /* BinaryExpression */:
17610 node = node.left;
17611 continue;
17612 case 214 /* ConditionalExpression */:
17613 node = node.condition;
17614 continue;
17615 case 202 /* TaggedTemplateExpression */:
17616 node = node.tag;
17617 continue;
17618 case 200 /* CallExpression */:
17619 if (stopAtCallExpressions) {
17620 return node;
17621 }
17622 // falls through
17623 case 221 /* AsExpression */:
17624 case 199 /* ElementAccessExpression */:
17625 case 198 /* PropertyAccessExpression */:
17626 case 222 /* NonNullExpression */:
17627 case 331 /* PartiallyEmittedExpression */:
17628 node = node.expression;
17629 continue;
17630 }
17631 return node;
17632 }
17633 }
17634 ts.getLeftmostExpression = getLeftmostExpression;
17635 function Symbol(flags, name) {
17636 this.flags = flags;
17637 this.escapedName = name;
17638 this.declarations = undefined;
17639 this.valueDeclaration = undefined;
17640 this.id = undefined;
17641 this.mergeId = undefined;
17642 this.parent = undefined;
17643 }
17644 function Type(checker, flags) {
17645 this.flags = flags;
17646 if (ts.Debug.isDebugging) {
17647 this.checker = checker;
17648 }
17649 }
17650 function Signature(checker, flags) {
17651 this.flags = flags;
17652 if (ts.Debug.isDebugging) {
17653 this.checker = checker;
17654 }
17655 }
17656 function Node(kind, pos, end) {
17657 this.pos = pos;
17658 this.end = end;
17659 this.kind = kind;
17660 this.id = 0;
17661 this.flags = 0 /* None */;
17662 this.modifierFlagsCache = 0 /* None */;
17663 this.transformFlags = 0 /* None */;
17664 this.parent = undefined;
17665 this.original = undefined;
17666 }
17667 function Token(kind, pos, end) {
17668 this.pos = pos;
17669 this.end = end;
17670 this.kind = kind;
17671 this.id = 0;
17672 this.flags = 0 /* None */;
17673 this.transformFlags = 0 /* None */;
17674 this.parent = undefined;
17675 }
17676 function Identifier(kind, pos, end) {
17677 this.pos = pos;
17678 this.end = end;
17679 this.kind = kind;
17680 this.id = 0;
17681 this.flags = 0 /* None */;
17682 this.transformFlags = 0 /* None */;
17683 this.parent = undefined;
17684 this.original = undefined;
17685 this.flowNode = undefined;
17686 }
17687 function SourceMapSource(fileName, text, skipTrivia) {
17688 this.fileName = fileName;
17689 this.text = text;
17690 this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17691 }
17692 // eslint-disable-next-line prefer-const
17693 ts.objectAllocator = {
17694 getNodeConstructor: function () { return Node; },
17695 getTokenConstructor: function () { return Token; },
17696 getIdentifierConstructor: function () { return Identifier; },
17697 getPrivateIdentifierConstructor: function () { return Node; },
17698 getSourceFileConstructor: function () { return Node; },
17699 getSymbolConstructor: function () { return Symbol; },
17700 getTypeConstructor: function () { return Type; },
17701 getSignatureConstructor: function () { return Signature; },
17702 getSourceMapSourceConstructor: function () { return SourceMapSource; },
17703 };
17704 function setObjectAllocator(alloc) {
17705 ts.objectAllocator = alloc;
17706 }
17707 ts.setObjectAllocator = setObjectAllocator;
17708 function formatStringFromArgs(text, args, baseIndex) {
17709 if (baseIndex === void 0) { baseIndex = 0; }
17710 return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17711 }
17712 ts.formatStringFromArgs = formatStringFromArgs;
17713 /* @internal */
17714 function setLocalizedDiagnosticMessages(messages) {
17715 ts.localizedDiagnosticMessages = messages;
17716 }
17717 ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17718 function getLocaleSpecificMessage(message) {
17719 return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17720 }
17721 ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17722 function createDetachedDiagnostic(fileName, start, length, message) {
17723 ts.Debug.assertGreaterThanOrEqual(start, 0);
17724 ts.Debug.assertGreaterThanOrEqual(length, 0);
17725 var text = getLocaleSpecificMessage(message);
17726 if (arguments.length > 4) {
17727 text = formatStringFromArgs(text, arguments, 4);
17728 }
17729 return {
17730 file: undefined,
17731 start: start,
17732 length: length,
17733 messageText: text,
17734 category: message.category,
17735 code: message.code,
17736 reportsUnnecessary: message.reportsUnnecessary,
17737 fileName: fileName,
17738 };
17739 }
17740 ts.createDetachedDiagnostic = createDetachedDiagnostic;
17741 function isDiagnosticWithDetachedLocation(diagnostic) {
17742 return diagnostic.file === undefined
17743 && diagnostic.start !== undefined
17744 && diagnostic.length !== undefined
17745 && typeof diagnostic.fileName === "string";
17746 }
17747 function attachFileToDiagnostic(diagnostic, file) {
17748 var fileName = file.fileName || "";
17749 var length = file.text.length;
17750 ts.Debug.assertEqual(diagnostic.fileName, fileName);
17751 ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
17752 ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
17753 var diagnosticWithLocation = {
17754 file: file,
17755 start: diagnostic.start,
17756 length: diagnostic.length,
17757 messageText: diagnostic.messageText,
17758 category: diagnostic.category,
17759 code: diagnostic.code,
17760 reportsUnnecessary: diagnostic.reportsUnnecessary
17761 };
17762 if (diagnostic.relatedInformation) {
17763 diagnosticWithLocation.relatedInformation = [];
17764 for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
17765 var related = _a[_i];
17766 if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
17767 ts.Debug.assertLessThanOrEqual(related.start, length);
17768 ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
17769 diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
17770 }
17771 else {
17772 diagnosticWithLocation.relatedInformation.push(related);
17773 }
17774 }
17775 }
17776 return diagnosticWithLocation;
17777 }
17778 function attachFileToDiagnostics(diagnostics, file) {
17779 var diagnosticsWithLocation = [];
17780 for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
17781 var diagnostic = diagnostics_1[_i];
17782 diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
17783 }
17784 return diagnosticsWithLocation;
17785 }
17786 ts.attachFileToDiagnostics = attachFileToDiagnostics;
17787 function createFileDiagnostic(file, start, length, message) {
17788 ts.Debug.assertGreaterThanOrEqual(start, 0);
17789 ts.Debug.assertGreaterThanOrEqual(length, 0);
17790 if (file) {
17791 ts.Debug.assertLessThanOrEqual(start, file.text.length);
17792 ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17793 }
17794 var text = getLocaleSpecificMessage(message);
17795 if (arguments.length > 4) {
17796 text = formatStringFromArgs(text, arguments, 4);
17797 }
17798 return {
17799 file: file,
17800 start: start,
17801 length: length,
17802 messageText: text,
17803 category: message.category,
17804 code: message.code,
17805 reportsUnnecessary: message.reportsUnnecessary,
17806 reportsDeprecated: message.reportsDeprecated
17807 };
17808 }
17809 ts.createFileDiagnostic = createFileDiagnostic;
17810 function formatMessage(_dummy, message) {
17811 var text = getLocaleSpecificMessage(message);
17812 if (arguments.length > 2) {
17813 text = formatStringFromArgs(text, arguments, 2);
17814 }
17815 return text;
17816 }
17817 ts.formatMessage = formatMessage;
17818 function createCompilerDiagnostic(message) {
17819 var text = getLocaleSpecificMessage(message);
17820 if (arguments.length > 1) {
17821 text = formatStringFromArgs(text, arguments, 1);
17822 }
17823 return {
17824 file: undefined,
17825 start: undefined,
17826 length: undefined,
17827 messageText: text,
17828 category: message.category,
17829 code: message.code,
17830 reportsUnnecessary: message.reportsUnnecessary,
17831 reportsDeprecated: message.reportsDeprecated
17832 };
17833 }
17834 ts.createCompilerDiagnostic = createCompilerDiagnostic;
17835 function createCompilerDiagnosticFromMessageChain(chain) {
17836 return {
17837 file: undefined,
17838 start: undefined,
17839 length: undefined,
17840 code: chain.code,
17841 category: chain.category,
17842 messageText: chain.next ? chain : chain.messageText,
17843 };
17844 }
17845 ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17846 function chainDiagnosticMessages(details, message) {
17847 var text = getLocaleSpecificMessage(message);
17848 if (arguments.length > 2) {
17849 text = formatStringFromArgs(text, arguments, 2);
17850 }
17851 return {
17852 messageText: text,
17853 category: message.category,
17854 code: message.code,
17855 next: details === undefined || Array.isArray(details) ? details : [details]
17856 };
17857 }
17858 ts.chainDiagnosticMessages = chainDiagnosticMessages;
17859 function concatenateDiagnosticMessageChains(headChain, tailChain) {
17860 var lastChain = headChain;
17861 while (lastChain.next) {
17862 lastChain = lastChain.next[0];
17863 }
17864 lastChain.next = [tailChain];
17865 }
17866 ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17867 function getDiagnosticFilePath(diagnostic) {
17868 return diagnostic.file ? diagnostic.file.path : undefined;
17869 }
17870 function compareDiagnostics(d1, d2) {
17871 return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17872 compareRelatedInformation(d1, d2) ||
17873 0 /* EqualTo */;
17874 }
17875 ts.compareDiagnostics = compareDiagnostics;
17876 function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17877 return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17878 ts.compareValues(d1.start, d2.start) ||
17879 ts.compareValues(d1.length, d2.length) ||
17880 ts.compareValues(d1.code, d2.code) ||
17881 compareMessageText(d1.messageText, d2.messageText) ||
17882 0 /* EqualTo */;
17883 }
17884 ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17885 function compareRelatedInformation(d1, d2) {
17886 if (!d1.relatedInformation && !d2.relatedInformation) {
17887 return 0 /* EqualTo */;
17888 }
17889 if (d1.relatedInformation && d2.relatedInformation) {
17890 return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17891 var d2i = d2.relatedInformation[index];
17892 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17893 }) || 0 /* EqualTo */;
17894 }
17895 return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17896 }
17897 function compareMessageText(t1, t2) {
17898 if (typeof t1 === "string" && typeof t2 === "string") {
17899 return ts.compareStringsCaseSensitive(t1, t2);
17900 }
17901 else if (typeof t1 === "string") {
17902 return -1 /* LessThan */;
17903 }
17904 else if (typeof t2 === "string") {
17905 return 1 /* GreaterThan */;
17906 }
17907 var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17908 if (res) {
17909 return res;
17910 }
17911 if (!t1.next && !t2.next) {
17912 return 0 /* EqualTo */;
17913 }
17914 if (!t1.next) {
17915 return -1 /* LessThan */;
17916 }
17917 if (!t2.next) {
17918 return 1 /* GreaterThan */;
17919 }
17920 var len = Math.min(t1.next.length, t2.next.length);
17921 for (var i = 0; i < len; i++) {
17922 res = compareMessageText(t1.next[i], t2.next[i]);
17923 if (res) {
17924 return res;
17925 }
17926 }
17927 if (t1.next.length < t2.next.length) {
17928 return -1 /* LessThan */;
17929 }
17930 else if (t1.next.length > t2.next.length) {
17931 return 1 /* GreaterThan */;
17932 }
17933 return 0 /* EqualTo */;
17934 }
17935 function getLanguageVariant(scriptKind) {
17936 // .tsx and .jsx files are treated as jsx language variant.
17937 return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
17938 }
17939 ts.getLanguageVariant = getLanguageVariant;
17940 function getEmitScriptTarget(compilerOptions) {
17941 return compilerOptions.target || 0 /* ES3 */;
17942 }
17943 ts.getEmitScriptTarget = getEmitScriptTarget;
17944 function getEmitModuleKind(compilerOptions) {
17945 return typeof compilerOptions.module === "number" ?
17946 compilerOptions.module :
17947 getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17948 }
17949 ts.getEmitModuleKind = getEmitModuleKind;
17950 function getEmitModuleResolutionKind(compilerOptions) {
17951 var moduleResolution = compilerOptions.moduleResolution;
17952 if (moduleResolution === undefined) {
17953 moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17954 }
17955 return moduleResolution;
17956 }
17957 ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17958 function hasJsonModuleEmitEnabled(options) {
17959 switch (getEmitModuleKind(options)) {
17960 case ts.ModuleKind.CommonJS:
17961 case ts.ModuleKind.AMD:
17962 case ts.ModuleKind.ES2015:
17963 case ts.ModuleKind.ES2020:
17964 case ts.ModuleKind.ESNext:
17965 return true;
17966 default:
17967 return false;
17968 }
17969 }
17970 ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17971 function unreachableCodeIsError(options) {
17972 return options.allowUnreachableCode === false;
17973 }
17974 ts.unreachableCodeIsError = unreachableCodeIsError;
17975 function unusedLabelIsError(options) {
17976 return options.allowUnusedLabels === false;
17977 }
17978 ts.unusedLabelIsError = unusedLabelIsError;
17979 function getAreDeclarationMapsEnabled(options) {
17980 return !!(getEmitDeclarations(options) && options.declarationMap);
17981 }
17982 ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17983 function getAllowSyntheticDefaultImports(compilerOptions) {
17984 var moduleKind = getEmitModuleKind(compilerOptions);
17985 return compilerOptions.allowSyntheticDefaultImports !== undefined
17986 ? compilerOptions.allowSyntheticDefaultImports
17987 : compilerOptions.esModuleInterop ||
17988 moduleKind === ts.ModuleKind.System;
17989 }
17990 ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17991 function getEmitDeclarations(compilerOptions) {
17992 return !!(compilerOptions.declaration || compilerOptions.composite);
17993 }
17994 ts.getEmitDeclarations = getEmitDeclarations;
17995 function isIncrementalCompilation(options) {
17996 return !!(options.incremental || options.composite);
17997 }
17998 ts.isIncrementalCompilation = isIncrementalCompilation;
17999 function getStrictOptionValue(compilerOptions, flag) {
18000 return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
18001 }
18002 ts.getStrictOptionValue = getStrictOptionValue;
18003 function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
18004 return oldOptions !== newOptions &&
18005 ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18006 }
18007 ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
18008 function compilerOptionsAffectEmit(newOptions, oldOptions) {
18009 return oldOptions !== newOptions &&
18010 ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18011 }
18012 ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
18013 function getCompilerOptionValue(options, option) {
18014 return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
18015 }
18016 ts.getCompilerOptionValue = getCompilerOptionValue;
18017 function hasZeroOrOneAsteriskCharacter(str) {
18018 var seenAsterisk = false;
18019 for (var i = 0; i < str.length; i++) {
18020 if (str.charCodeAt(i) === 42 /* asterisk */) {
18021 if (!seenAsterisk) {
18022 seenAsterisk = true;
18023 }
18024 else {
18025 // have already seen asterisk
18026 return false;
18027 }
18028 }
18029 }
18030 return true;
18031 }
18032 ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
18033 function createSymlinkCache() {
18034 var symlinkedDirectories;
18035 var symlinkedFiles;
18036 return {
18037 getSymlinkedFiles: function () { return symlinkedFiles; },
18038 getSymlinkedDirectories: function () { return symlinkedDirectories; },
18039 setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
18040 setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); },
18041 };
18042 }
18043 ts.createSymlinkCache = createSymlinkCache;
18044 function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
18045 var cache = createSymlinkCache();
18046 var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
18047 return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
18048 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
18049 })));
18050 }));
18051 for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
18052 var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
18053 var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1];
18054 if (commonResolved && commonOriginal) {
18055 cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
18056 }
18057 }
18058 return cache;
18059 }
18060 ts.discoverProbableSymlinks = discoverProbableSymlinks;
18061 function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
18062 var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
18063 var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
18064 var isDirectory = false;
18065 while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
18066 !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
18067 getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
18068 aParts.pop();
18069 bParts.pop();
18070 isDirectory = true;
18071 }
18072 return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
18073 }
18074 // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
18075 // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
18076 function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
18077 return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
18078 }
18079 function stripLeadingDirectorySeparator(s) {
18080 return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
18081 }
18082 function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
18083 var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
18084 return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
18085 }
18086 ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
18087 // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
18088 // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
18089 // proof.
18090 var reservedCharacterPattern = /[^\w\s\/]/g;
18091 function regExpEscape(text) {
18092 return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
18093 }
18094 ts.regExpEscape = regExpEscape;
18095 function escapeRegExpCharacter(match) {
18096 return "\\" + match;
18097 }
18098 var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18099 ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18100 var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18101 var filesMatcher = {
18102 /**
18103 * Matches any single directory segment unless it is the last segment and a .min.js file
18104 * Breakdown:
18105 * [^./] # matches everything up to the first . character (excluding directory separators)
18106 * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
18107 */
18108 singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18109 /**
18110 * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18111 * files or directories, does not match subdirectories that start with a . character
18112 */
18113 doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18114 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18115 };
18116 var directoriesMatcher = {
18117 singleAsteriskRegexFragment: "[^/]*",
18118 /**
18119 * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18120 * files or directories, does not match subdirectories that start with a . character
18121 */
18122 doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18123 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18124 };
18125 var excludeMatcher = {
18126 singleAsteriskRegexFragment: "[^/]*",
18127 doubleAsteriskRegexFragment: "(/.+?)?",
18128 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18129 };
18130 var wildcardMatchers = {
18131 files: filesMatcher,
18132 directories: directoriesMatcher,
18133 exclude: excludeMatcher
18134 };
18135 function getRegularExpressionForWildcard(specs, basePath, usage) {
18136 var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18137 if (!patterns || !patterns.length) {
18138 return undefined;
18139 }
18140 var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18141 // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18142 var terminator = usage === "exclude" ? "($|/)" : "$";
18143 return "^(" + pattern + ")" + terminator;
18144 }
18145 ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18146 function getRegularExpressionsForWildcards(specs, basePath, usage) {
18147 if (specs === undefined || specs.length === 0) {
18148 return undefined;
18149 }
18150 return ts.flatMap(specs, function (spec) {
18151 return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18152 });
18153 }
18154 ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18155 /**
18156 * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18157 * and does not contain any glob characters itself.
18158 */
18159 function isImplicitGlob(lastPathComponent) {
18160 return !/[.*?]/.test(lastPathComponent);
18161 }
18162 ts.isImplicitGlob = isImplicitGlob;
18163 function getSubPatternFromSpec(spec, basePath, usage, _a) {
18164 var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18165 var subpattern = "";
18166 var hasWrittenComponent = false;
18167 var components = ts.getNormalizedPathComponents(spec, basePath);
18168 var lastComponent = ts.last(components);
18169 if (usage !== "exclude" && lastComponent === "**") {
18170 return undefined;
18171 }
18172 // getNormalizedPathComponents includes the separator for the root component.
18173 // We need to remove to create our regex correctly.
18174 components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18175 if (isImplicitGlob(lastComponent)) {
18176 components.push("**", "*");
18177 }
18178 var optionalCount = 0;
18179 for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18180 var component = components_1[_i];
18181 if (component === "**") {
18182 subpattern += doubleAsteriskRegexFragment;
18183 }
18184 else {
18185 if (usage === "directories") {
18186 subpattern += "(";
18187 optionalCount++;
18188 }
18189 if (hasWrittenComponent) {
18190 subpattern += ts.directorySeparator;
18191 }
18192 if (usage !== "exclude") {
18193 var componentPattern = "";
18194 // The * and ? wildcards should not match directories or files that start with . if they
18195 // appear first in a component. Dotted directories and files can be included explicitly
18196 // like so: **/.*/.*
18197 if (component.charCodeAt(0) === 42 /* asterisk */) {
18198 componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18199 component = component.substr(1);
18200 }
18201 else if (component.charCodeAt(0) === 63 /* question */) {
18202 componentPattern += "[^./]";
18203 component = component.substr(1);
18204 }
18205 componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18206 // Patterns should not include subfolders like node_modules unless they are
18207 // explicitly included as part of the path.
18208 //
18209 // As an optimization, if the component pattern is the same as the component,
18210 // then there definitely were no wildcard characters and we do not need to
18211 // add the exclusion pattern.
18212 if (componentPattern !== component) {
18213 subpattern += implicitExcludePathRegexPattern;
18214 }
18215 subpattern += componentPattern;
18216 }
18217 else {
18218 subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18219 }
18220 }
18221 hasWrittenComponent = true;
18222 }
18223 while (optionalCount > 0) {
18224 subpattern += ")?";
18225 optionalCount--;
18226 }
18227 return subpattern;
18228 }
18229 function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18230 return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18231 }
18232 /** @param path directory of the tsconfig.json */
18233 function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18234 path = ts.normalizePath(path);
18235 currentDirectory = ts.normalizePath(currentDirectory);
18236 var absolutePath = ts.combinePaths(currentDirectory, path);
18237 return {
18238 includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18239 includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18240 includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18241 excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18242 basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18243 };
18244 }
18245 ts.getFileMatcherPatterns = getFileMatcherPatterns;
18246 function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18247 return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18248 }
18249 ts.getRegexFromPattern = getRegexFromPattern;
18250 /** @param path directory of the tsconfig.json */
18251 function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18252 path = ts.normalizePath(path);
18253 currentDirectory = ts.normalizePath(currentDirectory);
18254 var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18255 var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18256 var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18257 var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18258 // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18259 // If there are no "includes", then just put everything in results[0].
18260 var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18261 var visited = new ts.Map();
18262 var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18263 for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18264 var basePath = _a[_i];
18265 visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18266 }
18267 return ts.flatten(results);
18268 function visitDirectory(path, absolutePath, depth) {
18269 var canonicalPath = toCanonical(realpath(absolutePath));
18270 if (visited.has(canonicalPath))
18271 return;
18272 visited.set(canonicalPath, true);
18273 var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18274 var _loop_1 = function (current) {
18275 var name = ts.combinePaths(path, current);
18276 var absoluteName = ts.combinePaths(absolutePath, current);
18277 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18278 return "continue";
18279 if (excludeRegex && excludeRegex.test(absoluteName))
18280 return "continue";
18281 if (!includeFileRegexes) {
18282 results[0].push(name);
18283 }
18284 else {
18285 var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18286 if (includeIndex !== -1) {
18287 results[includeIndex].push(name);
18288 }
18289 }
18290 };
18291 for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18292 var current = _b[_i];
18293 _loop_1(current);
18294 }
18295 if (depth !== undefined) {
18296 depth--;
18297 if (depth === 0) {
18298 return;
18299 }
18300 }
18301 for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18302 var current = _d[_c];
18303 var name = ts.combinePaths(path, current);
18304 var absoluteName = ts.combinePaths(absolutePath, current);
18305 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18306 (!excludeRegex || !excludeRegex.test(absoluteName))) {
18307 visitDirectory(name, absoluteName, depth);
18308 }
18309 }
18310 }
18311 }
18312 ts.matchFiles = matchFiles;
18313 /**
18314 * Computes the unique non-wildcard base paths amongst the provided include patterns.
18315 */
18316 function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18317 // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18318 var basePaths = [path];
18319 if (includes) {
18320 // Storage for literal base paths amongst the include patterns.
18321 var includeBasePaths = [];
18322 for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18323 var include = includes_1[_i];
18324 // We also need to check the relative paths by converting them to absolute and normalizing
18325 // in case they escape the base path (e.g "..\somedirectory")
18326 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18327 // Append the literal and canonical candidate base paths.
18328 includeBasePaths.push(getIncludeBasePath(absolute));
18329 }
18330 // Sort the offsets array using either the literal or canonical path representations.
18331 includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18332 var _loop_2 = function (includeBasePath) {
18333 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18334 basePaths.push(includeBasePath);
18335 }
18336 };
18337 // Iterate over each include base path and include unique base paths that are not a
18338 // subpath of an existing base path
18339 for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18340 var includeBasePath = includeBasePaths_1[_a];
18341 _loop_2(includeBasePath);
18342 }
18343 }
18344 return basePaths;
18345 }
18346 function getIncludeBasePath(absolute) {
18347 var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18348 if (wildcardOffset < 0) {
18349 // No "*" or "?" in the path
18350 return !ts.hasExtension(absolute)
18351 ? absolute
18352 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18353 }
18354 return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18355 }
18356 function ensureScriptKind(fileName, scriptKind) {
18357 // Using scriptKind as a condition handles both:
18358 // - 'scriptKind' is unspecified and thus it is `undefined`
18359 // - 'scriptKind' is set and it is `Unknown` (0)
18360 // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18361 // to get the ScriptKind from the file name. If it cannot be resolved
18362 // from the file name then the default 'TS' script kind is returned.
18363 return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18364 }
18365 ts.ensureScriptKind = ensureScriptKind;
18366 function getScriptKindFromFileName(fileName) {
18367 var ext = fileName.substr(fileName.lastIndexOf("."));
18368 switch (ext.toLowerCase()) {
18369 case ".js" /* Js */:
18370 return 1 /* JS */;
18371 case ".jsx" /* Jsx */:
18372 return 2 /* JSX */;
18373 case ".ts" /* Ts */:
18374 return 3 /* TS */;
18375 case ".tsx" /* Tsx */:
18376 return 4 /* TSX */;
18377 case ".json" /* Json */:
18378 return 6 /* JSON */;
18379 default:
18380 return 0 /* Unknown */;
18381 }
18382 }
18383 ts.getScriptKindFromFileName = getScriptKindFromFileName;
18384 /**
18385 * List of supported extensions in order of file resolution precedence.
18386 */
18387 ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18388 ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18389 /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18390 ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18391 ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18392 ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18393 var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18394 var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18395 function getSupportedExtensions(options, extraFileExtensions) {
18396 var needJsExtensions = options && options.allowJs;
18397 if (!extraFileExtensions || extraFileExtensions.length === 0) {
18398 return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18399 }
18400 var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18401 return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18402 }
18403 ts.getSupportedExtensions = getSupportedExtensions;
18404 function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18405 if (!options || !options.resolveJsonModule) {
18406 return supportedExtensions;
18407 }
18408 if (supportedExtensions === allSupportedExtensions) {
18409 return allSupportedExtensionsWithJson;
18410 }
18411 if (supportedExtensions === ts.supportedTSExtensions) {
18412 return ts.supportedTSExtensionsWithJson;
18413 }
18414 return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18415 }
18416 ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18417 function isJSLike(scriptKind) {
18418 return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18419 }
18420 function hasJSFileExtension(fileName) {
18421 return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18422 }
18423 ts.hasJSFileExtension = hasJSFileExtension;
18424 function hasTSFileExtension(fileName) {
18425 return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18426 }
18427 ts.hasTSFileExtension = hasTSFileExtension;
18428 function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18429 if (!fileName) {
18430 return false;
18431 }
18432 var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18433 for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18434 var extension = _a[_i];
18435 if (ts.fileExtensionIs(fileName, extension)) {
18436 return true;
18437 }
18438 }
18439 return false;
18440 }
18441 ts.isSupportedSourceFileName = isSupportedSourceFileName;
18442 /**
18443 * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18444 * aligned to the offset of the highest priority extension in the
18445 * allSupportedExtensions array.
18446 */
18447 var ExtensionPriority;
18448 (function (ExtensionPriority) {
18449 ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18450 ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18451 ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18452 ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18453 })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18454 function getExtensionPriority(path, supportedExtensions) {
18455 for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18456 if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18457 return adjustExtensionPriority(i, supportedExtensions);
18458 }
18459 }
18460 // If its not in the list of supported extensions, this is likely a
18461 // TypeScript file with a non-ts extension
18462 return 0 /* Highest */;
18463 }
18464 ts.getExtensionPriority = getExtensionPriority;
18465 /**
18466 * Adjusts an extension priority to be the highest priority within the same range.
18467 */
18468 function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18469 if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18470 return 0 /* TypeScriptFiles */;
18471 }
18472 else if (extensionPriority < supportedExtensions.length) {
18473 return 2 /* DeclarationAndJavaScriptFiles */;
18474 }
18475 else {
18476 return supportedExtensions.length;
18477 }
18478 }
18479 ts.adjustExtensionPriority = adjustExtensionPriority;
18480 /**
18481 * Gets the next lowest extension priority for a given priority.
18482 */
18483 function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18484 if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18485 return 2 /* DeclarationAndJavaScriptFiles */;
18486 }
18487 else {
18488 return supportedExtensions.length;
18489 }
18490 }
18491 ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18492 var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18493 function removeFileExtension(path) {
18494 for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18495 var ext = extensionsToRemove_1[_i];
18496 var extensionless = tryRemoveExtension(path, ext);
18497 if (extensionless !== undefined) {
18498 return extensionless;
18499 }
18500 }
18501 return path;
18502 }
18503 ts.removeFileExtension = removeFileExtension;
18504 function tryRemoveExtension(path, extension) {
18505 return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18506 }
18507 ts.tryRemoveExtension = tryRemoveExtension;
18508 function removeExtension(path, extension) {
18509 return path.substring(0, path.length - extension.length);
18510 }
18511 ts.removeExtension = removeExtension;
18512 function changeExtension(path, newExtension) {
18513 return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18514 }
18515 ts.changeExtension = changeExtension;
18516 function tryParsePattern(pattern) {
18517 // This should be verified outside of here and a proper error thrown.
18518 ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18519 var indexOfStar = pattern.indexOf("*");
18520 return indexOfStar === -1 ? undefined : {
18521 prefix: pattern.substr(0, indexOfStar),
18522 suffix: pattern.substr(indexOfStar + 1)
18523 };
18524 }
18525 ts.tryParsePattern = tryParsePattern;
18526 function positionIsSynthesized(pos) {
18527 // This is a fast way of testing the following conditions:
18528 // pos === undefined || pos === null || isNaN(pos) || pos < 0;
18529 return !(pos >= 0);
18530 }
18531 ts.positionIsSynthesized = positionIsSynthesized;
18532 /** True if an extension is one of the supported TypeScript extensions. */
18533 function extensionIsTS(ext) {
18534 return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18535 }
18536 ts.extensionIsTS = extensionIsTS;
18537 function resolutionExtensionIsTSOrJson(ext) {
18538 return extensionIsTS(ext) || ext === ".json" /* Json */;
18539 }
18540 ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18541 /**
18542 * Gets the extension from a path.
18543 * Path must have a valid extension.
18544 */
18545 function extensionFromPath(path) {
18546 var ext = tryGetExtensionFromPath(path);
18547 return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18548 }
18549 ts.extensionFromPath = extensionFromPath;
18550 function isAnySupportedFileExtension(path) {
18551 return tryGetExtensionFromPath(path) !== undefined;
18552 }
18553 ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18554 function tryGetExtensionFromPath(path) {
18555 return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18556 }
18557 ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18558 function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18559 return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18560 }
18561 ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18562 ts.emptyFileSystemEntries = {
18563 files: ts.emptyArray,
18564 directories: ts.emptyArray
18565 };
18566 /**
18567 * patternStrings contains both pattern strings (containing "*") and regular strings.
18568 * Return an exact match if possible, or a pattern match, or undefined.
18569 * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18570 */
18571 function matchPatternOrExact(patternStrings, candidate) {
18572 var patterns = [];
18573 for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18574 var patternString = patternStrings_1[_i];
18575 if (!hasZeroOrOneAsteriskCharacter(patternString))
18576 continue;
18577 var pattern = tryParsePattern(patternString);
18578 if (pattern) {
18579 patterns.push(pattern);
18580 }
18581 else if (patternString === candidate) {
18582 // pattern was matched as is - no need to search further
18583 return patternString;
18584 }
18585 }
18586 return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18587 }
18588 ts.matchPatternOrExact = matchPatternOrExact;
18589 function sliceAfter(arr, value) {
18590 var index = arr.indexOf(value);
18591 ts.Debug.assert(index !== -1);
18592 return arr.slice(index);
18593 }
18594 ts.sliceAfter = sliceAfter;
18595 function addRelatedInfo(diagnostic) {
18596 var _a;
18597 var relatedInformation = [];
18598 for (var _i = 1; _i < arguments.length; _i++) {
18599 relatedInformation[_i - 1] = arguments[_i];
18600 }
18601 if (!relatedInformation.length) {
18602 return diagnostic;
18603 }
18604 if (!diagnostic.relatedInformation) {
18605 diagnostic.relatedInformation = [];
18606 }
18607 (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18608 return diagnostic;
18609 }
18610 ts.addRelatedInfo = addRelatedInfo;
18611 function minAndMax(arr, getValue) {
18612 ts.Debug.assert(arr.length !== 0);
18613 var min = getValue(arr[0]);
18614 var max = min;
18615 for (var i = 1; i < arr.length; i++) {
18616 var value = getValue(arr[i]);
18617 if (value < min) {
18618 min = value;
18619 }
18620 else if (value > max) {
18621 max = value;
18622 }
18623 }
18624 return { min: min, max: max };
18625 }
18626 ts.minAndMax = minAndMax;
18627 function rangeOfNode(node) {
18628 return { pos: getTokenPosOfNode(node), end: node.end };
18629 }
18630 ts.rangeOfNode = rangeOfNode;
18631 function rangeOfTypeParameters(typeParameters) {
18632 // Include the `<>`
18633 return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18634 }
18635 ts.rangeOfTypeParameters = rangeOfTypeParameters;
18636 function skipTypeChecking(sourceFile, options, host) {
18637 // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18638 // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18639 // '/// <reference no-default-lib="true"/>' directive.
18640 return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18641 options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18642 host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18643 }
18644 ts.skipTypeChecking = skipTypeChecking;
18645 function isJsonEqual(a, b) {
18646 // eslint-disable-next-line no-null/no-null
18647 return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18648 }
18649 ts.isJsonEqual = isJsonEqual;
18650 /**
18651 * Converts a bigint literal string, e.g. `0x1234n`,
18652 * to its decimal string representation, e.g. `4660`.
18653 */
18654 function parsePseudoBigInt(stringValue) {
18655 var log2Base;
18656 switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18657 case 98 /* b */:
18658 case 66 /* B */: // 0b or 0B
18659 log2Base = 1;
18660 break;
18661 case 111 /* o */:
18662 case 79 /* O */: // 0o or 0O
18663 log2Base = 3;
18664 break;
18665 case 120 /* x */:
18666 case 88 /* X */: // 0x or 0X
18667 log2Base = 4;
18668 break;
18669 default: // already in decimal; omit trailing "n"
18670 var nIndex = stringValue.length - 1;
18671 // Skip leading 0s
18672 var nonZeroStart = 0;
18673 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18674 nonZeroStart++;
18675 }
18676 return stringValue.slice(nonZeroStart, nIndex) || "0";
18677 }
18678 // Omit leading "0b", "0o", or "0x", and trailing "n"
18679 var startIndex = 2, endIndex = stringValue.length - 1;
18680 var bitsNeeded = (endIndex - startIndex) * log2Base;
18681 // Stores the value specified by the string as a LE array of 16-bit integers
18682 // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18683 var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18684 // Add the digits, one at a time
18685 for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18686 var segment = bitOffset >>> 4;
18687 var digitChar = stringValue.charCodeAt(i);
18688 // Find character range: 0-9 < A-F < a-f
18689 var digit = digitChar <= 57 /* _9 */
18690 ? digitChar - 48 /* _0 */
18691 : 10 + digitChar -
18692 (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18693 var shiftedDigit = digit << (bitOffset & 15);
18694 segments[segment] |= shiftedDigit;
18695 var residual = shiftedDigit >>> 16;
18696 if (residual)
18697 segments[segment + 1] |= residual; // overflows segment
18698 }
18699 // Repeatedly divide segments by 10 and add remainder to base10Value
18700 var base10Value = "";
18701 var firstNonzeroSegment = segments.length - 1;
18702 var segmentsRemaining = true;
18703 while (segmentsRemaining) {
18704 var mod10 = 0;
18705 segmentsRemaining = false;
18706 for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18707 var newSegment = mod10 << 16 | segments[segment];
18708 var segmentValue = (newSegment / 10) | 0;
18709 segments[segment] = segmentValue;
18710 mod10 = newSegment - segmentValue * 10;
18711 if (segmentValue && !segmentsRemaining) {
18712 firstNonzeroSegment = segment;
18713 segmentsRemaining = true;
18714 }
18715 }
18716 base10Value = mod10 + base10Value;
18717 }
18718 return base10Value;
18719 }
18720 ts.parsePseudoBigInt = parsePseudoBigInt;
18721 function pseudoBigIntToString(_a) {
18722 var negative = _a.negative, base10Value = _a.base10Value;
18723 return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18724 }
18725 ts.pseudoBigIntToString = pseudoBigIntToString;
18726 function isValidTypeOnlyAliasUseSite(useSite) {
18727 return !!(useSite.flags & 8388608 /* Ambient */)
18728 || isPartOfTypeQuery(useSite)
18729 || isIdentifierInNonEmittingHeritageClause(useSite)
18730 || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18731 || !isExpressionNode(useSite);
18732 }
18733 ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18734 function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18735 return typeOnlyDeclaration.kind === 267 /* ExportSpecifier */;
18736 }
18737 ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18738 function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18739 while (node.kind === 78 /* Identifier */ || node.kind === 198 /* PropertyAccessExpression */) {
18740 node = node.parent;
18741 }
18742 if (node.kind !== 157 /* ComputedPropertyName */) {
18743 return false;
18744 }
18745 if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
18746 return true;
18747 }
18748 var containerKind = node.parent.parent.kind;
18749 return containerKind === 250 /* InterfaceDeclaration */ || containerKind === 176 /* TypeLiteral */;
18750 }
18751 /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18752 function isIdentifierInNonEmittingHeritageClause(node) {
18753 if (node.kind !== 78 /* Identifier */)
18754 return false;
18755 var heritageClause = findAncestor(node.parent, function (parent) {
18756 switch (parent.kind) {
18757 case 283 /* HeritageClause */:
18758 return true;
18759 case 198 /* PropertyAccessExpression */:
18760 case 220 /* ExpressionWithTypeArguments */:
18761 return false;
18762 default:
18763 return "quit";
18764 }
18765 });
18766 return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 250 /* InterfaceDeclaration */;
18767 }
18768 function isIdentifierTypeReference(node) {
18769 return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18770 }
18771 ts.isIdentifierTypeReference = isIdentifierTypeReference;
18772 function arrayIsHomogeneous(array, comparer) {
18773 if (comparer === void 0) { comparer = ts.equateValues; }
18774 if (array.length < 2)
18775 return true;
18776 var first = array[0];
18777 for (var i = 1, length_1 = array.length; i < length_1; i++) {
18778 var target = array[i];
18779 if (!comparer(first, target))
18780 return false;
18781 }
18782 return true;
18783 }
18784 ts.arrayIsHomogeneous = arrayIsHomogeneous;
18785 /**
18786 * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
18787 */
18788 /* @internal */
18789 function setTextRangePos(range, pos) {
18790 range.pos = pos;
18791 return range;
18792 }
18793 ts.setTextRangePos = setTextRangePos;
18794 /**
18795 * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
18796 */
18797 /* @internal */
18798 function setTextRangeEnd(range, end) {
18799 range.end = end;
18800 return range;
18801 }
18802 ts.setTextRangeEnd = setTextRangeEnd;
18803 /**
18804 * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
18805 */
18806 /* @internal */
18807 function setTextRangePosEnd(range, pos, end) {
18808 return setTextRangeEnd(setTextRangePos(range, pos), end);
18809 }
18810 ts.setTextRangePosEnd = setTextRangePosEnd;
18811 /**
18812 * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
18813 * provided position and width.
18814 */
18815 /* @internal */
18816 function setTextRangePosWidth(range, pos, width) {
18817 return setTextRangePosEnd(range, pos, pos + width);
18818 }
18819 ts.setTextRangePosWidth = setTextRangePosWidth;
18820 function setNodeFlags(node, newFlags) {
18821 if (node) {
18822 node.flags = newFlags;
18823 }
18824 return node;
18825 }
18826 ts.setNodeFlags = setNodeFlags;
18827 function setParent(child, parent) {
18828 if (child && parent) {
18829 child.parent = parent;
18830 }
18831 return child;
18832 }
18833 ts.setParent = setParent;
18834 function setEachParent(children, parent) {
18835 if (children) {
18836 for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
18837 var child = children_1[_i];
18838 setParent(child, parent);
18839 }
18840 }
18841 return children;
18842 }
18843 ts.setEachParent = setEachParent;
18844 function setParentRecursive(rootNode, incremental) {
18845 if (!rootNode)
18846 return rootNode;
18847 ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
18848 return rootNode;
18849 function bindParentToChildIgnoringJSDoc(child, parent) {
18850 if (incremental && child.parent === parent) {
18851 return "skip";
18852 }
18853 setParent(child, parent);
18854 }
18855 function bindJSDoc(child) {
18856 if (ts.hasJSDocNodes(child)) {
18857 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
18858 var doc = _a[_i];
18859 bindParentToChildIgnoringJSDoc(doc, child);
18860 ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
18861 }
18862 }
18863 }
18864 function bindParentToChild(child, parent) {
18865 return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
18866 }
18867 }
18868 ts.setParentRecursive = setParentRecursive;
18869})(ts || (ts = {}));
18870/* @internal */
18871var ts;
18872(function (ts) {
18873 /**
18874 * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
18875 */
18876 function createBaseNodeFactory() {
18877 // tslint:disable variable-name
18878 var NodeConstructor;
18879 var TokenConstructor;
18880 var IdentifierConstructor;
18881 var PrivateIdentifierConstructor;
18882 var SourceFileConstructor;
18883 // tslint:enable variable-name
18884 return {
18885 createBaseSourceFileNode: createBaseSourceFileNode,
18886 createBaseIdentifierNode: createBaseIdentifierNode,
18887 createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
18888 createBaseTokenNode: createBaseTokenNode,
18889 createBaseNode: createBaseNode
18890 };
18891 function createBaseSourceFileNode(kind) {
18892 return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
18893 }
18894 function createBaseIdentifierNode(kind) {
18895 return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
18896 }
18897 function createBasePrivateIdentifierNode(kind) {
18898 return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
18899 }
18900 function createBaseTokenNode(kind) {
18901 return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
18902 }
18903 function createBaseNode(kind) {
18904 return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
18905 }
18906 }
18907 ts.createBaseNodeFactory = createBaseNodeFactory;
18908})(ts || (ts = {}));
18909/* @internal */
18910var ts;
18911(function (ts) {
18912 function createParenthesizerRules(factory) {
18913 return {
18914 parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
18915 parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
18916 parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
18917 parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
18918 parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
18919 parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
18920 parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
18921 parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
18922 parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
18923 parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
18924 parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
18925 parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
18926 parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
18927 parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
18928 parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
18929 parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
18930 parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
18931 parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
18932 parenthesizeTypeArguments: parenthesizeTypeArguments,
18933 };
18934 /**
18935 * Determines whether the operand to a BinaryExpression needs to be parenthesized.
18936 *
18937 * @param binaryOperator The operator for the BinaryExpression.
18938 * @param operand The operand for the BinaryExpression.
18939 * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
18940 * BinaryExpression.
18941 */
18942 function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
18943 // If the operand has lower precedence, then it needs to be parenthesized to preserve the
18944 // intent of the expression. For example, if the operand is `a + b` and the operator is
18945 // `*`, then we need to parenthesize the operand to preserve the intended order of
18946 // operations: `(a + b) * x`.
18947 //
18948 // If the operand has higher precedence, then it does not need to be parenthesized. For
18949 // example, if the operand is `a * b` and the operator is `+`, then we do not need to
18950 // parenthesize to preserve the intended order of operations: `a * b + x`.
18951 //
18952 // If the operand has the same precedence, then we need to check the associativity of
18953 // the operator based on whether this is the left or right operand of the expression.
18954 //
18955 // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
18956 // to preserve the intended order of operations: `x * (a / d)`
18957 //
18958 // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
18959 // the intended order of operations: `(a ** b) ** c`
18960 var binaryOperatorPrecedence = ts.getOperatorPrecedence(213 /* BinaryExpression */, binaryOperator);
18961 var binaryOperatorAssociativity = ts.getOperatorAssociativity(213 /* BinaryExpression */, binaryOperator);
18962 var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
18963 if (!isLeftSideOfBinary && operand.kind === 206 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
18964 // We need to parenthesize arrow functions on the right side to avoid it being
18965 // parsed as parenthesized expression: `a && (() => {})`
18966 return true;
18967 }
18968 var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
18969 switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
18970 case -1 /* LessThan */:
18971 // If the operand is the right side of a right-associative binary operation
18972 // and is a yield expression, then we do not need parentheses.
18973 if (!isLeftSideOfBinary
18974 && binaryOperatorAssociativity === 1 /* Right */
18975 && operand.kind === 216 /* YieldExpression */) {
18976 return false;
18977 }
18978 return true;
18979 case 1 /* GreaterThan */:
18980 return false;
18981 case 0 /* EqualTo */:
18982 if (isLeftSideOfBinary) {
18983 // No need to parenthesize the left operand when the binary operator is
18984 // left associative:
18985 // (a*b)/x -> a*b/x
18986 // (a**b)/x -> a**b/x
18987 //
18988 // Parentheses are needed for the left operand when the binary operator is
18989 // right associative:
18990 // (a/b)**x -> (a/b)**x
18991 // (a**b)**x -> (a**b)**x
18992 return binaryOperatorAssociativity === 1 /* Right */;
18993 }
18994 else {
18995 if (ts.isBinaryExpression(emittedOperand)
18996 && emittedOperand.operatorToken.kind === binaryOperator) {
18997 // No need to parenthesize the right operand when the binary operator and
18998 // operand are the same and one of the following:
18999 // x*(a*b) => x*a*b
19000 // x|(a|b) => x|a|b
19001 // x&(a&b) => x&a&b
19002 // x^(a^b) => x^a^b
19003 if (operatorHasAssociativeProperty(binaryOperator)) {
19004 return false;
19005 }
19006 // No need to parenthesize the right operand when the binary operator
19007 // is plus (+) if both the left and right operands consist solely of either
19008 // literals of the same kind or binary plus (+) expressions for literals of
19009 // the same kind (recursively).
19010 // "a"+(1+2) => "a"+(1+2)
19011 // "a"+("b"+"c") => "a"+"b"+"c"
19012 if (binaryOperator === 39 /* PlusToken */) {
19013 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
19014 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
19015 return false;
19016 }
19017 }
19018 }
19019 // No need to parenthesize the right operand when the operand is right
19020 // associative:
19021 // x/(a**b) -> x/a**b
19022 // x**(a**b) -> x**a**b
19023 //
19024 // Parentheses are needed for the right operand when the operand is left
19025 // associative:
19026 // x/(a*b) -> x/(a*b)
19027 // x**(a/b) -> x**(a/b)
19028 var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
19029 return operandAssociativity === 0 /* Left */;
19030 }
19031 }
19032 }
19033 /**
19034 * Determines whether a binary operator is mathematically associative.
19035 *
19036 * @param binaryOperator The binary operator.
19037 */
19038 function operatorHasAssociativeProperty(binaryOperator) {
19039 // The following operators are associative in JavaScript:
19040 // (a*b)*c -> a*(b*c) -> a*b*c
19041 // (a|b)|c -> a|(b|c) -> a|b|c
19042 // (a&b)&c -> a&(b&c) -> a&b&c
19043 // (a^b)^c -> a^(b^c) -> a^b^c
19044 //
19045 // While addition is associative in mathematics, JavaScript's `+` is not
19046 // guaranteed to be associative as it is overloaded with string concatenation.
19047 return binaryOperator === 41 /* AsteriskToken */
19048 || binaryOperator === 51 /* BarToken */
19049 || binaryOperator === 50 /* AmpersandToken */
19050 || binaryOperator === 52 /* CaretToken */;
19051 }
19052 /**
19053 * This function determines whether an expression consists of a homogeneous set of
19054 * literal expressions or binary plus expressions that all share the same literal kind.
19055 * It is used to determine whether the right-hand operand of a binary plus expression can be
19056 * emitted without parentheses.
19057 */
19058 function getLiteralKindOfBinaryPlusOperand(node) {
19059 node = ts.skipPartiallyEmittedExpressions(node);
19060 if (ts.isLiteralKind(node.kind)) {
19061 return node.kind;
19062 }
19063 if (node.kind === 213 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
19064 if (node.cachedLiteralKind !== undefined) {
19065 return node.cachedLiteralKind;
19066 }
19067 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
19068 var literalKind = ts.isLiteralKind(leftKind)
19069 && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
19070 ? leftKind
19071 : 0 /* Unknown */;
19072 node.cachedLiteralKind = literalKind;
19073 return literalKind;
19074 }
19075 return 0 /* Unknown */;
19076 }
19077 /**
19078 * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
19079 * order of operations.
19080 *
19081 * @param binaryOperator The operator for the BinaryExpression.
19082 * @param operand The operand for the BinaryExpression.
19083 * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19084 * BinaryExpression.
19085 */
19086 function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19087 var skipped = ts.skipPartiallyEmittedExpressions(operand);
19088 // If the resulting expression is already parenthesized, we do not need to do any further processing.
19089 if (skipped.kind === 204 /* ParenthesizedExpression */) {
19090 return operand;
19091 }
19092 return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
19093 ? factory.createParenthesizedExpression(operand)
19094 : operand;
19095 }
19096 function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
19097 return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
19098 }
19099 function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
19100 return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
19101 }
19102 function parenthesizeExpressionOfComputedPropertyName(expression) {
19103 return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
19104 }
19105 function parenthesizeConditionOfConditionalExpression(condition) {
19106 var conditionalPrecedence = ts.getOperatorPrecedence(214 /* ConditionalExpression */, 57 /* QuestionToken */);
19107 var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
19108 var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
19109 if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
19110 return factory.createParenthesizedExpression(condition);
19111 }
19112 return condition;
19113 }
19114 function parenthesizeBranchOfConditionalExpression(branch) {
19115 // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
19116 // so in case when comma expression is introduced as a part of previous transformations
19117 // if should be wrapped in parens since comma operator has the lowest precedence
19118 var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
19119 return ts.isCommaSequence(emittedExpression)
19120 ? factory.createParenthesizedExpression(branch)
19121 : branch;
19122 }
19123 /**
19124 * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
19125 * has a lookahead restriction for `function`, `async function`, and `class`.
19126 *
19127 * Basically, that means we need to parenthesize in the following cases:
19128 *
19129 * - BinaryExpression of CommaToken
19130 * - CommaList (synthetic list of multiple comma expressions)
19131 * - FunctionExpression
19132 * - ClassExpression
19133 */
19134 function parenthesizeExpressionOfExportDefault(expression) {
19135 var check = ts.skipPartiallyEmittedExpressions(expression);
19136 var needsParens = ts.isCommaSequence(check);
19137 if (!needsParens) {
19138 switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
19139 case 218 /* ClassExpression */:
19140 case 205 /* FunctionExpression */:
19141 needsParens = true;
19142 }
19143 }
19144 return needsParens ? factory.createParenthesizedExpression(expression) : expression;
19145 }
19146 /**
19147 * Wraps an expression in parentheses if it is needed in order to use the expression
19148 * as the expression of a `NewExpression` node.
19149 */
19150 function parenthesizeExpressionOfNew(expression) {
19151 var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
19152 switch (leftmostExpr.kind) {
19153 case 200 /* CallExpression */:
19154 return factory.createParenthesizedExpression(expression);
19155 case 201 /* NewExpression */:
19156 return !leftmostExpr.arguments
19157 ? factory.createParenthesizedExpression(expression)
19158 : expression; // TODO(rbuckton): Verify this assertion holds
19159 }
19160 return parenthesizeLeftSideOfAccess(expression);
19161 }
19162 /**
19163 * Wraps an expression in parentheses if it is needed in order to use the expression for
19164 * property or element access.
19165 */
19166 function parenthesizeLeftSideOfAccess(expression) {
19167 // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
19168 // to parenthesize the expression before a dot. The known exception is:
19169 //
19170 // NewExpression:
19171 // new C.x -> not the same as (new C).x
19172 //
19173 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19174 if (ts.isLeftHandSideExpression(emittedExpression)
19175 && (emittedExpression.kind !== 201 /* NewExpression */ || emittedExpression.arguments)) {
19176 // TODO(rbuckton): Verify whether this assertion holds.
19177 return expression;
19178 }
19179 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19180 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19181 }
19182 function parenthesizeOperandOfPostfixUnary(operand) {
19183 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19184 return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19185 }
19186 function parenthesizeOperandOfPrefixUnary(operand) {
19187 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19188 return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19189 }
19190 function parenthesizeExpressionsOfCommaDelimitedList(elements) {
19191 var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
19192 return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
19193 }
19194 function parenthesizeExpressionForDisallowedComma(expression) {
19195 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19196 var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
19197 var commaPrecedence = ts.getOperatorPrecedence(213 /* BinaryExpression */, 27 /* CommaToken */);
19198 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19199 return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19200 }
19201 function parenthesizeExpressionOfExpressionStatement(expression) {
19202 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19203 if (ts.isCallExpression(emittedExpression)) {
19204 var callee = emittedExpression.expression;
19205 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
19206 if (kind === 205 /* FunctionExpression */ || kind === 206 /* ArrowFunction */) {
19207 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19208 var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
19209 return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
19210 }
19211 }
19212 var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
19213 if (leftmostExpressionKind === 197 /* ObjectLiteralExpression */ || leftmostExpressionKind === 205 /* FunctionExpression */) {
19214 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19215 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19216 }
19217 return expression;
19218 }
19219 function parenthesizeConciseBodyOfArrowFunction(body) {
19220 if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 197 /* ObjectLiteralExpression */)) {
19221 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19222 return ts.setTextRange(factory.createParenthesizedExpression(body), body);
19223 }
19224 return body;
19225 }
19226 function parenthesizeMemberOfConditionalType(member) {
19227 return member.kind === 183 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
19228 }
19229 function parenthesizeMemberOfElementType(member) {
19230 switch (member.kind) {
19231 case 181 /* UnionType */:
19232 case 182 /* IntersectionType */:
19233 case 173 /* FunctionType */:
19234 case 174 /* ConstructorType */:
19235 return factory.createParenthesizedType(member);
19236 }
19237 return parenthesizeMemberOfConditionalType(member);
19238 }
19239 function parenthesizeElementTypeOfArrayType(member) {
19240 switch (member.kind) {
19241 case 175 /* TypeQuery */:
19242 case 187 /* TypeOperator */:
19243 case 184 /* InferType */:
19244 return factory.createParenthesizedType(member);
19245 }
19246 return parenthesizeMemberOfElementType(member);
19247 }
19248 function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
19249 return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
19250 }
19251 function parenthesizeOrdinalTypeArgument(node, i) {
19252 return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
19253 }
19254 function parenthesizeTypeArguments(typeArguments) {
19255 if (ts.some(typeArguments)) {
19256 return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
19257 }
19258 }
19259 }
19260 ts.createParenthesizerRules = createParenthesizerRules;
19261 ts.nullParenthesizerRules = {
19262 parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
19263 parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
19264 parenthesizeExpressionOfComputedPropertyName: ts.identity,
19265 parenthesizeConditionOfConditionalExpression: ts.identity,
19266 parenthesizeBranchOfConditionalExpression: ts.identity,
19267 parenthesizeExpressionOfExportDefault: ts.identity,
19268 parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19269 parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19270 parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
19271 parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
19272 parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19273 parenthesizeExpressionForDisallowedComma: ts.identity,
19274 parenthesizeExpressionOfExpressionStatement: ts.identity,
19275 parenthesizeConciseBodyOfArrowFunction: ts.identity,
19276 parenthesizeMemberOfConditionalType: ts.identity,
19277 parenthesizeMemberOfElementType: ts.identity,
19278 parenthesizeElementTypeOfArrayType: ts.identity,
19279 parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19280 parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
19281 };
19282})(ts || (ts = {}));
19283/* @internal */
19284var ts;
19285(function (ts) {
19286 function createNodeConverters(factory) {
19287 return {
19288 convertToFunctionBlock: convertToFunctionBlock,
19289 convertToFunctionExpression: convertToFunctionExpression,
19290 convertToArrayAssignmentElement: convertToArrayAssignmentElement,
19291 convertToObjectAssignmentElement: convertToObjectAssignmentElement,
19292 convertToAssignmentPattern: convertToAssignmentPattern,
19293 convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
19294 convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
19295 convertToAssignmentElementTarget: convertToAssignmentElementTarget,
19296 };
19297 function convertToFunctionBlock(node, multiLine) {
19298 if (ts.isBlock(node))
19299 return node;
19300 var returnStatement = factory.createReturnStatement(node);
19301 ts.setTextRange(returnStatement, node);
19302 var body = factory.createBlock([returnStatement], multiLine);
19303 ts.setTextRange(body, node);
19304 return body;
19305 }
19306 function convertToFunctionExpression(node) {
19307 if (!node.body)
19308 return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
19309 var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
19310 ts.setOriginalNode(updated, node);
19311 ts.setTextRange(updated, node);
19312 if (ts.getStartsOnNewLine(node)) {
19313 ts.setStartsOnNewLine(updated, /*newLine*/ true);
19314 }
19315 return updated;
19316 }
19317 function convertToArrayAssignmentElement(element) {
19318 if (ts.isBindingElement(element)) {
19319 if (element.dotDotDotToken) {
19320 ts.Debug.assertNode(element.name, ts.isIdentifier);
19321 return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
19322 }
19323 var expression = convertToAssignmentElementTarget(element.name);
19324 return element.initializer
19325 ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
19326 : expression;
19327 }
19328 return ts.cast(element, ts.isExpression);
19329 }
19330 function convertToObjectAssignmentElement(element) {
19331 if (ts.isBindingElement(element)) {
19332 if (element.dotDotDotToken) {
19333 ts.Debug.assertNode(element.name, ts.isIdentifier);
19334 return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
19335 }
19336 if (element.propertyName) {
19337 var expression = convertToAssignmentElementTarget(element.name);
19338 return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
19339 }
19340 ts.Debug.assertNode(element.name, ts.isIdentifier);
19341 return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
19342 }
19343 return ts.cast(element, ts.isObjectLiteralElementLike);
19344 }
19345 function convertToAssignmentPattern(node) {
19346 switch (node.kind) {
19347 case 194 /* ArrayBindingPattern */:
19348 case 196 /* ArrayLiteralExpression */:
19349 return convertToArrayAssignmentPattern(node);
19350 case 193 /* ObjectBindingPattern */:
19351 case 197 /* ObjectLiteralExpression */:
19352 return convertToObjectAssignmentPattern(node);
19353 }
19354 }
19355 function convertToObjectAssignmentPattern(node) {
19356 if (ts.isObjectBindingPattern(node)) {
19357 return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
19358 }
19359 return ts.cast(node, ts.isObjectLiteralExpression);
19360 }
19361 function convertToArrayAssignmentPattern(node) {
19362 if (ts.isArrayBindingPattern(node)) {
19363 return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
19364 }
19365 return ts.cast(node, ts.isArrayLiteralExpression);
19366 }
19367 function convertToAssignmentElementTarget(node) {
19368 if (ts.isBindingPattern(node)) {
19369 return convertToAssignmentPattern(node);
19370 }
19371 return ts.cast(node, ts.isExpression);
19372 }
19373 }
19374 ts.createNodeConverters = createNodeConverters;
19375 ts.nullNodeConverters = {
19376 convertToFunctionBlock: ts.notImplemented,
19377 convertToFunctionExpression: ts.notImplemented,
19378 convertToArrayAssignmentElement: ts.notImplemented,
19379 convertToObjectAssignmentElement: ts.notImplemented,
19380 convertToAssignmentPattern: ts.notImplemented,
19381 convertToObjectAssignmentPattern: ts.notImplemented,
19382 convertToArrayAssignmentPattern: ts.notImplemented,
19383 convertToAssignmentElementTarget: ts.notImplemented,
19384 };
19385})(ts || (ts = {}));
19386var ts;
19387(function (ts) {
19388 var nextAutoGenerateId = 0;
19389 /* @internal */
19390 var NodeFactoryFlags;
19391 (function (NodeFactoryFlags) {
19392 NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
19393 // Disables the parenthesizer rules for the factory.
19394 NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
19395 // Disables the node converters for the factory.
19396 NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
19397 // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
19398 NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
19399 // Do not set an `original` pointer when updating a node.
19400 NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
19401 })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
19402 /**
19403 * Creates a `NodeFactory` that can be used to create and update a syntax tree.
19404 * @param flags Flags that control factory behavior.
19405 * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
19406 */
19407 /* @internal */
19408 function createNodeFactory(flags, baseFactory) {
19409 var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
19410 // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
19411 var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
19412 var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
19413 // lazy initializaton of common operator factories
19414 var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
19415 var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
19416 var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
19417 var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
19418 var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
19419 var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
19420 var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
19421 var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
19422 var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
19423 var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
19424 var factory = {
19425 get parenthesizer() { return parenthesizerRules(); },
19426 get converters() { return converters(); },
19427 createNodeArray: createNodeArray,
19428 createNumericLiteral: createNumericLiteral,
19429 createBigIntLiteral: createBigIntLiteral,
19430 createStringLiteral: createStringLiteral,
19431 createStringLiteralFromNode: createStringLiteralFromNode,
19432 createRegularExpressionLiteral: createRegularExpressionLiteral,
19433 createLiteralLikeNode: createLiteralLikeNode,
19434 createIdentifier: createIdentifier,
19435 updateIdentifier: updateIdentifier,
19436 createTempVariable: createTempVariable,
19437 createLoopVariable: createLoopVariable,
19438 createUniqueName: createUniqueName,
19439 getGeneratedNameForNode: getGeneratedNameForNode,
19440 createPrivateIdentifier: createPrivateIdentifier,
19441 createToken: createToken,
19442 createSuper: createSuper,
19443 createThis: createThis,
19444 createNull: createNull,
19445 createTrue: createTrue,
19446 createFalse: createFalse,
19447 createModifier: createModifier,
19448 createModifiersFromModifierFlags: createModifiersFromModifierFlags,
19449 createQualifiedName: createQualifiedName,
19450 updateQualifiedName: updateQualifiedName,
19451 createComputedPropertyName: createComputedPropertyName,
19452 updateComputedPropertyName: updateComputedPropertyName,
19453 createTypeParameterDeclaration: createTypeParameterDeclaration,
19454 updateTypeParameterDeclaration: updateTypeParameterDeclaration,
19455 createParameterDeclaration: createParameterDeclaration,
19456 updateParameterDeclaration: updateParameterDeclaration,
19457 createDecorator: createDecorator,
19458 updateDecorator: updateDecorator,
19459 createPropertySignature: createPropertySignature,
19460 updatePropertySignature: updatePropertySignature,
19461 createPropertyDeclaration: createPropertyDeclaration,
19462 updatePropertyDeclaration: updatePropertyDeclaration,
19463 createMethodSignature: createMethodSignature,
19464 updateMethodSignature: updateMethodSignature,
19465 createMethodDeclaration: createMethodDeclaration,
19466 updateMethodDeclaration: updateMethodDeclaration,
19467 createConstructorDeclaration: createConstructorDeclaration,
19468 updateConstructorDeclaration: updateConstructorDeclaration,
19469 createGetAccessorDeclaration: createGetAccessorDeclaration,
19470 updateGetAccessorDeclaration: updateGetAccessorDeclaration,
19471 createSetAccessorDeclaration: createSetAccessorDeclaration,
19472 updateSetAccessorDeclaration: updateSetAccessorDeclaration,
19473 createCallSignature: createCallSignature,
19474 updateCallSignature: updateCallSignature,
19475 createConstructSignature: createConstructSignature,
19476 updateConstructSignature: updateConstructSignature,
19477 createIndexSignature: createIndexSignature,
19478 updateIndexSignature: updateIndexSignature,
19479 createKeywordTypeNode: createKeywordTypeNode,
19480 createTypePredicateNode: createTypePredicateNode,
19481 updateTypePredicateNode: updateTypePredicateNode,
19482 createTypeReferenceNode: createTypeReferenceNode,
19483 updateTypeReferenceNode: updateTypeReferenceNode,
19484 createFunctionTypeNode: createFunctionTypeNode,
19485 updateFunctionTypeNode: updateFunctionTypeNode,
19486 createConstructorTypeNode: createConstructorTypeNode,
19487 updateConstructorTypeNode: updateConstructorTypeNode,
19488 createTypeQueryNode: createTypeQueryNode,
19489 updateTypeQueryNode: updateTypeQueryNode,
19490 createTypeLiteralNode: createTypeLiteralNode,
19491 updateTypeLiteralNode: updateTypeLiteralNode,
19492 createArrayTypeNode: createArrayTypeNode,
19493 updateArrayTypeNode: updateArrayTypeNode,
19494 createTupleTypeNode: createTupleTypeNode,
19495 updateTupleTypeNode: updateTupleTypeNode,
19496 createNamedTupleMember: createNamedTupleMember,
19497 updateNamedTupleMember: updateNamedTupleMember,
19498 createOptionalTypeNode: createOptionalTypeNode,
19499 updateOptionalTypeNode: updateOptionalTypeNode,
19500 createRestTypeNode: createRestTypeNode,
19501 updateRestTypeNode: updateRestTypeNode,
19502 createUnionTypeNode: createUnionTypeNode,
19503 updateUnionTypeNode: updateUnionTypeNode,
19504 createIntersectionTypeNode: createIntersectionTypeNode,
19505 updateIntersectionTypeNode: updateIntersectionTypeNode,
19506 createConditionalTypeNode: createConditionalTypeNode,
19507 updateConditionalTypeNode: updateConditionalTypeNode,
19508 createInferTypeNode: createInferTypeNode,
19509 updateInferTypeNode: updateInferTypeNode,
19510 createImportTypeNode: createImportTypeNode,
19511 updateImportTypeNode: updateImportTypeNode,
19512 createParenthesizedType: createParenthesizedType,
19513 updateParenthesizedType: updateParenthesizedType,
19514 createThisTypeNode: createThisTypeNode,
19515 createTypeOperatorNode: createTypeOperatorNode,
19516 updateTypeOperatorNode: updateTypeOperatorNode,
19517 createIndexedAccessTypeNode: createIndexedAccessTypeNode,
19518 updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
19519 createMappedTypeNode: createMappedTypeNode,
19520 updateMappedTypeNode: updateMappedTypeNode,
19521 createLiteralTypeNode: createLiteralTypeNode,
19522 updateLiteralTypeNode: updateLiteralTypeNode,
19523 createObjectBindingPattern: createObjectBindingPattern,
19524 updateObjectBindingPattern: updateObjectBindingPattern,
19525 createArrayBindingPattern: createArrayBindingPattern,
19526 updateArrayBindingPattern: updateArrayBindingPattern,
19527 createBindingElement: createBindingElement,
19528 updateBindingElement: updateBindingElement,
19529 createArrayLiteralExpression: createArrayLiteralExpression,
19530 updateArrayLiteralExpression: updateArrayLiteralExpression,
19531 createObjectLiteralExpression: createObjectLiteralExpression,
19532 updateObjectLiteralExpression: updateObjectLiteralExpression,
19533 createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
19534 function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
19535 createPropertyAccessExpression,
19536 updatePropertyAccessExpression: updatePropertyAccessExpression,
19537 createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
19538 function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
19539 createPropertyAccessChain,
19540 updatePropertyAccessChain: updatePropertyAccessChain,
19541 createElementAccessExpression: createElementAccessExpression,
19542 updateElementAccessExpression: updateElementAccessExpression,
19543 createElementAccessChain: createElementAccessChain,
19544 updateElementAccessChain: updateElementAccessChain,
19545 createCallExpression: createCallExpression,
19546 updateCallExpression: updateCallExpression,
19547 createCallChain: createCallChain,
19548 updateCallChain: updateCallChain,
19549 createNewExpression: createNewExpression,
19550 updateNewExpression: updateNewExpression,
19551 createTaggedTemplateExpression: createTaggedTemplateExpression,
19552 updateTaggedTemplateExpression: updateTaggedTemplateExpression,
19553 createTypeAssertion: createTypeAssertion,
19554 updateTypeAssertion: updateTypeAssertion,
19555 createParenthesizedExpression: createParenthesizedExpression,
19556 updateParenthesizedExpression: updateParenthesizedExpression,
19557 createFunctionExpression: createFunctionExpression,
19558 updateFunctionExpression: updateFunctionExpression,
19559 createArrowFunction: createArrowFunction,
19560 updateArrowFunction: updateArrowFunction,
19561 createDeleteExpression: createDeleteExpression,
19562 updateDeleteExpression: updateDeleteExpression,
19563 createTypeOfExpression: createTypeOfExpression,
19564 updateTypeOfExpression: updateTypeOfExpression,
19565 createVoidExpression: createVoidExpression,
19566 updateVoidExpression: updateVoidExpression,
19567 createAwaitExpression: createAwaitExpression,
19568 updateAwaitExpression: updateAwaitExpression,
19569 createPrefixUnaryExpression: createPrefixUnaryExpression,
19570 updatePrefixUnaryExpression: updatePrefixUnaryExpression,
19571 createPostfixUnaryExpression: createPostfixUnaryExpression,
19572 updatePostfixUnaryExpression: updatePostfixUnaryExpression,
19573 createBinaryExpression: createBinaryExpression,
19574 updateBinaryExpression: updateBinaryExpression,
19575 createConditionalExpression: createConditionalExpression,
19576 updateConditionalExpression: updateConditionalExpression,
19577 createTemplateExpression: createTemplateExpression,
19578 updateTemplateExpression: updateTemplateExpression,
19579 createTemplateHead: createTemplateHead,
19580 createTemplateMiddle: createTemplateMiddle,
19581 createTemplateTail: createTemplateTail,
19582 createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
19583 createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
19584 createYieldExpression: createYieldExpression,
19585 updateYieldExpression: updateYieldExpression,
19586 createSpreadElement: createSpreadElement,
19587 updateSpreadElement: updateSpreadElement,
19588 createClassExpression: createClassExpression,
19589 updateClassExpression: updateClassExpression,
19590 createOmittedExpression: createOmittedExpression,
19591 createExpressionWithTypeArguments: createExpressionWithTypeArguments,
19592 updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
19593 createAsExpression: createAsExpression,
19594 updateAsExpression: updateAsExpression,
19595 createNonNullExpression: createNonNullExpression,
19596 updateNonNullExpression: updateNonNullExpression,
19597 createNonNullChain: createNonNullChain,
19598 updateNonNullChain: updateNonNullChain,
19599 createMetaProperty: createMetaProperty,
19600 updateMetaProperty: updateMetaProperty,
19601 createTemplateSpan: createTemplateSpan,
19602 updateTemplateSpan: updateTemplateSpan,
19603 createSemicolonClassElement: createSemicolonClassElement,
19604 createBlock: createBlock,
19605 updateBlock: updateBlock,
19606 createVariableStatement: createVariableStatement,
19607 updateVariableStatement: updateVariableStatement,
19608 createEmptyStatement: createEmptyStatement,
19609 createExpressionStatement: createExpressionStatement,
19610 updateExpressionStatement: updateExpressionStatement,
19611 createIfStatement: createIfStatement,
19612 updateIfStatement: updateIfStatement,
19613 createDoStatement: createDoStatement,
19614 updateDoStatement: updateDoStatement,
19615 createWhileStatement: createWhileStatement,
19616 updateWhileStatement: updateWhileStatement,
19617 createForStatement: createForStatement,
19618 updateForStatement: updateForStatement,
19619 createForInStatement: createForInStatement,
19620 updateForInStatement: updateForInStatement,
19621 createForOfStatement: createForOfStatement,
19622 updateForOfStatement: updateForOfStatement,
19623 createContinueStatement: createContinueStatement,
19624 updateContinueStatement: updateContinueStatement,
19625 createBreakStatement: createBreakStatement,
19626 updateBreakStatement: updateBreakStatement,
19627 createReturnStatement: createReturnStatement,
19628 updateReturnStatement: updateReturnStatement,
19629 createWithStatement: createWithStatement,
19630 updateWithStatement: updateWithStatement,
19631 createSwitchStatement: createSwitchStatement,
19632 updateSwitchStatement: updateSwitchStatement,
19633 createLabeledStatement: createLabeledStatement,
19634 updateLabeledStatement: updateLabeledStatement,
19635 createThrowStatement: createThrowStatement,
19636 updateThrowStatement: updateThrowStatement,
19637 createTryStatement: createTryStatement,
19638 updateTryStatement: updateTryStatement,
19639 createDebuggerStatement: createDebuggerStatement,
19640 createVariableDeclaration: createVariableDeclaration,
19641 updateVariableDeclaration: updateVariableDeclaration,
19642 createVariableDeclarationList: createVariableDeclarationList,
19643 updateVariableDeclarationList: updateVariableDeclarationList,
19644 createFunctionDeclaration: createFunctionDeclaration,
19645 updateFunctionDeclaration: updateFunctionDeclaration,
19646 createClassDeclaration: createClassDeclaration,
19647 updateClassDeclaration: updateClassDeclaration,
19648 createInterfaceDeclaration: createInterfaceDeclaration,
19649 updateInterfaceDeclaration: updateInterfaceDeclaration,
19650 createTypeAliasDeclaration: createTypeAliasDeclaration,
19651 updateTypeAliasDeclaration: updateTypeAliasDeclaration,
19652 createEnumDeclaration: createEnumDeclaration,
19653 updateEnumDeclaration: updateEnumDeclaration,
19654 createModuleDeclaration: createModuleDeclaration,
19655 updateModuleDeclaration: updateModuleDeclaration,
19656 createModuleBlock: createModuleBlock,
19657 updateModuleBlock: updateModuleBlock,
19658 createCaseBlock: createCaseBlock,
19659 updateCaseBlock: updateCaseBlock,
19660 createNamespaceExportDeclaration: createNamespaceExportDeclaration,
19661 updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
19662 createImportEqualsDeclaration: createImportEqualsDeclaration,
19663 updateImportEqualsDeclaration: updateImportEqualsDeclaration,
19664 createImportDeclaration: createImportDeclaration,
19665 updateImportDeclaration: updateImportDeclaration,
19666 createImportClause: createImportClause,
19667 updateImportClause: updateImportClause,
19668 createNamespaceImport: createNamespaceImport,
19669 updateNamespaceImport: updateNamespaceImport,
19670 createNamespaceExport: createNamespaceExport,
19671 updateNamespaceExport: updateNamespaceExport,
19672 createNamedImports: createNamedImports,
19673 updateNamedImports: updateNamedImports,
19674 createImportSpecifier: createImportSpecifier,
19675 updateImportSpecifier: updateImportSpecifier,
19676 createExportAssignment: createExportAssignment,
19677 updateExportAssignment: updateExportAssignment,
19678 createExportDeclaration: createExportDeclaration,
19679 updateExportDeclaration: updateExportDeclaration,
19680 createNamedExports: createNamedExports,
19681 updateNamedExports: updateNamedExports,
19682 createExportSpecifier: createExportSpecifier,
19683 updateExportSpecifier: updateExportSpecifier,
19684 createMissingDeclaration: createMissingDeclaration,
19685 createExternalModuleReference: createExternalModuleReference,
19686 updateExternalModuleReference: updateExternalModuleReference,
19687 // lazily load factory members for JSDoc types with similar structure
19688 get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(299 /* JSDocAllType */); },
19689 get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(300 /* JSDocUnknownType */); },
19690 get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(302 /* JSDocNonNullableType */); },
19691 get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(302 /* JSDocNonNullableType */); },
19692 get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(301 /* JSDocNullableType */); },
19693 get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(301 /* JSDocNullableType */); },
19694 get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(303 /* JSDocOptionalType */); },
19695 get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(303 /* JSDocOptionalType */); },
19696 get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocVariadicType */); },
19697 get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocVariadicType */); },
19698 get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNamepathType */); },
19699 get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNamepathType */); },
19700 createJSDocFunctionType: createJSDocFunctionType,
19701 updateJSDocFunctionType: updateJSDocFunctionType,
19702 createJSDocTypeLiteral: createJSDocTypeLiteral,
19703 updateJSDocTypeLiteral: updateJSDocTypeLiteral,
19704 createJSDocTypeExpression: createJSDocTypeExpression,
19705 updateJSDocTypeExpression: updateJSDocTypeExpression,
19706 createJSDocSignature: createJSDocSignature,
19707 updateJSDocSignature: updateJSDocSignature,
19708 createJSDocTemplateTag: createJSDocTemplateTag,
19709 updateJSDocTemplateTag: updateJSDocTemplateTag,
19710 createJSDocTypedefTag: createJSDocTypedefTag,
19711 updateJSDocTypedefTag: updateJSDocTypedefTag,
19712 createJSDocParameterTag: createJSDocParameterTag,
19713 updateJSDocParameterTag: updateJSDocParameterTag,
19714 createJSDocPropertyTag: createJSDocPropertyTag,
19715 updateJSDocPropertyTag: updateJSDocPropertyTag,
19716 createJSDocCallbackTag: createJSDocCallbackTag,
19717 updateJSDocCallbackTag: updateJSDocCallbackTag,
19718 createJSDocAugmentsTag: createJSDocAugmentsTag,
19719 updateJSDocAugmentsTag: updateJSDocAugmentsTag,
19720 createJSDocImplementsTag: createJSDocImplementsTag,
19721 updateJSDocImplementsTag: updateJSDocImplementsTag,
19722 // lazily load factory members for JSDoc tags with similar structure
19723 get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocTypeTag */); },
19724 get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocTypeTag */); },
19725 get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(323 /* JSDocReturnTag */); },
19726 get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(323 /* JSDocReturnTag */); },
19727 get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(324 /* JSDocThisTag */); },
19728 get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(324 /* JSDocThisTag */); },
19729 get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(321 /* JSDocEnumTag */); },
19730 get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(321 /* JSDocEnumTag */); },
19731 get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(313 /* JSDocAuthorTag */); },
19732 get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(313 /* JSDocAuthorTag */); },
19733 get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(315 /* JSDocClassTag */); },
19734 get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(315 /* JSDocClassTag */); },
19735 get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(316 /* JSDocPublicTag */); },
19736 get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(316 /* JSDocPublicTag */); },
19737 get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocPrivateTag */); },
19738 get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocPrivateTag */); },
19739 get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocProtectedTag */); },
19740 get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocProtectedTag */); },
19741 get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocReadonlyTag */); },
19742 get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocReadonlyTag */); },
19743 get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(314 /* JSDocDeprecatedTag */); },
19744 get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(314 /* JSDocDeprecatedTag */); },
19745 createJSDocUnknownTag: createJSDocUnknownTag,
19746 updateJSDocUnknownTag: updateJSDocUnknownTag,
19747 createJSDocComment: createJSDocComment,
19748 updateJSDocComment: updateJSDocComment,
19749 createJsxElement: createJsxElement,
19750 updateJsxElement: updateJsxElement,
19751 createJsxSelfClosingElement: createJsxSelfClosingElement,
19752 updateJsxSelfClosingElement: updateJsxSelfClosingElement,
19753 createJsxOpeningElement: createJsxOpeningElement,
19754 updateJsxOpeningElement: updateJsxOpeningElement,
19755 createJsxClosingElement: createJsxClosingElement,
19756 updateJsxClosingElement: updateJsxClosingElement,
19757 createJsxFragment: createJsxFragment,
19758 createJsxText: createJsxText,
19759 updateJsxText: updateJsxText,
19760 createJsxOpeningFragment: createJsxOpeningFragment,
19761 createJsxJsxClosingFragment: createJsxJsxClosingFragment,
19762 updateJsxFragment: updateJsxFragment,
19763 createJsxAttribute: createJsxAttribute,
19764 updateJsxAttribute: updateJsxAttribute,
19765 createJsxAttributes: createJsxAttributes,
19766 updateJsxAttributes: updateJsxAttributes,
19767 createJsxSpreadAttribute: createJsxSpreadAttribute,
19768 updateJsxSpreadAttribute: updateJsxSpreadAttribute,
19769 createJsxExpression: createJsxExpression,
19770 updateJsxExpression: updateJsxExpression,
19771 createCaseClause: createCaseClause,
19772 updateCaseClause: updateCaseClause,
19773 createDefaultClause: createDefaultClause,
19774 updateDefaultClause: updateDefaultClause,
19775 createHeritageClause: createHeritageClause,
19776 updateHeritageClause: updateHeritageClause,
19777 createCatchClause: createCatchClause,
19778 updateCatchClause: updateCatchClause,
19779 createPropertyAssignment: createPropertyAssignment,
19780 updatePropertyAssignment: updatePropertyAssignment,
19781 createShorthandPropertyAssignment: createShorthandPropertyAssignment,
19782 updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
19783 createSpreadAssignment: createSpreadAssignment,
19784 updateSpreadAssignment: updateSpreadAssignment,
19785 createEnumMember: createEnumMember,
19786 updateEnumMember: updateEnumMember,
19787 createSourceFile: createSourceFile,
19788 updateSourceFile: updateSourceFile,
19789 createBundle: createBundle,
19790 updateBundle: updateBundle,
19791 createUnparsedSource: createUnparsedSource,
19792 createUnparsedPrologue: createUnparsedPrologue,
19793 createUnparsedPrepend: createUnparsedPrepend,
19794 createUnparsedTextLike: createUnparsedTextLike,
19795 createUnparsedSyntheticReference: createUnparsedSyntheticReference,
19796 createInputFiles: createInputFiles,
19797 createSyntheticExpression: createSyntheticExpression,
19798 createSyntaxList: createSyntaxList,
19799 createNotEmittedStatement: createNotEmittedStatement,
19800 createPartiallyEmittedExpression: createPartiallyEmittedExpression,
19801 updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
19802 createCommaListExpression: createCommaListExpression,
19803 updateCommaListExpression: updateCommaListExpression,
19804 createEndOfDeclarationMarker: createEndOfDeclarationMarker,
19805 createMergeDeclarationMarker: createMergeDeclarationMarker,
19806 createSyntheticReferenceExpression: createSyntheticReferenceExpression,
19807 updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
19808 cloneNode: cloneNode,
19809 // Lazily load factory methods for common operator factories and utilities
19810 get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
19811 get createAssignment() { return getBinaryCreateFunction(62 /* EqualsToken */); },
19812 get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
19813 get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
19814 get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
19815 get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
19816 get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
19817 get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
19818 get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
19819 get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
19820 get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
19821 get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
19822 get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
19823 get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
19824 get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
19825 get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
19826 get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
19827 get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
19828 get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
19829 get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
19830 get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
19831 get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
19832 get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
19833 get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
19834 get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
19835 get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
19836 get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
19837 get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
19838 get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
19839 get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
19840 get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
19841 get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
19842 // Compound nodes
19843 createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
19844 createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
19845 createVoidZero: createVoidZero,
19846 createExportDefault: createExportDefault,
19847 createExternalModuleExport: createExternalModuleExport,
19848 createTypeCheck: createTypeCheck,
19849 createMethodCall: createMethodCall,
19850 createGlobalMethodCall: createGlobalMethodCall,
19851 createFunctionBindCall: createFunctionBindCall,
19852 createFunctionCallCall: createFunctionCallCall,
19853 createFunctionApplyCall: createFunctionApplyCall,
19854 createArraySliceCall: createArraySliceCall,
19855 createArrayConcatCall: createArrayConcatCall,
19856 createObjectDefinePropertyCall: createObjectDefinePropertyCall,
19857 createPropertyDescriptor: createPropertyDescriptor,
19858 createCallBinding: createCallBinding,
19859 // Utilities
19860 inlineExpressions: inlineExpressions,
19861 getInternalName: getInternalName,
19862 getLocalName: getLocalName,
19863 getExportName: getExportName,
19864 getDeclarationName: getDeclarationName,
19865 getNamespaceMemberName: getNamespaceMemberName,
19866 getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
19867 restoreOuterExpressions: restoreOuterExpressions,
19868 restoreEnclosingLabel: restoreEnclosingLabel,
19869 createUseStrictPrologue: createUseStrictPrologue,
19870 copyPrologue: copyPrologue,
19871 copyStandardPrologue: copyStandardPrologue,
19872 copyCustomPrologue: copyCustomPrologue,
19873 ensureUseStrict: ensureUseStrict,
19874 liftToBlock: liftToBlock,
19875 mergeLexicalEnvironment: mergeLexicalEnvironment,
19876 updateModifiers: updateModifiers,
19877 };
19878 return factory;
19879 // @api
19880 function createNodeArray(elements, hasTrailingComma) {
19881 if (elements === undefined || elements === ts.emptyArray) {
19882 elements = [];
19883 }
19884 else if (ts.isNodeArray(elements)) {
19885 // Ensure the transform flags have been aggregated for this NodeArray
19886 if (elements.transformFlags === undefined) {
19887 aggregateChildrenFlags(elements);
19888 }
19889 return elements;
19890 }
19891 // Since the element list of a node array is typically created by starting with an empty array and
19892 // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
19893 // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
19894 var length = elements.length;
19895 var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
19896 ts.setTextRangePosEnd(array, -1, -1);
19897 array.hasTrailingComma = !!hasTrailingComma;
19898 aggregateChildrenFlags(array);
19899 return array;
19900 }
19901 function createBaseNode(kind) {
19902 return baseFactory.createBaseNode(kind);
19903 }
19904 function createBaseDeclaration(kind, decorators, modifiers) {
19905 var node = createBaseNode(kind);
19906 node.decorators = asNodeArray(decorators);
19907 node.modifiers = asNodeArray(modifiers);
19908 node.transformFlags |=
19909 propagateChildrenFlags(node.decorators) |
19910 propagateChildrenFlags(node.modifiers);
19911 // NOTE: The following properties are commonly set by the binder and are added here to
19912 // ensure declarations have a stable shape.
19913 node.symbol = undefined; // initialized by binder
19914 node.localSymbol = undefined; // initialized by binder
19915 node.locals = undefined; // initialized by binder
19916 node.nextContainer = undefined; // initialized by binder
19917 return node;
19918 }
19919 function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
19920 var node = createBaseDeclaration(kind, decorators, modifiers);
19921 name = asName(name);
19922 node.name = name;
19923 // The PropertyName of a member is allowed to be `await`.
19924 // We don't need to exclude `await` for type signatures since types
19925 // don't propagate child flags.
19926 if (name) {
19927 switch (node.kind) {
19928 case 164 /* MethodDeclaration */:
19929 case 166 /* GetAccessor */:
19930 case 167 /* SetAccessor */:
19931 case 162 /* PropertyDeclaration */:
19932 case 285 /* PropertyAssignment */:
19933 if (ts.isIdentifier(name)) {
19934 node.transformFlags |= propagateIdentifierNameFlags(name);
19935 break;
19936 }
19937 // fall through
19938 default:
19939 node.transformFlags |= propagateChildFlags(name);
19940 break;
19941 }
19942 }
19943 return node;
19944 }
19945 function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
19946 var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
19947 node.typeParameters = asNodeArray(typeParameters);
19948 node.transformFlags |= propagateChildrenFlags(node.typeParameters);
19949 if (typeParameters)
19950 node.transformFlags |= 1 /* ContainsTypeScript */;
19951 return node;
19952 }
19953 function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
19954 var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
19955 node.parameters = createNodeArray(parameters);
19956 node.type = type;
19957 node.transformFlags |=
19958 propagateChildrenFlags(node.parameters) |
19959 propagateChildFlags(node.type);
19960 if (type)
19961 node.transformFlags |= 1 /* ContainsTypeScript */;
19962 return node;
19963 }
19964 function updateBaseSignatureDeclaration(updated, original) {
19965 // copy children used only for error reporting
19966 if (original.typeArguments)
19967 updated.typeArguments = original.typeArguments;
19968 return update(updated, original);
19969 }
19970 function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
19971 var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
19972 node.body = body;
19973 node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */;
19974 if (!body)
19975 node.transformFlags |= 1 /* ContainsTypeScript */;
19976 return node;
19977 }
19978 function updateBaseFunctionLikeDeclaration(updated, original) {
19979 // copy children used only for error reporting
19980 if (original.exclamationToken)
19981 updated.exclamationToken = original.exclamationToken;
19982 if (original.typeArguments)
19983 updated.typeArguments = original.typeArguments;
19984 return updateBaseSignatureDeclaration(updated, original);
19985 }
19986 function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
19987 var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
19988 node.heritageClauses = asNodeArray(heritageClauses);
19989 node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
19990 return node;
19991 }
19992 function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
19993 var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
19994 node.members = createNodeArray(members);
19995 node.transformFlags |= propagateChildrenFlags(node.members);
19996 return node;
19997 }
19998 function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
19999 var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
20000 node.initializer = initializer;
20001 node.transformFlags |= propagateChildFlags(node.initializer);
20002 return node;
20003 }
20004 function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
20005 var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
20006 node.type = type;
20007 node.transformFlags |= propagateChildFlags(type);
20008 if (type)
20009 node.transformFlags |= 1 /* ContainsTypeScript */;
20010 return node;
20011 }
20012 //
20013 // Literals
20014 //
20015 function createBaseLiteral(kind, text) {
20016 var node = createBaseToken(kind);
20017 node.text = text;
20018 return node;
20019 }
20020 // @api
20021 function createNumericLiteral(value, numericLiteralFlags) {
20022 if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
20023 var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
20024 node.numericLiteralFlags = numericLiteralFlags;
20025 if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
20026 node.transformFlags |= 256 /* ContainsES2015 */;
20027 return node;
20028 }
20029 // @api
20030 function createBigIntLiteral(value) {
20031 var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
20032 node.transformFlags |= 4 /* ContainsESNext */;
20033 return node;
20034 }
20035 function createBaseStringLiteral(text, isSingleQuote) {
20036 var node = createBaseLiteral(10 /* StringLiteral */, text);
20037 node.singleQuote = isSingleQuote;
20038 return node;
20039 }
20040 // @api
20041 function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
20042 var node = createBaseStringLiteral(text, isSingleQuote);
20043 node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
20044 if (hasExtendedUnicodeEscape)
20045 node.transformFlags |= 256 /* ContainsES2015 */;
20046 return node;
20047 }
20048 // @api
20049 function createStringLiteralFromNode(sourceNode) {
20050 var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
20051 node.textSourceNode = sourceNode;
20052 return node;
20053 }
20054 // @api
20055 function createRegularExpressionLiteral(text) {
20056 var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
20057 return node;
20058 }
20059 // @api
20060 function createLiteralLikeNode(kind, text) {
20061 switch (kind) {
20062 case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
20063 case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
20064 case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
20065 case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
20066 case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
20067 case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
20068 case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
20069 }
20070 }
20071 //
20072 // Identifiers
20073 //
20074 function createBaseIdentifier(text, originalKeywordKind) {
20075 if (originalKeywordKind === undefined && text) {
20076 originalKeywordKind = ts.stringToToken(text);
20077 }
20078 if (originalKeywordKind === 78 /* Identifier */) {
20079 originalKeywordKind = undefined;
20080 }
20081 var node = baseFactory.createBaseIdentifierNode(78 /* Identifier */);
20082 node.originalKeywordKind = originalKeywordKind;
20083 node.escapedText = ts.escapeLeadingUnderscores(text);
20084 return node;
20085 }
20086 function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
20087 var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
20088 node.autoGenerateFlags = autoGenerateFlags;
20089 node.autoGenerateId = nextAutoGenerateId;
20090 nextAutoGenerateId++;
20091 return node;
20092 }
20093 // @api
20094 function createIdentifier(text, typeArguments, originalKeywordKind) {
20095 var node = createBaseIdentifier(text, originalKeywordKind);
20096 if (typeArguments) {
20097 // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
20098 node.typeArguments = createNodeArray(typeArguments);
20099 }
20100 if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
20101 node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */;
20102 }
20103 return node;
20104 }
20105 // @api
20106 function updateIdentifier(node, typeArguments) {
20107 return node.typeArguments !== typeArguments
20108 ? update(createIdentifier(ts.idText(node), typeArguments), node)
20109 : node;
20110 }
20111 // @api
20112 function createTempVariable(recordTempVariable, reservedInNestedScopes) {
20113 var flags = 1 /* Auto */;
20114 if (reservedInNestedScopes)
20115 flags |= 8 /* ReservedInNestedScopes */;
20116 var name = createBaseGeneratedIdentifier("", flags);
20117 if (recordTempVariable) {
20118 recordTempVariable(name);
20119 }
20120 return name;
20121 }
20122 /** Create a unique temporary variable for use in a loop. */
20123 // @api
20124 function createLoopVariable() {
20125 return createBaseGeneratedIdentifier("", 2 /* Loop */);
20126 }
20127 /** Create a unique name based on the supplied text. */
20128 // @api
20129 function createUniqueName(text, flags) {
20130 if (flags === void 0) { flags = 0 /* None */; }
20131 ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20132 ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
20133 return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
20134 }
20135 /** Create a unique name generated for a node. */
20136 // @api
20137 function getGeneratedNameForNode(node, flags) {
20138 if (flags === void 0) { flags = 0; }
20139 ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20140 var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
20141 name.original = node;
20142 return name;
20143 }
20144 // @api
20145 function createPrivateIdentifier(text) {
20146 if (!ts.startsWith(text, "#"))
20147 ts.Debug.fail("First character of private identifier must be #: " + text);
20148 var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */);
20149 node.escapedText = ts.escapeLeadingUnderscores(text);
20150 node.transformFlags |= 4194304 /* ContainsClassFields */;
20151 return node;
20152 }
20153 //
20154 // Punctuation
20155 //
20156 function createBaseToken(kind) {
20157 return baseFactory.createBaseTokenNode(kind);
20158 }
20159 function createToken(token) {
20160 ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 155 /* LastToken */, "Invalid token");
20161 ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
20162 ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
20163 ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
20164 var node = createBaseToken(token);
20165 var transformFlags = 0 /* None */;
20166 switch (token) {
20167 case 129 /* AsyncKeyword */:
20168 // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
20169 transformFlags =
20170 64 /* ContainsES2017 */ |
20171 32 /* ContainsES2018 */;
20172 break;
20173 case 122 /* PublicKeyword */:
20174 case 120 /* PrivateKeyword */:
20175 case 121 /* ProtectedKeyword */:
20176 case 141 /* ReadonlyKeyword */:
20177 case 125 /* AbstractKeyword */:
20178 case 133 /* DeclareKeyword */:
20179 case 84 /* ConstKeyword */:
20180 case 128 /* AnyKeyword */:
20181 case 143 /* NumberKeyword */:
20182 case 154 /* BigIntKeyword */:
20183 case 140 /* NeverKeyword */:
20184 case 144 /* ObjectKeyword */:
20185 case 146 /* StringKeyword */:
20186 case 131 /* BooleanKeyword */:
20187 case 147 /* SymbolKeyword */:
20188 case 113 /* VoidKeyword */:
20189 case 151 /* UnknownKeyword */:
20190 case 149 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
20191 transformFlags = 1 /* ContainsTypeScript */;
20192 break;
20193 case 123 /* StaticKeyword */:
20194 case 105 /* SuperKeyword */:
20195 transformFlags = 256 /* ContainsES2015 */;
20196 break;
20197 case 107 /* ThisKeyword */:
20198 // 'this' indicates a lexical 'this'
20199 transformFlags = 4096 /* ContainsLexicalThis */;
20200 break;
20201 }
20202 if (transformFlags) {
20203 node.transformFlags |= transformFlags;
20204 }
20205 return node;
20206 }
20207 //
20208 // Reserved words
20209 //
20210 // @api
20211 function createSuper() {
20212 return createToken(105 /* SuperKeyword */);
20213 }
20214 // @api
20215 function createThis() {
20216 return createToken(107 /* ThisKeyword */);
20217 }
20218 // @api
20219 function createNull() {
20220 return createToken(103 /* NullKeyword */);
20221 }
20222 // @api
20223 function createTrue() {
20224 return createToken(109 /* TrueKeyword */);
20225 }
20226 // @api
20227 function createFalse() {
20228 return createToken(94 /* FalseKeyword */);
20229 }
20230 //
20231 // Modifiers
20232 //
20233 // @api
20234 function createModifier(kind) {
20235 return createToken(kind);
20236 }
20237 // @api
20238 function createModifiersFromModifierFlags(flags) {
20239 var result = [];
20240 if (flags & 1 /* Export */) {
20241 result.push(createModifier(92 /* ExportKeyword */));
20242 }
20243 if (flags & 2 /* Ambient */) {
20244 result.push(createModifier(133 /* DeclareKeyword */));
20245 }
20246 if (flags & 512 /* Default */) {
20247 result.push(createModifier(87 /* DefaultKeyword */));
20248 }
20249 if (flags & 2048 /* Const */) {
20250 result.push(createModifier(84 /* ConstKeyword */));
20251 }
20252 if (flags & 4 /* Public */) {
20253 result.push(createModifier(122 /* PublicKeyword */));
20254 }
20255 if (flags & 8 /* Private */) {
20256 result.push(createModifier(120 /* PrivateKeyword */));
20257 }
20258 if (flags & 16 /* Protected */) {
20259 result.push(createModifier(121 /* ProtectedKeyword */));
20260 }
20261 if (flags & 128 /* Abstract */) {
20262 result.push(createModifier(125 /* AbstractKeyword */));
20263 }
20264 if (flags & 32 /* Static */) {
20265 result.push(createModifier(123 /* StaticKeyword */));
20266 }
20267 if (flags & 64 /* Readonly */) {
20268 result.push(createModifier(141 /* ReadonlyKeyword */));
20269 }
20270 if (flags & 256 /* Async */) {
20271 result.push(createModifier(129 /* AsyncKeyword */));
20272 }
20273 return result;
20274 }
20275 //
20276 // Names
20277 //
20278 // @api
20279 function createQualifiedName(left, right) {
20280 var node = createBaseNode(156 /* QualifiedName */);
20281 node.left = left;
20282 node.right = asName(right);
20283 node.transformFlags |=
20284 propagateChildFlags(node.left) |
20285 propagateIdentifierNameFlags(node.right);
20286 return node;
20287 }
20288 // @api
20289 function updateQualifiedName(node, left, right) {
20290 return node.left !== left
20291 || node.right !== right
20292 ? update(createQualifiedName(left, right), node)
20293 : node;
20294 }
20295 // @api
20296 function createComputedPropertyName(expression) {
20297 var node = createBaseNode(157 /* ComputedPropertyName */);
20298 node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
20299 node.transformFlags |=
20300 propagateChildFlags(node.expression) |
20301 256 /* ContainsES2015 */ |
20302 32768 /* ContainsComputedPropertyName */;
20303 return node;
20304 }
20305 // @api
20306 function updateComputedPropertyName(node, expression) {
20307 return node.expression !== expression
20308 ? update(createComputedPropertyName(expression), node)
20309 : node;
20310 }
20311 //
20312 // Signature elements
20313 //
20314 // @api
20315 function createTypeParameterDeclaration(name, constraint, defaultType) {
20316 var node = createBaseNamedDeclaration(158 /* TypeParameter */,
20317 /*decorators*/ undefined,
20318 /*modifiers*/ undefined, name);
20319 node.constraint = constraint;
20320 node.default = defaultType;
20321 node.transformFlags = 1 /* ContainsTypeScript */;
20322 return node;
20323 }
20324 // @api
20325 function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
20326 return node.name !== name
20327 || node.constraint !== constraint
20328 || node.default !== defaultType
20329 ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
20330 : node;
20331 }
20332 // @api
20333 function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
20334 var node = createBaseVariableLikeDeclaration(159 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
20335 node.dotDotDotToken = dotDotDotToken;
20336 node.questionToken = questionToken;
20337 if (ts.isThisIdentifier(node.name)) {
20338 node.transformFlags = 1 /* ContainsTypeScript */;
20339 }
20340 else {
20341 node.transformFlags |=
20342 propagateChildFlags(node.dotDotDotToken) |
20343 propagateChildFlags(node.questionToken);
20344 if (questionToken)
20345 node.transformFlags |= 1 /* ContainsTypeScript */;
20346 if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */)
20347 node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
20348 if (initializer || dotDotDotToken)
20349 node.transformFlags |= 256 /* ContainsES2015 */;
20350 }
20351 return node;
20352 }
20353 // @api
20354 function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
20355 return node.decorators !== decorators
20356 || node.modifiers !== modifiers
20357 || node.dotDotDotToken !== dotDotDotToken
20358 || node.name !== name
20359 || node.questionToken !== questionToken
20360 || node.type !== type
20361 || node.initializer !== initializer
20362 ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
20363 : node;
20364 }
20365 // @api
20366 function createDecorator(expression) {
20367 var node = createBaseNode(160 /* Decorator */);
20368 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
20369 node.transformFlags |=
20370 propagateChildFlags(node.expression) |
20371 1 /* ContainsTypeScript */ |
20372 2048 /* ContainsTypeScriptClassSyntax */;
20373 return node;
20374 }
20375 // @api
20376 function updateDecorator(node, expression) {
20377 return node.expression !== expression
20378 ? update(createDecorator(expression), node)
20379 : node;
20380 }
20381 //
20382 // Type Elements
20383 //
20384 // @api
20385 function createPropertySignature(modifiers, name, questionToken, type) {
20386 var node = createBaseNamedDeclaration(161 /* PropertySignature */,
20387 /*decorators*/ undefined, modifiers, name);
20388 node.type = type;
20389 node.questionToken = questionToken;
20390 node.transformFlags = 1 /* ContainsTypeScript */;
20391 return node;
20392 }
20393 // @api
20394 function updatePropertySignature(node, modifiers, name, questionToken, type) {
20395 return node.modifiers !== modifiers
20396 || node.name !== name
20397 || node.questionToken !== questionToken
20398 || node.type !== type
20399 ? update(createPropertySignature(modifiers, name, questionToken, type), node)
20400 : node;
20401 }
20402 // @api
20403 function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
20404 var node = createBaseVariableLikeDeclaration(162 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
20405 node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
20406 node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
20407 node.transformFlags |=
20408 propagateChildFlags(node.questionToken) |
20409 propagateChildFlags(node.exclamationToken) |
20410 4194304 /* ContainsClassFields */;
20411 if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
20412 node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
20413 }
20414 if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
20415 node.transformFlags |= 1 /* ContainsTypeScript */;
20416 }
20417 return node;
20418 }
20419 // @api
20420 function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
20421 return node.decorators !== decorators
20422 || node.modifiers !== modifiers
20423 || node.name !== name
20424 || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
20425 || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
20426 || node.type !== type
20427 || node.initializer !== initializer
20428 ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
20429 : node;
20430 }
20431 // @api
20432 function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
20433 var node = createBaseSignatureDeclaration(163 /* MethodSignature */,
20434 /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
20435 node.questionToken = questionToken;
20436 node.transformFlags = 1 /* ContainsTypeScript */;
20437 return node;
20438 }
20439 // @api
20440 function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
20441 return node.modifiers !== modifiers
20442 || node.name !== name
20443 || node.questionToken !== questionToken
20444 || node.typeParameters !== typeParameters
20445 || node.parameters !== parameters
20446 || node.type !== type
20447 ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
20448 : node;
20449 }
20450 // @api
20451 function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
20452 var node = createBaseFunctionLikeDeclaration(164 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
20453 node.asteriskToken = asteriskToken;
20454 node.questionToken = questionToken;
20455 node.transformFlags |=
20456 propagateChildFlags(node.asteriskToken) |
20457 propagateChildFlags(node.questionToken) |
20458 256 /* ContainsES2015 */;
20459 if (questionToken) {
20460 node.transformFlags |= 1 /* ContainsTypeScript */;
20461 }
20462 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
20463 if (asteriskToken) {
20464 node.transformFlags |= 32 /* ContainsES2018 */;
20465 }
20466 else {
20467 node.transformFlags |= 64 /* ContainsES2017 */;
20468 }
20469 }
20470 else if (asteriskToken) {
20471 node.transformFlags |= 512 /* ContainsGenerator */;
20472 }
20473 return node;
20474 }
20475 // @api
20476 function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
20477 return node.decorators !== decorators
20478 || node.modifiers !== modifiers
20479 || node.asteriskToken !== asteriskToken
20480 || node.name !== name
20481 || node.questionToken !== questionToken
20482 || node.typeParameters !== typeParameters
20483 || node.parameters !== parameters
20484 || node.type !== type
20485 || node.body !== body
20486 ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
20487 : node;
20488 }
20489 // @api
20490 function createConstructorDeclaration(decorators, modifiers, parameters, body) {
20491 var node = createBaseFunctionLikeDeclaration(165 /* Constructor */, decorators, modifiers,
20492 /*name*/ undefined,
20493 /*typeParameters*/ undefined, parameters,
20494 /*type*/ undefined, body);
20495 node.transformFlags |= 256 /* ContainsES2015 */;
20496 return node;
20497 }
20498 // @api
20499 function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
20500 return node.decorators !== decorators
20501 || node.modifiers !== modifiers
20502 || node.parameters !== parameters
20503 || node.body !== body
20504 ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
20505 : node;
20506 }
20507 // @api
20508 function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
20509 return createBaseFunctionLikeDeclaration(166 /* GetAccessor */, decorators, modifiers, name,
20510 /*typeParameters*/ undefined, parameters, type, body);
20511 }
20512 // @api
20513 function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
20514 return node.decorators !== decorators
20515 || node.modifiers !== modifiers
20516 || node.name !== name
20517 || node.parameters !== parameters
20518 || node.type !== type
20519 || node.body !== body
20520 ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
20521 : node;
20522 }
20523 // @api
20524 function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
20525 return createBaseFunctionLikeDeclaration(167 /* SetAccessor */, decorators, modifiers, name,
20526 /*typeParameters*/ undefined, parameters,
20527 /*type*/ undefined, body);
20528 }
20529 // @api
20530 function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
20531 return node.decorators !== decorators
20532 || node.modifiers !== modifiers
20533 || node.name !== name
20534 || node.parameters !== parameters
20535 || node.body !== body
20536 ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
20537 : node;
20538 }
20539 // @api
20540 function createCallSignature(typeParameters, parameters, type) {
20541 var node = createBaseSignatureDeclaration(168 /* CallSignature */,
20542 /*decorators*/ undefined,
20543 /*modifiers*/ undefined,
20544 /*name*/ undefined, typeParameters, parameters, type);
20545 node.transformFlags = 1 /* ContainsTypeScript */;
20546 return node;
20547 }
20548 // @api
20549 function updateCallSignature(node, typeParameters, parameters, type) {
20550 return node.typeParameters !== typeParameters
20551 || node.parameters !== parameters
20552 || node.type !== type
20553 ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
20554 : node;
20555 }
20556 // @api
20557 function createConstructSignature(typeParameters, parameters, type) {
20558 var node = createBaseSignatureDeclaration(169 /* ConstructSignature */,
20559 /*decorators*/ undefined,
20560 /*modifiers*/ undefined,
20561 /*name*/ undefined, typeParameters, parameters, type);
20562 node.transformFlags = 1 /* ContainsTypeScript */;
20563 return node;
20564 }
20565 // @api
20566 function updateConstructSignature(node, typeParameters, parameters, type) {
20567 return node.typeParameters !== typeParameters
20568 || node.parameters !== parameters
20569 || node.type !== type
20570 ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
20571 : node;
20572 }
20573 // @api
20574 function createIndexSignature(decorators, modifiers, parameters, type) {
20575 var node = createBaseSignatureDeclaration(170 /* IndexSignature */, decorators, modifiers,
20576 /*name*/ undefined,
20577 /*typeParameters*/ undefined, parameters, type);
20578 node.transformFlags = 1 /* ContainsTypeScript */;
20579 return node;
20580 }
20581 // @api
20582 function updateIndexSignature(node, decorators, modifiers, parameters, type) {
20583 return node.parameters !== parameters
20584 || node.type !== type
20585 || node.decorators !== decorators
20586 || node.modifiers !== modifiers
20587 ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
20588 : node;
20589 }
20590 //
20591 // Types
20592 //
20593 // @api
20594 function createKeywordTypeNode(kind) {
20595 return createToken(kind);
20596 }
20597 // @api
20598 function createTypePredicateNode(assertsModifier, parameterName, type) {
20599 var node = createBaseNode(171 /* TypePredicate */);
20600 node.assertsModifier = assertsModifier;
20601 node.parameterName = asName(parameterName);
20602 node.type = type;
20603 node.transformFlags = 1 /* ContainsTypeScript */;
20604 return node;
20605 }
20606 // @api
20607 function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
20608 return node.assertsModifier !== assertsModifier
20609 || node.parameterName !== parameterName
20610 || node.type !== type
20611 ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
20612 : node;
20613 }
20614 // @api
20615 function createTypeReferenceNode(typeName, typeArguments) {
20616 var node = createBaseNode(172 /* TypeReference */);
20617 node.typeName = asName(typeName);
20618 node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
20619 node.transformFlags = 1 /* ContainsTypeScript */;
20620 return node;
20621 }
20622 // @api
20623 function updateTypeReferenceNode(node, typeName, typeArguments) {
20624 return node.typeName !== typeName
20625 || node.typeArguments !== typeArguments
20626 ? update(createTypeReferenceNode(typeName, typeArguments), node)
20627 : node;
20628 }
20629 // @api
20630 function createFunctionTypeNode(typeParameters, parameters, type) {
20631 var node = createBaseSignatureDeclaration(173 /* FunctionType */,
20632 /*decorators*/ undefined,
20633 /*modifiers*/ undefined,
20634 /*name*/ undefined, typeParameters, parameters, type);
20635 node.transformFlags = 1 /* ContainsTypeScript */;
20636 return node;
20637 }
20638 // @api
20639 function updateFunctionTypeNode(node, typeParameters, parameters, type) {
20640 return node.typeParameters !== typeParameters
20641 || node.parameters !== parameters
20642 || node.type !== type
20643 ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
20644 : node;
20645 }
20646 // @api
20647 function createConstructorTypeNode(typeParameters, parameters, type) {
20648 var node = createBaseSignatureDeclaration(174 /* ConstructorType */,
20649 /*decorators*/ undefined,
20650 /*modifiers*/ undefined,
20651 /*name*/ undefined, typeParameters, parameters, type);
20652 node.transformFlags = 1 /* ContainsTypeScript */;
20653 return node;
20654 }
20655 // @api
20656 function updateConstructorTypeNode(node, typeParameters, parameters, type) {
20657 return node.typeParameters !== typeParameters
20658 || node.parameters !== parameters
20659 || node.type !== type
20660 ? updateBaseSignatureDeclaration(createConstructorTypeNode(typeParameters, parameters, type), node)
20661 : node;
20662 }
20663 // @api
20664 function createTypeQueryNode(exprName) {
20665 var node = createBaseNode(175 /* TypeQuery */);
20666 node.exprName = exprName;
20667 node.transformFlags = 1 /* ContainsTypeScript */;
20668 return node;
20669 }
20670 // @api
20671 function updateTypeQueryNode(node, exprName) {
20672 return node.exprName !== exprName
20673 ? update(createTypeQueryNode(exprName), node)
20674 : node;
20675 }
20676 // @api
20677 function createTypeLiteralNode(members) {
20678 var node = createBaseNode(176 /* TypeLiteral */);
20679 node.members = createNodeArray(members);
20680 node.transformFlags = 1 /* ContainsTypeScript */;
20681 return node;
20682 }
20683 // @api
20684 function updateTypeLiteralNode(node, members) {
20685 return node.members !== members
20686 ? update(createTypeLiteralNode(members), node)
20687 : node;
20688 }
20689 // @api
20690 function createArrayTypeNode(elementType) {
20691 var node = createBaseNode(177 /* ArrayType */);
20692 node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
20693 node.transformFlags = 1 /* ContainsTypeScript */;
20694 return node;
20695 }
20696 // @api
20697 function updateArrayTypeNode(node, elementType) {
20698 return node.elementType !== elementType
20699 ? update(createArrayTypeNode(elementType), node)
20700 : node;
20701 }
20702 // @api
20703 function createTupleTypeNode(elements) {
20704 var node = createBaseNode(178 /* TupleType */);
20705 node.elements = createNodeArray(elements);
20706 node.transformFlags = 1 /* ContainsTypeScript */;
20707 return node;
20708 }
20709 // @api
20710 function updateTupleTypeNode(node, elements) {
20711 return node.elements !== elements
20712 ? update(createTupleTypeNode(elements), node)
20713 : node;
20714 }
20715 // @api
20716 function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
20717 var node = createBaseNode(191 /* NamedTupleMember */);
20718 node.dotDotDotToken = dotDotDotToken;
20719 node.name = name;
20720 node.questionToken = questionToken;
20721 node.type = type;
20722 node.transformFlags = 1 /* ContainsTypeScript */;
20723 return node;
20724 }
20725 // @api
20726 function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
20727 return node.dotDotDotToken !== dotDotDotToken
20728 || node.name !== name
20729 || node.questionToken !== questionToken
20730 || node.type !== type
20731 ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
20732 : node;
20733 }
20734 // @api
20735 function createOptionalTypeNode(type) {
20736 var node = createBaseNode(179 /* OptionalType */);
20737 node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
20738 node.transformFlags = 1 /* ContainsTypeScript */;
20739 return node;
20740 }
20741 // @api
20742 function updateOptionalTypeNode(node, type) {
20743 return node.type !== type
20744 ? update(createOptionalTypeNode(type), node)
20745 : node;
20746 }
20747 // @api
20748 function createRestTypeNode(type) {
20749 var node = createBaseNode(180 /* RestType */);
20750 node.type = type;
20751 node.transformFlags = 1 /* ContainsTypeScript */;
20752 return node;
20753 }
20754 // @api
20755 function updateRestTypeNode(node, type) {
20756 return node.type !== type
20757 ? update(createRestTypeNode(type), node)
20758 : node;
20759 }
20760 function createUnionOrIntersectionTypeNode(kind, types) {
20761 var node = createBaseNode(kind);
20762 node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
20763 node.transformFlags = 1 /* ContainsTypeScript */;
20764 return node;
20765 }
20766 function updateUnionOrIntersectionTypeNode(node, types) {
20767 return node.types !== types
20768 ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
20769 : node;
20770 }
20771 // @api
20772 function createUnionTypeNode(types) {
20773 return createUnionOrIntersectionTypeNode(181 /* UnionType */, types);
20774 }
20775 // @api
20776 function updateUnionTypeNode(node, types) {
20777 return updateUnionOrIntersectionTypeNode(node, types);
20778 }
20779 // @api
20780 function createIntersectionTypeNode(types) {
20781 return createUnionOrIntersectionTypeNode(182 /* IntersectionType */, types);
20782 }
20783 // @api
20784 function updateIntersectionTypeNode(node, types) {
20785 return updateUnionOrIntersectionTypeNode(node, types);
20786 }
20787 // @api
20788 function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
20789 var node = createBaseNode(183 /* ConditionalType */);
20790 node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
20791 node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
20792 node.trueType = trueType;
20793 node.falseType = falseType;
20794 node.transformFlags = 1 /* ContainsTypeScript */;
20795 return node;
20796 }
20797 // @api
20798 function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
20799 return node.checkType !== checkType
20800 || node.extendsType !== extendsType
20801 || node.trueType !== trueType
20802 || node.falseType !== falseType
20803 ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
20804 : node;
20805 }
20806 // @api
20807 function createInferTypeNode(typeParameter) {
20808 var node = createBaseNode(184 /* InferType */);
20809 node.typeParameter = typeParameter;
20810 node.transformFlags = 1 /* ContainsTypeScript */;
20811 return node;
20812 }
20813 // @api
20814 function updateInferTypeNode(node, typeParameter) {
20815 return node.typeParameter !== typeParameter
20816 ? update(createInferTypeNode(typeParameter), node)
20817 : node;
20818 }
20819 // @api
20820 function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
20821 if (isTypeOf === void 0) { isTypeOf = false; }
20822 var node = createBaseNode(192 /* ImportType */);
20823 node.argument = argument;
20824 node.qualifier = qualifier;
20825 node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
20826 node.isTypeOf = isTypeOf;
20827 node.transformFlags = 1 /* ContainsTypeScript */;
20828 return node;
20829 }
20830 // @api
20831 function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
20832 if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
20833 return node.argument !== argument
20834 || node.qualifier !== qualifier
20835 || node.typeArguments !== typeArguments
20836 || node.isTypeOf !== isTypeOf
20837 ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
20838 : node;
20839 }
20840 // @api
20841 function createParenthesizedType(type) {
20842 var node = createBaseNode(185 /* ParenthesizedType */);
20843 node.type = type;
20844 node.transformFlags = 1 /* ContainsTypeScript */;
20845 return node;
20846 }
20847 // @api
20848 function updateParenthesizedType(node, type) {
20849 return node.type !== type
20850 ? update(createParenthesizedType(type), node)
20851 : node;
20852 }
20853 // @api
20854 function createThisTypeNode() {
20855 var node = createBaseNode(186 /* ThisType */);
20856 node.transformFlags = 1 /* ContainsTypeScript */;
20857 return node;
20858 }
20859 // @api
20860 function createTypeOperatorNode(operator, type) {
20861 var node = createBaseNode(187 /* TypeOperator */);
20862 node.operator = operator;
20863 node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
20864 node.transformFlags = 1 /* ContainsTypeScript */;
20865 return node;
20866 }
20867 // @api
20868 function updateTypeOperatorNode(node, type) {
20869 return node.type !== type
20870 ? update(createTypeOperatorNode(node.operator, type), node)
20871 : node;
20872 }
20873 // @api
20874 function createIndexedAccessTypeNode(objectType, indexType) {
20875 var node = createBaseNode(188 /* IndexedAccessType */);
20876 node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
20877 node.indexType = indexType;
20878 node.transformFlags = 1 /* ContainsTypeScript */;
20879 return node;
20880 }
20881 // @api
20882 function updateIndexedAccessTypeNode(node, objectType, indexType) {
20883 return node.objectType !== objectType
20884 || node.indexType !== indexType
20885 ? update(createIndexedAccessTypeNode(objectType, indexType), node)
20886 : node;
20887 }
20888 // @api
20889 function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
20890 var node = createBaseNode(189 /* MappedType */);
20891 node.readonlyToken = readonlyToken;
20892 node.typeParameter = typeParameter;
20893 node.questionToken = questionToken;
20894 node.type = type;
20895 node.transformFlags = 1 /* ContainsTypeScript */;
20896 return node;
20897 }
20898 // @api
20899 function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
20900 return node.readonlyToken !== readonlyToken
20901 || node.typeParameter !== typeParameter
20902 || node.questionToken !== questionToken
20903 || node.type !== type
20904 ? update(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
20905 : node;
20906 }
20907 // @api
20908 function createLiteralTypeNode(literal) {
20909 var node = createBaseNode(190 /* LiteralType */);
20910 node.literal = literal;
20911 node.transformFlags = 1 /* ContainsTypeScript */;
20912 return node;
20913 }
20914 // @api
20915 function updateLiteralTypeNode(node, literal) {
20916 return node.literal !== literal
20917 ? update(createLiteralTypeNode(literal), node)
20918 : node;
20919 }
20920 //
20921 // Binding Patterns
20922 //
20923 // @api
20924 function createObjectBindingPattern(elements) {
20925 var node = createBaseNode(193 /* ObjectBindingPattern */);
20926 node.elements = createNodeArray(elements);
20927 node.transformFlags |=
20928 propagateChildrenFlags(node.elements) |
20929 256 /* ContainsES2015 */ |
20930 131072 /* ContainsBindingPattern */;
20931 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
20932 node.transformFlags |=
20933 32 /* ContainsES2018 */ |
20934 16384 /* ContainsObjectRestOrSpread */;
20935 }
20936 return node;
20937 }
20938 // @api
20939 function updateObjectBindingPattern(node, elements) {
20940 return node.elements !== elements
20941 ? update(createObjectBindingPattern(elements), node)
20942 : node;
20943 }
20944 // @api
20945 function createArrayBindingPattern(elements) {
20946 var node = createBaseNode(194 /* ArrayBindingPattern */);
20947 node.elements = createNodeArray(elements);
20948 node.transformFlags |=
20949 propagateChildrenFlags(node.elements) |
20950 256 /* ContainsES2015 */ |
20951 131072 /* ContainsBindingPattern */;
20952 return node;
20953 }
20954 // @api
20955 function updateArrayBindingPattern(node, elements) {
20956 return node.elements !== elements
20957 ? update(createArrayBindingPattern(elements), node)
20958 : node;
20959 }
20960 // @api
20961 function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
20962 var node = createBaseBindingLikeDeclaration(195 /* BindingElement */,
20963 /*decorators*/ undefined,
20964 /*modifiers*/ undefined, name, initializer);
20965 node.propertyName = asName(propertyName);
20966 node.dotDotDotToken = dotDotDotToken;
20967 node.transformFlags |=
20968 propagateChildFlags(node.dotDotDotToken) |
20969 256 /* ContainsES2015 */;
20970 if (node.propertyName) {
20971 node.transformFlags |= ts.isIdentifier(node.propertyName) ?
20972 propagateIdentifierNameFlags(node.propertyName) :
20973 propagateChildFlags(node.propertyName);
20974 }
20975 if (dotDotDotToken)
20976 node.transformFlags |= 8192 /* ContainsRestOrSpread */;
20977 return node;
20978 }
20979 // @api
20980 function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
20981 return node.propertyName !== propertyName
20982 || node.dotDotDotToken !== dotDotDotToken
20983 || node.name !== name
20984 || node.initializer !== initializer
20985 ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
20986 : node;
20987 }
20988 //
20989 // Expression
20990 //
20991 function createBaseExpression(kind) {
20992 var node = createBaseNode(kind);
20993 // the following properties are commonly set by the checker/binder
20994 return node;
20995 }
20996 // @api
20997 function createArrayLiteralExpression(elements, multiLine) {
20998 var node = createBaseExpression(196 /* ArrayLiteralExpression */);
20999 node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements));
21000 node.multiLine = multiLine;
21001 node.transformFlags |= propagateChildrenFlags(node.elements);
21002 return node;
21003 }
21004 // @api
21005 function updateArrayLiteralExpression(node, elements) {
21006 return node.elements !== elements
21007 ? update(createArrayLiteralExpression(elements, node.multiLine), node)
21008 : node;
21009 }
21010 // @api
21011 function createObjectLiteralExpression(properties, multiLine) {
21012 var node = createBaseExpression(197 /* ObjectLiteralExpression */);
21013 node.properties = createNodeArray(properties);
21014 node.multiLine = multiLine;
21015 node.transformFlags |= propagateChildrenFlags(node.properties);
21016 return node;
21017 }
21018 // @api
21019 function updateObjectLiteralExpression(node, properties) {
21020 return node.properties !== properties
21021 ? update(createObjectLiteralExpression(properties, node.multiLine), node)
21022 : node;
21023 }
21024 // @api
21025 function createPropertyAccessExpression(expression, name) {
21026 var node = createBaseExpression(198 /* PropertyAccessExpression */);
21027 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21028 node.name = asName(name);
21029 node.transformFlags =
21030 propagateChildFlags(node.expression) |
21031 (ts.isIdentifier(node.name) ?
21032 propagateIdentifierNameFlags(node.name) :
21033 propagateChildFlags(node.name));
21034 if (ts.isSuperKeyword(expression)) {
21035 // super method calls require a lexical 'this'
21036 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21037 node.transformFlags |=
21038 64 /* ContainsES2017 */ |
21039 32 /* ContainsES2018 */;
21040 }
21041 return node;
21042 }
21043 // @api
21044 function updatePropertyAccessExpression(node, expression, name) {
21045 if (ts.isPropertyAccessChain(node)) {
21046 return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
21047 }
21048 return node.expression !== expression
21049 || node.name !== name
21050 ? update(createPropertyAccessExpression(expression, name), node)
21051 : node;
21052 }
21053 // @api
21054 function createPropertyAccessChain(expression, questionDotToken, name) {
21055 var node = createBaseExpression(198 /* PropertyAccessExpression */);
21056 node.flags |= 32 /* OptionalChain */;
21057 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21058 node.questionDotToken = questionDotToken;
21059 node.name = asName(name);
21060 node.transformFlags |=
21061 8 /* ContainsES2020 */ |
21062 propagateChildFlags(node.expression) |
21063 propagateChildFlags(node.questionDotToken) |
21064 (ts.isIdentifier(node.name) ?
21065 propagateIdentifierNameFlags(node.name) :
21066 propagateChildFlags(node.name));
21067 return node;
21068 }
21069 // @api
21070 function updatePropertyAccessChain(node, expression, questionDotToken, name) {
21071 ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
21072 // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
21073 // instead of using the default from createPropertyAccess
21074 return node.expression !== expression
21075 || node.questionDotToken !== questionDotToken
21076 || node.name !== name
21077 ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
21078 : node;
21079 }
21080 // @api
21081 function createElementAccessExpression(expression, index) {
21082 var node = createBaseExpression(199 /* ElementAccessExpression */);
21083 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21084 node.argumentExpression = asExpression(index);
21085 node.transformFlags |=
21086 propagateChildFlags(node.expression) |
21087 propagateChildFlags(node.argumentExpression);
21088 if (ts.isSuperKeyword(expression)) {
21089 // super method calls require a lexical 'this'
21090 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21091 node.transformFlags |=
21092 64 /* ContainsES2017 */ |
21093 32 /* ContainsES2018 */;
21094 }
21095 return node;
21096 }
21097 // @api
21098 function updateElementAccessExpression(node, expression, argumentExpression) {
21099 if (ts.isElementAccessChain(node)) {
21100 return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
21101 }
21102 return node.expression !== expression
21103 || node.argumentExpression !== argumentExpression
21104 ? update(createElementAccessExpression(expression, argumentExpression), node)
21105 : node;
21106 }
21107 // @api
21108 function createElementAccessChain(expression, questionDotToken, index) {
21109 var node = createBaseExpression(199 /* ElementAccessExpression */);
21110 node.flags |= 32 /* OptionalChain */;
21111 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21112 node.questionDotToken = questionDotToken;
21113 node.argumentExpression = asExpression(index);
21114 node.transformFlags |=
21115 propagateChildFlags(node.expression) |
21116 propagateChildFlags(node.questionDotToken) |
21117 propagateChildFlags(node.argumentExpression) |
21118 8 /* ContainsES2020 */;
21119 return node;
21120 }
21121 // @api
21122 function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
21123 ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
21124 // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
21125 // instead of using the default from createElementAccess
21126 return node.expression !== expression
21127 || node.questionDotToken !== questionDotToken
21128 || node.argumentExpression !== argumentExpression
21129 ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
21130 : node;
21131 }
21132 // @api
21133 function createCallExpression(expression, typeArguments, argumentsArray) {
21134 var node = createBaseExpression(200 /* CallExpression */);
21135 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21136 node.typeArguments = asNodeArray(typeArguments);
21137 node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21138 node.transformFlags |=
21139 propagateChildFlags(node.expression) |
21140 propagateChildrenFlags(node.typeArguments) |
21141 propagateChildrenFlags(node.arguments);
21142 if (node.typeArguments) {
21143 node.transformFlags |= 1 /* ContainsTypeScript */;
21144 }
21145 if (ts.isImportKeyword(node.expression)) {
21146 node.transformFlags |= 2097152 /* ContainsDynamicImport */;
21147 }
21148 else if (ts.isSuperProperty(node.expression)) {
21149 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21150 }
21151 return node;
21152 }
21153 // @api
21154 function updateCallExpression(node, expression, typeArguments, argumentsArray) {
21155 if (ts.isCallChain(node)) {
21156 return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
21157 }
21158 return node.expression !== expression
21159 || node.typeArguments !== typeArguments
21160 || node.arguments !== argumentsArray
21161 ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
21162 : node;
21163 }
21164 // @api
21165 function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
21166 var node = createBaseExpression(200 /* CallExpression */);
21167 node.flags |= 32 /* OptionalChain */;
21168 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21169 node.questionDotToken = questionDotToken;
21170 node.typeArguments = asNodeArray(typeArguments);
21171 node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21172 node.transformFlags |=
21173 propagateChildFlags(node.expression) |
21174 propagateChildFlags(node.questionDotToken) |
21175 propagateChildrenFlags(node.typeArguments) |
21176 propagateChildrenFlags(node.arguments) |
21177 8 /* ContainsES2020 */;
21178 if (node.typeArguments) {
21179 node.transformFlags |= 1 /* ContainsTypeScript */;
21180 }
21181 if (ts.isSuperProperty(node.expression)) {
21182 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21183 }
21184 return node;
21185 }
21186 // @api
21187 function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
21188 ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
21189 return node.expression !== expression
21190 || node.questionDotToken !== questionDotToken
21191 || node.typeArguments !== typeArguments
21192 || node.arguments !== argumentsArray
21193 ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
21194 : node;
21195 }
21196 // @api
21197 function createNewExpression(expression, typeArguments, argumentsArray) {
21198 var node = createBaseExpression(201 /* NewExpression */);
21199 node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
21200 node.typeArguments = asNodeArray(typeArguments);
21201 node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
21202 node.transformFlags |=
21203 propagateChildFlags(node.expression) |
21204 propagateChildrenFlags(node.typeArguments) |
21205 propagateChildrenFlags(node.arguments) |
21206 8 /* ContainsES2020 */;
21207 if (node.typeArguments) {
21208 node.transformFlags |= 1 /* ContainsTypeScript */;
21209 }
21210 return node;
21211 }
21212 // @api
21213 function updateNewExpression(node, expression, typeArguments, argumentsArray) {
21214 return node.expression !== expression
21215 || node.typeArguments !== typeArguments
21216 || node.arguments !== argumentsArray
21217 ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
21218 : node;
21219 }
21220 // @api
21221 function createTaggedTemplateExpression(tag, typeArguments, template) {
21222 var node = createBaseExpression(202 /* TaggedTemplateExpression */);
21223 node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
21224 node.typeArguments = asNodeArray(typeArguments);
21225 node.template = template;
21226 node.transformFlags |=
21227 propagateChildFlags(node.tag) |
21228 propagateChildrenFlags(node.typeArguments) |
21229 propagateChildFlags(node.template) |
21230 256 /* ContainsES2015 */;
21231 if (node.typeArguments) {
21232 node.transformFlags |= 1 /* ContainsTypeScript */;
21233 }
21234 if (ts.hasInvalidEscape(node.template)) {
21235 node.transformFlags |= 32 /* ContainsES2018 */;
21236 }
21237 return node;
21238 }
21239 // @api
21240 function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
21241 return node.tag !== tag
21242 || node.typeArguments !== typeArguments
21243 || node.template !== template
21244 ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
21245 : node;
21246 }
21247 // @api
21248 function createTypeAssertion(type, expression) {
21249 var node = createBaseExpression(203 /* TypeAssertionExpression */);
21250 node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
21251 node.type = type;
21252 node.transformFlags |=
21253 propagateChildFlags(node.expression) |
21254 propagateChildFlags(node.type) |
21255 1 /* ContainsTypeScript */;
21256 return node;
21257 }
21258 // @api
21259 function updateTypeAssertion(node, type, expression) {
21260 return node.type !== type
21261 || node.expression !== expression
21262 ? update(createTypeAssertion(type, expression), node)
21263 : node;
21264 }
21265 // @api
21266 function createParenthesizedExpression(expression) {
21267 var node = createBaseExpression(204 /* ParenthesizedExpression */);
21268 node.expression = expression;
21269 node.transformFlags = propagateChildFlags(node.expression);
21270 return node;
21271 }
21272 // @api
21273 function updateParenthesizedExpression(node, expression) {
21274 return node.expression !== expression
21275 ? update(createParenthesizedExpression(expression), node)
21276 : node;
21277 }
21278 // @api
21279 function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
21280 var node = createBaseFunctionLikeDeclaration(205 /* FunctionExpression */,
21281 /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
21282 node.asteriskToken = asteriskToken;
21283 node.transformFlags |= propagateChildFlags(node.asteriskToken);
21284 if (node.typeParameters) {
21285 node.transformFlags |= 1 /* ContainsTypeScript */;
21286 }
21287 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
21288 if (node.asteriskToken) {
21289 node.transformFlags |= 32 /* ContainsES2018 */;
21290 }
21291 else {
21292 node.transformFlags |= 64 /* ContainsES2017 */;
21293 }
21294 }
21295 else if (node.asteriskToken) {
21296 node.transformFlags |= 512 /* ContainsGenerator */;
21297 }
21298 return node;
21299 }
21300 // @api
21301 function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
21302 return node.name !== name
21303 || node.modifiers !== modifiers
21304 || node.asteriskToken !== asteriskToken
21305 || node.typeParameters !== typeParameters
21306 || node.parameters !== parameters
21307 || node.type !== type
21308 || node.body !== body
21309 ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
21310 : node;
21311 }
21312 // @api
21313 function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
21314 var node = createBaseFunctionLikeDeclaration(206 /* ArrowFunction */,
21315 /*decorators*/ undefined, modifiers,
21316 /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
21317 node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
21318 node.transformFlags |=
21319 propagateChildFlags(node.equalsGreaterThanToken) |
21320 256 /* ContainsES2015 */;
21321 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
21322 node.transformFlags |= 64 /* ContainsES2017 */;
21323 }
21324 return node;
21325 }
21326 // @api
21327 function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
21328 return node.modifiers !== modifiers
21329 || node.typeParameters !== typeParameters
21330 || node.parameters !== parameters
21331 || node.type !== type
21332 || node.equalsGreaterThanToken !== equalsGreaterThanToken
21333 || node.body !== body
21334 ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
21335 : node;
21336 }
21337 // @api
21338 function createDeleteExpression(expression) {
21339 var node = createBaseExpression(207 /* DeleteExpression */);
21340 node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
21341 node.transformFlags |= propagateChildFlags(node.expression);
21342 return node;
21343 }
21344 // @api
21345 function updateDeleteExpression(node, expression) {
21346 return node.expression !== expression
21347 ? update(createDeleteExpression(expression), node)
21348 : node;
21349 }
21350 // @api
21351 function createTypeOfExpression(expression) {
21352 var node = createBaseExpression(208 /* TypeOfExpression */);
21353 node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
21354 node.transformFlags |= propagateChildFlags(node.expression);
21355 return node;
21356 }
21357 // @api
21358 function updateTypeOfExpression(node, expression) {
21359 return node.expression !== expression
21360 ? update(createTypeOfExpression(expression), node)
21361 : node;
21362 }
21363 // @api
21364 function createVoidExpression(expression) {
21365 var node = createBaseExpression(209 /* VoidExpression */);
21366 node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
21367 node.transformFlags |= propagateChildFlags(node.expression);
21368 return node;
21369 }
21370 // @api
21371 function updateVoidExpression(node, expression) {
21372 return node.expression !== expression
21373 ? update(createVoidExpression(expression), node)
21374 : node;
21375 }
21376 // @api
21377 function createAwaitExpression(expression) {
21378 var node = createBaseExpression(210 /* AwaitExpression */);
21379 node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
21380 node.transformFlags |=
21381 propagateChildFlags(node.expression) |
21382 64 /* ContainsES2017 */ |
21383 32 /* ContainsES2018 */ |
21384 524288 /* ContainsAwait */;
21385 return node;
21386 }
21387 // @api
21388 function updateAwaitExpression(node, expression) {
21389 return node.expression !== expression
21390 ? update(createAwaitExpression(expression), node)
21391 : node;
21392 }
21393 // @api
21394 function createPrefixUnaryExpression(operator, operand) {
21395 var node = createBaseExpression(211 /* PrefixUnaryExpression */);
21396 node.operator = operator;
21397 node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
21398 node.transformFlags |= propagateChildFlags(node.operand);
21399 return node;
21400 }
21401 // @api
21402 function updatePrefixUnaryExpression(node, operand) {
21403 return node.operand !== operand
21404 ? update(createPrefixUnaryExpression(node.operator, operand), node)
21405 : node;
21406 }
21407 // @api
21408 function createPostfixUnaryExpression(operand, operator) {
21409 var node = createBaseExpression(212 /* PostfixUnaryExpression */);
21410 node.operator = operator;
21411 node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
21412 node.transformFlags = propagateChildFlags(node.operand);
21413 return node;
21414 }
21415 // @api
21416 function updatePostfixUnaryExpression(node, operand) {
21417 return node.operand !== operand
21418 ? update(createPostfixUnaryExpression(operand, node.operator), node)
21419 : node;
21420 }
21421 // @api
21422 function createBinaryExpression(left, operator, right) {
21423 var node = createBaseExpression(213 /* BinaryExpression */);
21424 var operatorToken = asToken(operator);
21425 var operatorKind = operatorToken.kind;
21426 node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
21427 node.operatorToken = operatorToken;
21428 node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
21429 node.transformFlags |=
21430 propagateChildFlags(node.left) |
21431 propagateChildFlags(node.operatorToken) |
21432 propagateChildFlags(node.right);
21433 if (operatorKind === 60 /* QuestionQuestionToken */) {
21434 node.transformFlags |= 8 /* ContainsES2020 */;
21435 }
21436 else if (operatorKind === 62 /* EqualsToken */) {
21437 if (ts.isObjectLiteralExpression(node.left)) {
21438 node.transformFlags |=
21439 256 /* ContainsES2015 */ |
21440 32 /* ContainsES2018 */ |
21441 1024 /* ContainsDestructuringAssignment */;
21442 }
21443 else if (ts.isArrayLiteralExpression(node.left)) {
21444 node.transformFlags |=
21445 256 /* ContainsES2015 */ |
21446 1024 /* ContainsDestructuringAssignment */;
21447 }
21448 }
21449 else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) {
21450 node.transformFlags |= 128 /* ContainsES2016 */;
21451 }
21452 else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
21453 node.transformFlags |= 4 /* ContainsESNext */;
21454 }
21455 return node;
21456 }
21457 // @api
21458 function updateBinaryExpression(node, left, operator, right) {
21459 return node.left !== left
21460 || node.operatorToken !== operator
21461 || node.right !== right
21462 ? update(createBinaryExpression(left, operator, right), node)
21463 : node;
21464 }
21465 // @api
21466 function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
21467 var node = createBaseExpression(214 /* ConditionalExpression */);
21468 node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
21469 node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
21470 node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
21471 node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
21472 node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
21473 node.transformFlags |=
21474 propagateChildFlags(node.condition) |
21475 propagateChildFlags(node.questionToken) |
21476 propagateChildFlags(node.whenTrue) |
21477 propagateChildFlags(node.colonToken) |
21478 propagateChildFlags(node.whenFalse);
21479 return node;
21480 }
21481 // @api
21482 function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
21483 return node.condition !== condition
21484 || node.questionToken !== questionToken
21485 || node.whenTrue !== whenTrue
21486 || node.colonToken !== colonToken
21487 || node.whenFalse !== whenFalse
21488 ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
21489 : node;
21490 }
21491 // @api
21492 function createTemplateExpression(head, templateSpans) {
21493 var node = createBaseExpression(215 /* TemplateExpression */);
21494 node.head = head;
21495 node.templateSpans = createNodeArray(templateSpans);
21496 node.transformFlags |=
21497 propagateChildFlags(node.head) |
21498 propagateChildrenFlags(node.templateSpans) |
21499 256 /* ContainsES2015 */;
21500 return node;
21501 }
21502 // @api
21503 function updateTemplateExpression(node, head, templateSpans) {
21504 return node.head !== head
21505 || node.templateSpans !== templateSpans
21506 ? update(createTemplateExpression(head, templateSpans), node)
21507 : node;
21508 }
21509 function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
21510 if (templateFlags === void 0) { templateFlags = 0 /* None */; }
21511 ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
21512 // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
21513 // eslint-disable-next-line no-undef-init
21514 var cooked = undefined;
21515 if (rawText !== undefined && rawText !== text) {
21516 cooked = getCookedText(kind, rawText);
21517 if (typeof cooked === "object") {
21518 return ts.Debug.fail("Invalid raw text");
21519 }
21520 }
21521 if (text === undefined) {
21522 if (cooked === undefined) {
21523 return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
21524 }
21525 text = cooked;
21526 }
21527 else if (cooked !== undefined) {
21528 ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
21529 }
21530 return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
21531 }
21532 // @api
21533 function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
21534 var node = createBaseToken(kind);
21535 node.text = text;
21536 node.rawText = rawText;
21537 node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
21538 node.transformFlags |= 256 /* ContainsES2015 */;
21539 if (node.templateFlags) {
21540 node.transformFlags |= 32 /* ContainsES2018 */;
21541 }
21542 return node;
21543 }
21544 // @api
21545 function createTemplateHead(text, rawText, templateFlags) {
21546 return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
21547 }
21548 // @api
21549 function createTemplateMiddle(text, rawText, templateFlags) {
21550 return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
21551 }
21552 // @api
21553 function createTemplateTail(text, rawText, templateFlags) {
21554 return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
21555 }
21556 // @api
21557 function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
21558 return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
21559 }
21560 // @api
21561 function createYieldExpression(asteriskToken, expression) {
21562 ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
21563 var node = createBaseExpression(216 /* YieldExpression */);
21564 node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
21565 node.asteriskToken = asteriskToken;
21566 node.transformFlags |=
21567 propagateChildFlags(node.expression) |
21568 propagateChildFlags(node.asteriskToken) |
21569 256 /* ContainsES2015 */ |
21570 32 /* ContainsES2018 */ |
21571 262144 /* ContainsYield */;
21572 return node;
21573 }
21574 // @api
21575 function updateYieldExpression(node, asteriskToken, expression) {
21576 return node.expression !== expression
21577 || node.asteriskToken !== asteriskToken
21578 ? update(createYieldExpression(asteriskToken, expression), node)
21579 : node;
21580 }
21581 // @api
21582 function createSpreadElement(expression) {
21583 var node = createBaseExpression(217 /* SpreadElement */);
21584 node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
21585 node.transformFlags |=
21586 propagateChildFlags(node.expression) |
21587 256 /* ContainsES2015 */ |
21588 8192 /* ContainsRestOrSpread */;
21589 return node;
21590 }
21591 // @api
21592 function updateSpreadElement(node, expression) {
21593 return node.expression !== expression
21594 ? update(createSpreadElement(expression), node)
21595 : node;
21596 }
21597 // @api
21598 function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
21599 var node = createBaseClassLikeDeclaration(218 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
21600 node.transformFlags |= 256 /* ContainsES2015 */;
21601 return node;
21602 }
21603 // @api
21604 function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
21605 return node.decorators !== decorators
21606 || node.modifiers !== modifiers
21607 || node.name !== name
21608 || node.typeParameters !== typeParameters
21609 || node.heritageClauses !== heritageClauses
21610 || node.members !== members
21611 ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
21612 : node;
21613 }
21614 // @api
21615 function createOmittedExpression() {
21616 return createBaseExpression(219 /* OmittedExpression */);
21617 }
21618 // @api
21619 function createExpressionWithTypeArguments(expression, typeArguments) {
21620 var node = createBaseNode(220 /* ExpressionWithTypeArguments */);
21621 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21622 node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
21623 node.transformFlags |=
21624 propagateChildFlags(node.expression) |
21625 propagateChildrenFlags(node.typeArguments) |
21626 256 /* ContainsES2015 */;
21627 return node;
21628 }
21629 // @api
21630 function updateExpressionWithTypeArguments(node, expression, typeArguments) {
21631 return node.expression !== expression
21632 || node.typeArguments !== typeArguments
21633 ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
21634 : node;
21635 }
21636 // @api
21637 function createAsExpression(expression, type) {
21638 var node = createBaseExpression(221 /* AsExpression */);
21639 node.expression = expression;
21640 node.type = type;
21641 node.transformFlags |=
21642 propagateChildFlags(node.expression) |
21643 propagateChildFlags(node.type) |
21644 1 /* ContainsTypeScript */;
21645 return node;
21646 }
21647 // @api
21648 function updateAsExpression(node, expression, type) {
21649 return node.expression !== expression
21650 || node.type !== type
21651 ? update(createAsExpression(expression, type), node)
21652 : node;
21653 }
21654 // @api
21655 function createNonNullExpression(expression) {
21656 var node = createBaseExpression(222 /* NonNullExpression */);
21657 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21658 node.transformFlags |=
21659 propagateChildFlags(node.expression) |
21660 1 /* ContainsTypeScript */;
21661 return node;
21662 }
21663 // @api
21664 function updateNonNullExpression(node, expression) {
21665 if (ts.isNonNullChain(node)) {
21666 return updateNonNullChain(node, expression);
21667 }
21668 return node.expression !== expression
21669 ? update(createNonNullExpression(expression), node)
21670 : node;
21671 }
21672 // @api
21673 function createNonNullChain(expression) {
21674 var node = createBaseExpression(222 /* NonNullExpression */);
21675 node.flags |= 32 /* OptionalChain */;
21676 node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21677 node.transformFlags |=
21678 propagateChildFlags(node.expression) |
21679 1 /* ContainsTypeScript */;
21680 return node;
21681 }
21682 // @api
21683 function updateNonNullChain(node, expression) {
21684 ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
21685 return node.expression !== expression
21686 ? update(createNonNullChain(expression), node)
21687 : node;
21688 }
21689 // @api
21690 function createMetaProperty(keywordToken, name) {
21691 var node = createBaseExpression(223 /* MetaProperty */);
21692 node.keywordToken = keywordToken;
21693 node.name = name;
21694 node.transformFlags |= propagateChildFlags(node.name);
21695 switch (keywordToken) {
21696 case 102 /* NewKeyword */:
21697 node.transformFlags |= 256 /* ContainsES2015 */;
21698 break;
21699 case 99 /* ImportKeyword */:
21700 node.transformFlags |= 4 /* ContainsESNext */;
21701 break;
21702 default:
21703 return ts.Debug.assertNever(keywordToken);
21704 }
21705 return node;
21706 }
21707 // @api
21708 function updateMetaProperty(node, name) {
21709 return node.name !== name
21710 ? update(createMetaProperty(node.keywordToken, name), node)
21711 : node;
21712 }
21713 //
21714 // Misc
21715 //
21716 // @api
21717 function createTemplateSpan(expression, literal) {
21718 var node = createBaseNode(225 /* TemplateSpan */);
21719 node.expression = expression;
21720 node.literal = literal;
21721 node.transformFlags |=
21722 propagateChildFlags(node.expression) |
21723 propagateChildFlags(node.literal) |
21724 256 /* ContainsES2015 */;
21725 return node;
21726 }
21727 // @api
21728 function updateTemplateSpan(node, expression, literal) {
21729 return node.expression !== expression
21730 || node.literal !== literal
21731 ? update(createTemplateSpan(expression, literal), node)
21732 : node;
21733 }
21734 // @api
21735 function createSemicolonClassElement() {
21736 var node = createBaseNode(226 /* SemicolonClassElement */);
21737 node.transformFlags |= 256 /* ContainsES2015 */;
21738 return node;
21739 }
21740 //
21741 // Element
21742 //
21743 // @api
21744 function createBlock(statements, multiLine) {
21745 var node = createBaseNode(227 /* Block */);
21746 node.statements = createNodeArray(statements);
21747 node.multiLine = multiLine;
21748 node.transformFlags |= propagateChildrenFlags(node.statements);
21749 return node;
21750 }
21751 // @api
21752 function updateBlock(node, statements) {
21753 return node.statements !== statements
21754 ? update(createBlock(statements, node.multiLine), node)
21755 : node;
21756 }
21757 // @api
21758 function createVariableStatement(modifiers, declarationList) {
21759 var node = createBaseDeclaration(229 /* VariableStatement */, /*decorators*/ undefined, modifiers);
21760 node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
21761 node.transformFlags |=
21762 propagateChildFlags(node.declarationList);
21763 if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
21764 node.transformFlags = 1 /* ContainsTypeScript */;
21765 }
21766 return node;
21767 }
21768 // @api
21769 function updateVariableStatement(node, modifiers, declarationList) {
21770 return node.modifiers !== modifiers
21771 || node.declarationList !== declarationList
21772 ? update(createVariableStatement(modifiers, declarationList), node)
21773 : node;
21774 }
21775 // @api
21776 function createEmptyStatement() {
21777 return createBaseNode(228 /* EmptyStatement */);
21778 }
21779 // @api
21780 function createExpressionStatement(expression) {
21781 var node = createBaseNode(230 /* ExpressionStatement */);
21782 node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
21783 node.transformFlags |= propagateChildFlags(node.expression);
21784 return node;
21785 }
21786 // @api
21787 function updateExpressionStatement(node, expression) {
21788 return node.expression !== expression
21789 ? update(createExpressionStatement(expression), node)
21790 : node;
21791 }
21792 // @api
21793 function createIfStatement(expression, thenStatement, elseStatement) {
21794 var node = createBaseNode(231 /* IfStatement */);
21795 node.expression = expression;
21796 node.thenStatement = asEmbeddedStatement(thenStatement);
21797 node.elseStatement = asEmbeddedStatement(elseStatement);
21798 node.transformFlags |=
21799 propagateChildFlags(node.expression) |
21800 propagateChildFlags(node.thenStatement) |
21801 propagateChildFlags(node.elseStatement);
21802 return node;
21803 }
21804 // @api
21805 function updateIfStatement(node, expression, thenStatement, elseStatement) {
21806 return node.expression !== expression
21807 || node.thenStatement !== thenStatement
21808 || node.elseStatement !== elseStatement
21809 ? update(createIfStatement(expression, thenStatement, elseStatement), node)
21810 : node;
21811 }
21812 // @api
21813 function createDoStatement(statement, expression) {
21814 var node = createBaseNode(232 /* DoStatement */);
21815 node.statement = asEmbeddedStatement(statement);
21816 node.expression = expression;
21817 node.transformFlags |=
21818 propagateChildFlags(node.statement) |
21819 propagateChildFlags(node.expression);
21820 return node;
21821 }
21822 // @api
21823 function updateDoStatement(node, statement, expression) {
21824 return node.statement !== statement
21825 || node.expression !== expression
21826 ? update(createDoStatement(statement, expression), node)
21827 : node;
21828 }
21829 // @api
21830 function createWhileStatement(expression, statement) {
21831 var node = createBaseNode(233 /* WhileStatement */);
21832 node.expression = expression;
21833 node.statement = asEmbeddedStatement(statement);
21834 node.transformFlags |=
21835 propagateChildFlags(node.expression) |
21836 propagateChildFlags(node.statement);
21837 return node;
21838 }
21839 // @api
21840 function updateWhileStatement(node, expression, statement) {
21841 return node.expression !== expression
21842 || node.statement !== statement
21843 ? update(createWhileStatement(expression, statement), node)
21844 : node;
21845 }
21846 // @api
21847 function createForStatement(initializer, condition, incrementor, statement) {
21848 var node = createBaseNode(234 /* ForStatement */);
21849 node.initializer = initializer;
21850 node.condition = condition;
21851 node.incrementor = incrementor;
21852 node.statement = asEmbeddedStatement(statement);
21853 node.transformFlags |=
21854 propagateChildFlags(node.initializer) |
21855 propagateChildFlags(node.condition) |
21856 propagateChildFlags(node.incrementor) |
21857 propagateChildFlags(node.statement);
21858 return node;
21859 }
21860 // @api
21861 function updateForStatement(node, initializer, condition, incrementor, statement) {
21862 return node.initializer !== initializer
21863 || node.condition !== condition
21864 || node.incrementor !== incrementor
21865 || node.statement !== statement
21866 ? update(createForStatement(initializer, condition, incrementor, statement), node)
21867 : node;
21868 }
21869 // @api
21870 function createForInStatement(initializer, expression, statement) {
21871 var node = createBaseNode(235 /* ForInStatement */);
21872 node.initializer = initializer;
21873 node.expression = expression;
21874 node.statement = asEmbeddedStatement(statement);
21875 node.transformFlags |=
21876 propagateChildFlags(node.initializer) |
21877 propagateChildFlags(node.expression) |
21878 propagateChildFlags(node.statement);
21879 return node;
21880 }
21881 // @api
21882 function updateForInStatement(node, initializer, expression, statement) {
21883 return node.initializer !== initializer
21884 || node.expression !== expression
21885 || node.statement !== statement
21886 ? update(createForInStatement(initializer, expression, statement), node)
21887 : node;
21888 }
21889 // @api
21890 function createForOfStatement(awaitModifier, initializer, expression, statement) {
21891 var node = createBaseNode(236 /* ForOfStatement */);
21892 node.awaitModifier = awaitModifier;
21893 node.initializer = initializer;
21894 node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
21895 node.statement = asEmbeddedStatement(statement);
21896 node.transformFlags |=
21897 propagateChildFlags(node.awaitModifier) |
21898 propagateChildFlags(node.initializer) |
21899 propagateChildFlags(node.expression) |
21900 propagateChildFlags(node.statement) |
21901 256 /* ContainsES2015 */;
21902 if (awaitModifier)
21903 node.transformFlags |= 32 /* ContainsES2018 */;
21904 return node;
21905 }
21906 // @api
21907 function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
21908 return node.awaitModifier !== awaitModifier
21909 || node.initializer !== initializer
21910 || node.expression !== expression
21911 || node.statement !== statement
21912 ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
21913 : node;
21914 }
21915 // @api
21916 function createContinueStatement(label) {
21917 var node = createBaseNode(237 /* ContinueStatement */);
21918 node.label = asName(label);
21919 node.transformFlags |=
21920 propagateChildFlags(node.label) |
21921 1048576 /* ContainsHoistedDeclarationOrCompletion */;
21922 return node;
21923 }
21924 // @api
21925 function updateContinueStatement(node, label) {
21926 return node.label !== label
21927 ? update(createContinueStatement(label), node)
21928 : node;
21929 }
21930 // @api
21931 function createBreakStatement(label) {
21932 var node = createBaseNode(238 /* BreakStatement */);
21933 node.label = asName(label);
21934 node.transformFlags |=
21935 propagateChildFlags(node.label) |
21936 1048576 /* ContainsHoistedDeclarationOrCompletion */;
21937 return node;
21938 }
21939 // @api
21940 function updateBreakStatement(node, label) {
21941 return node.label !== label
21942 ? update(createBreakStatement(label), node)
21943 : node;
21944 }
21945 // @api
21946 function createReturnStatement(expression) {
21947 var node = createBaseNode(239 /* ReturnStatement */);
21948 node.expression = expression;
21949 // return in an ES2018 async generator must be awaited
21950 node.transformFlags |=
21951 propagateChildFlags(node.expression) |
21952 32 /* ContainsES2018 */ |
21953 1048576 /* ContainsHoistedDeclarationOrCompletion */;
21954 return node;
21955 }
21956 // @api
21957 function updateReturnStatement(node, expression) {
21958 return node.expression !== expression
21959 ? update(createReturnStatement(expression), node)
21960 : node;
21961 }
21962 // @api
21963 function createWithStatement(expression, statement) {
21964 var node = createBaseNode(240 /* WithStatement */);
21965 node.expression = expression;
21966 node.statement = asEmbeddedStatement(statement);
21967 node.transformFlags |=
21968 propagateChildFlags(node.expression) |
21969 propagateChildFlags(node.statement);
21970 return node;
21971 }
21972 // @api
21973 function updateWithStatement(node, expression, statement) {
21974 return node.expression !== expression
21975 || node.statement !== statement
21976 ? update(createWithStatement(expression, statement), node)
21977 : node;
21978 }
21979 // @api
21980 function createSwitchStatement(expression, caseBlock) {
21981 var node = createBaseNode(241 /* SwitchStatement */);
21982 node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
21983 node.caseBlock = caseBlock;
21984 node.transformFlags |=
21985 propagateChildFlags(node.expression) |
21986 propagateChildFlags(node.caseBlock);
21987 return node;
21988 }
21989 // @api
21990 function updateSwitchStatement(node, expression, caseBlock) {
21991 return node.expression !== expression
21992 || node.caseBlock !== caseBlock
21993 ? update(createSwitchStatement(expression, caseBlock), node)
21994 : node;
21995 }
21996 // @api
21997 function createLabeledStatement(label, statement) {
21998 var node = createBaseNode(242 /* LabeledStatement */);
21999 node.label = asName(label);
22000 node.statement = asEmbeddedStatement(statement);
22001 node.transformFlags |=
22002 propagateChildFlags(node.label) |
22003 propagateChildFlags(node.statement);
22004 return node;
22005 }
22006 // @api
22007 function updateLabeledStatement(node, label, statement) {
22008 return node.label !== label
22009 || node.statement !== statement
22010 ? update(createLabeledStatement(label, statement), node)
22011 : node;
22012 }
22013 // @api
22014 function createThrowStatement(expression) {
22015 var node = createBaseNode(243 /* ThrowStatement */);
22016 node.expression = expression;
22017 node.transformFlags |= propagateChildFlags(node.expression);
22018 return node;
22019 }
22020 // @api
22021 function updateThrowStatement(node, expression) {
22022 return node.expression !== expression
22023 ? update(createThrowStatement(expression), node)
22024 : node;
22025 }
22026 // @api
22027 function createTryStatement(tryBlock, catchClause, finallyBlock) {
22028 var node = createBaseNode(244 /* TryStatement */);
22029 node.tryBlock = tryBlock;
22030 node.catchClause = catchClause;
22031 node.finallyBlock = finallyBlock;
22032 node.transformFlags |=
22033 propagateChildFlags(node.tryBlock) |
22034 propagateChildFlags(node.catchClause) |
22035 propagateChildFlags(node.finallyBlock);
22036 return node;
22037 }
22038 // @api
22039 function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
22040 return node.tryBlock !== tryBlock
22041 || node.catchClause !== catchClause
22042 || node.finallyBlock !== finallyBlock
22043 ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
22044 : node;
22045 }
22046 // @api
22047 function createDebuggerStatement() {
22048 return createBaseNode(245 /* DebuggerStatement */);
22049 }
22050 // @api
22051 function createVariableDeclaration(name, exclamationToken, type, initializer) {
22052 var node = createBaseVariableLikeDeclaration(246 /* VariableDeclaration */,
22053 /*decorators*/ undefined,
22054 /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
22055 node.exclamationToken = exclamationToken;
22056 node.transformFlags |= propagateChildFlags(node.exclamationToken);
22057 if (exclamationToken) {
22058 node.transformFlags |= 1 /* ContainsTypeScript */;
22059 }
22060 return node;
22061 }
22062 // @api
22063 function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
22064 return node.name !== name
22065 || node.type !== type
22066 || node.exclamationToken !== exclamationToken
22067 || node.initializer !== initializer
22068 ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
22069 : node;
22070 }
22071 // @api
22072 function createVariableDeclarationList(declarations, flags) {
22073 if (flags === void 0) { flags = 0 /* None */; }
22074 var node = createBaseNode(247 /* VariableDeclarationList */);
22075 node.flags |= flags & 3 /* BlockScoped */;
22076 node.declarations = createNodeArray(declarations);
22077 node.transformFlags |=
22078 propagateChildrenFlags(node.declarations) |
22079 1048576 /* ContainsHoistedDeclarationOrCompletion */;
22080 if (flags & 3 /* BlockScoped */) {
22081 node.transformFlags |=
22082 256 /* ContainsES2015 */ |
22083 65536 /* ContainsBlockScopedBinding */;
22084 }
22085 return node;
22086 }
22087 // @api
22088 function updateVariableDeclarationList(node, declarations) {
22089 return node.declarations !== declarations
22090 ? update(createVariableDeclarationList(declarations, node.flags), node)
22091 : node;
22092 }
22093 // @api
22094 function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22095 var node = createBaseFunctionLikeDeclaration(248 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
22096 node.asteriskToken = asteriskToken;
22097 if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22098 node.transformFlags = 1 /* ContainsTypeScript */;
22099 }
22100 else {
22101 node.transformFlags |=
22102 propagateChildFlags(node.asteriskToken) |
22103 1048576 /* ContainsHoistedDeclarationOrCompletion */;
22104 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22105 if (node.asteriskToken) {
22106 node.transformFlags |= 32 /* ContainsES2018 */;
22107 }
22108 else {
22109 node.transformFlags |= 64 /* ContainsES2017 */;
22110 }
22111 }
22112 else if (node.asteriskToken) {
22113 node.transformFlags |= 512 /* ContainsGenerator */;
22114 }
22115 }
22116 return node;
22117 }
22118 // @api
22119 function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22120 return node.decorators !== decorators
22121 || node.modifiers !== modifiers
22122 || node.asteriskToken !== asteriskToken
22123 || node.name !== name
22124 || node.typeParameters !== typeParameters
22125 || node.parameters !== parameters
22126 || node.type !== type
22127 || node.body !== body
22128 ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22129 : node;
22130 }
22131 // @api
22132 function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22133 var node = createBaseClassLikeDeclaration(249 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22134 if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22135 node.transformFlags = 1 /* ContainsTypeScript */;
22136 }
22137 else {
22138 node.transformFlags |= 256 /* ContainsES2015 */;
22139 if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) {
22140 node.transformFlags |= 1 /* ContainsTypeScript */;
22141 }
22142 }
22143 return node;
22144 }
22145 // @api
22146 function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22147 return node.decorators !== decorators
22148 || node.modifiers !== modifiers
22149 || node.name !== name
22150 || node.typeParameters !== typeParameters
22151 || node.heritageClauses !== heritageClauses
22152 || node.members !== members
22153 ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22154 : node;
22155 }
22156 // @api
22157 function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22158 var node = createBaseInterfaceOrClassLikeDeclaration(250 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
22159 node.members = createNodeArray(members);
22160 node.transformFlags = 1 /* ContainsTypeScript */;
22161 return node;
22162 }
22163 // @api
22164 function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22165 return node.decorators !== decorators
22166 || node.modifiers !== modifiers
22167 || node.name !== name
22168 || node.typeParameters !== typeParameters
22169 || node.heritageClauses !== heritageClauses
22170 || node.members !== members
22171 ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22172 : node;
22173 }
22174 // @api
22175 function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
22176 var node = createBaseGenericNamedDeclaration(251 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
22177 node.type = type;
22178 node.transformFlags = 1 /* ContainsTypeScript */;
22179 return node;
22180 }
22181 // @api
22182 function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
22183 return node.decorators !== decorators
22184 || node.modifiers !== modifiers
22185 || node.name !== name
22186 || node.typeParameters !== typeParameters
22187 || node.type !== type
22188 ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
22189 : node;
22190 }
22191 // @api
22192 function createEnumDeclaration(decorators, modifiers, name, members) {
22193 var node = createBaseNamedDeclaration(252 /* EnumDeclaration */, decorators, modifiers, name);
22194 node.members = createNodeArray(members);
22195 node.transformFlags |=
22196 propagateChildrenFlags(node.members) |
22197 1 /* ContainsTypeScript */;
22198 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
22199 return node;
22200 }
22201 // @api
22202 function updateEnumDeclaration(node, decorators, modifiers, name, members) {
22203 return node.decorators !== decorators
22204 || node.modifiers !== modifiers
22205 || node.name !== name
22206 || node.members !== members
22207 ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
22208 : node;
22209 }
22210 // @api
22211 function createModuleDeclaration(decorators, modifiers, name, body, flags) {
22212 if (flags === void 0) { flags = 0 /* None */; }
22213 var node = createBaseDeclaration(253 /* ModuleDeclaration */, decorators, modifiers);
22214 node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
22215 node.name = name;
22216 node.body = body;
22217 if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22218 node.transformFlags = 1 /* ContainsTypeScript */;
22219 }
22220 else {
22221 node.transformFlags |=
22222 propagateChildFlags(node.name) |
22223 propagateChildFlags(node.body) |
22224 1 /* ContainsTypeScript */;
22225 }
22226 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
22227 return node;
22228 }
22229 // @api
22230 function updateModuleDeclaration(node, decorators, modifiers, name, body) {
22231 return node.decorators !== decorators
22232 || node.modifiers !== modifiers
22233 || node.name !== name
22234 || node.body !== body
22235 ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
22236 : node;
22237 }
22238 // @api
22239 function createModuleBlock(statements) {
22240 var node = createBaseNode(254 /* ModuleBlock */);
22241 node.statements = createNodeArray(statements);
22242 node.transformFlags |= propagateChildrenFlags(node.statements);
22243 return node;
22244 }
22245 // @api
22246 function updateModuleBlock(node, statements) {
22247 return node.statements !== statements
22248 ? update(createModuleBlock(statements), node)
22249 : node;
22250 }
22251 // @api
22252 function createCaseBlock(clauses) {
22253 var node = createBaseNode(255 /* CaseBlock */);
22254 node.clauses = createNodeArray(clauses);
22255 node.transformFlags |= propagateChildrenFlags(node.clauses);
22256 return node;
22257 }
22258 // @api
22259 function updateCaseBlock(node, clauses) {
22260 return node.clauses !== clauses
22261 ? update(createCaseBlock(clauses), node)
22262 : node;
22263 }
22264 // @api
22265 function createNamespaceExportDeclaration(name) {
22266 var node = createBaseNamedDeclaration(256 /* NamespaceExportDeclaration */,
22267 /*decorators*/ undefined,
22268 /*modifiers*/ undefined, name);
22269 node.transformFlags = 1 /* ContainsTypeScript */;
22270 return node;
22271 }
22272 // @api
22273 function updateNamespaceExportDeclaration(node, name) {
22274 return node.name !== name
22275 ? update(createNamespaceExportDeclaration(name), node)
22276 : node;
22277 }
22278 // @api
22279 function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
22280 var node = createBaseNamedDeclaration(257 /* ImportEqualsDeclaration */, decorators, modifiers, name);
22281 node.moduleReference = moduleReference;
22282 node.transformFlags |= propagateChildFlags(node.moduleReference);
22283 if (!ts.isExternalModuleReference(node.moduleReference))
22284 node.transformFlags |= 1 /* ContainsTypeScript */;
22285 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
22286 return node;
22287 }
22288 // @api
22289 function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
22290 return node.decorators !== decorators
22291 || node.modifiers !== modifiers
22292 || node.name !== name
22293 || node.moduleReference !== moduleReference
22294 ? update(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
22295 : node;
22296 }
22297 // @api
22298 function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
22299 var node = createBaseDeclaration(258 /* ImportDeclaration */, decorators, modifiers);
22300 node.importClause = importClause;
22301 node.moduleSpecifier = moduleSpecifier;
22302 node.transformFlags |=
22303 propagateChildFlags(node.importClause) |
22304 propagateChildFlags(node.moduleSpecifier);
22305 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22306 return node;
22307 }
22308 // @api
22309 function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
22310 return node.decorators !== decorators
22311 || node.modifiers !== modifiers
22312 || node.importClause !== importClause
22313 || node.moduleSpecifier !== moduleSpecifier
22314 ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
22315 : node;
22316 }
22317 // @api
22318 function createImportClause(isTypeOnly, name, namedBindings) {
22319 var node = createBaseNode(259 /* ImportClause */);
22320 node.isTypeOnly = isTypeOnly;
22321 node.name = name;
22322 node.namedBindings = namedBindings;
22323 node.transformFlags |=
22324 propagateChildFlags(node.name) |
22325 propagateChildFlags(node.namedBindings);
22326 if (isTypeOnly) {
22327 node.transformFlags |= 1 /* ContainsTypeScript */;
22328 }
22329 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22330 return node;
22331 }
22332 // @api
22333 function updateImportClause(node, isTypeOnly, name, namedBindings) {
22334 return node.isTypeOnly !== isTypeOnly
22335 || node.name !== name
22336 || node.namedBindings !== namedBindings
22337 ? update(createImportClause(isTypeOnly, name, namedBindings), node)
22338 : node;
22339 }
22340 // @api
22341 function createNamespaceImport(name) {
22342 var node = createBaseNode(260 /* NamespaceImport */);
22343 node.name = name;
22344 node.transformFlags |= propagateChildFlags(node.name);
22345 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22346 return node;
22347 }
22348 // @api
22349 function updateNamespaceImport(node, name) {
22350 return node.name !== name
22351 ? update(createNamespaceImport(name), node)
22352 : node;
22353 }
22354 // @api
22355 function createNamespaceExport(name) {
22356 var node = createBaseNode(266 /* NamespaceExport */);
22357 node.name = name;
22358 node.transformFlags |=
22359 propagateChildFlags(node.name) |
22360 4 /* ContainsESNext */;
22361 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22362 return node;
22363 }
22364 // @api
22365 function updateNamespaceExport(node, name) {
22366 return node.name !== name
22367 ? update(createNamespaceExport(name), node)
22368 : node;
22369 }
22370 // @api
22371 function createNamedImports(elements) {
22372 var node = createBaseNode(261 /* NamedImports */);
22373 node.elements = createNodeArray(elements);
22374 node.transformFlags |= propagateChildrenFlags(node.elements);
22375 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22376 return node;
22377 }
22378 // @api
22379 function updateNamedImports(node, elements) {
22380 return node.elements !== elements
22381 ? update(createNamedImports(elements), node)
22382 : node;
22383 }
22384 // @api
22385 function createImportSpecifier(propertyName, name) {
22386 var node = createBaseNode(262 /* ImportSpecifier */);
22387 node.propertyName = propertyName;
22388 node.name = name;
22389 node.transformFlags |=
22390 propagateChildFlags(node.propertyName) |
22391 propagateChildFlags(node.name);
22392 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22393 return node;
22394 }
22395 // @api
22396 function updateImportSpecifier(node, propertyName, name) {
22397 return node.propertyName !== propertyName
22398 || node.name !== name
22399 ? update(createImportSpecifier(propertyName, name), node)
22400 : node;
22401 }
22402 // @api
22403 function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
22404 var node = createBaseDeclaration(263 /* ExportAssignment */, decorators, modifiers);
22405 node.isExportEquals = isExportEquals;
22406 node.expression = isExportEquals
22407 ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression)
22408 : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
22409 node.transformFlags |= propagateChildFlags(node.expression);
22410 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22411 return node;
22412 }
22413 // @api
22414 function updateExportAssignment(node, decorators, modifiers, expression) {
22415 return node.decorators !== decorators
22416 || node.modifiers !== modifiers
22417 || node.expression !== expression
22418 ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
22419 : node;
22420 }
22421 // @api
22422 function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
22423 var node = createBaseDeclaration(264 /* ExportDeclaration */, decorators, modifiers);
22424 node.isTypeOnly = isTypeOnly;
22425 node.exportClause = exportClause;
22426 node.moduleSpecifier = moduleSpecifier;
22427 node.transformFlags |=
22428 propagateChildFlags(node.exportClause) |
22429 propagateChildFlags(node.moduleSpecifier);
22430 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22431 return node;
22432 }
22433 // @api
22434 function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
22435 return node.decorators !== decorators
22436 || node.modifiers !== modifiers
22437 || node.isTypeOnly !== isTypeOnly
22438 || node.exportClause !== exportClause
22439 || node.moduleSpecifier !== moduleSpecifier
22440 ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier), node)
22441 : node;
22442 }
22443 // @api
22444 function createNamedExports(elements) {
22445 var node = createBaseNode(265 /* NamedExports */);
22446 node.elements = createNodeArray(elements);
22447 node.transformFlags |= propagateChildrenFlags(node.elements);
22448 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22449 return node;
22450 }
22451 // @api
22452 function updateNamedExports(node, elements) {
22453 return node.elements !== elements
22454 ? update(createNamedExports(elements), node)
22455 : node;
22456 }
22457 // @api
22458 function createExportSpecifier(propertyName, name) {
22459 var node = createBaseNode(267 /* ExportSpecifier */);
22460 node.propertyName = asName(propertyName);
22461 node.name = asName(name);
22462 node.transformFlags |=
22463 propagateChildFlags(node.propertyName) |
22464 propagateChildFlags(node.name);
22465 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22466 return node;
22467 }
22468 // @api
22469 function updateExportSpecifier(node, propertyName, name) {
22470 return node.propertyName !== propertyName
22471 || node.name !== name
22472 ? update(createExportSpecifier(propertyName, name), node)
22473 : node;
22474 }
22475 // @api
22476 function createMissingDeclaration() {
22477 var node = createBaseDeclaration(268 /* MissingDeclaration */,
22478 /*decorators*/ undefined,
22479 /*modifiers*/ undefined);
22480 return node;
22481 }
22482 //
22483 // Module references
22484 //
22485 // @api
22486 function createExternalModuleReference(expression) {
22487 var node = createBaseNode(269 /* ExternalModuleReference */);
22488 node.expression = expression;
22489 node.transformFlags |= propagateChildFlags(node.expression);
22490 node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
22491 return node;
22492 }
22493 // @api
22494 function updateExternalModuleReference(node, expression) {
22495 return node.expression !== expression
22496 ? update(createExternalModuleReference(expression), node)
22497 : node;
22498 }
22499 //
22500 // JSDoc
22501 //
22502 // @api
22503 // createJSDocAllType
22504 // createJSDocUnknownType
22505 function createJSDocPrimaryTypeWorker(kind) {
22506 return createBaseNode(kind);
22507 }
22508 // @api
22509 // createJSDocNonNullableType
22510 // createJSDocNullableType
22511 // createJSDocOptionalType
22512 // createJSDocVariadicType
22513 // createJSDocNamepathType
22514 function createJSDocUnaryTypeWorker(kind, type) {
22515 var node = createBaseNode(kind);
22516 node.type = type;
22517 return node;
22518 }
22519 // @api
22520 // updateJSDocNonNullableType
22521 // updateJSDocNullableType
22522 // updateJSDocOptionalType
22523 // updateJSDocVariadicType
22524 // updateJSDocNamepathType
22525 function updateJSDocUnaryTypeWorker(kind, node, type) {
22526 return node.type !== type
22527 ? update(createJSDocUnaryTypeWorker(kind, type), node)
22528 : node;
22529 }
22530 // @api
22531 function createJSDocFunctionType(parameters, type) {
22532 var node = createBaseSignatureDeclaration(304 /* JSDocFunctionType */,
22533 /*decorators*/ undefined,
22534 /*modifiers*/ undefined,
22535 /*name*/ undefined,
22536 /*typeParameters*/ undefined, parameters, type);
22537 return node;
22538 }
22539 // @api
22540 function updateJSDocFunctionType(node, parameters, type) {
22541 return node.parameters !== parameters
22542 || node.type !== type
22543 ? update(createJSDocFunctionType(parameters, type), node)
22544 : node;
22545 }
22546 // @api
22547 function createJSDocTypeLiteral(propertyTags, isArrayType) {
22548 if (isArrayType === void 0) { isArrayType = false; }
22549 var node = createBaseNode(308 /* JSDocTypeLiteral */);
22550 node.jsDocPropertyTags = asNodeArray(propertyTags);
22551 node.isArrayType = isArrayType;
22552 return node;
22553 }
22554 // @api
22555 function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
22556 return node.jsDocPropertyTags !== propertyTags
22557 || node.isArrayType !== isArrayType
22558 ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
22559 : node;
22560 }
22561 // @api
22562 function createJSDocTypeExpression(type) {
22563 var node = createBaseNode(298 /* JSDocTypeExpression */);
22564 node.type = type;
22565 return node;
22566 }
22567 // @api
22568 function updateJSDocTypeExpression(node, type) {
22569 return node.type !== type
22570 ? update(createJSDocTypeExpression(type), node)
22571 : node;
22572 }
22573 // @api
22574 function createJSDocSignature(typeParameters, parameters, type) {
22575 var node = createBaseNode(309 /* JSDocSignature */);
22576 node.typeParameters = asNodeArray(typeParameters);
22577 node.parameters = createNodeArray(parameters);
22578 node.type = type;
22579 return node;
22580 }
22581 // @api
22582 function updateJSDocSignature(node, typeParameters, parameters, type) {
22583 return node.typeParameters !== typeParameters
22584 || node.parameters !== parameters
22585 || node.type !== type
22586 ? update(createJSDocSignature(typeParameters, parameters, type), node)
22587 : node;
22588 }
22589 function getDefaultTagName(node) {
22590 var defaultTagName = getDefaultTagNameForKind(node.kind);
22591 return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
22592 ? node.tagName
22593 : createIdentifier(defaultTagName);
22594 }
22595 // @api
22596 function createBaseJSDocTag(kind, tagName, comment) {
22597 var node = createBaseNode(kind);
22598 node.tagName = tagName;
22599 node.comment = comment;
22600 return node;
22601 }
22602 // @api
22603 function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
22604 var node = createBaseJSDocTag(326 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
22605 node.constraint = constraint;
22606 node.typeParameters = createNodeArray(typeParameters);
22607 return node;
22608 }
22609 // @api
22610 function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
22611 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22612 return node.tagName !== tagName
22613 || node.constraint !== constraint
22614 || node.typeParameters !== typeParameters
22615 || node.comment !== comment
22616 ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
22617 : node;
22618 }
22619 // @api
22620 function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
22621 var node = createBaseJSDocTag(327 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
22622 node.typeExpression = typeExpression;
22623 node.fullName = fullName;
22624 node.name = ts.getJSDocTypeAliasName(fullName);
22625 return node;
22626 }
22627 // @api
22628 function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
22629 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22630 return node.tagName !== tagName
22631 || node.typeExpression !== typeExpression
22632 || node.fullName !== fullName
22633 || node.comment !== comment
22634 ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
22635 : node;
22636 }
22637 // @api
22638 function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
22639 var node = createBaseJSDocTag(322 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
22640 node.typeExpression = typeExpression;
22641 node.name = name;
22642 node.isNameFirst = !!isNameFirst;
22643 node.isBracketed = isBracketed;
22644 return node;
22645 }
22646 // @api
22647 function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
22648 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22649 return node.tagName !== tagName
22650 || node.name !== name
22651 || node.isBracketed !== isBracketed
22652 || node.typeExpression !== typeExpression
22653 || node.isNameFirst !== isNameFirst
22654 || node.comment !== comment
22655 ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
22656 : node;
22657 }
22658 // @api
22659 function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
22660 var node = createBaseJSDocTag(328 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
22661 node.typeExpression = typeExpression;
22662 node.name = name;
22663 node.isNameFirst = !!isNameFirst;
22664 node.isBracketed = isBracketed;
22665 return node;
22666 }
22667 // @api
22668 function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
22669 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22670 return node.tagName !== tagName
22671 || node.name !== name
22672 || node.isBracketed !== isBracketed
22673 || node.typeExpression !== typeExpression
22674 || node.isNameFirst !== isNameFirst
22675 || node.comment !== comment
22676 ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
22677 : node;
22678 }
22679 // @api
22680 function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
22681 var node = createBaseJSDocTag(320 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
22682 node.typeExpression = typeExpression;
22683 node.fullName = fullName;
22684 node.name = ts.getJSDocTypeAliasName(fullName);
22685 return node;
22686 }
22687 // @api
22688 function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
22689 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22690 return node.tagName !== tagName
22691 || node.typeExpression !== typeExpression
22692 || node.fullName !== fullName
22693 || node.comment !== comment
22694 ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
22695 : node;
22696 }
22697 // @api
22698 function createJSDocAugmentsTag(tagName, className, comment) {
22699 var node = createBaseJSDocTag(311 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
22700 node.class = className;
22701 return node;
22702 }
22703 // @api
22704 function updateJSDocAugmentsTag(node, tagName, className, comment) {
22705 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22706 return node.tagName !== tagName
22707 || node.class !== className
22708 || node.comment !== comment
22709 ? update(createJSDocAugmentsTag(tagName, className, comment), node)
22710 : node;
22711 }
22712 // @api
22713 function createJSDocImplementsTag(tagName, className, comment) {
22714 var node = createBaseJSDocTag(312 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
22715 node.class = className;
22716 return node;
22717 }
22718 // @api
22719 function updateJSDocImplementsTag(node, tagName, className, comment) {
22720 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22721 return node.tagName !== tagName
22722 || node.class !== className
22723 || node.comment !== comment
22724 ? update(createJSDocImplementsTag(tagName, className, comment), node)
22725 : node;
22726 }
22727 // @api
22728 // createJSDocAuthorTag
22729 // createJSDocClassTag
22730 // createJSDocPublicTag
22731 // createJSDocPrivateTag
22732 // createJSDocProtectedTag
22733 // createJSDocReadonlyTag
22734 // createJSDocDeprecatedTag
22735 function createJSDocSimpleTagWorker(kind, tagName, comment) {
22736 var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
22737 return node;
22738 }
22739 // @api
22740 // updateJSDocAuthorTag
22741 // updateJSDocClassTag
22742 // updateJSDocPublicTag
22743 // updateJSDocPrivateTag
22744 // updateJSDocProtectedTag
22745 // updateJSDocReadonlyTag
22746 // updateJSDocDeprecatedTag
22747 function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
22748 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22749 return node.tagName !== tagName
22750 || node.comment !== comment
22751 ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
22752 node;
22753 }
22754 // @api
22755 // createJSDocTypeTag
22756 // createJSDocReturnTag
22757 // createJSDocThisTag
22758 // createJSDocEnumTag
22759 function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
22760 var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
22761 node.typeExpression = typeExpression;
22762 return node;
22763 }
22764 // @api
22765 // updateJSDocTypeTag
22766 // updateJSDocReturnTag
22767 // updateJSDocThisTag
22768 // updateJSDocEnumTag
22769 function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
22770 if (tagName === void 0) { tagName = getDefaultTagName(node); }
22771 return node.tagName !== tagName
22772 || node.typeExpression !== typeExpression
22773 || node.comment !== comment
22774 ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
22775 : node;
22776 }
22777 // @api
22778 function createJSDocUnknownTag(tagName, comment) {
22779 var node = createBaseJSDocTag(310 /* JSDocTag */, tagName, comment);
22780 return node;
22781 }
22782 // @api
22783 function updateJSDocUnknownTag(node, tagName, comment) {
22784 return node.tagName !== tagName
22785 || node.comment !== comment
22786 ? update(createJSDocUnknownTag(tagName, comment), node)
22787 : node;
22788 }
22789 // @api
22790 function createJSDocComment(comment, tags) {
22791 var node = createBaseNode(307 /* JSDocComment */);
22792 node.comment = comment;
22793 node.tags = asNodeArray(tags);
22794 return node;
22795 }
22796 // @api
22797 function updateJSDocComment(node, comment, tags) {
22798 return node.comment !== comment
22799 || node.tags !== tags
22800 ? update(createJSDocComment(comment, tags), node)
22801 : node;
22802 }
22803 //
22804 // JSX
22805 //
22806 // @api
22807 function createJsxElement(openingElement, children, closingElement) {
22808 var node = createBaseNode(270 /* JsxElement */);
22809 node.openingElement = openingElement;
22810 node.children = createNodeArray(children);
22811 node.closingElement = closingElement;
22812 node.transformFlags |=
22813 propagateChildFlags(node.openingElement) |
22814 propagateChildrenFlags(node.children) |
22815 propagateChildFlags(node.closingElement) |
22816 2 /* ContainsJsx */;
22817 return node;
22818 }
22819 // @api
22820 function updateJsxElement(node, openingElement, children, closingElement) {
22821 return node.openingElement !== openingElement
22822 || node.children !== children
22823 || node.closingElement !== closingElement
22824 ? update(createJsxElement(openingElement, children, closingElement), node)
22825 : node;
22826 }
22827 // @api
22828 function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
22829 var node = createBaseNode(271 /* JsxSelfClosingElement */);
22830 node.tagName = tagName;
22831 node.typeArguments = asNodeArray(typeArguments);
22832 node.attributes = attributes;
22833 node.transformFlags |=
22834 propagateChildFlags(node.tagName) |
22835 propagateChildrenFlags(node.typeArguments) |
22836 propagateChildFlags(node.attributes) |
22837 2 /* ContainsJsx */;
22838 if (node.typeArguments) {
22839 node.transformFlags |= 1 /* ContainsTypeScript */;
22840 }
22841 return node;
22842 }
22843 // @api
22844 function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
22845 return node.tagName !== tagName
22846 || node.typeArguments !== typeArguments
22847 || node.attributes !== attributes
22848 ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
22849 : node;
22850 }
22851 // @api
22852 function createJsxOpeningElement(tagName, typeArguments, attributes) {
22853 var node = createBaseNode(272 /* JsxOpeningElement */);
22854 node.tagName = tagName;
22855 node.typeArguments = asNodeArray(typeArguments);
22856 node.attributes = attributes;
22857 node.transformFlags |=
22858 propagateChildFlags(node.tagName) |
22859 propagateChildrenFlags(node.typeArguments) |
22860 propagateChildFlags(node.attributes) |
22861 2 /* ContainsJsx */;
22862 if (typeArguments) {
22863 node.transformFlags |= 1 /* ContainsTypeScript */;
22864 }
22865 return node;
22866 }
22867 // @api
22868 function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
22869 return node.tagName !== tagName
22870 || node.typeArguments !== typeArguments
22871 || node.attributes !== attributes
22872 ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
22873 : node;
22874 }
22875 // @api
22876 function createJsxClosingElement(tagName) {
22877 var node = createBaseNode(273 /* JsxClosingElement */);
22878 node.tagName = tagName;
22879 node.transformFlags |=
22880 propagateChildFlags(node.tagName) |
22881 2 /* ContainsJsx */;
22882 return node;
22883 }
22884 // @api
22885 function updateJsxClosingElement(node, tagName) {
22886 return node.tagName !== tagName
22887 ? update(createJsxClosingElement(tagName), node)
22888 : node;
22889 }
22890 // @api
22891 function createJsxFragment(openingFragment, children, closingFragment) {
22892 var node = createBaseNode(274 /* JsxFragment */);
22893 node.openingFragment = openingFragment;
22894 node.children = createNodeArray(children);
22895 node.closingFragment = closingFragment;
22896 node.transformFlags |=
22897 propagateChildFlags(node.openingFragment) |
22898 propagateChildrenFlags(node.children) |
22899 propagateChildFlags(node.closingFragment) |
22900 2 /* ContainsJsx */;
22901 return node;
22902 }
22903 // @api
22904 function updateJsxFragment(node, openingFragment, children, closingFragment) {
22905 return node.openingFragment !== openingFragment
22906 || node.children !== children
22907 || node.closingFragment !== closingFragment
22908 ? update(createJsxFragment(openingFragment, children, closingFragment), node)
22909 : node;
22910 }
22911 // @api
22912 function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
22913 var node = createBaseNode(11 /* JsxText */);
22914 node.text = text;
22915 node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
22916 node.transformFlags |= 2 /* ContainsJsx */;
22917 return node;
22918 }
22919 // @api
22920 function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
22921 return node.text !== text
22922 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
22923 ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
22924 : node;
22925 }
22926 // @api
22927 function createJsxOpeningFragment() {
22928 var node = createBaseNode(275 /* JsxOpeningFragment */);
22929 node.transformFlags |= 2 /* ContainsJsx */;
22930 return node;
22931 }
22932 // @api
22933 function createJsxJsxClosingFragment() {
22934 var node = createBaseNode(276 /* JsxClosingFragment */);
22935 node.transformFlags |= 2 /* ContainsJsx */;
22936 return node;
22937 }
22938 // @api
22939 function createJsxAttribute(name, initializer) {
22940 var node = createBaseNode(277 /* JsxAttribute */);
22941 node.name = name;
22942 node.initializer = initializer;
22943 node.transformFlags |=
22944 propagateChildFlags(node.name) |
22945 propagateChildFlags(node.initializer) |
22946 2 /* ContainsJsx */;
22947 return node;
22948 }
22949 // @api
22950 function updateJsxAttribute(node, name, initializer) {
22951 return node.name !== name
22952 || node.initializer !== initializer
22953 ? update(createJsxAttribute(name, initializer), node)
22954 : node;
22955 }
22956 // @api
22957 function createJsxAttributes(properties) {
22958 var node = createBaseNode(278 /* JsxAttributes */);
22959 node.properties = createNodeArray(properties);
22960 node.transformFlags |=
22961 propagateChildrenFlags(node.properties) |
22962 2 /* ContainsJsx */;
22963 return node;
22964 }
22965 // @api
22966 function updateJsxAttributes(node, properties) {
22967 return node.properties !== properties
22968 ? update(createJsxAttributes(properties), node)
22969 : node;
22970 }
22971 // @api
22972 function createJsxSpreadAttribute(expression) {
22973 var node = createBaseNode(279 /* JsxSpreadAttribute */);
22974 node.expression = expression;
22975 node.transformFlags |=
22976 propagateChildFlags(node.expression) |
22977 2 /* ContainsJsx */;
22978 return node;
22979 }
22980 // @api
22981 function updateJsxSpreadAttribute(node, expression) {
22982 return node.expression !== expression
22983 ? update(createJsxSpreadAttribute(expression), node)
22984 : node;
22985 }
22986 // @api
22987 function createJsxExpression(dotDotDotToken, expression) {
22988 var node = createBaseNode(280 /* JsxExpression */);
22989 node.dotDotDotToken = dotDotDotToken;
22990 node.expression = expression;
22991 node.transformFlags |=
22992 propagateChildFlags(node.dotDotDotToken) |
22993 propagateChildFlags(node.expression) |
22994 2 /* ContainsJsx */;
22995 return node;
22996 }
22997 // @api
22998 function updateJsxExpression(node, expression) {
22999 return node.expression !== expression
23000 ? update(createJsxExpression(node.dotDotDotToken, expression), node)
23001 : node;
23002 }
23003 //
23004 // Clauses
23005 //
23006 // @api
23007 function createCaseClause(expression, statements) {
23008 var node = createBaseNode(281 /* CaseClause */);
23009 node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23010 node.statements = createNodeArray(statements);
23011 node.transformFlags |=
23012 propagateChildFlags(node.expression) |
23013 propagateChildrenFlags(node.statements);
23014 return node;
23015 }
23016 // @api
23017 function updateCaseClause(node, expression, statements) {
23018 return node.expression !== expression
23019 || node.statements !== statements
23020 ? update(createCaseClause(expression, statements), node)
23021 : node;
23022 }
23023 // @api
23024 function createDefaultClause(statements) {
23025 var node = createBaseNode(282 /* DefaultClause */);
23026 node.statements = createNodeArray(statements);
23027 node.transformFlags = propagateChildrenFlags(node.statements);
23028 return node;
23029 }
23030 // @api
23031 function updateDefaultClause(node, statements) {
23032 return node.statements !== statements
23033 ? update(createDefaultClause(statements), node)
23034 : node;
23035 }
23036 // @api
23037 function createHeritageClause(token, types) {
23038 var node = createBaseNode(283 /* HeritageClause */);
23039 node.token = token;
23040 node.types = createNodeArray(types);
23041 node.transformFlags |= propagateChildrenFlags(node.types);
23042 switch (token) {
23043 case 93 /* ExtendsKeyword */:
23044 node.transformFlags |= 256 /* ContainsES2015 */;
23045 break;
23046 case 116 /* ImplementsKeyword */:
23047 node.transformFlags |= 1 /* ContainsTypeScript */;
23048 break;
23049 default:
23050 return ts.Debug.assertNever(token);
23051 }
23052 return node;
23053 }
23054 // @api
23055 function updateHeritageClause(node, types) {
23056 return node.types !== types
23057 ? update(createHeritageClause(node.token, types), node)
23058 : node;
23059 }
23060 // @api
23061 function createCatchClause(variableDeclaration, block) {
23062 var node = createBaseNode(284 /* CatchClause */);
23063 variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration,
23064 /*exclamationToken*/ undefined,
23065 /*type*/ undefined,
23066 /*initializer*/ undefined);
23067 node.variableDeclaration = variableDeclaration;
23068 node.block = block;
23069 node.transformFlags |=
23070 propagateChildFlags(node.variableDeclaration) |
23071 propagateChildFlags(node.block);
23072 if (!variableDeclaration)
23073 node.transformFlags |= 16 /* ContainsES2019 */;
23074 return node;
23075 }
23076 // @api
23077 function updateCatchClause(node, variableDeclaration, block) {
23078 return node.variableDeclaration !== variableDeclaration
23079 || node.block !== block
23080 ? update(createCatchClause(variableDeclaration, block), node)
23081 : node;
23082 }
23083 //
23084 // Property assignments
23085 //
23086 // @api
23087 function createPropertyAssignment(name, initializer) {
23088 var node = createBaseNamedDeclaration(285 /* PropertyAssignment */,
23089 /*decorators*/ undefined,
23090 /*modifiers*/ undefined, name);
23091 node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23092 node.transformFlags |=
23093 propagateChildFlags(node.name) |
23094 propagateChildFlags(node.initializer);
23095 return node;
23096 }
23097 function finishUpdatePropertyAssignment(updated, original) {
23098 // copy children used only for error reporting
23099 if (original.decorators)
23100 updated.decorators = original.decorators;
23101 if (original.modifiers)
23102 updated.modifiers = original.modifiers;
23103 if (original.questionToken)
23104 updated.questionToken = original.questionToken;
23105 if (original.exclamationToken)
23106 updated.exclamationToken = original.exclamationToken;
23107 return update(updated, original);
23108 }
23109 // @api
23110 function updatePropertyAssignment(node, name, initializer) {
23111 return node.name !== name
23112 || node.initializer !== initializer
23113 ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
23114 : node;
23115 }
23116 // @api
23117 function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
23118 var node = createBaseNamedDeclaration(286 /* ShorthandPropertyAssignment */,
23119 /*decorators*/ undefined,
23120 /*modifiers*/ undefined, name);
23121 node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
23122 node.transformFlags |=
23123 propagateChildFlags(node.objectAssignmentInitializer) |
23124 256 /* ContainsES2015 */;
23125 return node;
23126 }
23127 function finishUpdateShorthandPropertyAssignment(updated, original) {
23128 // copy children used only for error reporting
23129 if (original.decorators)
23130 updated.decorators = original.decorators;
23131 if (original.modifiers)
23132 updated.modifiers = original.modifiers;
23133 if (original.equalsToken)
23134 updated.equalsToken = original.equalsToken;
23135 if (original.questionToken)
23136 updated.questionToken = original.questionToken;
23137 if (original.exclamationToken)
23138 updated.exclamationToken = original.exclamationToken;
23139 return update(updated, original);
23140 }
23141 // @api
23142 function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
23143 return node.name !== name
23144 || node.objectAssignmentInitializer !== objectAssignmentInitializer
23145 ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
23146 : node;
23147 }
23148 // @api
23149 function createSpreadAssignment(expression) {
23150 var node = createBaseNode(287 /* SpreadAssignment */);
23151 node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23152 node.transformFlags |=
23153 propagateChildFlags(node.expression) |
23154 32 /* ContainsES2018 */ |
23155 16384 /* ContainsObjectRestOrSpread */;
23156 return node;
23157 }
23158 // @api
23159 function updateSpreadAssignment(node, expression) {
23160 return node.expression !== expression
23161 ? update(createSpreadAssignment(expression), node)
23162 : node;
23163 }
23164 //
23165 // Enum
23166 //
23167 // @api
23168 function createEnumMember(name, initializer) {
23169 var node = createBaseNode(288 /* EnumMember */);
23170 node.name = asName(name);
23171 node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23172 node.transformFlags |=
23173 propagateChildFlags(node.name) |
23174 propagateChildFlags(node.initializer) |
23175 1 /* ContainsTypeScript */;
23176 return node;
23177 }
23178 // @api
23179 function updateEnumMember(node, name, initializer) {
23180 return node.name !== name
23181 || node.initializer !== initializer
23182 ? update(createEnumMember(name, initializer), node)
23183 : node;
23184 }
23185 //
23186 // Top-level nodes
23187 //
23188 // @api
23189 function createSourceFile(statements, endOfFileToken, flags) {
23190 var node = baseFactory.createBaseSourceFileNode(294 /* SourceFile */);
23191 node.statements = createNodeArray(statements);
23192 node.endOfFileToken = endOfFileToken;
23193 node.flags |= flags;
23194 node.fileName = "";
23195 node.text = "";
23196 node.languageVersion = 0;
23197 node.languageVariant = 0;
23198 node.scriptKind = 0;
23199 node.isDeclarationFile = false;
23200 node.hasNoDefaultLib = false;
23201 node.transformFlags |=
23202 propagateChildrenFlags(node.statements) |
23203 propagateChildFlags(node.endOfFileToken);
23204 return node;
23205 }
23206 function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
23207 var node = baseFactory.createBaseSourceFileNode(294 /* SourceFile */);
23208 for (var p in source) {
23209 if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
23210 continue;
23211 node[p] = source[p];
23212 }
23213 node.flags |= source.flags;
23214 node.statements = createNodeArray(statements);
23215 node.endOfFileToken = source.endOfFileToken;
23216 node.isDeclarationFile = isDeclarationFile;
23217 node.referencedFiles = referencedFiles;
23218 node.typeReferenceDirectives = typeReferences;
23219 node.hasNoDefaultLib = hasNoDefaultLib;
23220 node.libReferenceDirectives = libReferences;
23221 node.transformFlags =
23222 propagateChildrenFlags(node.statements) |
23223 propagateChildFlags(node.endOfFileToken);
23224 return node;
23225 }
23226 // @api
23227 function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
23228 if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
23229 if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
23230 if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
23231 if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
23232 if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
23233 return node.statements !== statements
23234 || node.isDeclarationFile !== isDeclarationFile
23235 || node.referencedFiles !== referencedFiles
23236 || node.typeReferenceDirectives !== typeReferenceDirectives
23237 || node.hasNoDefaultLib !== hasNoDefaultLib
23238 || node.libReferenceDirectives !== libReferenceDirectives
23239 ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
23240 : node;
23241 }
23242 // @api
23243 function createBundle(sourceFiles, prepends) {
23244 if (prepends === void 0) { prepends = ts.emptyArray; }
23245 var node = createBaseNode(295 /* Bundle */);
23246 node.prepends = prepends;
23247 node.sourceFiles = sourceFiles;
23248 return node;
23249 }
23250 // @api
23251 function updateBundle(node, sourceFiles, prepends) {
23252 if (prepends === void 0) { prepends = ts.emptyArray; }
23253 return node.sourceFiles !== sourceFiles
23254 || node.prepends !== prepends
23255 ? update(createBundle(sourceFiles, prepends), node)
23256 : node;
23257 }
23258 // @api
23259 function createUnparsedSource(prologues, syntheticReferences, texts) {
23260 var node = createBaseNode(296 /* UnparsedSource */);
23261 node.prologues = prologues;
23262 node.syntheticReferences = syntheticReferences;
23263 node.texts = texts;
23264 node.fileName = "";
23265 node.text = "";
23266 node.referencedFiles = ts.emptyArray;
23267 node.libReferenceDirectives = ts.emptyArray;
23268 node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
23269 return node;
23270 }
23271 function createBaseUnparsedNode(kind, data) {
23272 var node = createBaseNode(kind);
23273 node.data = data;
23274 return node;
23275 }
23276 // @api
23277 function createUnparsedPrologue(data) {
23278 return createBaseUnparsedNode(289 /* UnparsedPrologue */, data);
23279 }
23280 // @api
23281 function createUnparsedPrepend(data, texts) {
23282 var node = createBaseUnparsedNode(290 /* UnparsedPrepend */, data);
23283 node.texts = texts;
23284 return node;
23285 }
23286 // @api
23287 function createUnparsedTextLike(data, internal) {
23288 return createBaseUnparsedNode(internal ? 292 /* UnparsedInternalText */ : 291 /* UnparsedText */, data);
23289 }
23290 // @api
23291 function createUnparsedSyntheticReference(section) {
23292 var node = createBaseNode(293 /* UnparsedSyntheticReference */);
23293 node.data = section.data;
23294 node.section = section;
23295 return node;
23296 }
23297 // @api
23298 function createInputFiles() {
23299 var node = createBaseNode(297 /* InputFiles */);
23300 node.javascriptText = "";
23301 node.declarationText = "";
23302 return node;
23303 }
23304 //
23305 // Synthetic Nodes (used by checker)
23306 //
23307 // @api
23308 function createSyntheticExpression(type, isSpread, tupleNameSource) {
23309 if (isSpread === void 0) { isSpread = false; }
23310 var node = createBaseNode(224 /* SyntheticExpression */);
23311 node.type = type;
23312 node.isSpread = isSpread;
23313 node.tupleNameSource = tupleNameSource;
23314 return node;
23315 }
23316 // @api
23317 function createSyntaxList(children) {
23318 var node = createBaseNode(329 /* SyntaxList */);
23319 node._children = children;
23320 return node;
23321 }
23322 //
23323 // Transformation nodes
23324 //
23325 /**
23326 * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
23327 * order to preserve comments.
23328 *
23329 * @param original The original statement.
23330 */
23331 // @api
23332 function createNotEmittedStatement(original) {
23333 var node = createBaseNode(330 /* NotEmittedStatement */);
23334 node.original = original;
23335 ts.setTextRange(node, original);
23336 return node;
23337 }
23338 /**
23339 * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
23340 * order to preserve comments or sourcemap positions.
23341 *
23342 * @param expression The inner expression to emit.
23343 * @param original The original outer expression.
23344 */
23345 // @api
23346 function createPartiallyEmittedExpression(expression, original) {
23347 var node = createBaseNode(331 /* PartiallyEmittedExpression */);
23348 node.expression = expression;
23349 node.original = original;
23350 node.transformFlags |=
23351 propagateChildFlags(node.expression) |
23352 1 /* ContainsTypeScript */;
23353 ts.setTextRange(node, original);
23354 return node;
23355 }
23356 // @api
23357 function updatePartiallyEmittedExpression(node, expression) {
23358 return node.expression !== expression
23359 ? update(createPartiallyEmittedExpression(expression, node.original), node)
23360 : node;
23361 }
23362 function flattenCommaElements(node) {
23363 if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
23364 if (ts.isCommaListExpression(node)) {
23365 return node.elements;
23366 }
23367 if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
23368 return [node.left, node.right];
23369 }
23370 }
23371 return node;
23372 }
23373 // @api
23374 function createCommaListExpression(elements) {
23375 var node = createBaseNode(332 /* CommaListExpression */);
23376 node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
23377 node.transformFlags |= propagateChildrenFlags(node.elements);
23378 return node;
23379 }
23380 // @api
23381 function updateCommaListExpression(node, elements) {
23382 return node.elements !== elements
23383 ? update(createCommaListExpression(elements), node)
23384 : node;
23385 }
23386 /**
23387 * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
23388 * order to properly emit exports.
23389 */
23390 // @api
23391 function createEndOfDeclarationMarker(original) {
23392 var node = createBaseNode(334 /* EndOfDeclarationMarker */);
23393 node.emitNode = {};
23394 node.original = original;
23395 return node;
23396 }
23397 /**
23398 * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
23399 * order to properly emit exports.
23400 */
23401 // @api
23402 function createMergeDeclarationMarker(original) {
23403 var node = createBaseNode(333 /* MergeDeclarationMarker */);
23404 node.emitNode = {};
23405 node.original = original;
23406 return node;
23407 }
23408 // @api
23409 function createSyntheticReferenceExpression(expression, thisArg) {
23410 var node = createBaseNode(335 /* SyntheticReferenceExpression */);
23411 node.expression = expression;
23412 node.thisArg = thisArg;
23413 node.transformFlags |=
23414 propagateChildFlags(node.expression) |
23415 propagateChildFlags(node.thisArg);
23416 return node;
23417 }
23418 // @api
23419 function updateSyntheticReferenceExpression(node, expression, thisArg) {
23420 return node.expression !== expression
23421 || node.thisArg !== thisArg
23422 ? update(createSyntheticReferenceExpression(expression, thisArg), node)
23423 : node;
23424 }
23425 function cloneNode(node) {
23426 // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
23427 // the original node. We also need to exclude specific properties and only include own-
23428 // properties (to skip members already defined on the shared prototype).
23429 if (node === undefined) {
23430 return node;
23431 }
23432 var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(294 /* SourceFile */) :
23433 ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) :
23434 ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) :
23435 !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
23436 baseFactory.createBaseNode(node.kind);
23437 clone.flags |= (node.flags & ~8 /* Synthesized */);
23438 clone.transformFlags = node.transformFlags;
23439 setOriginalNode(clone, node);
23440 for (var key in node) {
23441 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
23442 continue;
23443 }
23444 clone[key] = node[key];
23445 }
23446 return clone;
23447 }
23448 function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
23449 return createCallExpression(createFunctionExpression(
23450 /*modifiers*/ undefined,
23451 /*asteriskToken*/ undefined,
23452 /*name*/ undefined,
23453 /*typeParameters*/ undefined,
23454 /*parameters*/ param ? [param] : [],
23455 /*type*/ undefined, createBlock(statements, /*multiLine*/ true)),
23456 /*typeArguments*/ undefined,
23457 /*argumentsArray*/ paramValue ? [paramValue] : []);
23458 }
23459 function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
23460 return createCallExpression(createArrowFunction(
23461 /*modifiers*/ undefined,
23462 /*typeParameters*/ undefined,
23463 /*parameters*/ param ? [param] : [],
23464 /*type*/ undefined,
23465 /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)),
23466 /*typeArguments*/ undefined,
23467 /*argumentsArray*/ paramValue ? [paramValue] : []);
23468 }
23469 function createVoidZero() {
23470 return createVoidExpression(createNumericLiteral("0"));
23471 }
23472 function createExportDefault(expression) {
23473 return createExportAssignment(
23474 /*decorators*/ undefined,
23475 /*modifiers*/ undefined,
23476 /*isExportEquals*/ false, expression);
23477 }
23478 function createExternalModuleExport(exportName) {
23479 return createExportDeclaration(
23480 /*decorators*/ undefined,
23481 /*modifiers*/ undefined,
23482 /*isTypeOnly*/ false, createNamedExports([
23483 createExportSpecifier(/*propertyName*/ undefined, exportName)
23484 ]));
23485 }
23486 //
23487 // Utilities
23488 //
23489 function createTypeCheck(value, tag) {
23490 return tag === "undefined"
23491 ? factory.createStrictEquality(value, createVoidZero())
23492 : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
23493 }
23494 function createMethodCall(object, methodName, argumentsList) {
23495 return createCallExpression(createPropertyAccessExpression(object, methodName),
23496 /*typeArguments*/ undefined, argumentsList);
23497 }
23498 function createFunctionBindCall(target, thisArg, argumentsList) {
23499 return createMethodCall(target, "bind", __spreadArrays([thisArg], argumentsList));
23500 }
23501 function createFunctionCallCall(target, thisArg, argumentsList) {
23502 return createMethodCall(target, "call", __spreadArrays([thisArg], argumentsList));
23503 }
23504 function createFunctionApplyCall(target, thisArg, argumentsExpression) {
23505 return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
23506 }
23507 function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
23508 return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
23509 }
23510 function createArraySliceCall(array, start) {
23511 return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
23512 }
23513 function createArrayConcatCall(array, argumentsList) {
23514 return createMethodCall(array, "concat", argumentsList);
23515 }
23516 function createObjectDefinePropertyCall(target, propertyName, attributes) {
23517 return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
23518 }
23519 function tryAddPropertyAssignment(properties, propertyName, expression) {
23520 if (expression) {
23521 properties.push(createPropertyAssignment(propertyName, expression));
23522 return true;
23523 }
23524 return false;
23525 }
23526 function createPropertyDescriptor(attributes, singleLine) {
23527 var properties = [];
23528 tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
23529 tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
23530 var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
23531 isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
23532 var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
23533 isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
23534 ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
23535 return createObjectLiteralExpression(properties, !singleLine);
23536 }
23537 function updateOuterExpression(outerExpression, expression) {
23538 switch (outerExpression.kind) {
23539 case 204 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
23540 case 203 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
23541 case 221 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
23542 case 222 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
23543 case 331 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
23544 }
23545 }
23546 /**
23547 * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
23548 *
23549 * A parenthesized expression can be ignored when all of the following are true:
23550 *
23551 * - It's `pos` and `end` are not -1
23552 * - It does not have a custom source map range
23553 * - It does not have a custom comment range
23554 * - It does not have synthetic leading or trailing comments
23555 *
23556 * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
23557 * the expression to maintain precedence, a new parenthesized expression should be created automatically when
23558 * the containing expression is created/updated.
23559 */
23560 function isIgnorableParen(node) {
23561 return ts.isParenthesizedExpression(node)
23562 && ts.nodeIsSynthesized(node)
23563 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
23564 && ts.nodeIsSynthesized(ts.getCommentRange(node))
23565 && !ts.some(ts.getSyntheticLeadingComments(node))
23566 && !ts.some(ts.getSyntheticTrailingComments(node));
23567 }
23568 function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
23569 if (kinds === void 0) { kinds = 15 /* All */; }
23570 if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
23571 return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
23572 }
23573 return innerExpression;
23574 }
23575 function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
23576 if (!outermostLabeledStatement) {
23577 return node;
23578 }
23579 var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
23580 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
23581 : node);
23582 if (afterRestoreLabelCallback) {
23583 afterRestoreLabelCallback(outermostLabeledStatement);
23584 }
23585 return updated;
23586 }
23587 function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
23588 var target = ts.skipParentheses(node);
23589 switch (target.kind) {
23590 case 78 /* Identifier */:
23591 return cacheIdentifiers;
23592 case 107 /* ThisKeyword */:
23593 case 8 /* NumericLiteral */:
23594 case 9 /* BigIntLiteral */:
23595 case 10 /* StringLiteral */:
23596 return false;
23597 case 196 /* ArrayLiteralExpression */:
23598 var elements = target.elements;
23599 if (elements.length === 0) {
23600 return false;
23601 }
23602 return true;
23603 case 197 /* ObjectLiteralExpression */:
23604 return target.properties.length > 0;
23605 default:
23606 return true;
23607 }
23608 }
23609 function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
23610 if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
23611 var callee = ts.skipOuterExpressions(expression, 15 /* All */);
23612 var thisArg;
23613 var target;
23614 if (ts.isSuperProperty(callee)) {
23615 thisArg = createThis();
23616 target = callee;
23617 }
23618 else if (ts.isSuperKeyword(callee)) {
23619 thisArg = createThis();
23620 target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
23621 ? ts.setTextRange(createIdentifier("_super"), callee)
23622 : callee;
23623 }
23624 else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
23625 thisArg = createVoidZero();
23626 target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
23627 }
23628 else if (ts.isPropertyAccessExpression(callee)) {
23629 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
23630 // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
23631 thisArg = createTempVariable(recordTempVariable);
23632 target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
23633 ts.setTextRange(target, callee);
23634 }
23635 else {
23636 thisArg = callee.expression;
23637 target = callee;
23638 }
23639 }
23640 else if (ts.isElementAccessExpression(callee)) {
23641 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
23642 // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
23643 thisArg = createTempVariable(recordTempVariable);
23644 target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
23645 ts.setTextRange(target, callee);
23646 }
23647 else {
23648 thisArg = callee.expression;
23649 target = callee;
23650 }
23651 }
23652 else {
23653 // for `a()` target is `a` and thisArg is `void 0`
23654 thisArg = createVoidZero();
23655 target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23656 }
23657 return { target: target, thisArg: thisArg };
23658 }
23659 function inlineExpressions(expressions) {
23660 // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
23661 // stack size exceeded" errors.
23662 return expressions.length > 10
23663 ? createCommaListExpression(expressions)
23664 : ts.reduceLeft(expressions, factory.createComma);
23665 }
23666 function getName(node, allowComments, allowSourceMaps, emitFlags) {
23667 if (emitFlags === void 0) { emitFlags = 0; }
23668 var nodeName = ts.getNameOfDeclaration(node);
23669 if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
23670 // TODO(rbuckton): Does this need to be parented?
23671 var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
23672 emitFlags |= ts.getEmitFlags(nodeName);
23673 if (!allowSourceMaps)
23674 emitFlags |= 48 /* NoSourceMap */;
23675 if (!allowComments)
23676 emitFlags |= 1536 /* NoComments */;
23677 if (emitFlags)
23678 ts.setEmitFlags(name, emitFlags);
23679 return name;
23680 }
23681 return getGeneratedNameForNode(node);
23682 }
23683 /**
23684 * Gets the internal name of a declaration. This is primarily used for declarations that can be
23685 * referred to by name in the body of an ES5 class function body. An internal name will *never*
23686 * be prefixed with an module or namespace export modifier like "exports." when emitted as an
23687 * expression. An internal name will also *never* be renamed due to a collision with a block
23688 * scoped variable.
23689 *
23690 * @param node The declaration.
23691 * @param allowComments A value indicating whether comments may be emitted for the name.
23692 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23693 */
23694 function getInternalName(node, allowComments, allowSourceMaps) {
23695 return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
23696 }
23697 /**
23698 * Gets the local name of a declaration. This is primarily used for declarations that can be
23699 * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
23700 * local name will *never* be prefixed with an module or namespace export modifier like
23701 * "exports." when emitted as an expression.
23702 *
23703 * @param node The declaration.
23704 * @param allowComments A value indicating whether comments may be emitted for the name.
23705 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23706 */
23707 function getLocalName(node, allowComments, allowSourceMaps) {
23708 return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
23709 }
23710 /**
23711 * Gets the export name of a declaration. This is primarily used for declarations that can be
23712 * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
23713 * export name will *always* be prefixed with an module or namespace export modifier like
23714 * `"exports."` when emitted as an expression if the name points to an exported symbol.
23715 *
23716 * @param node The declaration.
23717 * @param allowComments A value indicating whether comments may be emitted for the name.
23718 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23719 */
23720 function getExportName(node, allowComments, allowSourceMaps) {
23721 return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
23722 }
23723 /**
23724 * Gets the name of a declaration for use in declarations.
23725 *
23726 * @param node The declaration.
23727 * @param allowComments A value indicating whether comments may be emitted for the name.
23728 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23729 */
23730 function getDeclarationName(node, allowComments, allowSourceMaps) {
23731 return getName(node, allowComments, allowSourceMaps);
23732 }
23733 /**
23734 * Gets a namespace-qualified name for use in expressions.
23735 *
23736 * @param ns The namespace identifier.
23737 * @param name The name.
23738 * @param allowComments A value indicating whether comments may be emitted for the name.
23739 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23740 */
23741 function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
23742 var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
23743 ts.setTextRange(qualifiedName, name);
23744 var emitFlags = 0;
23745 if (!allowSourceMaps)
23746 emitFlags |= 48 /* NoSourceMap */;
23747 if (!allowComments)
23748 emitFlags |= 1536 /* NoComments */;
23749 if (emitFlags)
23750 ts.setEmitFlags(qualifiedName, emitFlags);
23751 return qualifiedName;
23752 }
23753 /**
23754 * Gets the exported name of a declaration for use in expressions.
23755 *
23756 * An exported name will *always* be prefixed with an module or namespace export modifier like
23757 * "exports." if the name points to an exported symbol.
23758 *
23759 * @param ns The namespace identifier.
23760 * @param node The declaration.
23761 * @param allowComments A value indicating whether comments may be emitted for the name.
23762 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
23763 */
23764 function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
23765 if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
23766 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
23767 }
23768 return getExportName(node, allowComments, allowSourceMaps);
23769 }
23770 /**
23771 * Copies any necessary standard and custom prologue-directives into target array.
23772 * @param source origin statements array
23773 * @param target result statements array
23774 * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
23775 * @param visitor Optional callback used to visit any custom prologue directives.
23776 */
23777 function copyPrologue(source, target, ensureUseStrict, visitor) {
23778 var offset = copyStandardPrologue(source, target, ensureUseStrict);
23779 return copyCustomPrologue(source, target, offset, visitor);
23780 }
23781 function isUseStrictPrologue(node) {
23782 return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
23783 }
23784 function createUseStrictPrologue() {
23785 return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
23786 }
23787 /**
23788 * Copies only the standard (string-expression) prologue-directives into the target statement-array.
23789 * @param source origin statements array
23790 * @param target result statements array
23791 * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
23792 */
23793 function copyStandardPrologue(source, target, ensureUseStrict) {
23794 ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
23795 var foundUseStrict = false;
23796 var statementOffset = 0;
23797 var numStatements = source.length;
23798 while (statementOffset < numStatements) {
23799 var statement = source[statementOffset];
23800 if (ts.isPrologueDirective(statement)) {
23801 if (isUseStrictPrologue(statement)) {
23802 foundUseStrict = true;
23803 }
23804 target.push(statement);
23805 }
23806 else {
23807 break;
23808 }
23809 statementOffset++;
23810 }
23811 if (ensureUseStrict && !foundUseStrict) {
23812 target.push(createUseStrictPrologue());
23813 }
23814 return statementOffset;
23815 }
23816 function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
23817 if (filter === void 0) { filter = ts.returnTrue; }
23818 var numStatements = source.length;
23819 while (statementOffset !== undefined && statementOffset < numStatements) {
23820 var statement = source[statementOffset];
23821 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
23822 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
23823 }
23824 else {
23825 break;
23826 }
23827 statementOffset++;
23828 }
23829 return statementOffset;
23830 }
23831 /**
23832 * Ensures "use strict" directive is added
23833 *
23834 * @param statements An array of statements
23835 */
23836 function ensureUseStrict(statements) {
23837 var foundUseStrict = ts.findUseStrictPrologue(statements);
23838 if (!foundUseStrict) {
23839 return ts.setTextRange(createNodeArray(__spreadArrays([createUseStrictPrologue()], statements)), statements);
23840 }
23841 return statements;
23842 }
23843 /**
23844 * Lifts a NodeArray containing only Statement nodes to a block.
23845 *
23846 * @param nodes The NodeArray.
23847 */
23848 function liftToBlock(nodes) {
23849 ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
23850 return ts.singleOrUndefined(nodes) || createBlock(nodes);
23851 }
23852 function findSpanEnd(array, test, start) {
23853 var i = start;
23854 while (i < array.length && test(array[i])) {
23855 i++;
23856 }
23857 return i;
23858 }
23859 function mergeLexicalEnvironment(statements, declarations) {
23860 if (!ts.some(declarations)) {
23861 return statements;
23862 }
23863 // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
23864 //
23865 // Given:
23866 //
23867 // | Left | Right |
23868 // |------------------------------------|-------------------------------------|
23869 // | [standard prologues (left)] | [standard prologues (right)] |
23870 // | [hoisted functions (left)] | [hoisted functions (right)] |
23871 // | [hoisted variables (left)] | [hoisted variables (right)] |
23872 // | [lexical init statements (left)] | [lexical init statements (right)] |
23873 // | [other statements (left)] | |
23874 //
23875 // The resulting statement list will be:
23876 //
23877 // | Result |
23878 // |-------------------------------------|
23879 // | [standard prologues (right)] |
23880 // | [standard prologues (left)] |
23881 // | [hoisted functions (right)] |
23882 // | [hoisted functions (left)] |
23883 // | [hoisted variables (right)] |
23884 // | [hoisted variables (left)] |
23885 // | [lexical init statements (right)] |
23886 // | [lexical init statements (left)] |
23887 // | [other statements (left)] |
23888 //
23889 // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
23890 // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
23891 // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
23892 var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
23893 var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
23894 var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
23895 // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
23896 var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
23897 var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
23898 var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
23899 var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
23900 ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
23901 // splice prologues from the right into the left. We do this in reverse order
23902 // so that we don't need to recompute the index on the left when we insert items.
23903 var left = ts.isNodeArray(statements) ? statements.slice() : statements;
23904 // splice other custom prologues from right into left
23905 if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
23906 left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
23907 }
23908 // splice hoisted variables from right into left
23909 if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
23910 left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
23911 }
23912 // splice hoisted functions from right into left
23913 if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
23914 left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
23915 }
23916 // splice standard prologues from right into left (that are not already in left)
23917 if (rightStandardPrologueEnd > 0) {
23918 if (leftStandardPrologueEnd === 0) {
23919 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
23920 }
23921 else {
23922 var leftPrologues = new ts.Map();
23923 for (var i = 0; i < leftStandardPrologueEnd; i++) {
23924 var leftPrologue = statements[i];
23925 leftPrologues.set(leftPrologue.expression.text, true);
23926 }
23927 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
23928 var rightPrologue = declarations[i];
23929 if (!leftPrologues.has(rightPrologue.expression.text)) {
23930 left.unshift(rightPrologue);
23931 }
23932 }
23933 }
23934 }
23935 if (ts.isNodeArray(statements)) {
23936 return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
23937 }
23938 return statements;
23939 }
23940 function updateModifiers(node, modifiers) {
23941 var _a;
23942 if (typeof modifiers === "number") {
23943 modifiers = createModifiersFromModifierFlags(modifiers);
23944 }
23945 return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
23946 ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
23947 ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
23948 ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
23949 ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
23950 ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
23951 ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
23952 ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
23953 ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
23954 ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
23955 ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
23956 ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
23957 ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
23958 ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
23959 ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
23960 ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
23961 ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
23962 ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
23963 ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
23964 ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.name, node.moduleReference) :
23965 ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
23966 ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
23967 ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
23968 ts.Debug.assertNever(node);
23969 }
23970 function asNodeArray(array) {
23971 return array ? createNodeArray(array) : undefined;
23972 }
23973 function asName(name) {
23974 return typeof name === "string" ? createIdentifier(name) :
23975 name;
23976 }
23977 function asExpression(value) {
23978 return typeof value === "string" ? createStringLiteral(value) :
23979 typeof value === "number" ? createNumericLiteral(value) :
23980 typeof value === "boolean" ? value ? createTrue() : createFalse() :
23981 value;
23982 }
23983 function asToken(value) {
23984 return typeof value === "number" ? createToken(value) : value;
23985 }
23986 function asEmbeddedStatement(statement) {
23987 return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
23988 }
23989 }
23990 ts.createNodeFactory = createNodeFactory;
23991 function updateWithoutOriginal(updated, original) {
23992 if (updated !== original) {
23993 ts.setTextRange(updated, original);
23994 }
23995 return updated;
23996 }
23997 function updateWithOriginal(updated, original) {
23998 if (updated !== original) {
23999 setOriginalNode(updated, original);
24000 ts.setTextRange(updated, original);
24001 }
24002 return updated;
24003 }
24004 function getDefaultTagNameForKind(kind) {
24005 switch (kind) {
24006 case 325 /* JSDocTypeTag */: return "type";
24007 case 323 /* JSDocReturnTag */: return "returns";
24008 case 324 /* JSDocThisTag */: return "this";
24009 case 321 /* JSDocEnumTag */: return "enum";
24010 case 313 /* JSDocAuthorTag */: return "author";
24011 case 315 /* JSDocClassTag */: return "class";
24012 case 316 /* JSDocPublicTag */: return "public";
24013 case 317 /* JSDocPrivateTag */: return "private";
24014 case 318 /* JSDocProtectedTag */: return "protected";
24015 case 319 /* JSDocReadonlyTag */: return "readonly";
24016 case 326 /* JSDocTemplateTag */: return "template";
24017 case 327 /* JSDocTypedefTag */: return "typedef";
24018 case 322 /* JSDocParameterTag */: return "param";
24019 case 328 /* JSDocPropertyTag */: return "prop";
24020 case 320 /* JSDocCallbackTag */: return "callback";
24021 case 311 /* JSDocAugmentsTag */: return "augments";
24022 case 312 /* JSDocImplementsTag */: return "implements";
24023 default:
24024 return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind));
24025 }
24026 }
24027 var rawTextScanner;
24028 var invalidValueSentinel = {};
24029 function getCookedText(kind, rawText) {
24030 if (!rawTextScanner) {
24031 rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
24032 }
24033 switch (kind) {
24034 case 14 /* NoSubstitutionTemplateLiteral */:
24035 rawTextScanner.setText("`" + rawText + "`");
24036 break;
24037 case 15 /* TemplateHead */:
24038 // tslint:disable-next-line no-invalid-template-strings
24039 rawTextScanner.setText("`" + rawText + "${");
24040 break;
24041 case 16 /* TemplateMiddle */:
24042 // tslint:disable-next-line no-invalid-template-strings
24043 rawTextScanner.setText("}" + rawText + "${");
24044 break;
24045 case 17 /* TemplateTail */:
24046 rawTextScanner.setText("}" + rawText + "`");
24047 break;
24048 }
24049 var token = rawTextScanner.scan();
24050 if (token === 23 /* CloseBracketToken */) {
24051 token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
24052 }
24053 if (rawTextScanner.isUnterminated()) {
24054 rawTextScanner.setText(undefined);
24055 return invalidValueSentinel;
24056 }
24057 var tokenValue;
24058 switch (token) {
24059 case 14 /* NoSubstitutionTemplateLiteral */:
24060 case 15 /* TemplateHead */:
24061 case 16 /* TemplateMiddle */:
24062 case 17 /* TemplateTail */:
24063 tokenValue = rawTextScanner.getTokenValue();
24064 break;
24065 }
24066 if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
24067 rawTextScanner.setText(undefined);
24068 return invalidValueSentinel;
24069 }
24070 rawTextScanner.setText(undefined);
24071 return tokenValue;
24072 }
24073 function propagateIdentifierNameFlags(node) {
24074 // An IdentifierName is allowed to be `await`
24075 return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */;
24076 }
24077 function propagatePropertyNameFlagsOfChild(node, transformFlags) {
24078 return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
24079 }
24080 function propagateChildFlags(child) {
24081 if (!child)
24082 return 0 /* None */;
24083 var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
24084 return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
24085 }
24086 function propagateChildrenFlags(children) {
24087 return children ? children.transformFlags : 0 /* None */;
24088 }
24089 function aggregateChildrenFlags(children) {
24090 var subtreeFlags = 0 /* None */;
24091 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
24092 var child = children_2[_i];
24093 subtreeFlags |= propagateChildFlags(child);
24094 }
24095 children.transformFlags = subtreeFlags;
24096 }
24097 /**
24098 * Gets the transform flags to exclude when unioning the transform flags of a subtree.
24099 */
24100 /* @internal */
24101 function getTransformFlagsSubtreeExclusions(kind) {
24102 if (kind >= 171 /* FirstTypeNode */ && kind <= 192 /* LastTypeNode */) {
24103 return -2 /* TypeExcludes */;
24104 }
24105 switch (kind) {
24106 case 200 /* CallExpression */:
24107 case 201 /* NewExpression */:
24108 case 196 /* ArrayLiteralExpression */:
24109 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
24110 case 253 /* ModuleDeclaration */:
24111 return 546379776 /* ModuleExcludes */;
24112 case 159 /* Parameter */:
24113 return 536870912 /* ParameterExcludes */;
24114 case 206 /* ArrowFunction */:
24115 return 547309568 /* ArrowFunctionExcludes */;
24116 case 205 /* FunctionExpression */:
24117 case 248 /* FunctionDeclaration */:
24118 return 547313664 /* FunctionExcludes */;
24119 case 247 /* VariableDeclarationList */:
24120 return 537018368 /* VariableDeclarationListExcludes */;
24121 case 249 /* ClassDeclaration */:
24122 case 218 /* ClassExpression */:
24123 return 536905728 /* ClassExcludes */;
24124 case 165 /* Constructor */:
24125 return 547311616 /* ConstructorExcludes */;
24126 case 162 /* PropertyDeclaration */:
24127 return 536875008 /* PropertyExcludes */;
24128 case 164 /* MethodDeclaration */:
24129 case 166 /* GetAccessor */:
24130 case 167 /* SetAccessor */:
24131 return 538923008 /* MethodOrAccessorExcludes */;
24132 case 128 /* AnyKeyword */:
24133 case 143 /* NumberKeyword */:
24134 case 154 /* BigIntKeyword */:
24135 case 140 /* NeverKeyword */:
24136 case 146 /* StringKeyword */:
24137 case 144 /* ObjectKeyword */:
24138 case 131 /* BooleanKeyword */:
24139 case 147 /* SymbolKeyword */:
24140 case 113 /* VoidKeyword */:
24141 case 158 /* TypeParameter */:
24142 case 161 /* PropertySignature */:
24143 case 163 /* MethodSignature */:
24144 case 168 /* CallSignature */:
24145 case 169 /* ConstructSignature */:
24146 case 170 /* IndexSignature */:
24147 case 250 /* InterfaceDeclaration */:
24148 case 251 /* TypeAliasDeclaration */:
24149 return -2 /* TypeExcludes */;
24150 case 197 /* ObjectLiteralExpression */:
24151 return 536922112 /* ObjectLiteralExcludes */;
24152 case 284 /* CatchClause */:
24153 return 536887296 /* CatchClauseExcludes */;
24154 case 193 /* ObjectBindingPattern */:
24155 case 194 /* ArrayBindingPattern */:
24156 return 536879104 /* BindingPatternExcludes */;
24157 case 203 /* TypeAssertionExpression */:
24158 case 221 /* AsExpression */:
24159 case 331 /* PartiallyEmittedExpression */:
24160 case 204 /* ParenthesizedExpression */:
24161 case 105 /* SuperKeyword */:
24162 return 536870912 /* OuterExpressionExcludes */;
24163 case 198 /* PropertyAccessExpression */:
24164 case 199 /* ElementAccessExpression */:
24165 return 536870912 /* PropertyAccessExcludes */;
24166 default:
24167 return 536870912 /* NodeExcludes */;
24168 }
24169 }
24170 ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
24171 var baseFactory = ts.createBaseNodeFactory();
24172 function makeSynthetic(node) {
24173 node.flags |= 8 /* Synthesized */;
24174 return node;
24175 }
24176 var syntheticFactory = {
24177 createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
24178 createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
24179 createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
24180 createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
24181 createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
24182 };
24183 ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
24184 function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
24185 var stripInternal;
24186 var bundleFileInfo;
24187 var fileName;
24188 var text;
24189 var length;
24190 var sourceMapPath;
24191 var sourceMapText;
24192 var getText;
24193 var getSourceMapText;
24194 var oldFileOfCurrentEmit;
24195 if (!ts.isString(textOrInputFiles)) {
24196 ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
24197 fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
24198 sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
24199 getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
24200 getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
24201 length = function () { return getText().length; };
24202 if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
24203 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
24204 stripInternal = mapTextOrStripInternal;
24205 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
24206 oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
24207 }
24208 }
24209 else {
24210 fileName = "";
24211 text = textOrInputFiles;
24212 length = textOrInputFiles.length;
24213 sourceMapPath = mapPathOrType;
24214 sourceMapText = mapTextOrStripInternal;
24215 }
24216 var node = oldFileOfCurrentEmit ?
24217 parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
24218 parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
24219 node.fileName = fileName;
24220 node.sourceMapPath = sourceMapPath;
24221 node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
24222 if (getText && getSourceMapText) {
24223 Object.defineProperty(node, "text", { get: getText });
24224 Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
24225 }
24226 else {
24227 ts.Debug.assert(!oldFileOfCurrentEmit);
24228 node.text = text !== null && text !== void 0 ? text : "";
24229 node.sourceMapText = sourceMapText;
24230 }
24231 return node;
24232 }
24233 ts.createUnparsedSourceFile = createUnparsedSourceFile;
24234 function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
24235 var prologues;
24236 var helpers;
24237 var referencedFiles;
24238 var typeReferenceDirectives;
24239 var libReferenceDirectives;
24240 var prependChildren;
24241 var texts;
24242 var hasNoDefaultLib;
24243 for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
24244 var section = _a[_i];
24245 switch (section.kind) {
24246 case "prologue" /* Prologue */:
24247 prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
24248 break;
24249 case "emitHelpers" /* EmitHelpers */:
24250 helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
24251 break;
24252 case "no-default-lib" /* NoDefaultLib */:
24253 hasNoDefaultLib = true;
24254 break;
24255 case "reference" /* Reference */:
24256 referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
24257 break;
24258 case "type" /* Type */:
24259 typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
24260 break;
24261 case "lib" /* Lib */:
24262 libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
24263 break;
24264 case "prepend" /* Prepend */:
24265 var prependTexts = void 0;
24266 for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
24267 var text = _c[_b];
24268 if (!stripInternal || text.kind !== "internal" /* Internal */) {
24269 prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
24270 }
24271 }
24272 prependChildren = ts.addRange(prependChildren, prependTexts);
24273 texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
24274 break;
24275 case "internal" /* Internal */:
24276 if (stripInternal) {
24277 if (!texts)
24278 texts = [];
24279 break;
24280 }
24281 // falls through
24282 case "text" /* Text */:
24283 texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
24284 break;
24285 default:
24286 ts.Debug.assertNever(section);
24287 }
24288 }
24289 if (!texts) {
24290 var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
24291 ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
24292 texts = [textNode];
24293 }
24294 var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
24295 ts.setEachParent(prologues, node);
24296 ts.setEachParent(texts, node);
24297 ts.setEachParent(prependChildren, node);
24298 node.hasNoDefaultLib = hasNoDefaultLib;
24299 node.helpers = helpers;
24300 node.referencedFiles = referencedFiles || ts.emptyArray;
24301 node.typeReferenceDirectives = typeReferenceDirectives;
24302 node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
24303 return node;
24304 }
24305 function parseOldFileOfCurrentEmit(bundleFileInfo) {
24306 var texts;
24307 var syntheticReferences;
24308 for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
24309 var section = _a[_i];
24310 switch (section.kind) {
24311 case "internal" /* Internal */:
24312 case "text" /* Text */:
24313 texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
24314 break;
24315 case "no-default-lib" /* NoDefaultLib */:
24316 case "reference" /* Reference */:
24317 case "type" /* Type */:
24318 case "lib" /* Lib */:
24319 syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
24320 break;
24321 // Ignore
24322 case "prologue" /* Prologue */:
24323 case "emitHelpers" /* EmitHelpers */:
24324 case "prepend" /* Prepend */:
24325 break;
24326 default:
24327 ts.Debug.assertNever(section);
24328 }
24329 }
24330 var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
24331 ts.setEachParent(syntheticReferences, node);
24332 ts.setEachParent(texts, node);
24333 node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
24334 return node;
24335 }
24336 function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
24337 var node = ts.parseNodeFactory.createInputFiles();
24338 if (!ts.isString(javascriptTextOrReadFileText)) {
24339 var cache_1 = new ts.Map();
24340 var textGetter_1 = function (path) {
24341 if (path === undefined)
24342 return undefined;
24343 var value = cache_1.get(path);
24344 if (value === undefined) {
24345 value = javascriptTextOrReadFileText(path);
24346 cache_1.set(path, value !== undefined ? value : false);
24347 }
24348 return value !== false ? value : undefined;
24349 };
24350 var definedTextGetter_1 = function (path) {
24351 var result = textGetter_1(path);
24352 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
24353 };
24354 var buildInfo_1;
24355 var getAndCacheBuildInfo_1 = function (getText) {
24356 if (buildInfo_1 === undefined) {
24357 var result = getText();
24358 buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
24359 }
24360 return buildInfo_1 || undefined;
24361 };
24362 node.javascriptPath = declarationTextOrJavascriptPath;
24363 node.javascriptMapPath = javascriptMapPath;
24364 node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
24365 node.declarationMapPath = declarationMapPath;
24366 node.buildInfoPath = declarationMapTextOrBuildInfoPath;
24367 Object.defineProperties(node, {
24368 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
24369 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
24370 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
24371 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
24372 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
24373 });
24374 }
24375 else {
24376 node.javascriptText = javascriptTextOrReadFileText;
24377 node.javascriptMapPath = javascriptMapPath;
24378 node.javascriptMapText = javascriptMapTextOrDeclarationPath;
24379 node.declarationText = declarationTextOrJavascriptPath;
24380 node.declarationMapPath = declarationMapPath;
24381 node.declarationMapText = declarationMapTextOrBuildInfoPath;
24382 node.javascriptPath = javascriptPath;
24383 node.declarationPath = declarationPath;
24384 node.buildInfoPath = buildInfoPath;
24385 node.buildInfo = buildInfo;
24386 node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
24387 }
24388 return node;
24389 }
24390 ts.createInputFiles = createInputFiles;
24391 // tslint:disable-next-line variable-name
24392 var SourceMapSource;
24393 /**
24394 * Create an external source map source file reference
24395 */
24396 function createSourceMapSource(fileName, text, skipTrivia) {
24397 return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
24398 }
24399 ts.createSourceMapSource = createSourceMapSource;
24400 // Utilities
24401 function setOriginalNode(node, original) {
24402 node.original = original;
24403 if (original) {
24404 var emitNode = original.emitNode;
24405 if (emitNode)
24406 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
24407 }
24408 return node;
24409 }
24410 ts.setOriginalNode = setOriginalNode;
24411 function mergeEmitNode(sourceEmitNode, destEmitNode) {
24412 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;
24413 if (!destEmitNode)
24414 destEmitNode = {};
24415 // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
24416 if (leadingComments)
24417 destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
24418 if (trailingComments)
24419 destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
24420 if (flags)
24421 destEmitNode.flags = flags;
24422 if (commentRange)
24423 destEmitNode.commentRange = commentRange;
24424 if (sourceMapRange)
24425 destEmitNode.sourceMapRange = sourceMapRange;
24426 if (tokenSourceMapRanges)
24427 destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
24428 if (constantValue !== undefined)
24429 destEmitNode.constantValue = constantValue;
24430 if (helpers) {
24431 for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
24432 var helper = helpers_1[_i];
24433 destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
24434 }
24435 }
24436 if (startsOnNewLine !== undefined)
24437 destEmitNode.startsOnNewLine = startsOnNewLine;
24438 return destEmitNode;
24439 }
24440 function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
24441 if (!destRanges)
24442 destRanges = [];
24443 for (var key in sourceRanges) {
24444 destRanges[key] = sourceRanges[key];
24445 }
24446 return destRanges;
24447 }
24448})(ts || (ts = {}));
24449var ts;
24450(function (ts) {
24451 /**
24452 * Associates a node with the current transformation, initializing
24453 * various transient transformation properties.
24454 * @internal
24455 */
24456 function getOrCreateEmitNode(node) {
24457 var _a;
24458 if (!node.emitNode) {
24459 if (ts.isParseTreeNode(node)) {
24460 // To avoid holding onto transformation artifacts, we keep track of any
24461 // parse tree node we are annotating. This allows us to clean them up after
24462 // all transformations have completed.
24463 if (node.kind === 294 /* SourceFile */) {
24464 return node.emitNode = { annotatedNodes: [node] };
24465 }
24466 var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
24467 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
24468 }
24469 node.emitNode = {};
24470 }
24471 return node.emitNode;
24472 }
24473 ts.getOrCreateEmitNode = getOrCreateEmitNode;
24474 /**
24475 * Clears any `EmitNode` entries from parse-tree nodes.
24476 * @param sourceFile A source file.
24477 */
24478 function disposeEmitNodes(sourceFile) {
24479 var _a, _b;
24480 // During transformation we may need to annotate a parse tree node with transient
24481 // transformation properties. As parse tree nodes live longer than transformation
24482 // nodes, we need to make sure we reclaim any memory allocated for custom ranges
24483 // from these nodes to ensure we do not hold onto entire subtrees just for position
24484 // information. We also need to reset these nodes to a pre-transformation state
24485 // for incremental parsing scenarios so that we do not impact later emit.
24486 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;
24487 if (annotatedNodes) {
24488 for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
24489 var node = annotatedNodes_1[_i];
24490 node.emitNode = undefined;
24491 }
24492 }
24493 }
24494 ts.disposeEmitNodes = disposeEmitNodes;
24495 /**
24496 * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
24497 * @internal
24498 */
24499 function removeAllComments(node) {
24500 var emitNode = getOrCreateEmitNode(node);
24501 emitNode.flags |= 1536 /* NoComments */;
24502 emitNode.leadingComments = undefined;
24503 emitNode.trailingComments = undefined;
24504 return node;
24505 }
24506 ts.removeAllComments = removeAllComments;
24507 /**
24508 * Sets flags that control emit behavior of a node.
24509 */
24510 function setEmitFlags(node, emitFlags) {
24511 getOrCreateEmitNode(node).flags = emitFlags;
24512 return node;
24513 }
24514 ts.setEmitFlags = setEmitFlags;
24515 /**
24516 * Sets flags that control emit behavior of a node.
24517 */
24518 /* @internal */
24519 function addEmitFlags(node, emitFlags) {
24520 var emitNode = getOrCreateEmitNode(node);
24521 emitNode.flags = emitNode.flags | emitFlags;
24522 return node;
24523 }
24524 ts.addEmitFlags = addEmitFlags;
24525 /**
24526 * Gets a custom text range to use when emitting source maps.
24527 */
24528 function getSourceMapRange(node) {
24529 var _a, _b;
24530 return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
24531 }
24532 ts.getSourceMapRange = getSourceMapRange;
24533 /**
24534 * Sets a custom text range to use when emitting source maps.
24535 */
24536 function setSourceMapRange(node, range) {
24537 getOrCreateEmitNode(node).sourceMapRange = range;
24538 return node;
24539 }
24540 ts.setSourceMapRange = setSourceMapRange;
24541 /**
24542 * Gets the TextRange to use for source maps for a token of a node.
24543 */
24544 function getTokenSourceMapRange(node, token) {
24545 var _a, _b;
24546 return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
24547 }
24548 ts.getTokenSourceMapRange = getTokenSourceMapRange;
24549 /**
24550 * Sets the TextRange to use for source maps for a token of a node.
24551 */
24552 function setTokenSourceMapRange(node, token, range) {
24553 var _a;
24554 var emitNode = getOrCreateEmitNode(node);
24555 var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
24556 tokenSourceMapRanges[token] = range;
24557 return node;
24558 }
24559 ts.setTokenSourceMapRange = setTokenSourceMapRange;
24560 /**
24561 * Gets a custom text range to use when emitting comments.
24562 */
24563 /*@internal*/
24564 function getStartsOnNewLine(node) {
24565 var _a;
24566 return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
24567 }
24568 ts.getStartsOnNewLine = getStartsOnNewLine;
24569 /**
24570 * Sets a custom text range to use when emitting comments.
24571 */
24572 /*@internal*/
24573 function setStartsOnNewLine(node, newLine) {
24574 getOrCreateEmitNode(node).startsOnNewLine = newLine;
24575 return node;
24576 }
24577 ts.setStartsOnNewLine = setStartsOnNewLine;
24578 /**
24579 * Gets a custom text range to use when emitting comments.
24580 */
24581 function getCommentRange(node) {
24582 var _a, _b;
24583 return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
24584 }
24585 ts.getCommentRange = getCommentRange;
24586 /**
24587 * Sets a custom text range to use when emitting comments.
24588 */
24589 function setCommentRange(node, range) {
24590 getOrCreateEmitNode(node).commentRange = range;
24591 return node;
24592 }
24593 ts.setCommentRange = setCommentRange;
24594 function getSyntheticLeadingComments(node) {
24595 var _a;
24596 return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
24597 }
24598 ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
24599 function setSyntheticLeadingComments(node, comments) {
24600 getOrCreateEmitNode(node).leadingComments = comments;
24601 return node;
24602 }
24603 ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
24604 function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
24605 return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
24606 }
24607 ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
24608 function getSyntheticTrailingComments(node) {
24609 var _a;
24610 return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
24611 }
24612 ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
24613 function setSyntheticTrailingComments(node, comments) {
24614 getOrCreateEmitNode(node).trailingComments = comments;
24615 return node;
24616 }
24617 ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
24618 function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
24619 return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
24620 }
24621 ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
24622 function moveSyntheticComments(node, original) {
24623 setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
24624 setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
24625 var emit = getOrCreateEmitNode(original);
24626 emit.leadingComments = undefined;
24627 emit.trailingComments = undefined;
24628 return node;
24629 }
24630 ts.moveSyntheticComments = moveSyntheticComments;
24631 /**
24632 * Gets the constant value to emit for an expression representing an enum.
24633 */
24634 function getConstantValue(node) {
24635 var _a;
24636 return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
24637 }
24638 ts.getConstantValue = getConstantValue;
24639 /**
24640 * Sets the constant value to emit for an expression.
24641 */
24642 function setConstantValue(node, value) {
24643 var emitNode = getOrCreateEmitNode(node);
24644 emitNode.constantValue = value;
24645 return node;
24646 }
24647 ts.setConstantValue = setConstantValue;
24648 /**
24649 * Adds an EmitHelper to a node.
24650 */
24651 function addEmitHelper(node, helper) {
24652 var emitNode = getOrCreateEmitNode(node);
24653 emitNode.helpers = ts.append(emitNode.helpers, helper);
24654 return node;
24655 }
24656 ts.addEmitHelper = addEmitHelper;
24657 /**
24658 * Add EmitHelpers to a node.
24659 */
24660 function addEmitHelpers(node, helpers) {
24661 if (ts.some(helpers)) {
24662 var emitNode = getOrCreateEmitNode(node);
24663 for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
24664 var helper = helpers_2[_i];
24665 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
24666 }
24667 }
24668 return node;
24669 }
24670 ts.addEmitHelpers = addEmitHelpers;
24671 /**
24672 * Removes an EmitHelper from a node.
24673 */
24674 function removeEmitHelper(node, helper) {
24675 var _a;
24676 var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
24677 if (helpers) {
24678 return ts.orderedRemoveItem(helpers, helper);
24679 }
24680 return false;
24681 }
24682 ts.removeEmitHelper = removeEmitHelper;
24683 /**
24684 * Gets the EmitHelpers of a node.
24685 */
24686 function getEmitHelpers(node) {
24687 var _a;
24688 return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
24689 }
24690 ts.getEmitHelpers = getEmitHelpers;
24691 /**
24692 * Moves matching emit helpers from a source node to a target node.
24693 */
24694 function moveEmitHelpers(source, target, predicate) {
24695 var sourceEmitNode = source.emitNode;
24696 var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
24697 if (!ts.some(sourceEmitHelpers))
24698 return;
24699 var targetEmitNode = getOrCreateEmitNode(target);
24700 var helpersRemoved = 0;
24701 for (var i = 0; i < sourceEmitHelpers.length; i++) {
24702 var helper = sourceEmitHelpers[i];
24703 if (predicate(helper)) {
24704 helpersRemoved++;
24705 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
24706 }
24707 else if (helpersRemoved > 0) {
24708 sourceEmitHelpers[i - helpersRemoved] = helper;
24709 }
24710 }
24711 if (helpersRemoved > 0) {
24712 sourceEmitHelpers.length -= helpersRemoved;
24713 }
24714 }
24715 ts.moveEmitHelpers = moveEmitHelpers;
24716 /* @internal */
24717 function ignoreSourceNewlines(node) {
24718 getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
24719 return node;
24720 }
24721 ts.ignoreSourceNewlines = ignoreSourceNewlines;
24722})(ts || (ts = {}));
24723/* @internal */
24724var ts;
24725(function (ts) {
24726 function createEmitHelperFactory(context) {
24727 var factory = context.factory;
24728 return {
24729 getUnscopedHelperName: getUnscopedHelperName,
24730 // TypeScript Helpers
24731 createDecorateHelper: createDecorateHelper,
24732 createMetadataHelper: createMetadataHelper,
24733 createParamHelper: createParamHelper,
24734 // ES2018 Helpers
24735 createAssignHelper: createAssignHelper,
24736 createAwaitHelper: createAwaitHelper,
24737 createAsyncGeneratorHelper: createAsyncGeneratorHelper,
24738 createAsyncDelegatorHelper: createAsyncDelegatorHelper,
24739 createAsyncValuesHelper: createAsyncValuesHelper,
24740 // ES2018 Destructuring Helpers
24741 createRestHelper: createRestHelper,
24742 // ES2017 Helpers
24743 createAwaiterHelper: createAwaiterHelper,
24744 // ES2015 Helpers
24745 createExtendsHelper: createExtendsHelper,
24746 createTemplateObjectHelper: createTemplateObjectHelper,
24747 createSpreadHelper: createSpreadHelper,
24748 createSpreadArraysHelper: createSpreadArraysHelper,
24749 // ES2015 Destructuring Helpers
24750 createValuesHelper: createValuesHelper,
24751 createReadHelper: createReadHelper,
24752 // ES2015 Generator Helpers
24753 createGeneratorHelper: createGeneratorHelper,
24754 // ES Module Helpers
24755 createCreateBindingHelper: createCreateBindingHelper,
24756 createImportStarHelper: createImportStarHelper,
24757 createImportStarCallbackHelper: createImportStarCallbackHelper,
24758 createImportDefaultHelper: createImportDefaultHelper,
24759 createExportStarHelper: createExportStarHelper,
24760 // Class Fields Helpers
24761 createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
24762 createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
24763 };
24764 /**
24765 * Gets an identifier for the name of an *unscoped* emit helper.
24766 */
24767 function getUnscopedHelperName(name) {
24768 return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
24769 }
24770 // TypeScript Helpers
24771 function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
24772 context.requestEmitHelper(ts.decorateHelper);
24773 var argumentsArray = [];
24774 argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
24775 argumentsArray.push(target);
24776 if (memberName) {
24777 argumentsArray.push(memberName);
24778 if (descriptor) {
24779 argumentsArray.push(descriptor);
24780 }
24781 }
24782 return factory.createCallExpression(getUnscopedHelperName("__decorate"),
24783 /*typeArguments*/ undefined, argumentsArray);
24784 }
24785 function createMetadataHelper(metadataKey, metadataValue) {
24786 context.requestEmitHelper(ts.metadataHelper);
24787 return factory.createCallExpression(getUnscopedHelperName("__metadata"),
24788 /*typeArguments*/ undefined, [
24789 factory.createStringLiteral(metadataKey),
24790 metadataValue
24791 ]);
24792 }
24793 function createParamHelper(expression, parameterOffset, location) {
24794 context.requestEmitHelper(ts.paramHelper);
24795 return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"),
24796 /*typeArguments*/ undefined, [
24797 factory.createNumericLiteral(parameterOffset + ""),
24798 expression
24799 ]), location);
24800 }
24801 // ES2018 Helpers
24802 function createAssignHelper(attributesSegments) {
24803 if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
24804 return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"),
24805 /*typeArguments*/ undefined, attributesSegments);
24806 }
24807 context.requestEmitHelper(ts.assignHelper);
24808 return factory.createCallExpression(getUnscopedHelperName("__assign"),
24809 /*typeArguments*/ undefined, attributesSegments);
24810 }
24811 function createAwaitHelper(expression) {
24812 context.requestEmitHelper(ts.awaitHelper);
24813 return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
24814 }
24815 function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
24816 context.requestEmitHelper(ts.awaitHelper);
24817 context.requestEmitHelper(ts.asyncGeneratorHelper);
24818 // Mark this node as originally an async function
24819 (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
24820 return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"),
24821 /*typeArguments*/ undefined, [
24822 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
24823 factory.createIdentifier("arguments"),
24824 generatorFunc
24825 ]);
24826 }
24827 function createAsyncDelegatorHelper(expression) {
24828 context.requestEmitHelper(ts.awaitHelper);
24829 context.requestEmitHelper(ts.asyncDelegator);
24830 return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"),
24831 /*typeArguments*/ undefined, [expression]);
24832 }
24833 function createAsyncValuesHelper(expression) {
24834 context.requestEmitHelper(ts.asyncValues);
24835 return factory.createCallExpression(getUnscopedHelperName("__asyncValues"),
24836 /*typeArguments*/ undefined, [expression]);
24837 }
24838 // ES2018 Destructuring Helpers
24839 /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
24840 * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
24841 */
24842 function createRestHelper(value, elements, computedTempVariables, location) {
24843 context.requestEmitHelper(ts.restHelper);
24844 var propertyNames = [];
24845 var computedTempVariableOffset = 0;
24846 for (var i = 0; i < elements.length - 1; i++) {
24847 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
24848 if (propertyName) {
24849 if (ts.isComputedPropertyName(propertyName)) {
24850 ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
24851 var temp = computedTempVariables[computedTempVariableOffset];
24852 computedTempVariableOffset++;
24853 // typeof _tmp === "symbol" ? _tmp : _tmp + ""
24854 propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"),
24855 /*questionToken*/ undefined, temp,
24856 /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
24857 }
24858 else {
24859 propertyNames.push(factory.createStringLiteralFromNode(propertyName));
24860 }
24861 }
24862 }
24863 return factory.createCallExpression(getUnscopedHelperName("__rest"),
24864 /*typeArguments*/ undefined, [
24865 value,
24866 ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
24867 ]);
24868 }
24869 // ES2017 Helpers
24870 function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
24871 context.requestEmitHelper(ts.awaiterHelper);
24872 var generatorFunc = factory.createFunctionExpression(
24873 /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */),
24874 /*name*/ undefined,
24875 /*typeParameters*/ undefined,
24876 /*parameters*/ [],
24877 /*type*/ undefined, body);
24878 // Mark this node as originally an async function
24879 (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
24880 return factory.createCallExpression(getUnscopedHelperName("__awaiter"),
24881 /*typeArguments*/ undefined, [
24882 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
24883 hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
24884 promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
24885 generatorFunc
24886 ]);
24887 }
24888 // ES2015 Helpers
24889 function createExtendsHelper(name) {
24890 context.requestEmitHelper(ts.extendsHelper);
24891 return factory.createCallExpression(getUnscopedHelperName("__extends"),
24892 /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
24893 }
24894 function createTemplateObjectHelper(cooked, raw) {
24895 context.requestEmitHelper(ts.templateObjectHelper);
24896 return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"),
24897 /*typeArguments*/ undefined, [cooked, raw]);
24898 }
24899 function createSpreadHelper(argumentList) {
24900 context.requestEmitHelper(ts.readHelper);
24901 context.requestEmitHelper(ts.spreadHelper);
24902 return factory.createCallExpression(getUnscopedHelperName("__spread"),
24903 /*typeArguments*/ undefined, argumentList);
24904 }
24905 function createSpreadArraysHelper(argumentList) {
24906 context.requestEmitHelper(ts.spreadArraysHelper);
24907 return factory.createCallExpression(getUnscopedHelperName("__spreadArrays"),
24908 /*typeArguments*/ undefined, argumentList);
24909 }
24910 // ES2015 Destructuring Helpers
24911 function createValuesHelper(expression) {
24912 context.requestEmitHelper(ts.valuesHelper);
24913 return factory.createCallExpression(getUnscopedHelperName("__values"),
24914 /*typeArguments*/ undefined, [expression]);
24915 }
24916 function createReadHelper(iteratorRecord, count) {
24917 context.requestEmitHelper(ts.readHelper);
24918 return factory.createCallExpression(getUnscopedHelperName("__read"),
24919 /*typeArguments*/ undefined, count !== undefined
24920 ? [iteratorRecord, factory.createNumericLiteral(count + "")]
24921 : [iteratorRecord]);
24922 }
24923 // ES2015 Generator Helpers
24924 function createGeneratorHelper(body) {
24925 context.requestEmitHelper(ts.generatorHelper);
24926 return factory.createCallExpression(getUnscopedHelperName("__generator"),
24927 /*typeArguments*/ undefined, [factory.createThis(), body]);
24928 }
24929 // ES Module Helpers
24930 function createCreateBindingHelper(module, inputName, outputName) {
24931 context.requestEmitHelper(ts.createBindingHelper);
24932 return factory.createCallExpression(getUnscopedHelperName("__createBinding"),
24933 /*typeArguments*/ undefined, __spreadArrays([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
24934 }
24935 function createImportStarHelper(expression) {
24936 context.requestEmitHelper(ts.importStarHelper);
24937 return factory.createCallExpression(getUnscopedHelperName("__importStar"),
24938 /*typeArguments*/ undefined, [expression]);
24939 }
24940 function createImportStarCallbackHelper() {
24941 context.requestEmitHelper(ts.importStarHelper);
24942 return getUnscopedHelperName("__importStar");
24943 }
24944 function createImportDefaultHelper(expression) {
24945 context.requestEmitHelper(ts.importDefaultHelper);
24946 return factory.createCallExpression(getUnscopedHelperName("__importDefault"),
24947 /*typeArguments*/ undefined, [expression]);
24948 }
24949 function createExportStarHelper(moduleExpression, exportsExpression) {
24950 if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
24951 context.requestEmitHelper(ts.exportStarHelper);
24952 context.requestEmitHelper(ts.createBindingHelper);
24953 return factory.createCallExpression(getUnscopedHelperName("__exportStar"),
24954 /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
24955 }
24956 // Class Fields Helpers
24957 function createClassPrivateFieldGetHelper(receiver, privateField) {
24958 context.requestEmitHelper(ts.classPrivateFieldGetHelper);
24959 return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]);
24960 }
24961 function createClassPrivateFieldSetHelper(receiver, privateField, value) {
24962 context.requestEmitHelper(ts.classPrivateFieldSetHelper);
24963 return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]);
24964 }
24965 }
24966 ts.createEmitHelperFactory = createEmitHelperFactory;
24967 /* @internal */
24968 function compareEmitHelpers(x, y) {
24969 if (x === y)
24970 return 0 /* EqualTo */;
24971 if (x.priority === y.priority)
24972 return 0 /* EqualTo */;
24973 if (x.priority === undefined)
24974 return 1 /* GreaterThan */;
24975 if (y.priority === undefined)
24976 return -1 /* LessThan */;
24977 return ts.compareValues(x.priority, y.priority);
24978 }
24979 ts.compareEmitHelpers = compareEmitHelpers;
24980 /**
24981 * @param input Template string input strings
24982 * @param args Names which need to be made file-level unique
24983 */
24984 function helperString(input) {
24985 var args = [];
24986 for (var _i = 1; _i < arguments.length; _i++) {
24987 args[_i - 1] = arguments[_i];
24988 }
24989 return function (uniqueName) {
24990 var result = "";
24991 for (var i = 0; i < args.length; i++) {
24992 result += input[i];
24993 result += uniqueName(args[i]);
24994 }
24995 result += input[input.length - 1];
24996 return result;
24997 };
24998 }
24999 ts.helperString = helperString;
25000 // TypeScript Helpers
25001 ts.decorateHelper = {
25002 name: "typescript:decorate",
25003 importName: "__decorate",
25004 scoped: false,
25005 priority: 2,
25006 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 };"
25007 };
25008 ts.metadataHelper = {
25009 name: "typescript:metadata",
25010 importName: "__metadata",
25011 scoped: false,
25012 priority: 3,
25013 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 };"
25014 };
25015 ts.paramHelper = {
25016 name: "typescript:param",
25017 importName: "__param",
25018 scoped: false,
25019 priority: 4,
25020 text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
25021 };
25022 // ES2018 Helpers
25023 ts.assignHelper = {
25024 name: "typescript:assign",
25025 importName: "__assign",
25026 scoped: false,
25027 priority: 1,
25028 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 };"
25029 };
25030 ts.awaitHelper = {
25031 name: "typescript:await",
25032 importName: "__await",
25033 scoped: false,
25034 text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
25035 };
25036 ts.asyncGeneratorHelper = {
25037 name: "typescript:asyncGenerator",
25038 importName: "__asyncGenerator",
25039 scoped: false,
25040 dependencies: [ts.awaitHelper],
25041 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 };"
25042 };
25043 ts.asyncDelegator = {
25044 name: "typescript:asyncDelegator",
25045 importName: "__asyncDelegator",
25046 scoped: false,
25047 dependencies: [ts.awaitHelper],
25048 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 };"
25049 };
25050 ts.asyncValues = {
25051 name: "typescript:asyncValues",
25052 importName: "__asyncValues",
25053 scoped: false,
25054 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 };"
25055 };
25056 // ES2018 Destructuring Helpers
25057 ts.restHelper = {
25058 name: "typescript:rest",
25059 importName: "__rest",
25060 scoped: false,
25061 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 };"
25062 };
25063 // ES2017 Helpers
25064 ts.awaiterHelper = {
25065 name: "typescript:awaiter",
25066 importName: "__awaiter",
25067 scoped: false,
25068 priority: 5,
25069 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 };"
25070 };
25071 // ES2015 Helpers
25072 ts.extendsHelper = {
25073 name: "typescript:extends",
25074 importName: "__extends",
25075 scoped: false,
25076 priority: 0,
25077 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 })();"
25078 };
25079 ts.templateObjectHelper = {
25080 name: "typescript:makeTemplateObject",
25081 importName: "__makeTemplateObject",
25082 scoped: false,
25083 priority: 0,
25084 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 };"
25085 };
25086 ts.readHelper = {
25087 name: "typescript:read",
25088 importName: "__read",
25089 scoped: false,
25090 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 };"
25091 };
25092 ts.spreadHelper = {
25093 name: "typescript:spread",
25094 importName: "__spread",
25095 scoped: false,
25096 dependencies: [ts.readHelper],
25097 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 };"
25098 };
25099 ts.spreadArraysHelper = {
25100 name: "typescript:spreadArrays",
25101 importName: "__spreadArrays",
25102 scoped: false,
25103 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 };"
25104 };
25105 // ES2015 Destructuring Helpers
25106 ts.valuesHelper = {
25107 name: "typescript:values",
25108 importName: "__values",
25109 scoped: false,
25110 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 };"
25111 };
25112 // ES2015 Generator Helpers
25113 // The __generator helper is used by down-level transformations to emulate the runtime
25114 // semantics of an ES2015 generator function. When called, this helper returns an
25115 // object that implements the Iterator protocol, in that it has `next`, `return`, and
25116 // `throw` methods that step through the generator when invoked.
25117 //
25118 // parameters:
25119 // @param thisArg The value to use as the `this` binding for the transformed generator body.
25120 // @param body A function that acts as the transformed generator body.
25121 //
25122 // variables:
25123 // _ Persistent state for the generator that is shared between the helper and the
25124 // generator body. The state object has the following members:
25125 // sent() - A method that returns or throws the current completion value.
25126 // label - The next point at which to resume evaluation of the generator body.
25127 // trys - A stack of protected regions (try/catch/finally blocks).
25128 // ops - A stack of pending instructions when inside of a finally block.
25129 // f A value indicating whether the generator is executing.
25130 // y An iterator to delegate for a yield*.
25131 // t A temporary variable that holds one of the following values (note that these
25132 // cases do not overlap):
25133 // - The completion value when resuming from a `yield` or `yield*`.
25134 // - The error value for a catch block.
25135 // - The current protected region (array of try/catch/finally/end labels).
25136 // - The verb (`next`, `throw`, or `return` method) to delegate to the expression
25137 // of a `yield*`.
25138 // - The result of evaluating the verb delegated to the expression of a `yield*`.
25139 //
25140 // functions:
25141 // verb(n) Creates a bound callback to the `step` function for opcode `n`.
25142 // step(op) Evaluates opcodes in a generator body until execution is suspended or
25143 // completed.
25144 //
25145 // The __generator helper understands a limited set of instructions:
25146 // 0: next(value?) - Start or resume the generator with the specified value.
25147 // 1: throw(error) - Resume the generator with an exception. If the generator is
25148 // suspended inside of one or more protected regions, evaluates
25149 // any intervening finally blocks between the current label and
25150 // the nearest catch block or function boundary. If uncaught, the
25151 // exception is thrown to the caller.
25152 // 2: return(value?) - Resume the generator as if with a return. If the generator is
25153 // suspended inside of one or more protected regions, evaluates any
25154 // intervening finally blocks.
25155 // 3: break(label) - Jump to the specified label. If the label is outside of the
25156 // current protected region, evaluates any intervening finally
25157 // blocks.
25158 // 4: yield(value?) - Yield execution to the caller with an optional value. When
25159 // resumed, the generator will continue at the next label.
25160 // 5: yield*(value) - Delegates evaluation to the supplied iterator. When
25161 // delegation completes, the generator will continue at the next
25162 // label.
25163 // 6: catch(error) - Handles an exception thrown from within the generator body. If
25164 // the current label is inside of one or more protected regions,
25165 // evaluates any intervening finally blocks between the current
25166 // label and the nearest catch block or function boundary. If
25167 // uncaught, the exception is thrown to the caller.
25168 // 7: endfinally - Ends a finally block, resuming the last instruction prior to
25169 // entering a finally block.
25170 //
25171 // For examples of how these are used, see the comments in ./transformers/generators.ts
25172 ts.generatorHelper = {
25173 name: "typescript:generator",
25174 importName: "__generator",
25175 scoped: false,
25176 priority: 6,
25177 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 };"
25178 };
25179 // ES Module Helpers
25180 ts.createBindingHelper = {
25181 name: "typescript:commonjscreatebinding",
25182 importName: "__createBinding",
25183 scoped: false,
25184 priority: 1,
25185 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 }));"
25186 };
25187 ts.setModuleDefaultHelper = {
25188 name: "typescript:commonjscreatevalue",
25189 importName: "__setModuleDefault",
25190 scoped: false,
25191 priority: 1,
25192 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 });"
25193 };
25194 // emit helper for `import * as Name from "foo"`
25195 ts.importStarHelper = {
25196 name: "typescript:commonjsimportstar",
25197 importName: "__importStar",
25198 scoped: false,
25199 dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
25200 priority: 2,
25201 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 };"
25202 };
25203 // emit helper for `import Name from "foo"`
25204 ts.importDefaultHelper = {
25205 name: "typescript:commonjsimportdefault",
25206 importName: "__importDefault",
25207 scoped: false,
25208 text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };"
25209 };
25210 // emit output for the __export helper function
25211 ts.exportStarHelper = {
25212 name: "typescript:export-star",
25213 importName: "__exportStar",
25214 scoped: false,
25215 dependencies: [ts.createBindingHelper],
25216 priority: 2,
25217 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 };"
25218 };
25219 // Class fields helpers
25220 ts.classPrivateFieldGetHelper = {
25221 name: "typescript:classPrivateFieldGet",
25222 importName: "__classPrivateFieldGet",
25223 scoped: false,
25224 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 };"
25225 };
25226 ts.classPrivateFieldSetHelper = {
25227 name: "typescript:classPrivateFieldSet",
25228 importName: "__classPrivateFieldSet",
25229 scoped: false,
25230 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 };"
25231 };
25232 var allUnscopedEmitHelpers;
25233 function getAllUnscopedEmitHelpers() {
25234 return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
25235 ts.decorateHelper,
25236 ts.metadataHelper,
25237 ts.paramHelper,
25238 ts.assignHelper,
25239 ts.awaitHelper,
25240 ts.asyncGeneratorHelper,
25241 ts.asyncDelegator,
25242 ts.asyncValues,
25243 ts.restHelper,
25244 ts.awaiterHelper,
25245 ts.extendsHelper,
25246 ts.templateObjectHelper,
25247 ts.spreadHelper,
25248 ts.spreadArraysHelper,
25249 ts.valuesHelper,
25250 ts.readHelper,
25251 ts.generatorHelper,
25252 ts.importStarHelper,
25253 ts.importDefaultHelper,
25254 ts.exportStarHelper,
25255 ts.classPrivateFieldGetHelper,
25256 ts.classPrivateFieldSetHelper,
25257 ts.createBindingHelper,
25258 ts.setModuleDefaultHelper
25259 ], function (helper) { return helper.name; }));
25260 }
25261 ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
25262 ts.asyncSuperHelper = {
25263 name: "typescript:async-super",
25264 scoped: true,
25265 text: helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex")
25266 };
25267 ts.advancedAsyncSuperHelper = {
25268 name: "typescript:advanced-async-super",
25269 scoped: true,
25270 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")
25271 };
25272})(ts || (ts = {}));
25273var ts;
25274(function (ts) {
25275 // Literals
25276 function isNumericLiteral(node) {
25277 return node.kind === 8 /* NumericLiteral */;
25278 }
25279 ts.isNumericLiteral = isNumericLiteral;
25280 function isBigIntLiteral(node) {
25281 return node.kind === 9 /* BigIntLiteral */;
25282 }
25283 ts.isBigIntLiteral = isBigIntLiteral;
25284 function isStringLiteral(node) {
25285 return node.kind === 10 /* StringLiteral */;
25286 }
25287 ts.isStringLiteral = isStringLiteral;
25288 function isJsxText(node) {
25289 return node.kind === 11 /* JsxText */;
25290 }
25291 ts.isJsxText = isJsxText;
25292 function isRegularExpressionLiteral(node) {
25293 return node.kind === 13 /* RegularExpressionLiteral */;
25294 }
25295 ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
25296 function isNoSubstitutionTemplateLiteral(node) {
25297 return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
25298 }
25299 ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
25300 // Pseudo-literals
25301 function isTemplateHead(node) {
25302 return node.kind === 15 /* TemplateHead */;
25303 }
25304 ts.isTemplateHead = isTemplateHead;
25305 function isTemplateMiddle(node) {
25306 return node.kind === 16 /* TemplateMiddle */;
25307 }
25308 ts.isTemplateMiddle = isTemplateMiddle;
25309 function isTemplateTail(node) {
25310 return node.kind === 17 /* TemplateTail */;
25311 }
25312 ts.isTemplateTail = isTemplateTail;
25313 // Identifiers
25314 function isIdentifier(node) {
25315 return node.kind === 78 /* Identifier */;
25316 }
25317 ts.isIdentifier = isIdentifier;
25318 // Names
25319 function isQualifiedName(node) {
25320 return node.kind === 156 /* QualifiedName */;
25321 }
25322 ts.isQualifiedName = isQualifiedName;
25323 function isComputedPropertyName(node) {
25324 return node.kind === 157 /* ComputedPropertyName */;
25325 }
25326 ts.isComputedPropertyName = isComputedPropertyName;
25327 function isPrivateIdentifier(node) {
25328 return node.kind === 79 /* PrivateIdentifier */;
25329 }
25330 ts.isPrivateIdentifier = isPrivateIdentifier;
25331 // Tokens
25332 /*@internal*/
25333 function isSuperKeyword(node) {
25334 return node.kind === 105 /* SuperKeyword */;
25335 }
25336 ts.isSuperKeyword = isSuperKeyword;
25337 /*@internal*/
25338 function isImportKeyword(node) {
25339 return node.kind === 99 /* ImportKeyword */;
25340 }
25341 ts.isImportKeyword = isImportKeyword;
25342 /*@internal*/
25343 function isCommaToken(node) {
25344 return node.kind === 27 /* CommaToken */;
25345 }
25346 ts.isCommaToken = isCommaToken;
25347 /*@internal*/
25348 function isQuestionToken(node) {
25349 return node.kind === 57 /* QuestionToken */;
25350 }
25351 ts.isQuestionToken = isQuestionToken;
25352 /*@internal*/
25353 function isExclamationToken(node) {
25354 return node.kind === 53 /* ExclamationToken */;
25355 }
25356 ts.isExclamationToken = isExclamationToken;
25357 // Signature elements
25358 function isTypeParameterDeclaration(node) {
25359 return node.kind === 158 /* TypeParameter */;
25360 }
25361 ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
25362 // TODO(rbuckton): Rename to 'isParameterDeclaration'
25363 function isParameter(node) {
25364 return node.kind === 159 /* Parameter */;
25365 }
25366 ts.isParameter = isParameter;
25367 function isDecorator(node) {
25368 return node.kind === 160 /* Decorator */;
25369 }
25370 ts.isDecorator = isDecorator;
25371 // TypeMember
25372 function isPropertySignature(node) {
25373 return node.kind === 161 /* PropertySignature */;
25374 }
25375 ts.isPropertySignature = isPropertySignature;
25376 function isPropertyDeclaration(node) {
25377 return node.kind === 162 /* PropertyDeclaration */;
25378 }
25379 ts.isPropertyDeclaration = isPropertyDeclaration;
25380 function isMethodSignature(node) {
25381 return node.kind === 163 /* MethodSignature */;
25382 }
25383 ts.isMethodSignature = isMethodSignature;
25384 function isMethodDeclaration(node) {
25385 return node.kind === 164 /* MethodDeclaration */;
25386 }
25387 ts.isMethodDeclaration = isMethodDeclaration;
25388 function isConstructorDeclaration(node) {
25389 return node.kind === 165 /* Constructor */;
25390 }
25391 ts.isConstructorDeclaration = isConstructorDeclaration;
25392 function isGetAccessorDeclaration(node) {
25393 return node.kind === 166 /* GetAccessor */;
25394 }
25395 ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
25396 function isSetAccessorDeclaration(node) {
25397 return node.kind === 167 /* SetAccessor */;
25398 }
25399 ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
25400 function isCallSignatureDeclaration(node) {
25401 return node.kind === 168 /* CallSignature */;
25402 }
25403 ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
25404 function isConstructSignatureDeclaration(node) {
25405 return node.kind === 169 /* ConstructSignature */;
25406 }
25407 ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
25408 function isIndexSignatureDeclaration(node) {
25409 return node.kind === 170 /* IndexSignature */;
25410 }
25411 ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
25412 // Type
25413 function isTypePredicateNode(node) {
25414 return node.kind === 171 /* TypePredicate */;
25415 }
25416 ts.isTypePredicateNode = isTypePredicateNode;
25417 function isTypeReferenceNode(node) {
25418 return node.kind === 172 /* TypeReference */;
25419 }
25420 ts.isTypeReferenceNode = isTypeReferenceNode;
25421 function isFunctionTypeNode(node) {
25422 return node.kind === 173 /* FunctionType */;
25423 }
25424 ts.isFunctionTypeNode = isFunctionTypeNode;
25425 function isConstructorTypeNode(node) {
25426 return node.kind === 174 /* ConstructorType */;
25427 }
25428 ts.isConstructorTypeNode = isConstructorTypeNode;
25429 function isTypeQueryNode(node) {
25430 return node.kind === 175 /* TypeQuery */;
25431 }
25432 ts.isTypeQueryNode = isTypeQueryNode;
25433 function isTypeLiteralNode(node) {
25434 return node.kind === 176 /* TypeLiteral */;
25435 }
25436 ts.isTypeLiteralNode = isTypeLiteralNode;
25437 function isArrayTypeNode(node) {
25438 return node.kind === 177 /* ArrayType */;
25439 }
25440 ts.isArrayTypeNode = isArrayTypeNode;
25441 function isTupleTypeNode(node) {
25442 return node.kind === 178 /* TupleType */;
25443 }
25444 ts.isTupleTypeNode = isTupleTypeNode;
25445 function isNamedTupleMember(node) {
25446 return node.kind === 191 /* NamedTupleMember */;
25447 }
25448 ts.isNamedTupleMember = isNamedTupleMember;
25449 function isOptionalTypeNode(node) {
25450 return node.kind === 179 /* OptionalType */;
25451 }
25452 ts.isOptionalTypeNode = isOptionalTypeNode;
25453 function isRestTypeNode(node) {
25454 return node.kind === 180 /* RestType */;
25455 }
25456 ts.isRestTypeNode = isRestTypeNode;
25457 function isUnionTypeNode(node) {
25458 return node.kind === 181 /* UnionType */;
25459 }
25460 ts.isUnionTypeNode = isUnionTypeNode;
25461 function isIntersectionTypeNode(node) {
25462 return node.kind === 182 /* IntersectionType */;
25463 }
25464 ts.isIntersectionTypeNode = isIntersectionTypeNode;
25465 function isConditionalTypeNode(node) {
25466 return node.kind === 183 /* ConditionalType */;
25467 }
25468 ts.isConditionalTypeNode = isConditionalTypeNode;
25469 function isInferTypeNode(node) {
25470 return node.kind === 184 /* InferType */;
25471 }
25472 ts.isInferTypeNode = isInferTypeNode;
25473 function isParenthesizedTypeNode(node) {
25474 return node.kind === 185 /* ParenthesizedType */;
25475 }
25476 ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
25477 function isThisTypeNode(node) {
25478 return node.kind === 186 /* ThisType */;
25479 }
25480 ts.isThisTypeNode = isThisTypeNode;
25481 function isTypeOperatorNode(node) {
25482 return node.kind === 187 /* TypeOperator */;
25483 }
25484 ts.isTypeOperatorNode = isTypeOperatorNode;
25485 function isIndexedAccessTypeNode(node) {
25486 return node.kind === 188 /* IndexedAccessType */;
25487 }
25488 ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
25489 function isMappedTypeNode(node) {
25490 return node.kind === 189 /* MappedType */;
25491 }
25492 ts.isMappedTypeNode = isMappedTypeNode;
25493 function isLiteralTypeNode(node) {
25494 return node.kind === 190 /* LiteralType */;
25495 }
25496 ts.isLiteralTypeNode = isLiteralTypeNode;
25497 function isImportTypeNode(node) {
25498 return node.kind === 192 /* ImportType */;
25499 }
25500 ts.isImportTypeNode = isImportTypeNode;
25501 // Binding patterns
25502 function isObjectBindingPattern(node) {
25503 return node.kind === 193 /* ObjectBindingPattern */;
25504 }
25505 ts.isObjectBindingPattern = isObjectBindingPattern;
25506 function isArrayBindingPattern(node) {
25507 return node.kind === 194 /* ArrayBindingPattern */;
25508 }
25509 ts.isArrayBindingPattern = isArrayBindingPattern;
25510 function isBindingElement(node) {
25511 return node.kind === 195 /* BindingElement */;
25512 }
25513 ts.isBindingElement = isBindingElement;
25514 // Expression
25515 function isArrayLiteralExpression(node) {
25516 return node.kind === 196 /* ArrayLiteralExpression */;
25517 }
25518 ts.isArrayLiteralExpression = isArrayLiteralExpression;
25519 function isObjectLiteralExpression(node) {
25520 return node.kind === 197 /* ObjectLiteralExpression */;
25521 }
25522 ts.isObjectLiteralExpression = isObjectLiteralExpression;
25523 function isPropertyAccessExpression(node) {
25524 return node.kind === 198 /* PropertyAccessExpression */;
25525 }
25526 ts.isPropertyAccessExpression = isPropertyAccessExpression;
25527 function isElementAccessExpression(node) {
25528 return node.kind === 199 /* ElementAccessExpression */;
25529 }
25530 ts.isElementAccessExpression = isElementAccessExpression;
25531 function isCallExpression(node) {
25532 return node.kind === 200 /* CallExpression */;
25533 }
25534 ts.isCallExpression = isCallExpression;
25535 function isNewExpression(node) {
25536 return node.kind === 201 /* NewExpression */;
25537 }
25538 ts.isNewExpression = isNewExpression;
25539 function isTaggedTemplateExpression(node) {
25540 return node.kind === 202 /* TaggedTemplateExpression */;
25541 }
25542 ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
25543 function isTypeAssertionExpression(node) {
25544 return node.kind === 203 /* TypeAssertionExpression */;
25545 }
25546 ts.isTypeAssertionExpression = isTypeAssertionExpression;
25547 function isParenthesizedExpression(node) {
25548 return node.kind === 204 /* ParenthesizedExpression */;
25549 }
25550 ts.isParenthesizedExpression = isParenthesizedExpression;
25551 function isFunctionExpression(node) {
25552 return node.kind === 205 /* FunctionExpression */;
25553 }
25554 ts.isFunctionExpression = isFunctionExpression;
25555 function isArrowFunction(node) {
25556 return node.kind === 206 /* ArrowFunction */;
25557 }
25558 ts.isArrowFunction = isArrowFunction;
25559 function isDeleteExpression(node) {
25560 return node.kind === 207 /* DeleteExpression */;
25561 }
25562 ts.isDeleteExpression = isDeleteExpression;
25563 function isTypeOfExpression(node) {
25564 return node.kind === 208 /* TypeOfExpression */;
25565 }
25566 ts.isTypeOfExpression = isTypeOfExpression;
25567 function isVoidExpression(node) {
25568 return node.kind === 209 /* VoidExpression */;
25569 }
25570 ts.isVoidExpression = isVoidExpression;
25571 function isAwaitExpression(node) {
25572 return node.kind === 210 /* AwaitExpression */;
25573 }
25574 ts.isAwaitExpression = isAwaitExpression;
25575 function isPrefixUnaryExpression(node) {
25576 return node.kind === 211 /* PrefixUnaryExpression */;
25577 }
25578 ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
25579 function isPostfixUnaryExpression(node) {
25580 return node.kind === 212 /* PostfixUnaryExpression */;
25581 }
25582 ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
25583 function isBinaryExpression(node) {
25584 return node.kind === 213 /* BinaryExpression */;
25585 }
25586 ts.isBinaryExpression = isBinaryExpression;
25587 function isConditionalExpression(node) {
25588 return node.kind === 214 /* ConditionalExpression */;
25589 }
25590 ts.isConditionalExpression = isConditionalExpression;
25591 function isTemplateExpression(node) {
25592 return node.kind === 215 /* TemplateExpression */;
25593 }
25594 ts.isTemplateExpression = isTemplateExpression;
25595 function isYieldExpression(node) {
25596 return node.kind === 216 /* YieldExpression */;
25597 }
25598 ts.isYieldExpression = isYieldExpression;
25599 function isSpreadElement(node) {
25600 return node.kind === 217 /* SpreadElement */;
25601 }
25602 ts.isSpreadElement = isSpreadElement;
25603 function isClassExpression(node) {
25604 return node.kind === 218 /* ClassExpression */;
25605 }
25606 ts.isClassExpression = isClassExpression;
25607 function isOmittedExpression(node) {
25608 return node.kind === 219 /* OmittedExpression */;
25609 }
25610 ts.isOmittedExpression = isOmittedExpression;
25611 function isExpressionWithTypeArguments(node) {
25612 return node.kind === 220 /* ExpressionWithTypeArguments */;
25613 }
25614 ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
25615 function isAsExpression(node) {
25616 return node.kind === 221 /* AsExpression */;
25617 }
25618 ts.isAsExpression = isAsExpression;
25619 function isNonNullExpression(node) {
25620 return node.kind === 222 /* NonNullExpression */;
25621 }
25622 ts.isNonNullExpression = isNonNullExpression;
25623 function isMetaProperty(node) {
25624 return node.kind === 223 /* MetaProperty */;
25625 }
25626 ts.isMetaProperty = isMetaProperty;
25627 function isSyntheticExpression(node) {
25628 return node.kind === 224 /* SyntheticExpression */;
25629 }
25630 ts.isSyntheticExpression = isSyntheticExpression;
25631 function isPartiallyEmittedExpression(node) {
25632 return node.kind === 331 /* PartiallyEmittedExpression */;
25633 }
25634 ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
25635 function isCommaListExpression(node) {
25636 return node.kind === 332 /* CommaListExpression */;
25637 }
25638 ts.isCommaListExpression = isCommaListExpression;
25639 // Misc
25640 function isTemplateSpan(node) {
25641 return node.kind === 225 /* TemplateSpan */;
25642 }
25643 ts.isTemplateSpan = isTemplateSpan;
25644 function isSemicolonClassElement(node) {
25645 return node.kind === 226 /* SemicolonClassElement */;
25646 }
25647 ts.isSemicolonClassElement = isSemicolonClassElement;
25648 // Elements
25649 function isBlock(node) {
25650 return node.kind === 227 /* Block */;
25651 }
25652 ts.isBlock = isBlock;
25653 function isVariableStatement(node) {
25654 return node.kind === 229 /* VariableStatement */;
25655 }
25656 ts.isVariableStatement = isVariableStatement;
25657 function isEmptyStatement(node) {
25658 return node.kind === 228 /* EmptyStatement */;
25659 }
25660 ts.isEmptyStatement = isEmptyStatement;
25661 function isExpressionStatement(node) {
25662 return node.kind === 230 /* ExpressionStatement */;
25663 }
25664 ts.isExpressionStatement = isExpressionStatement;
25665 function isIfStatement(node) {
25666 return node.kind === 231 /* IfStatement */;
25667 }
25668 ts.isIfStatement = isIfStatement;
25669 function isDoStatement(node) {
25670 return node.kind === 232 /* DoStatement */;
25671 }
25672 ts.isDoStatement = isDoStatement;
25673 function isWhileStatement(node) {
25674 return node.kind === 233 /* WhileStatement */;
25675 }
25676 ts.isWhileStatement = isWhileStatement;
25677 function isForStatement(node) {
25678 return node.kind === 234 /* ForStatement */;
25679 }
25680 ts.isForStatement = isForStatement;
25681 function isForInStatement(node) {
25682 return node.kind === 235 /* ForInStatement */;
25683 }
25684 ts.isForInStatement = isForInStatement;
25685 function isForOfStatement(node) {
25686 return node.kind === 236 /* ForOfStatement */;
25687 }
25688 ts.isForOfStatement = isForOfStatement;
25689 function isContinueStatement(node) {
25690 return node.kind === 237 /* ContinueStatement */;
25691 }
25692 ts.isContinueStatement = isContinueStatement;
25693 function isBreakStatement(node) {
25694 return node.kind === 238 /* BreakStatement */;
25695 }
25696 ts.isBreakStatement = isBreakStatement;
25697 function isReturnStatement(node) {
25698 return node.kind === 239 /* ReturnStatement */;
25699 }
25700 ts.isReturnStatement = isReturnStatement;
25701 function isWithStatement(node) {
25702 return node.kind === 240 /* WithStatement */;
25703 }
25704 ts.isWithStatement = isWithStatement;
25705 function isSwitchStatement(node) {
25706 return node.kind === 241 /* SwitchStatement */;
25707 }
25708 ts.isSwitchStatement = isSwitchStatement;
25709 function isLabeledStatement(node) {
25710 return node.kind === 242 /* LabeledStatement */;
25711 }
25712 ts.isLabeledStatement = isLabeledStatement;
25713 function isThrowStatement(node) {
25714 return node.kind === 243 /* ThrowStatement */;
25715 }
25716 ts.isThrowStatement = isThrowStatement;
25717 function isTryStatement(node) {
25718 return node.kind === 244 /* TryStatement */;
25719 }
25720 ts.isTryStatement = isTryStatement;
25721 function isDebuggerStatement(node) {
25722 return node.kind === 245 /* DebuggerStatement */;
25723 }
25724 ts.isDebuggerStatement = isDebuggerStatement;
25725 function isVariableDeclaration(node) {
25726 return node.kind === 246 /* VariableDeclaration */;
25727 }
25728 ts.isVariableDeclaration = isVariableDeclaration;
25729 function isVariableDeclarationList(node) {
25730 return node.kind === 247 /* VariableDeclarationList */;
25731 }
25732 ts.isVariableDeclarationList = isVariableDeclarationList;
25733 function isFunctionDeclaration(node) {
25734 return node.kind === 248 /* FunctionDeclaration */;
25735 }
25736 ts.isFunctionDeclaration = isFunctionDeclaration;
25737 function isClassDeclaration(node) {
25738 return node.kind === 249 /* ClassDeclaration */;
25739 }
25740 ts.isClassDeclaration = isClassDeclaration;
25741 function isInterfaceDeclaration(node) {
25742 return node.kind === 250 /* InterfaceDeclaration */;
25743 }
25744 ts.isInterfaceDeclaration = isInterfaceDeclaration;
25745 function isTypeAliasDeclaration(node) {
25746 return node.kind === 251 /* TypeAliasDeclaration */;
25747 }
25748 ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
25749 function isEnumDeclaration(node) {
25750 return node.kind === 252 /* EnumDeclaration */;
25751 }
25752 ts.isEnumDeclaration = isEnumDeclaration;
25753 function isModuleDeclaration(node) {
25754 return node.kind === 253 /* ModuleDeclaration */;
25755 }
25756 ts.isModuleDeclaration = isModuleDeclaration;
25757 function isModuleBlock(node) {
25758 return node.kind === 254 /* ModuleBlock */;
25759 }
25760 ts.isModuleBlock = isModuleBlock;
25761 function isCaseBlock(node) {
25762 return node.kind === 255 /* CaseBlock */;
25763 }
25764 ts.isCaseBlock = isCaseBlock;
25765 function isNamespaceExportDeclaration(node) {
25766 return node.kind === 256 /* NamespaceExportDeclaration */;
25767 }
25768 ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
25769 function isImportEqualsDeclaration(node) {
25770 return node.kind === 257 /* ImportEqualsDeclaration */;
25771 }
25772 ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
25773 function isImportDeclaration(node) {
25774 return node.kind === 258 /* ImportDeclaration */;
25775 }
25776 ts.isImportDeclaration = isImportDeclaration;
25777 function isImportClause(node) {
25778 return node.kind === 259 /* ImportClause */;
25779 }
25780 ts.isImportClause = isImportClause;
25781 function isNamespaceImport(node) {
25782 return node.kind === 260 /* NamespaceImport */;
25783 }
25784 ts.isNamespaceImport = isNamespaceImport;
25785 function isNamespaceExport(node) {
25786 return node.kind === 266 /* NamespaceExport */;
25787 }
25788 ts.isNamespaceExport = isNamespaceExport;
25789 function isNamedImports(node) {
25790 return node.kind === 261 /* NamedImports */;
25791 }
25792 ts.isNamedImports = isNamedImports;
25793 function isImportSpecifier(node) {
25794 return node.kind === 262 /* ImportSpecifier */;
25795 }
25796 ts.isImportSpecifier = isImportSpecifier;
25797 function isExportAssignment(node) {
25798 return node.kind === 263 /* ExportAssignment */;
25799 }
25800 ts.isExportAssignment = isExportAssignment;
25801 function isExportDeclaration(node) {
25802 return node.kind === 264 /* ExportDeclaration */;
25803 }
25804 ts.isExportDeclaration = isExportDeclaration;
25805 function isNamedExports(node) {
25806 return node.kind === 265 /* NamedExports */;
25807 }
25808 ts.isNamedExports = isNamedExports;
25809 function isExportSpecifier(node) {
25810 return node.kind === 267 /* ExportSpecifier */;
25811 }
25812 ts.isExportSpecifier = isExportSpecifier;
25813 function isMissingDeclaration(node) {
25814 return node.kind === 268 /* MissingDeclaration */;
25815 }
25816 ts.isMissingDeclaration = isMissingDeclaration;
25817 function isNotEmittedStatement(node) {
25818 return node.kind === 330 /* NotEmittedStatement */;
25819 }
25820 ts.isNotEmittedStatement = isNotEmittedStatement;
25821 /* @internal */
25822 function isSyntheticReference(node) {
25823 return node.kind === 335 /* SyntheticReferenceExpression */;
25824 }
25825 ts.isSyntheticReference = isSyntheticReference;
25826 /* @internal */
25827 function isMergeDeclarationMarker(node) {
25828 return node.kind === 333 /* MergeDeclarationMarker */;
25829 }
25830 ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
25831 /* @internal */
25832 function isEndOfDeclarationMarker(node) {
25833 return node.kind === 334 /* EndOfDeclarationMarker */;
25834 }
25835 ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
25836 // Module References
25837 function isExternalModuleReference(node) {
25838 return node.kind === 269 /* ExternalModuleReference */;
25839 }
25840 ts.isExternalModuleReference = isExternalModuleReference;
25841 // JSX
25842 function isJsxElement(node) {
25843 return node.kind === 270 /* JsxElement */;
25844 }
25845 ts.isJsxElement = isJsxElement;
25846 function isJsxSelfClosingElement(node) {
25847 return node.kind === 271 /* JsxSelfClosingElement */;
25848 }
25849 ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
25850 function isJsxOpeningElement(node) {
25851 return node.kind === 272 /* JsxOpeningElement */;
25852 }
25853 ts.isJsxOpeningElement = isJsxOpeningElement;
25854 function isJsxClosingElement(node) {
25855 return node.kind === 273 /* JsxClosingElement */;
25856 }
25857 ts.isJsxClosingElement = isJsxClosingElement;
25858 function isJsxFragment(node) {
25859 return node.kind === 274 /* JsxFragment */;
25860 }
25861 ts.isJsxFragment = isJsxFragment;
25862 function isJsxOpeningFragment(node) {
25863 return node.kind === 275 /* JsxOpeningFragment */;
25864 }
25865 ts.isJsxOpeningFragment = isJsxOpeningFragment;
25866 function isJsxClosingFragment(node) {
25867 return node.kind === 276 /* JsxClosingFragment */;
25868 }
25869 ts.isJsxClosingFragment = isJsxClosingFragment;
25870 function isJsxAttribute(node) {
25871 return node.kind === 277 /* JsxAttribute */;
25872 }
25873 ts.isJsxAttribute = isJsxAttribute;
25874 function isJsxAttributes(node) {
25875 return node.kind === 278 /* JsxAttributes */;
25876 }
25877 ts.isJsxAttributes = isJsxAttributes;
25878 function isJsxSpreadAttribute(node) {
25879 return node.kind === 279 /* JsxSpreadAttribute */;
25880 }
25881 ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
25882 function isJsxExpression(node) {
25883 return node.kind === 280 /* JsxExpression */;
25884 }
25885 ts.isJsxExpression = isJsxExpression;
25886 // Clauses
25887 function isCaseClause(node) {
25888 return node.kind === 281 /* CaseClause */;
25889 }
25890 ts.isCaseClause = isCaseClause;
25891 function isDefaultClause(node) {
25892 return node.kind === 282 /* DefaultClause */;
25893 }
25894 ts.isDefaultClause = isDefaultClause;
25895 function isHeritageClause(node) {
25896 return node.kind === 283 /* HeritageClause */;
25897 }
25898 ts.isHeritageClause = isHeritageClause;
25899 function isCatchClause(node) {
25900 return node.kind === 284 /* CatchClause */;
25901 }
25902 ts.isCatchClause = isCatchClause;
25903 // Property assignments
25904 function isPropertyAssignment(node) {
25905 return node.kind === 285 /* PropertyAssignment */;
25906 }
25907 ts.isPropertyAssignment = isPropertyAssignment;
25908 function isShorthandPropertyAssignment(node) {
25909 return node.kind === 286 /* ShorthandPropertyAssignment */;
25910 }
25911 ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
25912 function isSpreadAssignment(node) {
25913 return node.kind === 287 /* SpreadAssignment */;
25914 }
25915 ts.isSpreadAssignment = isSpreadAssignment;
25916 // Enum
25917 function isEnumMember(node) {
25918 return node.kind === 288 /* EnumMember */;
25919 }
25920 ts.isEnumMember = isEnumMember;
25921 // Unparsed
25922 // TODO(rbuckton): isUnparsedPrologue
25923 function isUnparsedPrepend(node) {
25924 return node.kind === 290 /* UnparsedPrepend */;
25925 }
25926 ts.isUnparsedPrepend = isUnparsedPrepend;
25927 // TODO(rbuckton): isUnparsedText
25928 // TODO(rbuckton): isUnparsedInternalText
25929 // TODO(rbuckton): isUnparsedSyntheticReference
25930 // Top-level nodes
25931 function isSourceFile(node) {
25932 return node.kind === 294 /* SourceFile */;
25933 }
25934 ts.isSourceFile = isSourceFile;
25935 function isBundle(node) {
25936 return node.kind === 295 /* Bundle */;
25937 }
25938 ts.isBundle = isBundle;
25939 function isUnparsedSource(node) {
25940 return node.kind === 296 /* UnparsedSource */;
25941 }
25942 ts.isUnparsedSource = isUnparsedSource;
25943 // TODO(rbuckton): isInputFiles
25944 // JSDoc Elements
25945 function isJSDocTypeExpression(node) {
25946 return node.kind === 298 /* JSDocTypeExpression */;
25947 }
25948 ts.isJSDocTypeExpression = isJSDocTypeExpression;
25949 function isJSDocAllType(node) {
25950 return node.kind === 299 /* JSDocAllType */;
25951 }
25952 ts.isJSDocAllType = isJSDocAllType;
25953 function isJSDocUnknownType(node) {
25954 return node.kind === 300 /* JSDocUnknownType */;
25955 }
25956 ts.isJSDocUnknownType = isJSDocUnknownType;
25957 function isJSDocNullableType(node) {
25958 return node.kind === 301 /* JSDocNullableType */;
25959 }
25960 ts.isJSDocNullableType = isJSDocNullableType;
25961 function isJSDocNonNullableType(node) {
25962 return node.kind === 302 /* JSDocNonNullableType */;
25963 }
25964 ts.isJSDocNonNullableType = isJSDocNonNullableType;
25965 function isJSDocOptionalType(node) {
25966 return node.kind === 303 /* JSDocOptionalType */;
25967 }
25968 ts.isJSDocOptionalType = isJSDocOptionalType;
25969 function isJSDocFunctionType(node) {
25970 return node.kind === 304 /* JSDocFunctionType */;
25971 }
25972 ts.isJSDocFunctionType = isJSDocFunctionType;
25973 function isJSDocVariadicType(node) {
25974 return node.kind === 305 /* JSDocVariadicType */;
25975 }
25976 ts.isJSDocVariadicType = isJSDocVariadicType;
25977 function isJSDocNamepathType(node) {
25978 return node.kind === 306 /* JSDocNamepathType */;
25979 }
25980 ts.isJSDocNamepathType = isJSDocNamepathType;
25981 function isJSDoc(node) {
25982 return node.kind === 307 /* JSDocComment */;
25983 }
25984 ts.isJSDoc = isJSDoc;
25985 function isJSDocTypeLiteral(node) {
25986 return node.kind === 308 /* JSDocTypeLiteral */;
25987 }
25988 ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
25989 function isJSDocSignature(node) {
25990 return node.kind === 309 /* JSDocSignature */;
25991 }
25992 ts.isJSDocSignature = isJSDocSignature;
25993 // JSDoc Tags
25994 function isJSDocAugmentsTag(node) {
25995 return node.kind === 311 /* JSDocAugmentsTag */;
25996 }
25997 ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
25998 function isJSDocAuthorTag(node) {
25999 return node.kind === 313 /* JSDocAuthorTag */;
26000 }
26001 ts.isJSDocAuthorTag = isJSDocAuthorTag;
26002 function isJSDocClassTag(node) {
26003 return node.kind === 315 /* JSDocClassTag */;
26004 }
26005 ts.isJSDocClassTag = isJSDocClassTag;
26006 function isJSDocCallbackTag(node) {
26007 return node.kind === 320 /* JSDocCallbackTag */;
26008 }
26009 ts.isJSDocCallbackTag = isJSDocCallbackTag;
26010 function isJSDocPublicTag(node) {
26011 return node.kind === 316 /* JSDocPublicTag */;
26012 }
26013 ts.isJSDocPublicTag = isJSDocPublicTag;
26014 function isJSDocPrivateTag(node) {
26015 return node.kind === 317 /* JSDocPrivateTag */;
26016 }
26017 ts.isJSDocPrivateTag = isJSDocPrivateTag;
26018 function isJSDocProtectedTag(node) {
26019 return node.kind === 318 /* JSDocProtectedTag */;
26020 }
26021 ts.isJSDocProtectedTag = isJSDocProtectedTag;
26022 function isJSDocReadonlyTag(node) {
26023 return node.kind === 319 /* JSDocReadonlyTag */;
26024 }
26025 ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
26026 function isJSDocDeprecatedTag(node) {
26027 return node.kind === 314 /* JSDocDeprecatedTag */;
26028 }
26029 ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
26030 function isJSDocEnumTag(node) {
26031 return node.kind === 321 /* JSDocEnumTag */;
26032 }
26033 ts.isJSDocEnumTag = isJSDocEnumTag;
26034 function isJSDocParameterTag(node) {
26035 return node.kind === 322 /* JSDocParameterTag */;
26036 }
26037 ts.isJSDocParameterTag = isJSDocParameterTag;
26038 function isJSDocReturnTag(node) {
26039 return node.kind === 323 /* JSDocReturnTag */;
26040 }
26041 ts.isJSDocReturnTag = isJSDocReturnTag;
26042 function isJSDocThisTag(node) {
26043 return node.kind === 324 /* JSDocThisTag */;
26044 }
26045 ts.isJSDocThisTag = isJSDocThisTag;
26046 function isJSDocTypeTag(node) {
26047 return node.kind === 325 /* JSDocTypeTag */;
26048 }
26049 ts.isJSDocTypeTag = isJSDocTypeTag;
26050 function isJSDocTemplateTag(node) {
26051 return node.kind === 326 /* JSDocTemplateTag */;
26052 }
26053 ts.isJSDocTemplateTag = isJSDocTemplateTag;
26054 function isJSDocTypedefTag(node) {
26055 return node.kind === 327 /* JSDocTypedefTag */;
26056 }
26057 ts.isJSDocTypedefTag = isJSDocTypedefTag;
26058 function isJSDocUnknownTag(node) {
26059 return node.kind === 310 /* JSDocTag */;
26060 }
26061 ts.isJSDocUnknownTag = isJSDocUnknownTag;
26062 function isJSDocPropertyTag(node) {
26063 return node.kind === 328 /* JSDocPropertyTag */;
26064 }
26065 ts.isJSDocPropertyTag = isJSDocPropertyTag;
26066 function isJSDocImplementsTag(node) {
26067 return node.kind === 312 /* JSDocImplementsTag */;
26068 }
26069 ts.isJSDocImplementsTag = isJSDocImplementsTag;
26070 // Synthesized list
26071 /* @internal */
26072 function isSyntaxList(n) {
26073 return n.kind === 329 /* SyntaxList */;
26074 }
26075 ts.isSyntaxList = isSyntaxList;
26076})(ts || (ts = {}));
26077/* @internal */
26078var ts;
26079(function (ts) {
26080 // Compound nodes
26081 function createEmptyExports(factory) {
26082 return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
26083 }
26084 ts.createEmptyExports = createEmptyExports;
26085 function createMemberAccessForPropertyName(factory, target, memberName, location) {
26086 if (ts.isComputedPropertyName(memberName)) {
26087 return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
26088 }
26089 else {
26090 var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName)
26091 ? factory.createPropertyAccessExpression(target, memberName)
26092 : factory.createElementAccessExpression(target, memberName), memberName);
26093 ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
26094 return expression;
26095 }
26096 }
26097 ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
26098 function createReactNamespace(reactNamespace, parent) {
26099 // To ensure the emit resolver can properly resolve the namespace, we need to
26100 // treat this identifier as if it were a source tree node by clearing the `Synthesized`
26101 // flag and setting a parent node.
26102 var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
26103 // Set the parent that is in parse tree
26104 // this makes sure that parent chain is intact for checker to traverse complete scope tree
26105 ts.setParent(react, ts.getParseTreeNode(parent));
26106 return react;
26107 }
26108 function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
26109 if (ts.isQualifiedName(jsxFactory)) {
26110 var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
26111 var right = factory.createIdentifier(ts.idText(jsxFactory.right));
26112 right.escapedText = jsxFactory.right.escapedText;
26113 return factory.createPropertyAccessExpression(left, right);
26114 }
26115 else {
26116 return createReactNamespace(ts.idText(jsxFactory), parent);
26117 }
26118 }
26119 function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
26120 return jsxFactoryEntity ?
26121 createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
26122 factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
26123 }
26124 function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
26125 return jsxFragmentFactoryEntity ?
26126 createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
26127 factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
26128 }
26129 function createExpressionForJsxElement(factory, jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
26130 var argumentsList = [tagName];
26131 if (props) {
26132 argumentsList.push(props);
26133 }
26134 if (children && children.length > 0) {
26135 if (!props) {
26136 argumentsList.push(factory.createNull());
26137 }
26138 if (children.length > 1) {
26139 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
26140 var child = children_3[_i];
26141 startOnNewLine(child);
26142 argumentsList.push(child);
26143 }
26144 }
26145 else {
26146 argumentsList.push(children[0]);
26147 }
26148 }
26149 return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement),
26150 /*typeArguments*/ undefined, argumentsList), location);
26151 }
26152 ts.createExpressionForJsxElement = createExpressionForJsxElement;
26153 function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
26154 var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
26155 var argumentsList = [tagName, factory.createNull()];
26156 if (children && children.length > 0) {
26157 if (children.length > 1) {
26158 for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
26159 var child = children_4[_i];
26160 startOnNewLine(child);
26161 argumentsList.push(child);
26162 }
26163 }
26164 else {
26165 argumentsList.push(children[0]);
26166 }
26167 }
26168 return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement),
26169 /*typeArguments*/ undefined, argumentsList), location);
26170 }
26171 ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
26172 // Utilities
26173 function createForOfBindingStatement(factory, node, boundValue) {
26174 if (ts.isVariableDeclarationList(node)) {
26175 var firstDeclaration = ts.first(node.declarations);
26176 var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
26177 /*exclamationToken*/ undefined,
26178 /*type*/ undefined, boundValue);
26179 return ts.setTextRange(factory.createVariableStatement(
26180 /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])),
26181 /*location*/ node);
26182 }
26183 else {
26184 var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
26185 return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
26186 }
26187 }
26188 ts.createForOfBindingStatement = createForOfBindingStatement;
26189 function insertLeadingStatement(factory, dest, source) {
26190 if (ts.isBlock(dest)) {
26191 return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
26192 }
26193 else {
26194 return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
26195 }
26196 }
26197 ts.insertLeadingStatement = insertLeadingStatement;
26198 function createExpressionFromEntityName(factory, node) {
26199 if (ts.isQualifiedName(node)) {
26200 var left = createExpressionFromEntityName(factory, node.left);
26201 // TODO(rbuckton): Does this need to be parented?
26202 var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
26203 return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
26204 }
26205 else {
26206 // TODO(rbuckton): Does this need to be parented?
26207 return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
26208 }
26209 }
26210 ts.createExpressionFromEntityName = createExpressionFromEntityName;
26211 function createExpressionForPropertyName(factory, memberName) {
26212 if (ts.isIdentifier(memberName)) {
26213 return factory.createStringLiteralFromNode(memberName);
26214 }
26215 else if (ts.isComputedPropertyName(memberName)) {
26216 // TODO(rbuckton): Does this need to be parented?
26217 return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
26218 }
26219 else {
26220 // TODO(rbuckton): Does this need to be parented?
26221 return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
26222 }
26223 }
26224 ts.createExpressionForPropertyName = createExpressionForPropertyName;
26225 function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
26226 var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
26227 if (property === firstAccessor) {
26228 return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
26229 enumerable: factory.createFalse(),
26230 configurable: true,
26231 get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers,
26232 /*asteriskToken*/ undefined,
26233 /*name*/ undefined,
26234 /*typeParameters*/ undefined, getAccessor.parameters,
26235 /*type*/ undefined, getAccessor.body // TODO: GH#18217
26236 ), getAccessor), getAccessor),
26237 set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers,
26238 /*asteriskToken*/ undefined,
26239 /*name*/ undefined,
26240 /*typeParameters*/ undefined, setAccessor.parameters,
26241 /*type*/ undefined, setAccessor.body // TODO: GH#18217
26242 ), setAccessor), setAccessor)
26243 }, !multiLine)), firstAccessor);
26244 }
26245 return undefined;
26246 }
26247 function createExpressionForPropertyAssignment(factory, property, receiver) {
26248 return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
26249 }
26250 function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
26251 return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)),
26252 /*location*/ property),
26253 /*original*/ property);
26254 }
26255 function createExpressionForMethodDeclaration(factory, method, receiver) {
26256 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,
26257 /*name*/ undefined,
26258 /*typeParameters*/ undefined, method.parameters,
26259 /*type*/ undefined, method.body // TODO: GH#18217
26260 ),
26261 /*location*/ method),
26262 /*original*/ method)),
26263 /*location*/ method),
26264 /*original*/ method);
26265 }
26266 function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
26267 if (property.name && ts.isPrivateIdentifier(property.name)) {
26268 ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
26269 }
26270 switch (property.kind) {
26271 case 166 /* GetAccessor */:
26272 case 167 /* SetAccessor */:
26273 return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
26274 case 285 /* PropertyAssignment */:
26275 return createExpressionForPropertyAssignment(factory, property, receiver);
26276 case 286 /* ShorthandPropertyAssignment */:
26277 return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
26278 case 164 /* MethodDeclaration */:
26279 return createExpressionForMethodDeclaration(factory, property, receiver);
26280 }
26281 }
26282 ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
26283 /**
26284 * Gets whether an identifier should only be referred to by its internal name.
26285 */
26286 function isInternalName(node) {
26287 return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
26288 }
26289 ts.isInternalName = isInternalName;
26290 /**
26291 * Gets whether an identifier should only be referred to by its local name.
26292 */
26293 function isLocalName(node) {
26294 return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
26295 }
26296 ts.isLocalName = isLocalName;
26297 /**
26298 * Gets whether an identifier should only be referred to by its export representation if the
26299 * name points to an exported symbol.
26300 */
26301 function isExportName(node) {
26302 return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
26303 }
26304 ts.isExportName = isExportName;
26305 function isUseStrictPrologue(node) {
26306 return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
26307 }
26308 function findUseStrictPrologue(statements) {
26309 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
26310 var statement = statements_1[_i];
26311 if (ts.isPrologueDirective(statement)) {
26312 if (isUseStrictPrologue(statement)) {
26313 return statement;
26314 }
26315 }
26316 else {
26317 break;
26318 }
26319 }
26320 return undefined;
26321 }
26322 ts.findUseStrictPrologue = findUseStrictPrologue;
26323 function startsWithUseStrict(statements) {
26324 var firstStatement = ts.firstOrUndefined(statements);
26325 return firstStatement !== undefined
26326 && ts.isPrologueDirective(firstStatement)
26327 && isUseStrictPrologue(firstStatement);
26328 }
26329 ts.startsWithUseStrict = startsWithUseStrict;
26330 function isCommaSequence(node) {
26331 return node.kind === 213 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
26332 node.kind === 332 /* CommaListExpression */;
26333 }
26334 ts.isCommaSequence = isCommaSequence;
26335 function isOuterExpression(node, kinds) {
26336 if (kinds === void 0) { kinds = 15 /* All */; }
26337 switch (node.kind) {
26338 case 204 /* ParenthesizedExpression */:
26339 return (kinds & 1 /* Parentheses */) !== 0;
26340 case 203 /* TypeAssertionExpression */:
26341 case 221 /* AsExpression */:
26342 return (kinds & 2 /* TypeAssertions */) !== 0;
26343 case 222 /* NonNullExpression */:
26344 return (kinds & 4 /* NonNullAssertions */) !== 0;
26345 case 331 /* PartiallyEmittedExpression */:
26346 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
26347 }
26348 return false;
26349 }
26350 ts.isOuterExpression = isOuterExpression;
26351 function skipOuterExpressions(node, kinds) {
26352 if (kinds === void 0) { kinds = 15 /* All */; }
26353 while (isOuterExpression(node, kinds)) {
26354 node = node.expression;
26355 }
26356 return node;
26357 }
26358 ts.skipOuterExpressions = skipOuterExpressions;
26359 function skipAssertions(node) {
26360 return skipOuterExpressions(node, 6 /* Assertions */);
26361 }
26362 ts.skipAssertions = skipAssertions;
26363 function startOnNewLine(node) {
26364 return ts.setStartsOnNewLine(node, /*newLine*/ true);
26365 }
26366 ts.startOnNewLine = startOnNewLine;
26367 function getExternalHelpersModuleName(node) {
26368 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
26369 var emitNode = parseNode && parseNode.emitNode;
26370 return emitNode && emitNode.externalHelpersModuleName;
26371 }
26372 ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
26373 function hasRecordedExternalHelpers(sourceFile) {
26374 var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
26375 var emitNode = parseNode && parseNode.emitNode;
26376 return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
26377 }
26378 ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
26379 function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
26380 if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
26381 var namedBindings = void 0;
26382 var moduleKind = ts.getEmitModuleKind(compilerOptions);
26383 if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
26384 // use named imports
26385 var helpers = ts.getEmitHelpers(sourceFile);
26386 if (helpers) {
26387 var helperNames = [];
26388 for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
26389 var helper = helpers_3[_i];
26390 if (!helper.scoped) {
26391 var importName = helper.importName;
26392 if (importName) {
26393 ts.pushIfUnique(helperNames, importName);
26394 }
26395 }
26396 }
26397 if (ts.some(helperNames)) {
26398 helperNames.sort(ts.compareStringsCaseSensitive);
26399 // Alias the imports if the names are used somewhere in the file.
26400 // NOTE: We don't need to care about global import collisions as this is a module.
26401 namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
26402 ? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
26403 : nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
26404 var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
26405 var emitNode = ts.getOrCreateEmitNode(parseNode);
26406 emitNode.externalHelpers = true;
26407 }
26408 }
26409 }
26410 else {
26411 // use a namespace import
26412 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
26413 if (externalHelpersModuleName) {
26414 namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
26415 }
26416 }
26417 if (namedBindings) {
26418 var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
26419 /*decorators*/ undefined,
26420 /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText));
26421 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
26422 return externalHelpersImportDeclaration;
26423 }
26424 }
26425 }
26426 ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
26427 function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
26428 if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
26429 var externalHelpersModuleName = getExternalHelpersModuleName(node);
26430 if (externalHelpersModuleName) {
26431 return externalHelpersModuleName;
26432 }
26433 var moduleKind = ts.getEmitModuleKind(compilerOptions);
26434 var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
26435 && moduleKind !== ts.ModuleKind.System
26436 && moduleKind < ts.ModuleKind.ES2015;
26437 if (!create) {
26438 var helpers = ts.getEmitHelpers(node);
26439 if (helpers) {
26440 for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
26441 var helper = helpers_4[_i];
26442 if (!helper.scoped) {
26443 create = true;
26444 break;
26445 }
26446 }
26447 }
26448 }
26449 if (create) {
26450 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
26451 var emitNode = ts.getOrCreateEmitNode(parseNode);
26452 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
26453 }
26454 }
26455 }
26456 ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
26457 /**
26458 * Get the name of that target module from an import or export declaration
26459 */
26460 function getLocalNameForExternalImport(factory, node, sourceFile) {
26461 var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
26462 if (namespaceDeclaration && !ts.isDefaultImport(node)) {
26463 var name = namespaceDeclaration.name;
26464 return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
26465 }
26466 if (node.kind === 258 /* ImportDeclaration */ && node.importClause) {
26467 return factory.getGeneratedNameForNode(node);
26468 }
26469 if (node.kind === 264 /* ExportDeclaration */ && node.moduleSpecifier) {
26470 return factory.getGeneratedNameForNode(node);
26471 }
26472 return undefined;
26473 }
26474 ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
26475 /**
26476 * Get the name of a target module from an import/export declaration as should be written in the emitted output.
26477 * The emitted output name can be different from the input if:
26478 * 1. The module has a /// <amd-module name="<new name>" />
26479 * 2. --out or --outFile is used, making the name relative to the rootDir
26480 * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
26481 * Otherwise, a new StringLiteral node representing the module name will be returned.
26482 */
26483 function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
26484 var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
26485 if (moduleName.kind === 10 /* StringLiteral */) {
26486 return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
26487 || tryRenameExternalModule(factory, moduleName, sourceFile)
26488 || factory.cloneNode(moduleName);
26489 }
26490 return undefined;
26491 }
26492 ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
26493 /**
26494 * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
26495 * Here we check if alternative name was provided for a given moduleName and return it if possible.
26496 */
26497 function tryRenameExternalModule(factory, moduleName, sourceFile) {
26498 var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
26499 return rename && factory.createStringLiteral(rename);
26500 }
26501 /**
26502 * Get the name of a module as should be written in the emitted output.
26503 * The emitted output name can be different from the input if:
26504 * 1. The module has a /// <amd-module name="<new name>" />
26505 * 2. --out or --outFile is used, making the name relative to the rootDir
26506 * Otherwise, a new StringLiteral node representing the module name will be returned.
26507 */
26508 function tryGetModuleNameFromFile(factory, file, host, options) {
26509 if (!file) {
26510 return undefined;
26511 }
26512 if (file.moduleName) {
26513 return factory.createStringLiteral(file.moduleName);
26514 }
26515 if (!file.isDeclarationFile && ts.outFile(options)) {
26516 return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
26517 }
26518 return undefined;
26519 }
26520 ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
26521 function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
26522 return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
26523 }
26524 /**
26525 * Gets the initializer of an BindingOrAssignmentElement.
26526 */
26527 function getInitializerOfBindingOrAssignmentElement(bindingElement) {
26528 if (ts.isDeclarationBindingElement(bindingElement)) {
26529 // `1` in `let { a = 1 } = ...`
26530 // `1` in `let { a: b = 1 } = ...`
26531 // `1` in `let { a: {b} = 1 } = ...`
26532 // `1` in `let { a: [b] = 1 } = ...`
26533 // `1` in `let [a = 1] = ...`
26534 // `1` in `let [{a} = 1] = ...`
26535 // `1` in `let [[a] = 1] = ...`
26536 return bindingElement.initializer;
26537 }
26538 if (ts.isPropertyAssignment(bindingElement)) {
26539 // `1` in `({ a: b = 1 } = ...)`
26540 // `1` in `({ a: {b} = 1 } = ...)`
26541 // `1` in `({ a: [b] = 1 } = ...)`
26542 var initializer = bindingElement.initializer;
26543 return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
26544 ? initializer.right
26545 : undefined;
26546 }
26547 if (ts.isShorthandPropertyAssignment(bindingElement)) {
26548 // `1` in `({ a = 1 } = ...)`
26549 return bindingElement.objectAssignmentInitializer;
26550 }
26551 if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
26552 // `1` in `[a = 1] = ...`
26553 // `1` in `[{a} = 1] = ...`
26554 // `1` in `[[a] = 1] = ...`
26555 return bindingElement.right;
26556 }
26557 if (ts.isSpreadElement(bindingElement)) {
26558 // Recovery consistent with existing emit.
26559 return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
26560 }
26561 }
26562 ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
26563 /**
26564 * Gets the name of an BindingOrAssignmentElement.
26565 */
26566 function getTargetOfBindingOrAssignmentElement(bindingElement) {
26567 if (ts.isDeclarationBindingElement(bindingElement)) {
26568 // `a` in `let { a } = ...`
26569 // `a` in `let { a = 1 } = ...`
26570 // `b` in `let { a: b } = ...`
26571 // `b` in `let { a: b = 1 } = ...`
26572 // `a` in `let { ...a } = ...`
26573 // `{b}` in `let { a: {b} } = ...`
26574 // `{b}` in `let { a: {b} = 1 } = ...`
26575 // `[b]` in `let { a: [b] } = ...`
26576 // `[b]` in `let { a: [b] = 1 } = ...`
26577 // `a` in `let [a] = ...`
26578 // `a` in `let [a = 1] = ...`
26579 // `a` in `let [...a] = ...`
26580 // `{a}` in `let [{a}] = ...`
26581 // `{a}` in `let [{a} = 1] = ...`
26582 // `[a]` in `let [[a]] = ...`
26583 // `[a]` in `let [[a] = 1] = ...`
26584 return bindingElement.name;
26585 }
26586 if (ts.isObjectLiteralElementLike(bindingElement)) {
26587 switch (bindingElement.kind) {
26588 case 285 /* PropertyAssignment */:
26589 // `b` in `({ a: b } = ...)`
26590 // `b` in `({ a: b = 1 } = ...)`
26591 // `{b}` in `({ a: {b} } = ...)`
26592 // `{b}` in `({ a: {b} = 1 } = ...)`
26593 // `[b]` in `({ a: [b] } = ...)`
26594 // `[b]` in `({ a: [b] = 1 } = ...)`
26595 // `b.c` in `({ a: b.c } = ...)`
26596 // `b.c` in `({ a: b.c = 1 } = ...)`
26597 // `b[0]` in `({ a: b[0] } = ...)`
26598 // `b[0]` in `({ a: b[0] = 1 } = ...)`
26599 return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
26600 case 286 /* ShorthandPropertyAssignment */:
26601 // `a` in `({ a } = ...)`
26602 // `a` in `({ a = 1 } = ...)`
26603 return bindingElement.name;
26604 case 287 /* SpreadAssignment */:
26605 // `a` in `({ ...a } = ...)`
26606 return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
26607 }
26608 // no target
26609 return undefined;
26610 }
26611 if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
26612 // `a` in `[a = 1] = ...`
26613 // `{a}` in `[{a} = 1] = ...`
26614 // `[a]` in `[[a] = 1] = ...`
26615 // `a.b` in `[a.b = 1] = ...`
26616 // `a[0]` in `[a[0] = 1] = ...`
26617 return getTargetOfBindingOrAssignmentElement(bindingElement.left);
26618 }
26619 if (ts.isSpreadElement(bindingElement)) {
26620 // `a` in `[...a] = ...`
26621 return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
26622 }
26623 // `a` in `[a] = ...`
26624 // `{a}` in `[{a}] = ...`
26625 // `[a]` in `[[a]] = ...`
26626 // `a.b` in `[a.b] = ...`
26627 // `a[0]` in `[a[0]] = ...`
26628 return bindingElement;
26629 }
26630 ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
26631 /**
26632 * Determines whether an BindingOrAssignmentElement is a rest element.
26633 */
26634 function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
26635 switch (bindingElement.kind) {
26636 case 159 /* Parameter */:
26637 case 195 /* BindingElement */:
26638 // `...` in `let [...a] = ...`
26639 return bindingElement.dotDotDotToken;
26640 case 217 /* SpreadElement */:
26641 case 287 /* SpreadAssignment */:
26642 // `...` in `[...a] = ...`
26643 return bindingElement;
26644 }
26645 return undefined;
26646 }
26647 ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
26648 /**
26649 * Gets the property name of a BindingOrAssignmentElement
26650 */
26651 function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
26652 var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
26653 ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
26654 return propertyName;
26655 }
26656 ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
26657 function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
26658 switch (bindingElement.kind) {
26659 case 195 /* BindingElement */:
26660 // `a` in `let { a: b } = ...`
26661 // `[a]` in `let { [a]: b } = ...`
26662 // `"a"` in `let { "a": b } = ...`
26663 // `1` in `let { 1: b } = ...`
26664 if (bindingElement.propertyName) {
26665 var propertyName = bindingElement.propertyName;
26666 if (ts.isPrivateIdentifier(propertyName)) {
26667 return ts.Debug.failBadSyntaxKind(propertyName);
26668 }
26669 return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
26670 ? propertyName.expression
26671 : propertyName;
26672 }
26673 break;
26674 case 285 /* PropertyAssignment */:
26675 // `a` in `({ a: b } = ...)`
26676 // `[a]` in `({ [a]: b } = ...)`
26677 // `"a"` in `({ "a": b } = ...)`
26678 // `1` in `({ 1: b } = ...)`
26679 if (bindingElement.name) {
26680 var propertyName = bindingElement.name;
26681 if (ts.isPrivateIdentifier(propertyName)) {
26682 return ts.Debug.failBadSyntaxKind(propertyName);
26683 }
26684 return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
26685 ? propertyName.expression
26686 : propertyName;
26687 }
26688 break;
26689 case 287 /* SpreadAssignment */:
26690 // `a` in `({ ...a } = ...)`
26691 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
26692 return ts.Debug.failBadSyntaxKind(bindingElement.name);
26693 }
26694 return bindingElement.name;
26695 }
26696 var target = getTargetOfBindingOrAssignmentElement(bindingElement);
26697 if (target && ts.isPropertyName(target)) {
26698 return target;
26699 }
26700 }
26701 ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
26702 function isStringOrNumericLiteral(node) {
26703 var kind = node.kind;
26704 return kind === 10 /* StringLiteral */
26705 || kind === 8 /* NumericLiteral */;
26706 }
26707 /**
26708 * Gets the elements of a BindingOrAssignmentPattern
26709 */
26710 function getElementsOfBindingOrAssignmentPattern(name) {
26711 switch (name.kind) {
26712 case 193 /* ObjectBindingPattern */:
26713 case 194 /* ArrayBindingPattern */:
26714 case 196 /* ArrayLiteralExpression */:
26715 // `a` in `{a}`
26716 // `a` in `[a]`
26717 return name.elements;
26718 case 197 /* ObjectLiteralExpression */:
26719 // `a` in `{a}`
26720 return name.properties;
26721 }
26722 }
26723 ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
26724 /* @internal */
26725 function getJSDocTypeAliasName(fullName) {
26726 if (fullName) {
26727 var rightNode = fullName;
26728 while (true) {
26729 if (ts.isIdentifier(rightNode) || !rightNode.body) {
26730 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
26731 }
26732 rightNode = rightNode.body;
26733 }
26734 }
26735 }
26736 ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
26737 function canHaveModifiers(node) {
26738 var kind = node.kind;
26739 return kind === 159 /* Parameter */
26740 || kind === 161 /* PropertySignature */
26741 || kind === 162 /* PropertyDeclaration */
26742 || kind === 163 /* MethodSignature */
26743 || kind === 164 /* MethodDeclaration */
26744 || kind === 165 /* Constructor */
26745 || kind === 166 /* GetAccessor */
26746 || kind === 167 /* SetAccessor */
26747 || kind === 170 /* IndexSignature */
26748 || kind === 205 /* FunctionExpression */
26749 || kind === 206 /* ArrowFunction */
26750 || kind === 218 /* ClassExpression */
26751 || kind === 229 /* VariableStatement */
26752 || kind === 248 /* FunctionDeclaration */
26753 || kind === 249 /* ClassDeclaration */
26754 || kind === 250 /* InterfaceDeclaration */
26755 || kind === 251 /* TypeAliasDeclaration */
26756 || kind === 252 /* EnumDeclaration */
26757 || kind === 253 /* ModuleDeclaration */
26758 || kind === 257 /* ImportEqualsDeclaration */
26759 || kind === 258 /* ImportDeclaration */
26760 || kind === 263 /* ExportAssignment */
26761 || kind === 264 /* ExportDeclaration */;
26762 }
26763 ts.canHaveModifiers = canHaveModifiers;
26764 /* @internal */
26765 function isExportModifier(node) {
26766 return node.kind === 92 /* ExportKeyword */;
26767 }
26768 ts.isExportModifier = isExportModifier;
26769 /* @internal */
26770 function isAsyncModifier(node) {
26771 return node.kind === 129 /* AsyncKeyword */;
26772 }
26773 ts.isAsyncModifier = isAsyncModifier;
26774 /* @internal */
26775 function isStaticModifier(node) {
26776 return node.kind === 123 /* StaticKeyword */;
26777 }
26778 ts.isStaticModifier = isStaticModifier;
26779})(ts || (ts = {}));
26780var ts;
26781(function (ts) {
26782 function setTextRange(range, location) {
26783 return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
26784 }
26785 ts.setTextRange = setTextRange;
26786})(ts || (ts = {}));
26787var ts;
26788(function (ts) {
26789 var SignatureFlags;
26790 (function (SignatureFlags) {
26791 SignatureFlags[SignatureFlags["None"] = 0] = "None";
26792 SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
26793 SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
26794 SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
26795 SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
26796 SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
26797 })(SignatureFlags || (SignatureFlags = {}));
26798 var SpeculationKind;
26799 (function (SpeculationKind) {
26800 SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
26801 SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
26802 SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
26803 })(SpeculationKind || (SpeculationKind = {}));
26804 var NodeConstructor;
26805 var TokenConstructor;
26806 var IdentifierConstructor;
26807 var PrivateIdentifierConstructor;
26808 var SourceFileConstructor;
26809 /**
26810 * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/compat/deprecations.ts`.
26811 */
26812 /* @internal */
26813 ts.parseBaseNodeFactory = {
26814 createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
26815 createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
26816 createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
26817 createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
26818 createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
26819 };
26820 /* @internal */
26821 ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
26822 function visitNode(cbNode, node) {
26823 return node && cbNode(node);
26824 }
26825 function visitNodes(cbNode, cbNodes, nodes) {
26826 if (nodes) {
26827 if (cbNodes) {
26828 return cbNodes(nodes);
26829 }
26830 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
26831 var node = nodes_1[_i];
26832 var result = cbNode(node);
26833 if (result) {
26834 return result;
26835 }
26836 }
26837 }
26838 }
26839 /*@internal*/
26840 function isJSDocLikeText(text, start) {
26841 return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
26842 text.charCodeAt(start + 2) === 42 /* asterisk */ &&
26843 text.charCodeAt(start + 3) !== 47 /* slash */;
26844 }
26845 ts.isJSDocLikeText = isJSDocLikeText;
26846 /**
26847 * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
26848 * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
26849 * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
26850 * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
26851 *
26852 * @param node a given node to visit its children
26853 * @param cbNode a callback to be invoked for all child nodes
26854 * @param cbNodes a callback to be invoked for embedded array
26855 *
26856 * @remarks `forEachChild` must visit the children of a node in the order
26857 * that they appear in the source code. The language service depends on this property to locate nodes by position.
26858 */
26859 function forEachChild(node, cbNode, cbNodes) {
26860 if (!node || node.kind <= 155 /* LastToken */) {
26861 return;
26862 }
26863 switch (node.kind) {
26864 case 156 /* QualifiedName */:
26865 return visitNode(cbNode, node.left) ||
26866 visitNode(cbNode, node.right);
26867 case 158 /* TypeParameter */:
26868 return visitNode(cbNode, node.name) ||
26869 visitNode(cbNode, node.constraint) ||
26870 visitNode(cbNode, node.default) ||
26871 visitNode(cbNode, node.expression);
26872 case 286 /* ShorthandPropertyAssignment */:
26873 return visitNodes(cbNode, cbNodes, node.decorators) ||
26874 visitNodes(cbNode, cbNodes, node.modifiers) ||
26875 visitNode(cbNode, node.name) ||
26876 visitNode(cbNode, node.questionToken) ||
26877 visitNode(cbNode, node.exclamationToken) ||
26878 visitNode(cbNode, node.equalsToken) ||
26879 visitNode(cbNode, node.objectAssignmentInitializer);
26880 case 287 /* SpreadAssignment */:
26881 return visitNode(cbNode, node.expression);
26882 case 159 /* Parameter */:
26883 return visitNodes(cbNode, cbNodes, node.decorators) ||
26884 visitNodes(cbNode, cbNodes, node.modifiers) ||
26885 visitNode(cbNode, node.dotDotDotToken) ||
26886 visitNode(cbNode, node.name) ||
26887 visitNode(cbNode, node.questionToken) ||
26888 visitNode(cbNode, node.type) ||
26889 visitNode(cbNode, node.initializer);
26890 case 162 /* PropertyDeclaration */:
26891 return visitNodes(cbNode, cbNodes, node.decorators) ||
26892 visitNodes(cbNode, cbNodes, node.modifiers) ||
26893 visitNode(cbNode, node.name) ||
26894 visitNode(cbNode, node.questionToken) ||
26895 visitNode(cbNode, node.exclamationToken) ||
26896 visitNode(cbNode, node.type) ||
26897 visitNode(cbNode, node.initializer);
26898 case 161 /* PropertySignature */:
26899 return visitNodes(cbNode, cbNodes, node.decorators) ||
26900 visitNodes(cbNode, cbNodes, node.modifiers) ||
26901 visitNode(cbNode, node.name) ||
26902 visitNode(cbNode, node.questionToken) ||
26903 visitNode(cbNode, node.type) ||
26904 visitNode(cbNode, node.initializer);
26905 case 285 /* PropertyAssignment */:
26906 return visitNodes(cbNode, cbNodes, node.decorators) ||
26907 visitNodes(cbNode, cbNodes, node.modifiers) ||
26908 visitNode(cbNode, node.name) ||
26909 visitNode(cbNode, node.questionToken) ||
26910 visitNode(cbNode, node.initializer);
26911 case 246 /* VariableDeclaration */:
26912 return visitNodes(cbNode, cbNodes, node.decorators) ||
26913 visitNodes(cbNode, cbNodes, node.modifiers) ||
26914 visitNode(cbNode, node.name) ||
26915 visitNode(cbNode, node.exclamationToken) ||
26916 visitNode(cbNode, node.type) ||
26917 visitNode(cbNode, node.initializer);
26918 case 195 /* BindingElement */:
26919 return visitNodes(cbNode, cbNodes, node.decorators) ||
26920 visitNodes(cbNode, cbNodes, node.modifiers) ||
26921 visitNode(cbNode, node.dotDotDotToken) ||
26922 visitNode(cbNode, node.propertyName) ||
26923 visitNode(cbNode, node.name) ||
26924 visitNode(cbNode, node.initializer);
26925 case 173 /* FunctionType */:
26926 case 174 /* ConstructorType */:
26927 case 168 /* CallSignature */:
26928 case 169 /* ConstructSignature */:
26929 case 170 /* IndexSignature */:
26930 return visitNodes(cbNode, cbNodes, node.decorators) ||
26931 visitNodes(cbNode, cbNodes, node.modifiers) ||
26932 visitNodes(cbNode, cbNodes, node.typeParameters) ||
26933 visitNodes(cbNode, cbNodes, node.parameters) ||
26934 visitNode(cbNode, node.type);
26935 case 164 /* MethodDeclaration */:
26936 case 163 /* MethodSignature */:
26937 case 165 /* Constructor */:
26938 case 166 /* GetAccessor */:
26939 case 167 /* SetAccessor */:
26940 case 205 /* FunctionExpression */:
26941 case 248 /* FunctionDeclaration */:
26942 case 206 /* ArrowFunction */:
26943 return visitNodes(cbNode, cbNodes, node.decorators) ||
26944 visitNodes(cbNode, cbNodes, node.modifiers) ||
26945 visitNode(cbNode, node.asteriskToken) ||
26946 visitNode(cbNode, node.name) ||
26947 visitNode(cbNode, node.questionToken) ||
26948 visitNode(cbNode, node.exclamationToken) ||
26949 visitNodes(cbNode, cbNodes, node.typeParameters) ||
26950 visitNodes(cbNode, cbNodes, node.parameters) ||
26951 visitNode(cbNode, node.type) ||
26952 visitNode(cbNode, node.equalsGreaterThanToken) ||
26953 visitNode(cbNode, node.body);
26954 case 172 /* TypeReference */:
26955 return visitNode(cbNode, node.typeName) ||
26956 visitNodes(cbNode, cbNodes, node.typeArguments);
26957 case 171 /* TypePredicate */:
26958 return visitNode(cbNode, node.assertsModifier) ||
26959 visitNode(cbNode, node.parameterName) ||
26960 visitNode(cbNode, node.type);
26961 case 175 /* TypeQuery */:
26962 return visitNode(cbNode, node.exprName);
26963 case 176 /* TypeLiteral */:
26964 return visitNodes(cbNode, cbNodes, node.members);
26965 case 177 /* ArrayType */:
26966 return visitNode(cbNode, node.elementType);
26967 case 178 /* TupleType */:
26968 return visitNodes(cbNode, cbNodes, node.elements);
26969 case 181 /* UnionType */:
26970 case 182 /* IntersectionType */:
26971 return visitNodes(cbNode, cbNodes, node.types);
26972 case 183 /* ConditionalType */:
26973 return visitNode(cbNode, node.checkType) ||
26974 visitNode(cbNode, node.extendsType) ||
26975 visitNode(cbNode, node.trueType) ||
26976 visitNode(cbNode, node.falseType);
26977 case 184 /* InferType */:
26978 return visitNode(cbNode, node.typeParameter);
26979 case 192 /* ImportType */:
26980 return visitNode(cbNode, node.argument) ||
26981 visitNode(cbNode, node.qualifier) ||
26982 visitNodes(cbNode, cbNodes, node.typeArguments);
26983 case 185 /* ParenthesizedType */:
26984 case 187 /* TypeOperator */:
26985 return visitNode(cbNode, node.type);
26986 case 188 /* IndexedAccessType */:
26987 return visitNode(cbNode, node.objectType) ||
26988 visitNode(cbNode, node.indexType);
26989 case 189 /* MappedType */:
26990 return visitNode(cbNode, node.readonlyToken) ||
26991 visitNode(cbNode, node.typeParameter) ||
26992 visitNode(cbNode, node.questionToken) ||
26993 visitNode(cbNode, node.type);
26994 case 190 /* LiteralType */:
26995 return visitNode(cbNode, node.literal);
26996 case 191 /* NamedTupleMember */:
26997 return visitNode(cbNode, node.dotDotDotToken) ||
26998 visitNode(cbNode, node.name) ||
26999 visitNode(cbNode, node.questionToken) ||
27000 visitNode(cbNode, node.type);
27001 case 193 /* ObjectBindingPattern */:
27002 case 194 /* ArrayBindingPattern */:
27003 return visitNodes(cbNode, cbNodes, node.elements);
27004 case 196 /* ArrayLiteralExpression */:
27005 return visitNodes(cbNode, cbNodes, node.elements);
27006 case 197 /* ObjectLiteralExpression */:
27007 return visitNodes(cbNode, cbNodes, node.properties);
27008 case 198 /* PropertyAccessExpression */:
27009 return visitNode(cbNode, node.expression) ||
27010 visitNode(cbNode, node.questionDotToken) ||
27011 visitNode(cbNode, node.name);
27012 case 199 /* ElementAccessExpression */:
27013 return visitNode(cbNode, node.expression) ||
27014 visitNode(cbNode, node.questionDotToken) ||
27015 visitNode(cbNode, node.argumentExpression);
27016 case 200 /* CallExpression */:
27017 case 201 /* NewExpression */:
27018 return visitNode(cbNode, node.expression) ||
27019 visitNode(cbNode, node.questionDotToken) ||
27020 visitNodes(cbNode, cbNodes, node.typeArguments) ||
27021 visitNodes(cbNode, cbNodes, node.arguments);
27022 case 202 /* TaggedTemplateExpression */:
27023 return visitNode(cbNode, node.tag) ||
27024 visitNode(cbNode, node.questionDotToken) ||
27025 visitNodes(cbNode, cbNodes, node.typeArguments) ||
27026 visitNode(cbNode, node.template);
27027 case 203 /* TypeAssertionExpression */:
27028 return visitNode(cbNode, node.type) ||
27029 visitNode(cbNode, node.expression);
27030 case 204 /* ParenthesizedExpression */:
27031 return visitNode(cbNode, node.expression);
27032 case 207 /* DeleteExpression */:
27033 return visitNode(cbNode, node.expression);
27034 case 208 /* TypeOfExpression */:
27035 return visitNode(cbNode, node.expression);
27036 case 209 /* VoidExpression */:
27037 return visitNode(cbNode, node.expression);
27038 case 211 /* PrefixUnaryExpression */:
27039 return visitNode(cbNode, node.operand);
27040 case 216 /* YieldExpression */:
27041 return visitNode(cbNode, node.asteriskToken) ||
27042 visitNode(cbNode, node.expression);
27043 case 210 /* AwaitExpression */:
27044 return visitNode(cbNode, node.expression);
27045 case 212 /* PostfixUnaryExpression */:
27046 return visitNode(cbNode, node.operand);
27047 case 213 /* BinaryExpression */:
27048 return visitNode(cbNode, node.left) ||
27049 visitNode(cbNode, node.operatorToken) ||
27050 visitNode(cbNode, node.right);
27051 case 221 /* AsExpression */:
27052 return visitNode(cbNode, node.expression) ||
27053 visitNode(cbNode, node.type);
27054 case 222 /* NonNullExpression */:
27055 return visitNode(cbNode, node.expression);
27056 case 223 /* MetaProperty */:
27057 return visitNode(cbNode, node.name);
27058 case 214 /* ConditionalExpression */:
27059 return visitNode(cbNode, node.condition) ||
27060 visitNode(cbNode, node.questionToken) ||
27061 visitNode(cbNode, node.whenTrue) ||
27062 visitNode(cbNode, node.colonToken) ||
27063 visitNode(cbNode, node.whenFalse);
27064 case 217 /* SpreadElement */:
27065 return visitNode(cbNode, node.expression);
27066 case 227 /* Block */:
27067 case 254 /* ModuleBlock */:
27068 return visitNodes(cbNode, cbNodes, node.statements);
27069 case 294 /* SourceFile */:
27070 return visitNodes(cbNode, cbNodes, node.statements) ||
27071 visitNode(cbNode, node.endOfFileToken);
27072 case 229 /* VariableStatement */:
27073 return visitNodes(cbNode, cbNodes, node.decorators) ||
27074 visitNodes(cbNode, cbNodes, node.modifiers) ||
27075 visitNode(cbNode, node.declarationList);
27076 case 247 /* VariableDeclarationList */:
27077 return visitNodes(cbNode, cbNodes, node.declarations);
27078 case 230 /* ExpressionStatement */:
27079 return visitNode(cbNode, node.expression);
27080 case 231 /* IfStatement */:
27081 return visitNode(cbNode, node.expression) ||
27082 visitNode(cbNode, node.thenStatement) ||
27083 visitNode(cbNode, node.elseStatement);
27084 case 232 /* DoStatement */:
27085 return visitNode(cbNode, node.statement) ||
27086 visitNode(cbNode, node.expression);
27087 case 233 /* WhileStatement */:
27088 return visitNode(cbNode, node.expression) ||
27089 visitNode(cbNode, node.statement);
27090 case 234 /* ForStatement */:
27091 return visitNode(cbNode, node.initializer) ||
27092 visitNode(cbNode, node.condition) ||
27093 visitNode(cbNode, node.incrementor) ||
27094 visitNode(cbNode, node.statement);
27095 case 235 /* ForInStatement */:
27096 return visitNode(cbNode, node.initializer) ||
27097 visitNode(cbNode, node.expression) ||
27098 visitNode(cbNode, node.statement);
27099 case 236 /* ForOfStatement */:
27100 return visitNode(cbNode, node.awaitModifier) ||
27101 visitNode(cbNode, node.initializer) ||
27102 visitNode(cbNode, node.expression) ||
27103 visitNode(cbNode, node.statement);
27104 case 237 /* ContinueStatement */:
27105 case 238 /* BreakStatement */:
27106 return visitNode(cbNode, node.label);
27107 case 239 /* ReturnStatement */:
27108 return visitNode(cbNode, node.expression);
27109 case 240 /* WithStatement */:
27110 return visitNode(cbNode, node.expression) ||
27111 visitNode(cbNode, node.statement);
27112 case 241 /* SwitchStatement */:
27113 return visitNode(cbNode, node.expression) ||
27114 visitNode(cbNode, node.caseBlock);
27115 case 255 /* CaseBlock */:
27116 return visitNodes(cbNode, cbNodes, node.clauses);
27117 case 281 /* CaseClause */:
27118 return visitNode(cbNode, node.expression) ||
27119 visitNodes(cbNode, cbNodes, node.statements);
27120 case 282 /* DefaultClause */:
27121 return visitNodes(cbNode, cbNodes, node.statements);
27122 case 242 /* LabeledStatement */:
27123 return visitNode(cbNode, node.label) ||
27124 visitNode(cbNode, node.statement);
27125 case 243 /* ThrowStatement */:
27126 return visitNode(cbNode, node.expression);
27127 case 244 /* TryStatement */:
27128 return visitNode(cbNode, node.tryBlock) ||
27129 visitNode(cbNode, node.catchClause) ||
27130 visitNode(cbNode, node.finallyBlock);
27131 case 284 /* CatchClause */:
27132 return visitNode(cbNode, node.variableDeclaration) ||
27133 visitNode(cbNode, node.block);
27134 case 160 /* Decorator */:
27135 return visitNode(cbNode, node.expression);
27136 case 249 /* ClassDeclaration */:
27137 case 218 /* ClassExpression */:
27138 return visitNodes(cbNode, cbNodes, node.decorators) ||
27139 visitNodes(cbNode, cbNodes, node.modifiers) ||
27140 visitNode(cbNode, node.name) ||
27141 visitNodes(cbNode, cbNodes, node.typeParameters) ||
27142 visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27143 visitNodes(cbNode, cbNodes, node.members);
27144 case 250 /* InterfaceDeclaration */:
27145 return visitNodes(cbNode, cbNodes, node.decorators) ||
27146 visitNodes(cbNode, cbNodes, node.modifiers) ||
27147 visitNode(cbNode, node.name) ||
27148 visitNodes(cbNode, cbNodes, node.typeParameters) ||
27149 visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27150 visitNodes(cbNode, cbNodes, node.members);
27151 case 251 /* TypeAliasDeclaration */:
27152 return visitNodes(cbNode, cbNodes, node.decorators) ||
27153 visitNodes(cbNode, cbNodes, node.modifiers) ||
27154 visitNode(cbNode, node.name) ||
27155 visitNodes(cbNode, cbNodes, node.typeParameters) ||
27156 visitNode(cbNode, node.type);
27157 case 252 /* EnumDeclaration */:
27158 return visitNodes(cbNode, cbNodes, node.decorators) ||
27159 visitNodes(cbNode, cbNodes, node.modifiers) ||
27160 visitNode(cbNode, node.name) ||
27161 visitNodes(cbNode, cbNodes, node.members);
27162 case 288 /* EnumMember */:
27163 return visitNode(cbNode, node.name) ||
27164 visitNode(cbNode, node.initializer);
27165 case 253 /* ModuleDeclaration */:
27166 return visitNodes(cbNode, cbNodes, node.decorators) ||
27167 visitNodes(cbNode, cbNodes, node.modifiers) ||
27168 visitNode(cbNode, node.name) ||
27169 visitNode(cbNode, node.body);
27170 case 257 /* ImportEqualsDeclaration */:
27171 return visitNodes(cbNode, cbNodes, node.decorators) ||
27172 visitNodes(cbNode, cbNodes, node.modifiers) ||
27173 visitNode(cbNode, node.name) ||
27174 visitNode(cbNode, node.moduleReference);
27175 case 258 /* ImportDeclaration */:
27176 return visitNodes(cbNode, cbNodes, node.decorators) ||
27177 visitNodes(cbNode, cbNodes, node.modifiers) ||
27178 visitNode(cbNode, node.importClause) ||
27179 visitNode(cbNode, node.moduleSpecifier);
27180 case 259 /* ImportClause */:
27181 return visitNode(cbNode, node.name) ||
27182 visitNode(cbNode, node.namedBindings);
27183 case 256 /* NamespaceExportDeclaration */:
27184 return visitNode(cbNode, node.name);
27185 case 260 /* NamespaceImport */:
27186 return visitNode(cbNode, node.name);
27187 case 266 /* NamespaceExport */:
27188 return visitNode(cbNode, node.name);
27189 case 261 /* NamedImports */:
27190 case 265 /* NamedExports */:
27191 return visitNodes(cbNode, cbNodes, node.elements);
27192 case 264 /* ExportDeclaration */:
27193 return visitNodes(cbNode, cbNodes, node.decorators) ||
27194 visitNodes(cbNode, cbNodes, node.modifiers) ||
27195 visitNode(cbNode, node.exportClause) ||
27196 visitNode(cbNode, node.moduleSpecifier);
27197 case 262 /* ImportSpecifier */:
27198 case 267 /* ExportSpecifier */:
27199 return visitNode(cbNode, node.propertyName) ||
27200 visitNode(cbNode, node.name);
27201 case 263 /* ExportAssignment */:
27202 return visitNodes(cbNode, cbNodes, node.decorators) ||
27203 visitNodes(cbNode, cbNodes, node.modifiers) ||
27204 visitNode(cbNode, node.expression);
27205 case 215 /* TemplateExpression */:
27206 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
27207 case 225 /* TemplateSpan */:
27208 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
27209 case 157 /* ComputedPropertyName */:
27210 return visitNode(cbNode, node.expression);
27211 case 283 /* HeritageClause */:
27212 return visitNodes(cbNode, cbNodes, node.types);
27213 case 220 /* ExpressionWithTypeArguments */:
27214 return visitNode(cbNode, node.expression) ||
27215 visitNodes(cbNode, cbNodes, node.typeArguments);
27216 case 269 /* ExternalModuleReference */:
27217 return visitNode(cbNode, node.expression);
27218 case 268 /* MissingDeclaration */:
27219 return visitNodes(cbNode, cbNodes, node.decorators);
27220 case 332 /* CommaListExpression */:
27221 return visitNodes(cbNode, cbNodes, node.elements);
27222 case 270 /* JsxElement */:
27223 return visitNode(cbNode, node.openingElement) ||
27224 visitNodes(cbNode, cbNodes, node.children) ||
27225 visitNode(cbNode, node.closingElement);
27226 case 274 /* JsxFragment */:
27227 return visitNode(cbNode, node.openingFragment) ||
27228 visitNodes(cbNode, cbNodes, node.children) ||
27229 visitNode(cbNode, node.closingFragment);
27230 case 271 /* JsxSelfClosingElement */:
27231 case 272 /* JsxOpeningElement */:
27232 return visitNode(cbNode, node.tagName) ||
27233 visitNodes(cbNode, cbNodes, node.typeArguments) ||
27234 visitNode(cbNode, node.attributes);
27235 case 278 /* JsxAttributes */:
27236 return visitNodes(cbNode, cbNodes, node.properties);
27237 case 277 /* JsxAttribute */:
27238 return visitNode(cbNode, node.name) ||
27239 visitNode(cbNode, node.initializer);
27240 case 279 /* JsxSpreadAttribute */:
27241 return visitNode(cbNode, node.expression);
27242 case 280 /* JsxExpression */:
27243 return visitNode(cbNode, node.dotDotDotToken) ||
27244 visitNode(cbNode, node.expression);
27245 case 273 /* JsxClosingElement */:
27246 return visitNode(cbNode, node.tagName);
27247 case 179 /* OptionalType */:
27248 case 180 /* RestType */:
27249 case 298 /* JSDocTypeExpression */:
27250 case 302 /* JSDocNonNullableType */:
27251 case 301 /* JSDocNullableType */:
27252 case 303 /* JSDocOptionalType */:
27253 case 305 /* JSDocVariadicType */:
27254 return visitNode(cbNode, node.type);
27255 case 304 /* JSDocFunctionType */:
27256 return visitNodes(cbNode, cbNodes, node.parameters) ||
27257 visitNode(cbNode, node.type);
27258 case 307 /* JSDocComment */:
27259 return visitNodes(cbNode, cbNodes, node.tags);
27260 case 322 /* JSDocParameterTag */:
27261 case 328 /* JSDocPropertyTag */:
27262 return visitNode(cbNode, node.tagName) ||
27263 (node.isNameFirst
27264 ? visitNode(cbNode, node.name) ||
27265 visitNode(cbNode, node.typeExpression)
27266 : visitNode(cbNode, node.typeExpression) ||
27267 visitNode(cbNode, node.name));
27268 case 313 /* JSDocAuthorTag */:
27269 return visitNode(cbNode, node.tagName);
27270 case 312 /* JSDocImplementsTag */:
27271 return visitNode(cbNode, node.tagName) ||
27272 visitNode(cbNode, node.class);
27273 case 311 /* JSDocAugmentsTag */:
27274 return visitNode(cbNode, node.tagName) ||
27275 visitNode(cbNode, node.class);
27276 case 326 /* JSDocTemplateTag */:
27277 return visitNode(cbNode, node.tagName) ||
27278 visitNode(cbNode, node.constraint) ||
27279 visitNodes(cbNode, cbNodes, node.typeParameters);
27280 case 327 /* JSDocTypedefTag */:
27281 return visitNode(cbNode, node.tagName) ||
27282 (node.typeExpression &&
27283 node.typeExpression.kind === 298 /* JSDocTypeExpression */
27284 ? visitNode(cbNode, node.typeExpression) ||
27285 visitNode(cbNode, node.fullName)
27286 : visitNode(cbNode, node.fullName) ||
27287 visitNode(cbNode, node.typeExpression));
27288 case 320 /* JSDocCallbackTag */:
27289 return visitNode(cbNode, node.tagName) ||
27290 visitNode(cbNode, node.fullName) ||
27291 visitNode(cbNode, node.typeExpression);
27292 case 323 /* JSDocReturnTag */:
27293 case 325 /* JSDocTypeTag */:
27294 case 324 /* JSDocThisTag */:
27295 case 321 /* JSDocEnumTag */:
27296 return visitNode(cbNode, node.tagName) ||
27297 visitNode(cbNode, node.typeExpression);
27298 case 309 /* JSDocSignature */:
27299 return ts.forEach(node.typeParameters, cbNode) ||
27300 ts.forEach(node.parameters, cbNode) ||
27301 visitNode(cbNode, node.type);
27302 case 308 /* JSDocTypeLiteral */:
27303 return ts.forEach(node.jsDocPropertyTags, cbNode);
27304 case 310 /* JSDocTag */:
27305 case 315 /* JSDocClassTag */:
27306 case 316 /* JSDocPublicTag */:
27307 case 317 /* JSDocPrivateTag */:
27308 case 318 /* JSDocProtectedTag */:
27309 case 319 /* JSDocReadonlyTag */:
27310 return visitNode(cbNode, node.tagName);
27311 case 331 /* PartiallyEmittedExpression */:
27312 return visitNode(cbNode, node.expression);
27313 }
27314 }
27315 ts.forEachChild = forEachChild;
27316 /** @internal */
27317 /**
27318 * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
27319 * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
27320 * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
27321 * If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
27322 *
27323 * @param node a given node to visit its children
27324 * @param cbNode a callback to be invoked for all child nodes
27325 * @param cbNodes a callback to be invoked for embedded array
27326 *
27327 * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
27328 * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
27329 */
27330 function forEachChildRecursively(rootNode, cbNode, cbNodes) {
27331 var stack = [rootNode];
27332 while (stack.length) {
27333 var parent = stack.pop();
27334 var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
27335 if (res) {
27336 return res;
27337 }
27338 }
27339 return;
27340 function gatherPossibleChildren(node) {
27341 var children = [];
27342 forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
27343 return children;
27344 function addWorkItem(n) {
27345 children.unshift(n);
27346 }
27347 }
27348 function visitAllPossibleChildren(parent, children) {
27349 for (var _i = 0, children_5 = children; _i < children_5.length; _i++) {
27350 var child = children_5[_i];
27351 if (ts.isArray(child)) {
27352 if (cbNodes) {
27353 var res = cbNodes(child, parent);
27354 if (res) {
27355 if (res === "skip")
27356 continue;
27357 return res;
27358 }
27359 }
27360 for (var i = child.length - 1; i >= 0; i--) {
27361 var realChild = child[i];
27362 var res = cbNode(realChild, parent);
27363 if (res) {
27364 if (res === "skip")
27365 continue;
27366 return res;
27367 }
27368 stack.push(realChild);
27369 }
27370 }
27371 else {
27372 stack.push(child);
27373 var res = cbNode(child, parent);
27374 if (res) {
27375 if (res === "skip")
27376 continue;
27377 return res;
27378 }
27379 }
27380 }
27381 }
27382 }
27383 ts.forEachChildRecursively = forEachChildRecursively;
27384 function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
27385 if (setParentNodes === void 0) { setParentNodes = false; }
27386 ts.performance.mark("beforeParse");
27387 var result;
27388 ts.perfLogger.logStartParseSourceFile(fileName);
27389 if (languageVersion === 100 /* JSON */) {
27390 result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
27391 }
27392 else {
27393 result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
27394 }
27395 ts.perfLogger.logStopParseSourceFile();
27396 ts.performance.mark("afterParse");
27397 ts.performance.measure("Parse", "beforeParse", "afterParse");
27398 return result;
27399 }
27400 ts.createSourceFile = createSourceFile;
27401 function parseIsolatedEntityName(text, languageVersion) {
27402 return Parser.parseIsolatedEntityName(text, languageVersion);
27403 }
27404 ts.parseIsolatedEntityName = parseIsolatedEntityName;
27405 /**
27406 * Parse json text into SyntaxTree and return node and parse errors if any
27407 * @param fileName
27408 * @param sourceText
27409 */
27410 function parseJsonText(fileName, sourceText) {
27411 return Parser.parseJsonText(fileName, sourceText);
27412 }
27413 ts.parseJsonText = parseJsonText;
27414 // See also `isExternalOrCommonJsModule` in utilities.ts
27415 function isExternalModule(file) {
27416 return file.externalModuleIndicator !== undefined;
27417 }
27418 ts.isExternalModule = isExternalModule;
27419 // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
27420 // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
27421 // The SourceFile will be created with the compiler attempting to reuse as many nodes from
27422 // this file as possible.
27423 //
27424 // Note: this function mutates nodes from this SourceFile. That means any existing nodes
27425 // from this SourceFile that are being held onto may change as a result (including
27426 // becoming detached from any SourceFile). It is recommended that this SourceFile not
27427 // be used once 'update' is called on it.
27428 function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
27429 if (aggressiveChecks === void 0) { aggressiveChecks = false; }
27430 var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
27431 // 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.
27432 // We will manually port the flag to the new source file.
27433 newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
27434 return newSourceFile;
27435 }
27436 ts.updateSourceFile = updateSourceFile;
27437 /* @internal */
27438 function parseIsolatedJSDocComment(content, start, length) {
27439 var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
27440 if (result && result.jsDoc) {
27441 // because the jsDocComment was parsed out of the source file, it might
27442 // not be covered by the fixupParentReferences.
27443 Parser.fixupParentReferences(result.jsDoc);
27444 }
27445 return result;
27446 }
27447 ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
27448 /* @internal */
27449 // Exposed only for testing.
27450 function parseJSDocTypeExpressionForTests(content, start, length) {
27451 return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
27452 }
27453 ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
27454 // Implement the parser as a singleton module. We do this for perf reasons because creating
27455 // parser instances can actually be expensive enough to impact us on projects with many source
27456 // files.
27457 var Parser;
27458 (function (Parser) {
27459 // Share a single scanner across all calls to parse a source file. This helps speed things
27460 // up by avoiding the cost of creating/compiling scanners over and over again.
27461 var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
27462 var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
27463 // capture constructors in 'initializeState' to avoid null checks
27464 // tslint:disable variable-name
27465 var NodeConstructor;
27466 var TokenConstructor;
27467 var IdentifierConstructor;
27468 var PrivateIdentifierConstructor;
27469 var SourceFileConstructor;
27470 // tslint:enable variable-name
27471 function countNode(node) {
27472 nodeCount++;
27473 return node;
27474 }
27475 // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
27476 // constructors above, which are reset each time `initializeState` is called.
27477 var baseNodeFactory = {
27478 createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
27479 createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
27480 createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
27481 createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
27482 createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
27483 };
27484 var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
27485 var fileName;
27486 var sourceFlags;
27487 var sourceText;
27488 var languageVersion;
27489 var scriptKind;
27490 var languageVariant;
27491 var parseDiagnostics;
27492 var jsDocDiagnostics;
27493 var syntaxCursor;
27494 var currentToken;
27495 var nodeCount;
27496 var identifiers;
27497 var privateIdentifiers;
27498 var identifierCount;
27499 var parsingContext;
27500 var notParenthesizedArrow;
27501 // Flags that dictate what parsing context we're in. For example:
27502 // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
27503 // that some tokens that would be considered identifiers may be considered keywords.
27504 //
27505 // When adding more parser context flags, consider which is the more common case that the
27506 // flag will be in. This should be the 'false' state for that flag. The reason for this is
27507 // that we don't store data in our nodes unless the value is in the *non-default* state. So,
27508 // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
27509 // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
27510 // all nodes would need extra state on them to store this info.
27511 //
27512 // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
27513 // grammar specification.
27514 //
27515 // An important thing about these context concepts. By default they are effectively inherited
27516 // while parsing through every grammar production. i.e. if you don't change them, then when
27517 // you parse a sub-production, it will have the same context values as the parent production.
27518 // This is great most of the time. After all, consider all the 'expression' grammar productions
27519 // and how nearly all of them pass along the 'in' and 'yield' context values:
27520 //
27521 // EqualityExpression[In, Yield] :
27522 // RelationalExpression[?In, ?Yield]
27523 // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
27524 // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
27525 // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
27526 // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
27527 //
27528 // Where you have to be careful is then understanding what the points are in the grammar
27529 // where the values are *not* passed along. For example:
27530 //
27531 // SingleNameBinding[Yield,GeneratorParameter]
27532 // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
27533 // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
27534 //
27535 // Here this is saying that if the GeneratorParameter context flag is set, that we should
27536 // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
27537 // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
27538 // production. Conversely, if the GeneratorParameter context flag is not set, then we
27539 // should leave the 'yield' context flag alone.
27540 //
27541 // Getting this all correct is tricky and requires careful reading of the grammar to
27542 // understand when these values should be changed versus when they should be inherited.
27543 //
27544 // Note: it should not be necessary to save/restore these flags during speculative/lookahead
27545 // parsing. These context flags are naturally stored and restored through normal recursive
27546 // descent parsing and unwinding.
27547 var contextFlags;
27548 // Indicates whether we are currently parsing top-level statements.
27549 var topLevel = true;
27550 // Whether or not we've had a parse error since creating the last AST node. If we have
27551 // encountered an error, it will be stored on the next AST node we create. Parse errors
27552 // can be broken down into three categories:
27553 //
27554 // 1) An error that occurred during scanning. For example, an unterminated literal, or a
27555 // character that was completely not understood.
27556 //
27557 // 2) A token was expected, but was not present. This type of error is commonly produced
27558 // by the 'parseExpected' function.
27559 //
27560 // 3) A token was present that no parsing function was able to consume. This type of error
27561 // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
27562 // decides to skip the token.
27563 //
27564 // In all of these cases, we want to mark the next node as having had an error before it.
27565 // With this mark, we can know in incremental settings if this node can be reused, or if
27566 // we have to reparse it. If we don't keep this information around, we may just reuse the
27567 // node. in that event we would then not produce the same errors as we did before, causing
27568 // significant confusion problems.
27569 //
27570 // Note: it is necessary that this value be saved/restored during speculative/lookahead
27571 // parsing. During lookahead parsing, we will often create a node. That node will have
27572 // this value attached, and then this value will be set back to 'false'. If we decide to
27573 // rewind, we must get back to the same value we had prior to the lookahead.
27574 //
27575 // Note: any errors at the end of the file that do not precede a regular node, should get
27576 // attached to the EOF token.
27577 var parseErrorBeforeNextFinishedNode = false;
27578 function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
27579 if (setParentNodes === void 0) { setParentNodes = false; }
27580 scriptKind = ts.ensureScriptKind(fileName, scriptKind);
27581 if (scriptKind === 6 /* JSON */) {
27582 var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
27583 ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27584 result_3.referencedFiles = ts.emptyArray;
27585 result_3.typeReferenceDirectives = ts.emptyArray;
27586 result_3.libReferenceDirectives = ts.emptyArray;
27587 result_3.amdDependencies = ts.emptyArray;
27588 result_3.hasNoDefaultLib = false;
27589 result_3.pragmas = ts.emptyMap;
27590 return result_3;
27591 }
27592 initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
27593 var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
27594 clearState();
27595 return result;
27596 }
27597 Parser.parseSourceFile = parseSourceFile;
27598 function parseIsolatedEntityName(content, languageVersion) {
27599 // Choice of `isDeclarationFile` should be arbitrary
27600 initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
27601 // Prime the scanner.
27602 nextToken();
27603 var entityName = parseEntityName(/*allowReservedWords*/ true);
27604 var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
27605 clearState();
27606 return isInvalid ? entityName : undefined;
27607 }
27608 Parser.parseIsolatedEntityName = parseIsolatedEntityName;
27609 function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
27610 if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
27611 if (setParentNodes === void 0) { setParentNodes = false; }
27612 initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
27613 sourceFlags = contextFlags;
27614 // Prime the scanner.
27615 nextToken();
27616 var pos = getNodePos();
27617 var statements, endOfFileToken;
27618 if (token() === 1 /* EndOfFileToken */) {
27619 statements = createNodeArray([], pos, pos);
27620 endOfFileToken = parseTokenNode();
27621 }
27622 else {
27623 var expression = void 0;
27624 switch (token()) {
27625 case 22 /* OpenBracketToken */:
27626 expression = parseArrayLiteralExpression();
27627 break;
27628 case 109 /* TrueKeyword */:
27629 case 94 /* FalseKeyword */:
27630 case 103 /* NullKeyword */:
27631 expression = parseTokenNode();
27632 break;
27633 case 40 /* MinusToken */:
27634 if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
27635 expression = parsePrefixUnaryExpression();
27636 }
27637 else {
27638 expression = parseObjectLiteralExpression();
27639 }
27640 break;
27641 case 8 /* NumericLiteral */:
27642 case 10 /* StringLiteral */:
27643 if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
27644 expression = parseLiteralNode();
27645 break;
27646 }
27647 // falls through
27648 default:
27649 expression = parseObjectLiteralExpression();
27650 break;
27651 }
27652 var statement = factory.createExpressionStatement(expression);
27653 finishNode(statement, pos);
27654 statements = createNodeArray([statement], pos);
27655 endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
27656 }
27657 // Set source file so that errors will be reported with this file name
27658 var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
27659 if (setParentNodes) {
27660 fixupParentReferences(sourceFile);
27661 }
27662 sourceFile.nodeCount = nodeCount;
27663 sourceFile.identifierCount = identifierCount;
27664 sourceFile.identifiers = identifiers;
27665 sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
27666 if (jsDocDiagnostics) {
27667 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
27668 }
27669 var result = sourceFile;
27670 clearState();
27671 return result;
27672 }
27673 Parser.parseJsonText = parseJsonText;
27674 function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
27675 NodeConstructor = ts.objectAllocator.getNodeConstructor();
27676 TokenConstructor = ts.objectAllocator.getTokenConstructor();
27677 IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
27678 PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
27679 SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
27680 fileName = ts.normalizePath(_fileName);
27681 sourceText = _sourceText;
27682 languageVersion = _languageVersion;
27683 syntaxCursor = _syntaxCursor;
27684 scriptKind = _scriptKind;
27685 languageVariant = ts.getLanguageVariant(_scriptKind);
27686 parseDiagnostics = [];
27687 parsingContext = 0;
27688 identifiers = new ts.Map();
27689 privateIdentifiers = new ts.Map();
27690 identifierCount = 0;
27691 nodeCount = 0;
27692 sourceFlags = 0;
27693 topLevel = true;
27694 switch (scriptKind) {
27695 case 1 /* JS */:
27696 case 2 /* JSX */:
27697 contextFlags = 131072 /* JavaScriptFile */;
27698 break;
27699 case 6 /* JSON */:
27700 contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
27701 break;
27702 default:
27703 contextFlags = 0 /* None */;
27704 break;
27705 }
27706 parseErrorBeforeNextFinishedNode = false;
27707 // Initialize and prime the scanner before parsing the source elements.
27708 scanner.setText(sourceText);
27709 scanner.setOnError(scanError);
27710 scanner.setScriptTarget(languageVersion);
27711 scanner.setLanguageVariant(languageVariant);
27712 }
27713 function clearState() {
27714 // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
27715 scanner.clearCommentDirectives();
27716 scanner.setText("");
27717 scanner.setOnError(undefined);
27718 // Clear any data. We don't want to accidentally hold onto it for too long.
27719 sourceText = undefined;
27720 languageVersion = undefined;
27721 syntaxCursor = undefined;
27722 scriptKind = undefined;
27723 languageVariant = undefined;
27724 sourceFlags = 0;
27725 parseDiagnostics = undefined;
27726 jsDocDiagnostics = undefined;
27727 parsingContext = 0;
27728 identifiers = undefined;
27729 notParenthesizedArrow = undefined;
27730 topLevel = true;
27731 }
27732 function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
27733 var isDeclarationFile = isDeclarationFileName(fileName);
27734 if (isDeclarationFile) {
27735 contextFlags |= 8388608 /* Ambient */;
27736 }
27737 sourceFlags = contextFlags;
27738 // Prime the scanner.
27739 nextToken();
27740 var statements = parseList(0 /* SourceElements */, parseStatement);
27741 ts.Debug.assert(token() === 1 /* EndOfFileToken */);
27742 var endOfFileToken = addJSDocComment(parseTokenNode());
27743 var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
27744 // 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
27745 processCommentPragmas(sourceFile, sourceText);
27746 processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
27747 sourceFile.commentDirectives = scanner.getCommentDirectives();
27748 sourceFile.nodeCount = nodeCount;
27749 sourceFile.identifierCount = identifierCount;
27750 sourceFile.identifiers = identifiers;
27751 sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
27752 if (jsDocDiagnostics) {
27753 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
27754 }
27755 if (setParentNodes) {
27756 fixupParentReferences(sourceFile);
27757 }
27758 return sourceFile;
27759 function reportPragmaDiagnostic(pos, end, diagnostic) {
27760 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
27761 }
27762 }
27763 function withJSDoc(node, hasJSDoc) {
27764 return hasJSDoc ? addJSDocComment(node) : node;
27765 }
27766 var hasDeprecatedTag = false;
27767 function addJSDocComment(node) {
27768 ts.Debug.assert(!node.jsDoc); // Should only be called once per node
27769 var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
27770 if (jsDoc.length)
27771 node.jsDoc = jsDoc;
27772 if (hasDeprecatedTag) {
27773 hasDeprecatedTag = false;
27774 node.flags |= 134217728 /* Deprecated */;
27775 }
27776 return node;
27777 }
27778 function reparseTopLevelAwait(sourceFile) {
27779 var savedSyntaxCursor = syntaxCursor;
27780 var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
27781 syntaxCursor = { currentNode: currentNode };
27782 var statements = [];
27783 var savedParseDiagnostics = parseDiagnostics;
27784 parseDiagnostics = [];
27785 var pos = 0;
27786 var start = findNextStatementWithAwait(sourceFile.statements, 0);
27787 var _loop_3 = function () {
27788 // append all statements between pos and start
27789 var prevStatement = sourceFile.statements[pos];
27790 var nextStatement = sourceFile.statements[start];
27791 ts.addRange(statements, sourceFile.statements, pos, start);
27792 pos = findNextStatementWithoutAwait(sourceFile.statements, start);
27793 // append all diagnostics associated with the copied range
27794 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
27795 var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
27796 if (diagnosticStart >= 0) {
27797 ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
27798 }
27799 // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
27800 speculationHelper(function () {
27801 var savedContextFlags = contextFlags;
27802 contextFlags |= 32768 /* AwaitContext */;
27803 scanner.setTextPos(nextStatement.pos);
27804 nextToken();
27805 while (token() !== 1 /* EndOfFileToken */) {
27806 var startPos = scanner.getStartPos();
27807 var statement = parseListElement(0 /* SourceElements */, parseStatement);
27808 statements.push(statement);
27809 if (startPos === scanner.getStartPos()) {
27810 nextToken();
27811 }
27812 if (pos >= 0) {
27813 var nonAwaitStatement = sourceFile.statements[pos];
27814 if (statement.end === nonAwaitStatement.pos) {
27815 // done reparsing this section
27816 break;
27817 }
27818 if (statement.end > nonAwaitStatement.pos) {
27819 // we ate into the next statement, so we must reparse it.
27820 pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
27821 }
27822 }
27823 }
27824 contextFlags = savedContextFlags;
27825 }, 2 /* Reparse */);
27826 // find the next statement containing an `await`
27827 start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
27828 };
27829 while (start !== -1) {
27830 _loop_3();
27831 }
27832 // append all statements between pos and the end of the list
27833 if (pos >= 0) {
27834 var prevStatement_1 = sourceFile.statements[pos];
27835 ts.addRange(statements, sourceFile.statements, pos);
27836 // append all diagnostics associated with the copied range
27837 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
27838 if (diagnosticStart >= 0) {
27839 ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
27840 }
27841 }
27842 syntaxCursor = savedSyntaxCursor;
27843 return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
27844 function containsPossibleTopLevelAwait(node) {
27845 return !(node.flags & 32768 /* AwaitContext */)
27846 && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */);
27847 }
27848 function findNextStatementWithAwait(statements, start) {
27849 for (var i = start; i < statements.length; i++) {
27850 if (containsPossibleTopLevelAwait(statements[i])) {
27851 return i;
27852 }
27853 }
27854 return -1;
27855 }
27856 function findNextStatementWithoutAwait(statements, start) {
27857 for (var i = start; i < statements.length; i++) {
27858 if (!containsPossibleTopLevelAwait(statements[i])) {
27859 return i;
27860 }
27861 }
27862 return -1;
27863 }
27864 function currentNode(position) {
27865 var node = baseSyntaxCursor.currentNode(position);
27866 if (topLevel && node && containsPossibleTopLevelAwait(node)) {
27867 node.intersectsChange = true;
27868 }
27869 return node;
27870 }
27871 }
27872 function fixupParentReferences(rootNode) {
27873 // normally parent references are set during binding. However, for clients that only need
27874 // a syntax tree, and no semantic features, then the binding process is an unnecessary
27875 // overhead. This functions allows us to set all the parents, without all the expense of
27876 // binding.
27877 ts.setParentRecursive(rootNode, /*incremental*/ true);
27878 }
27879 Parser.fixupParentReferences = fixupParentReferences;
27880 function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
27881 // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
27882 // this is quite rare comparing to other nodes and createNode should be as fast as possible
27883 var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags);
27884 ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
27885 setExternalModuleIndicator(sourceFile);
27886 // If we parsed this as an external module, it may contain top-level await
27887 if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) {
27888 sourceFile = reparseTopLevelAwait(sourceFile);
27889 }
27890 sourceFile.text = sourceText;
27891 sourceFile.bindDiagnostics = [];
27892 sourceFile.bindSuggestionDiagnostics = undefined;
27893 sourceFile.languageVersion = languageVersion;
27894 sourceFile.fileName = fileName;
27895 sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
27896 sourceFile.isDeclarationFile = isDeclarationFile;
27897 sourceFile.scriptKind = scriptKind;
27898 return sourceFile;
27899 }
27900 function setContextFlag(val, flag) {
27901 if (val) {
27902 contextFlags |= flag;
27903 }
27904 else {
27905 contextFlags &= ~flag;
27906 }
27907 }
27908 function setDisallowInContext(val) {
27909 setContextFlag(val, 4096 /* DisallowInContext */);
27910 }
27911 function setYieldContext(val) {
27912 setContextFlag(val, 8192 /* YieldContext */);
27913 }
27914 function setDecoratorContext(val) {
27915 setContextFlag(val, 16384 /* DecoratorContext */);
27916 }
27917 function setAwaitContext(val) {
27918 setContextFlag(val, 32768 /* AwaitContext */);
27919 }
27920 function doOutsideOfContext(context, func) {
27921 // contextFlagsToClear will contain only the context flags that are
27922 // currently set that we need to temporarily clear
27923 // We don't just blindly reset to the previous flags to ensure
27924 // that we do not mutate cached flags for the incremental
27925 // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
27926 // HasAggregatedChildData).
27927 var contextFlagsToClear = context & contextFlags;
27928 if (contextFlagsToClear) {
27929 // clear the requested context flags
27930 setContextFlag(/*val*/ false, contextFlagsToClear);
27931 var result = func();
27932 // restore the context flags we just cleared
27933 setContextFlag(/*val*/ true, contextFlagsToClear);
27934 return result;
27935 }
27936 // no need to do anything special as we are not in any of the requested contexts
27937 return func();
27938 }
27939 function doInsideOfContext(context, func) {
27940 // contextFlagsToSet will contain only the context flags that
27941 // are not currently set that we need to temporarily enable.
27942 // We don't just blindly reset to the previous flags to ensure
27943 // that we do not mutate cached flags for the incremental
27944 // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
27945 // HasAggregatedChildData).
27946 var contextFlagsToSet = context & ~contextFlags;
27947 if (contextFlagsToSet) {
27948 // set the requested context flags
27949 setContextFlag(/*val*/ true, contextFlagsToSet);
27950 var result = func();
27951 // reset the context flags we just set
27952 setContextFlag(/*val*/ false, contextFlagsToSet);
27953 return result;
27954 }
27955 // no need to do anything special as we are already in all of the requested contexts
27956 return func();
27957 }
27958 function allowInAnd(func) {
27959 return doOutsideOfContext(4096 /* DisallowInContext */, func);
27960 }
27961 function disallowInAnd(func) {
27962 return doInsideOfContext(4096 /* DisallowInContext */, func);
27963 }
27964 function doInYieldContext(func) {
27965 return doInsideOfContext(8192 /* YieldContext */, func);
27966 }
27967 function doInDecoratorContext(func) {
27968 return doInsideOfContext(16384 /* DecoratorContext */, func);
27969 }
27970 function doInAwaitContext(func) {
27971 return doInsideOfContext(32768 /* AwaitContext */, func);
27972 }
27973 function doOutsideOfAwaitContext(func) {
27974 return doOutsideOfContext(32768 /* AwaitContext */, func);
27975 }
27976 function doInYieldAndAwaitContext(func) {
27977 return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
27978 }
27979 function doOutsideOfYieldAndAwaitContext(func) {
27980 return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
27981 }
27982 function inContext(flags) {
27983 return (contextFlags & flags) !== 0;
27984 }
27985 function inYieldContext() {
27986 return inContext(8192 /* YieldContext */);
27987 }
27988 function inDisallowInContext() {
27989 return inContext(4096 /* DisallowInContext */);
27990 }
27991 function inDecoratorContext() {
27992 return inContext(16384 /* DecoratorContext */);
27993 }
27994 function inAwaitContext() {
27995 return inContext(32768 /* AwaitContext */);
27996 }
27997 function parseErrorAtCurrentToken(message, arg0) {
27998 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
27999 }
28000 function parseErrorAtPosition(start, length, message, arg0) {
28001 // Don't report another error if it would just be at the same position as the last error.
28002 var lastError = ts.lastOrUndefined(parseDiagnostics);
28003 if (!lastError || start !== lastError.start) {
28004 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, start, length, message, arg0));
28005 }
28006 // Mark that we've encountered an error. We'll set an appropriate bit on the next
28007 // node we finish so that it can't be reused incrementally.
28008 parseErrorBeforeNextFinishedNode = true;
28009 }
28010 function parseErrorAt(start, end, message, arg0) {
28011 parseErrorAtPosition(start, end - start, message, arg0);
28012 }
28013 function parseErrorAtRange(range, message, arg0) {
28014 parseErrorAt(range.pos, range.end, message, arg0);
28015 }
28016 function scanError(message, length) {
28017 parseErrorAtPosition(scanner.getTextPos(), length, message);
28018 }
28019 function getNodePos() {
28020 return scanner.getStartPos();
28021 }
28022 function hasPrecedingJSDocComment() {
28023 return scanner.hasPrecedingJSDocComment();
28024 }
28025 // Use this function to access the current token instead of reading the currentToken
28026 // variable. Since function results aren't narrowed in control flow analysis, this ensures
28027 // that the type checker doesn't make wrong assumptions about the type of the current
28028 // token (e.g. a call to nextToken() changes the current token but the checker doesn't
28029 // reason about this side effect). Mainstream VMs inline simple functions like this, so
28030 // there is no performance penalty.
28031 function token() {
28032 return currentToken;
28033 }
28034 function nextTokenWithoutCheck() {
28035 return currentToken = scanner.scan();
28036 }
28037 function nextTokenAnd(func) {
28038 nextToken();
28039 return func();
28040 }
28041 function nextToken() {
28042 // if the keyword had an escape
28043 if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
28044 // issue a parse error for the escape
28045 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
28046 }
28047 return nextTokenWithoutCheck();
28048 }
28049 function nextTokenJSDoc() {
28050 return currentToken = scanner.scanJsDocToken();
28051 }
28052 function reScanGreaterToken() {
28053 return currentToken = scanner.reScanGreaterToken();
28054 }
28055 function reScanSlashToken() {
28056 return currentToken = scanner.reScanSlashToken();
28057 }
28058 function reScanTemplateToken(isTaggedTemplate) {
28059 return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
28060 }
28061 function reScanTemplateHeadOrNoSubstitutionTemplate() {
28062 return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
28063 }
28064 function reScanLessThanToken() {
28065 return currentToken = scanner.reScanLessThanToken();
28066 }
28067 function scanJsxIdentifier() {
28068 return currentToken = scanner.scanJsxIdentifier();
28069 }
28070 function scanJsxText() {
28071 return currentToken = scanner.scanJsxToken();
28072 }
28073 function scanJsxAttributeValue() {
28074 return currentToken = scanner.scanJsxAttributeValue();
28075 }
28076 function speculationHelper(callback, speculationKind) {
28077 // Keep track of the state we'll need to rollback to if lookahead fails (or if the
28078 // caller asked us to always reset our state).
28079 var saveToken = currentToken;
28080 var saveParseDiagnosticsLength = parseDiagnostics.length;
28081 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
28082 // Note: it is not actually necessary to save/restore the context flags here. That's
28083 // because the saving/restoring of these flags happens naturally through the recursive
28084 // descent nature of our parser. However, we still store this here just so we can
28085 // assert that invariant holds.
28086 var saveContextFlags = contextFlags;
28087 // If we're only looking ahead, then tell the scanner to only lookahead as well.
28088 // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
28089 // same.
28090 var result = speculationKind !== 0 /* TryParse */
28091 ? scanner.lookAhead(callback)
28092 : scanner.tryScan(callback);
28093 ts.Debug.assert(saveContextFlags === contextFlags);
28094 // If our callback returned something 'falsy' or we're just looking ahead,
28095 // then unconditionally restore us to where we were.
28096 if (!result || speculationKind !== 0 /* TryParse */) {
28097 currentToken = saveToken;
28098 if (speculationKind !== 2 /* Reparse */) {
28099 parseDiagnostics.length = saveParseDiagnosticsLength;
28100 }
28101 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
28102 }
28103 return result;
28104 }
28105 /** Invokes the provided callback then unconditionally restores the parser to the state it
28106 * was in immediately prior to invoking the callback. The result of invoking the callback
28107 * is returned from this function.
28108 */
28109 function lookAhead(callback) {
28110 return speculationHelper(callback, 1 /* Lookahead */);
28111 }
28112 /** Invokes the provided callback. If the callback returns something falsy, then it restores
28113 * the parser to the state it was in immediately prior to invoking the callback. If the
28114 * callback returns something truthy, then the parser state is not rolled back. The result
28115 * of invoking the callback is returned from this function.
28116 */
28117 function tryParse(callback) {
28118 return speculationHelper(callback, 0 /* TryParse */);
28119 }
28120 function isBindingIdentifier() {
28121 if (token() === 78 /* Identifier */) {
28122 return true;
28123 }
28124 return token() > 115 /* LastReservedWord */;
28125 }
28126 // Ignore strict mode flag because we will report an error in type checker instead.
28127 function isIdentifier() {
28128 if (token() === 78 /* Identifier */) {
28129 return true;
28130 }
28131 // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
28132 // considered a keyword and is not an identifier.
28133 if (token() === 124 /* YieldKeyword */ && inYieldContext()) {
28134 return false;
28135 }
28136 // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
28137 // considered a keyword and is not an identifier.
28138 if (token() === 130 /* AwaitKeyword */ && inAwaitContext()) {
28139 return false;
28140 }
28141 return token() > 115 /* LastReservedWord */;
28142 }
28143 function parseExpected(kind, diagnosticMessage, shouldAdvance) {
28144 if (shouldAdvance === void 0) { shouldAdvance = true; }
28145 if (token() === kind) {
28146 if (shouldAdvance) {
28147 nextToken();
28148 }
28149 return true;
28150 }
28151 // Report specific message if provided with one. Otherwise, report generic fallback message.
28152 if (diagnosticMessage) {
28153 parseErrorAtCurrentToken(diagnosticMessage);
28154 }
28155 else {
28156 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
28157 }
28158 return false;
28159 }
28160 function parseExpectedJSDoc(kind) {
28161 if (token() === kind) {
28162 nextTokenJSDoc();
28163 return true;
28164 }
28165 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
28166 return false;
28167 }
28168 function parseOptional(t) {
28169 if (token() === t) {
28170 nextToken();
28171 return true;
28172 }
28173 return false;
28174 }
28175 function parseOptionalToken(t) {
28176 if (token() === t) {
28177 return parseTokenNode();
28178 }
28179 return undefined;
28180 }
28181 function parseOptionalTokenJSDoc(t) {
28182 if (token() === t) {
28183 return parseTokenNodeJSDoc();
28184 }
28185 return undefined;
28186 }
28187 function parseExpectedToken(t, diagnosticMessage, arg0) {
28188 return parseOptionalToken(t) ||
28189 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
28190 }
28191 function parseExpectedTokenJSDoc(t) {
28192 return parseOptionalTokenJSDoc(t) ||
28193 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
28194 }
28195 function parseTokenNode() {
28196 var pos = getNodePos();
28197 var kind = token();
28198 nextToken();
28199 return finishNode(factory.createToken(kind), pos);
28200 }
28201 function parseTokenNodeJSDoc() {
28202 var pos = getNodePos();
28203 var kind = token();
28204 nextTokenJSDoc();
28205 return finishNode(factory.createToken(kind), pos);
28206 }
28207 function canParseSemicolon() {
28208 // If there's a real semicolon, then we can always parse it out.
28209 if (token() === 26 /* SemicolonToken */) {
28210 return true;
28211 }
28212 // We can parse out an optional semicolon in ASI cases in the following cases.
28213 return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
28214 }
28215 function parseSemicolon() {
28216 if (canParseSemicolon()) {
28217 if (token() === 26 /* SemicolonToken */) {
28218 // consume the semicolon if it was explicitly provided.
28219 nextToken();
28220 }
28221 return true;
28222 }
28223 else {
28224 return parseExpected(26 /* SemicolonToken */);
28225 }
28226 }
28227 function createNodeArray(elements, pos, end, hasTrailingComma) {
28228 var array = factory.createNodeArray(elements, hasTrailingComma);
28229 ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
28230 return array;
28231 }
28232 function finishNode(node, pos, end) {
28233 ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
28234 if (contextFlags) {
28235 node.flags |= contextFlags;
28236 }
28237 // Keep track on the node if we encountered an error while parsing it. If we did, then
28238 // we cannot reuse the node incrementally. Once we've marked this node, clear out the
28239 // flag so that we don't mark any subsequent nodes.
28240 if (parseErrorBeforeNextFinishedNode) {
28241 parseErrorBeforeNextFinishedNode = false;
28242 node.flags |= 65536 /* ThisNodeHasError */;
28243 }
28244 return node;
28245 }
28246 function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
28247 if (reportAtCurrentPosition) {
28248 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
28249 }
28250 else if (diagnosticMessage) {
28251 parseErrorAtCurrentToken(diagnosticMessage, arg0);
28252 }
28253 var pos = getNodePos();
28254 var result = kind === 78 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
28255 ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
28256 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
28257 kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
28258 kind === 268 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
28259 factory.createToken(kind);
28260 return finishNode(result, pos);
28261 }
28262 function internIdentifier(text) {
28263 var identifier = identifiers.get(text);
28264 if (identifier === undefined) {
28265 identifiers.set(text, identifier = text);
28266 }
28267 return identifier;
28268 }
28269 // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
28270 // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
28271 // each identifier in order to reduce memory consumption.
28272 function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
28273 identifierCount++;
28274 if (isIdentifier) {
28275 var pos = getNodePos();
28276 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
28277 var originalKeywordKind = token();
28278 var text = internIdentifier(scanner.getTokenValue());
28279 nextTokenWithoutCheck();
28280 return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
28281 }
28282 if (token() === 79 /* PrivateIdentifier */) {
28283 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
28284 return createIdentifier(/*isIdentifier*/ true);
28285 }
28286 // Only for end of file because the error gets reported incorrectly on embedded script tags.
28287 var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
28288 var isReservedWord = scanner.isReservedWord();
28289 var msgArg = scanner.getTokenText();
28290 var defaultMessage = isReservedWord ?
28291 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
28292 ts.Diagnostics.Identifier_expected;
28293 return createMissingNode(78 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
28294 }
28295 function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
28296 return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
28297 }
28298 function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
28299 return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
28300 }
28301 function parseIdentifierName(diagnosticMessage) {
28302 return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
28303 }
28304 function isLiteralPropertyName() {
28305 return ts.tokenIsIdentifierOrKeyword(token()) ||
28306 token() === 10 /* StringLiteral */ ||
28307 token() === 8 /* NumericLiteral */;
28308 }
28309 function parsePropertyNameWorker(allowComputedPropertyNames) {
28310 if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
28311 var node = parseLiteralNode();
28312 node.text = internIdentifier(node.text);
28313 return node;
28314 }
28315 if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
28316 return parseComputedPropertyName();
28317 }
28318 if (token() === 79 /* PrivateIdentifier */) {
28319 return parsePrivateIdentifier();
28320 }
28321 return parseIdentifierName();
28322 }
28323 function parsePropertyName() {
28324 return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
28325 }
28326 function parseComputedPropertyName() {
28327 // PropertyName [Yield]:
28328 // LiteralPropertyName
28329 // ComputedPropertyName[?Yield]
28330 var pos = getNodePos();
28331 parseExpected(22 /* OpenBracketToken */);
28332 // We parse any expression (including a comma expression). But the grammar
28333 // says that only an assignment expression is allowed, so the grammar checker
28334 // will error if it sees a comma expression.
28335 var expression = allowInAnd(parseExpression);
28336 parseExpected(23 /* CloseBracketToken */);
28337 return finishNode(factory.createComputedPropertyName(expression), pos);
28338 }
28339 function internPrivateIdentifier(text) {
28340 var privateIdentifier = privateIdentifiers.get(text);
28341 if (privateIdentifier === undefined) {
28342 privateIdentifiers.set(text, privateIdentifier = text);
28343 }
28344 return privateIdentifier;
28345 }
28346 function parsePrivateIdentifier() {
28347 var pos = getNodePos();
28348 var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
28349 nextToken();
28350 return finishNode(node, pos);
28351 }
28352 function parseContextualModifier(t) {
28353 return token() === t && tryParse(nextTokenCanFollowModifier);
28354 }
28355 function nextTokenIsOnSameLineAndCanFollowModifier() {
28356 nextToken();
28357 if (scanner.hasPrecedingLineBreak()) {
28358 return false;
28359 }
28360 return canFollowModifier();
28361 }
28362 function nextTokenCanFollowModifier() {
28363 switch (token()) {
28364 case 84 /* ConstKeyword */:
28365 // 'const' is only a modifier if followed by 'enum'.
28366 return nextToken() === 91 /* EnumKeyword */;
28367 case 92 /* ExportKeyword */:
28368 nextToken();
28369 if (token() === 87 /* DefaultKeyword */) {
28370 return lookAhead(nextTokenCanFollowDefaultKeyword);
28371 }
28372 if (token() === 148 /* TypeKeyword */) {
28373 return lookAhead(nextTokenCanFollowExportModifier);
28374 }
28375 return canFollowExportModifier();
28376 case 87 /* DefaultKeyword */:
28377 return nextTokenCanFollowDefaultKeyword();
28378 case 123 /* StaticKeyword */:
28379 case 134 /* GetKeyword */:
28380 case 145 /* SetKeyword */:
28381 nextToken();
28382 return canFollowModifier();
28383 default:
28384 return nextTokenIsOnSameLineAndCanFollowModifier();
28385 }
28386 }
28387 function canFollowExportModifier() {
28388 return token() !== 41 /* AsteriskToken */
28389 && token() !== 126 /* AsKeyword */
28390 && token() !== 18 /* OpenBraceToken */
28391 && canFollowModifier();
28392 }
28393 function nextTokenCanFollowExportModifier() {
28394 nextToken();
28395 return canFollowExportModifier();
28396 }
28397 function parseAnyContextualModifier() {
28398 return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
28399 }
28400 function canFollowModifier() {
28401 return token() === 22 /* OpenBracketToken */
28402 || token() === 18 /* OpenBraceToken */
28403 || token() === 41 /* AsteriskToken */
28404 || token() === 25 /* DotDotDotToken */
28405 || isLiteralPropertyName();
28406 }
28407 function nextTokenCanFollowDefaultKeyword() {
28408 nextToken();
28409 return token() === 83 /* ClassKeyword */ || token() === 97 /* FunctionKeyword */ ||
28410 token() === 117 /* InterfaceKeyword */ ||
28411 (token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
28412 (token() === 129 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
28413 }
28414 // True if positioned at the start of a list element
28415 function isListElement(parsingContext, inErrorRecovery) {
28416 var node = currentNode(parsingContext);
28417 if (node) {
28418 return true;
28419 }
28420 switch (parsingContext) {
28421 case 0 /* SourceElements */:
28422 case 1 /* BlockStatements */:
28423 case 3 /* SwitchClauseStatements */:
28424 // If we're in error recovery, then we don't want to treat ';' as an empty statement.
28425 // The problem is that ';' can show up in far too many contexts, and if we see one
28426 // and assume it's a statement, then we may bail out inappropriately from whatever
28427 // we're parsing. For example, if we have a semicolon in the middle of a class, then
28428 // we really don't want to assume the class is over and we're on a statement in the
28429 // outer module. We just want to consume and move on.
28430 return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
28431 case 2 /* SwitchClauses */:
28432 return token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
28433 case 4 /* TypeMembers */:
28434 return lookAhead(isTypeMemberStart);
28435 case 5 /* ClassMembers */:
28436 // We allow semicolons as class elements (as specified by ES6) as long as we're
28437 // not in error recovery. If we're in error recovery, we don't want an errant
28438 // semicolon to be treated as a class member (since they're almost always used
28439 // for statements.
28440 return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
28441 case 6 /* EnumMembers */:
28442 // Include open bracket computed properties. This technically also lets in indexers,
28443 // which would be a candidate for improved error reporting.
28444 return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
28445 case 12 /* ObjectLiteralMembers */:
28446 switch (token()) {
28447 case 22 /* OpenBracketToken */:
28448 case 41 /* AsteriskToken */:
28449 case 25 /* DotDotDotToken */:
28450 case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
28451 return true;
28452 default:
28453 return isLiteralPropertyName();
28454 }
28455 case 18 /* RestProperties */:
28456 return isLiteralPropertyName();
28457 case 9 /* ObjectBindingElements */:
28458 return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
28459 case 7 /* HeritageClauseElement */:
28460 // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
28461 // That way we won't consume the body of a class in its heritage clause.
28462 if (token() === 18 /* OpenBraceToken */) {
28463 return lookAhead(isValidHeritageClauseObjectLiteral);
28464 }
28465 if (!inErrorRecovery) {
28466 return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
28467 }
28468 else {
28469 // If we're in error recovery we tighten up what we're willing to match.
28470 // That way we don't treat something like "this" as a valid heritage clause
28471 // element during recovery.
28472 return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
28473 }
28474 case 8 /* VariableDeclarations */:
28475 return isBindingIdentifierOrPrivateIdentifierOrPattern();
28476 case 10 /* ArrayBindingElements */:
28477 return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
28478 case 19 /* TypeParameters */:
28479 return isIdentifier();
28480 case 15 /* ArrayLiteralMembers */:
28481 switch (token()) {
28482 case 27 /* CommaToken */:
28483 case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
28484 return true;
28485 }
28486 // falls through
28487 case 11 /* ArgumentExpressions */:
28488 return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
28489 case 16 /* Parameters */:
28490 return isStartOfParameter(/*isJSDocParameter*/ false);
28491 case 17 /* JSDocParameters */:
28492 return isStartOfParameter(/*isJSDocParameter*/ true);
28493 case 20 /* TypeArguments */:
28494 case 21 /* TupleElementTypes */:
28495 return token() === 27 /* CommaToken */ || isStartOfType();
28496 case 22 /* HeritageClauses */:
28497 return isHeritageClause();
28498 case 23 /* ImportOrExportSpecifiers */:
28499 return ts.tokenIsIdentifierOrKeyword(token());
28500 case 13 /* JsxAttributes */:
28501 return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
28502 case 14 /* JsxChildren */:
28503 return true;
28504 }
28505 return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
28506 }
28507 function isValidHeritageClauseObjectLiteral() {
28508 ts.Debug.assert(token() === 18 /* OpenBraceToken */);
28509 if (nextToken() === 19 /* CloseBraceToken */) {
28510 // if we see "extends {}" then only treat the {} as what we're extending (and not
28511 // the class body) if we have:
28512 //
28513 // extends {} {
28514 // extends {},
28515 // extends {} extends
28516 // extends {} implements
28517 var next = nextToken();
28518 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 93 /* ExtendsKeyword */ || next === 116 /* ImplementsKeyword */;
28519 }
28520 return true;
28521 }
28522 function nextTokenIsIdentifier() {
28523 nextToken();
28524 return isIdentifier();
28525 }
28526 function nextTokenIsIdentifierOrKeyword() {
28527 nextToken();
28528 return ts.tokenIsIdentifierOrKeyword(token());
28529 }
28530 function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
28531 nextToken();
28532 return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
28533 }
28534 function isHeritageClauseExtendsOrImplementsKeyword() {
28535 if (token() === 116 /* ImplementsKeyword */ ||
28536 token() === 93 /* ExtendsKeyword */) {
28537 return lookAhead(nextTokenIsStartOfExpression);
28538 }
28539 return false;
28540 }
28541 function nextTokenIsStartOfExpression() {
28542 nextToken();
28543 return isStartOfExpression();
28544 }
28545 function nextTokenIsStartOfType() {
28546 nextToken();
28547 return isStartOfType();
28548 }
28549 // True if positioned at a list terminator
28550 function isListTerminator(kind) {
28551 if (token() === 1 /* EndOfFileToken */) {
28552 // Being at the end of the file ends all lists.
28553 return true;
28554 }
28555 switch (kind) {
28556 case 1 /* BlockStatements */:
28557 case 2 /* SwitchClauses */:
28558 case 4 /* TypeMembers */:
28559 case 5 /* ClassMembers */:
28560 case 6 /* EnumMembers */:
28561 case 12 /* ObjectLiteralMembers */:
28562 case 9 /* ObjectBindingElements */:
28563 case 23 /* ImportOrExportSpecifiers */:
28564 return token() === 19 /* CloseBraceToken */;
28565 case 3 /* SwitchClauseStatements */:
28566 return token() === 19 /* CloseBraceToken */ || token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
28567 case 7 /* HeritageClauseElement */:
28568 return token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
28569 case 8 /* VariableDeclarations */:
28570 return isVariableDeclaratorListTerminator();
28571 case 19 /* TypeParameters */:
28572 // Tokens other than '>' are here for better error recovery
28573 return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
28574 case 11 /* ArgumentExpressions */:
28575 // Tokens other than ')' are here for better error recovery
28576 return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
28577 case 15 /* ArrayLiteralMembers */:
28578 case 21 /* TupleElementTypes */:
28579 case 10 /* ArrayBindingElements */:
28580 return token() === 23 /* CloseBracketToken */;
28581 case 17 /* JSDocParameters */:
28582 case 16 /* Parameters */:
28583 case 18 /* RestProperties */:
28584 // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
28585 return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
28586 case 20 /* TypeArguments */:
28587 // All other tokens should cause the type-argument to terminate except comma token
28588 return token() !== 27 /* CommaToken */;
28589 case 22 /* HeritageClauses */:
28590 return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
28591 case 13 /* JsxAttributes */:
28592 return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
28593 case 14 /* JsxChildren */:
28594 return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
28595 default:
28596 return false;
28597 }
28598 }
28599 function isVariableDeclaratorListTerminator() {
28600 // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
28601 // with parsing the list of variable declarators.
28602 if (canParseSemicolon()) {
28603 return true;
28604 }
28605 // in the case where we're parsing the variable declarator of a 'for-in' statement, we
28606 // are done if we see an 'in' keyword in front of us. Same with for-of
28607 if (isInOrOfKeyword(token())) {
28608 return true;
28609 }
28610 // ERROR RECOVERY TWEAK:
28611 // For better error recovery, if we see an '=>' then we just stop immediately. We've got an
28612 // arrow function here and it's going to be very unlikely that we'll resynchronize and get
28613 // another variable declaration.
28614 if (token() === 38 /* EqualsGreaterThanToken */) {
28615 return true;
28616 }
28617 // Keep trying to parse out variable declarators.
28618 return false;
28619 }
28620 // True if positioned at element or terminator of the current list or any enclosing list
28621 function isInSomeParsingContext() {
28622 for (var kind = 0; kind < 24 /* Count */; kind++) {
28623 if (parsingContext & (1 << kind)) {
28624 if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
28625 return true;
28626 }
28627 }
28628 }
28629 return false;
28630 }
28631 // Parses a list of elements
28632 function parseList(kind, parseElement) {
28633 var saveParsingContext = parsingContext;
28634 parsingContext |= 1 << kind;
28635 var list = [];
28636 var listPos = getNodePos();
28637 while (!isListTerminator(kind)) {
28638 if (isListElement(kind, /*inErrorRecovery*/ false)) {
28639 var element = parseListElement(kind, parseElement);
28640 list.push(element);
28641 continue;
28642 }
28643 if (abortParsingListOrMoveToNextToken(kind)) {
28644 break;
28645 }
28646 }
28647 parsingContext = saveParsingContext;
28648 return createNodeArray(list, listPos);
28649 }
28650 function parseListElement(parsingContext, parseElement) {
28651 var node = currentNode(parsingContext);
28652 if (node) {
28653 return consumeNode(node);
28654 }
28655 return parseElement();
28656 }
28657 function currentNode(parsingContext) {
28658 // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
28659 //
28660 // If there is an outstanding parse error that we've encountered, but not attached to
28661 // some node, then we cannot get a node from the old source tree. This is because we
28662 // want to mark the next node we encounter as being unusable.
28663 //
28664 // Note: This may be too conservative. Perhaps we could reuse the node and set the bit
28665 // on it (or its leftmost child) as having the error. For now though, being conservative
28666 // is nice and likely won't ever affect perf.
28667 if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
28668 return undefined;
28669 }
28670 var node = syntaxCursor.currentNode(scanner.getStartPos());
28671 // Can't reuse a missing node.
28672 // Can't reuse a node that intersected the change range.
28673 // Can't reuse a node that contains a parse error. This is necessary so that we
28674 // produce the same set of errors again.
28675 if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
28676 return undefined;
28677 }
28678 // We can only reuse a node if it was parsed under the same strict mode that we're
28679 // currently in. i.e. if we originally parsed a node in non-strict mode, but then
28680 // the user added 'using strict' at the top of the file, then we can't use that node
28681 // again as the presence of strict mode may cause us to parse the tokens in the file
28682 // differently.
28683 //
28684 // Note: we *can* reuse tokens when the strict mode changes. That's because tokens
28685 // are unaffected by strict mode. It's just the parser will decide what to do with it
28686 // differently depending on what mode it is in.
28687 //
28688 // This also applies to all our other context flags as well.
28689 var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
28690 if (nodeContextFlags !== contextFlags) {
28691 return undefined;
28692 }
28693 // Ok, we have a node that looks like it could be reused. Now verify that it is valid
28694 // in the current list parsing context that we're currently at.
28695 if (!canReuseNode(node, parsingContext)) {
28696 return undefined;
28697 }
28698 if (node.jsDocCache) {
28699 // jsDocCache may include tags from parent nodes, which might have been modified.
28700 node.jsDocCache = undefined;
28701 }
28702 return node;
28703 }
28704 function consumeNode(node) {
28705 // Move the scanner so it is after the node we just consumed.
28706 scanner.setTextPos(node.end);
28707 nextToken();
28708 return node;
28709 }
28710 function isReusableParsingContext(parsingContext) {
28711 switch (parsingContext) {
28712 case 5 /* ClassMembers */:
28713 case 2 /* SwitchClauses */:
28714 case 0 /* SourceElements */:
28715 case 1 /* BlockStatements */:
28716 case 3 /* SwitchClauseStatements */:
28717 case 6 /* EnumMembers */:
28718 case 4 /* TypeMembers */:
28719 case 8 /* VariableDeclarations */:
28720 case 17 /* JSDocParameters */:
28721 case 16 /* Parameters */:
28722 return true;
28723 }
28724 return false;
28725 }
28726 function canReuseNode(node, parsingContext) {
28727 switch (parsingContext) {
28728 case 5 /* ClassMembers */:
28729 return isReusableClassMember(node);
28730 case 2 /* SwitchClauses */:
28731 return isReusableSwitchClause(node);
28732 case 0 /* SourceElements */:
28733 case 1 /* BlockStatements */:
28734 case 3 /* SwitchClauseStatements */:
28735 return isReusableStatement(node);
28736 case 6 /* EnumMembers */:
28737 return isReusableEnumMember(node);
28738 case 4 /* TypeMembers */:
28739 return isReusableTypeMember(node);
28740 case 8 /* VariableDeclarations */:
28741 return isReusableVariableDeclaration(node);
28742 case 17 /* JSDocParameters */:
28743 case 16 /* Parameters */:
28744 return isReusableParameter(node);
28745 // Any other lists we do not care about reusing nodes in. But feel free to add if
28746 // you can do so safely. Danger areas involve nodes that may involve speculative
28747 // parsing. If speculative parsing is involved with the node, then the range the
28748 // parser reached while looking ahead might be in the edited range (see the example
28749 // in canReuseVariableDeclaratorNode for a good case of this).
28750 // case ParsingContext.HeritageClauses:
28751 // This would probably be safe to reuse. There is no speculative parsing with
28752 // heritage clauses.
28753 // case ParsingContext.TypeParameters:
28754 // This would probably be safe to reuse. There is no speculative parsing with
28755 // type parameters. Note that that's because type *parameters* only occur in
28756 // unambiguous *type* contexts. While type *arguments* occur in very ambiguous
28757 // *expression* contexts.
28758 // case ParsingContext.TupleElementTypes:
28759 // This would probably be safe to reuse. There is no speculative parsing with
28760 // tuple types.
28761 // Technically, type argument list types are probably safe to reuse. While
28762 // speculative parsing is involved with them (since type argument lists are only
28763 // produced from speculative parsing a < as a type argument list), we only have
28764 // the types because speculative parsing succeeded. Thus, the lookahead never
28765 // went past the end of the list and rewound.
28766 // case ParsingContext.TypeArguments:
28767 // Note: these are almost certainly not safe to ever reuse. Expressions commonly
28768 // need a large amount of lookahead, and we should not reuse them as they may
28769 // have actually intersected the edit.
28770 // case ParsingContext.ArgumentExpressions:
28771 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
28772 // cases. i.e. a property assignment may end with an expression, and thus might
28773 // have lookahead far beyond it's old node.
28774 // case ParsingContext.ObjectLiteralMembers:
28775 // This is probably not safe to reuse. There can be speculative parsing with
28776 // type names in a heritage clause. There can be generic names in the type
28777 // name list, and there can be left hand side expressions (which can have type
28778 // arguments.)
28779 // case ParsingContext.HeritageClauseElement:
28780 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
28781 // on any given element. Same for children.
28782 // case ParsingContext.JsxAttributes:
28783 // case ParsingContext.JsxChildren:
28784 }
28785 return false;
28786 }
28787 function isReusableClassMember(node) {
28788 if (node) {
28789 switch (node.kind) {
28790 case 165 /* Constructor */:
28791 case 170 /* IndexSignature */:
28792 case 166 /* GetAccessor */:
28793 case 167 /* SetAccessor */:
28794 case 162 /* PropertyDeclaration */:
28795 case 226 /* SemicolonClassElement */:
28796 return true;
28797 case 164 /* MethodDeclaration */:
28798 // Method declarations are not necessarily reusable. An object-literal
28799 // may have a method calls "constructor(...)" and we must reparse that
28800 // into an actual .ConstructorDeclaration.
28801 var methodDeclaration = node;
28802 var nameIsConstructor = methodDeclaration.name.kind === 78 /* Identifier */ &&
28803 methodDeclaration.name.originalKeywordKind === 132 /* ConstructorKeyword */;
28804 return !nameIsConstructor;
28805 }
28806 }
28807 return false;
28808 }
28809 function isReusableSwitchClause(node) {
28810 if (node) {
28811 switch (node.kind) {
28812 case 281 /* CaseClause */:
28813 case 282 /* DefaultClause */:
28814 return true;
28815 }
28816 }
28817 return false;
28818 }
28819 function isReusableStatement(node) {
28820 if (node) {
28821 switch (node.kind) {
28822 case 248 /* FunctionDeclaration */:
28823 case 229 /* VariableStatement */:
28824 case 227 /* Block */:
28825 case 231 /* IfStatement */:
28826 case 230 /* ExpressionStatement */:
28827 case 243 /* ThrowStatement */:
28828 case 239 /* ReturnStatement */:
28829 case 241 /* SwitchStatement */:
28830 case 238 /* BreakStatement */:
28831 case 237 /* ContinueStatement */:
28832 case 235 /* ForInStatement */:
28833 case 236 /* ForOfStatement */:
28834 case 234 /* ForStatement */:
28835 case 233 /* WhileStatement */:
28836 case 240 /* WithStatement */:
28837 case 228 /* EmptyStatement */:
28838 case 244 /* TryStatement */:
28839 case 242 /* LabeledStatement */:
28840 case 232 /* DoStatement */:
28841 case 245 /* DebuggerStatement */:
28842 case 258 /* ImportDeclaration */:
28843 case 257 /* ImportEqualsDeclaration */:
28844 case 264 /* ExportDeclaration */:
28845 case 263 /* ExportAssignment */:
28846 case 253 /* ModuleDeclaration */:
28847 case 249 /* ClassDeclaration */:
28848 case 250 /* InterfaceDeclaration */:
28849 case 252 /* EnumDeclaration */:
28850 case 251 /* TypeAliasDeclaration */:
28851 return true;
28852 }
28853 }
28854 return false;
28855 }
28856 function isReusableEnumMember(node) {
28857 return node.kind === 288 /* EnumMember */;
28858 }
28859 function isReusableTypeMember(node) {
28860 if (node) {
28861 switch (node.kind) {
28862 case 169 /* ConstructSignature */:
28863 case 163 /* MethodSignature */:
28864 case 170 /* IndexSignature */:
28865 case 161 /* PropertySignature */:
28866 case 168 /* CallSignature */:
28867 return true;
28868 }
28869 }
28870 return false;
28871 }
28872 function isReusableVariableDeclaration(node) {
28873 if (node.kind !== 246 /* VariableDeclaration */) {
28874 return false;
28875 }
28876 // Very subtle incremental parsing bug. Consider the following code:
28877 //
28878 // let v = new List < A, B
28879 //
28880 // This is actually legal code. It's a list of variable declarators "v = new List<A"
28881 // on one side and "B" on the other. If you then change that to:
28882 //
28883 // let v = new List < A, B >()
28884 //
28885 // then we have a problem. "v = new List<A" doesn't intersect the change range, so we
28886 // start reparsing at "B" and we completely fail to handle this properly.
28887 //
28888 // In order to prevent this, we do not allow a variable declarator to be reused if it
28889 // has an initializer.
28890 var variableDeclarator = node;
28891 return variableDeclarator.initializer === undefined;
28892 }
28893 function isReusableParameter(node) {
28894 if (node.kind !== 159 /* Parameter */) {
28895 return false;
28896 }
28897 // See the comment in isReusableVariableDeclaration for why we do this.
28898 var parameter = node;
28899 return parameter.initializer === undefined;
28900 }
28901 // Returns true if we should abort parsing.
28902 function abortParsingListOrMoveToNextToken(kind) {
28903 parseErrorAtCurrentToken(parsingContextErrors(kind));
28904 if (isInSomeParsingContext()) {
28905 return true;
28906 }
28907 nextToken();
28908 return false;
28909 }
28910 function parsingContextErrors(context) {
28911 switch (context) {
28912 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
28913 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
28914 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
28915 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
28916 case 18 /* RestProperties */: // fallthrough
28917 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
28918 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
28919 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
28920 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
28921 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
28922 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
28923 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
28924 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
28925 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
28926 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
28927 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
28928 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
28929 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
28930 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
28931 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
28932 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
28933 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
28934 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
28935 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
28936 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
28937 }
28938 }
28939 // Parses a comma-delimited list of elements
28940 function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
28941 var saveParsingContext = parsingContext;
28942 parsingContext |= 1 << kind;
28943 var list = [];
28944 var listPos = getNodePos();
28945 var commaStart = -1; // Meaning the previous token was not a comma
28946 while (true) {
28947 if (isListElement(kind, /*inErrorRecovery*/ false)) {
28948 var startPos = scanner.getStartPos();
28949 list.push(parseListElement(kind, parseElement));
28950 commaStart = scanner.getTokenPos();
28951 if (parseOptional(27 /* CommaToken */)) {
28952 // No need to check for a zero length node since we know we parsed a comma
28953 continue;
28954 }
28955 commaStart = -1; // Back to the state where the last token was not a comma
28956 if (isListTerminator(kind)) {
28957 break;
28958 }
28959 // We didn't get a comma, and the list wasn't terminated, explicitly parse
28960 // out a comma so we give a good error message.
28961 parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
28962 // If the token was a semicolon, and the caller allows that, then skip it and
28963 // continue. This ensures we get back on track and don't result in tons of
28964 // parse errors. For example, this can happen when people do things like use
28965 // a semicolon to delimit object literal members. Note: we'll have already
28966 // reported an error when we called parseExpected above.
28967 if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
28968 nextToken();
28969 }
28970 if (startPos === scanner.getStartPos()) {
28971 // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
28972 // Consume a token to advance the parser in some way and avoid an infinite loop
28973 // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
28974 // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
28975 nextToken();
28976 }
28977 continue;
28978 }
28979 if (isListTerminator(kind)) {
28980 break;
28981 }
28982 if (abortParsingListOrMoveToNextToken(kind)) {
28983 break;
28984 }
28985 }
28986 parsingContext = saveParsingContext;
28987 // Recording the trailing comma is deliberately done after the previous
28988 // loop, and not just if we see a list terminator. This is because the list
28989 // may have ended incorrectly, but it is still important to know if there
28990 // was a trailing comma.
28991 // Check if the last token was a comma.
28992 // Always preserve a trailing comma by marking it on the NodeArray
28993 return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0);
28994 }
28995 function getExpectedCommaDiagnostic(kind) {
28996 return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
28997 }
28998 function createMissingList() {
28999 var list = createNodeArray([], getNodePos());
29000 list.isMissingList = true;
29001 return list;
29002 }
29003 function isMissingList(arr) {
29004 return !!arr.isMissingList;
29005 }
29006 function parseBracketedList(kind, parseElement, open, close) {
29007 if (parseExpected(open)) {
29008 var result = parseDelimitedList(kind, parseElement);
29009 parseExpected(close);
29010 return result;
29011 }
29012 return createMissingList();
29013 }
29014 function parseEntityName(allowReservedWords, diagnosticMessage) {
29015 var pos = getNodePos();
29016 var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
29017 var dotPos = getNodePos();
29018 while (parseOptional(24 /* DotToken */)) {
29019 if (token() === 29 /* LessThanToken */) {
29020 // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
29021 entity.jsdocDotPos = dotPos;
29022 break;
29023 }
29024 dotPos = getNodePos();
29025 entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
29026 }
29027 return entity;
29028 }
29029 function createQualifiedName(entity, name) {
29030 return finishNode(factory.createQualifiedName(entity, name), entity.pos);
29031 }
29032 function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
29033 // Technically a keyword is valid here as all identifiers and keywords are identifier names.
29034 // However, often we'll encounter this in error situations when the identifier or keyword
29035 // is actually starting another valid construct.
29036 //
29037 // So, we check for the following specific case:
29038 //
29039 // name.
29040 // identifierOrKeyword identifierNameOrKeyword
29041 //
29042 // Note: the newlines are important here. For example, if that above code
29043 // were rewritten into:
29044 //
29045 // name.identifierOrKeyword
29046 // identifierNameOrKeyword
29047 //
29048 // Then we would consider it valid. That's because ASI would take effect and
29049 // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
29050 // In the first case though, ASI will not take effect because there is not a
29051 // line terminator after the identifier or keyword.
29052 if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
29053 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
29054 if (matchesPattern) {
29055 // Report that we need an identifier. However, report it right after the dot,
29056 // and not on the next token. This is because the next token might actually
29057 // be an identifier and the error would be quite confusing.
29058 return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29059 }
29060 }
29061 if (token() === 79 /* PrivateIdentifier */) {
29062 var node = parsePrivateIdentifier();
29063 return allowPrivateIdentifiers ? node : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29064 }
29065 return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
29066 }
29067 function parseTemplateSpans(isTaggedTemplate) {
29068 var pos = getNodePos();
29069 var list = [];
29070 var node;
29071 do {
29072 node = parseTemplateSpan(isTaggedTemplate);
29073 list.push(node);
29074 } while (node.literal.kind === 16 /* TemplateMiddle */);
29075 return createNodeArray(list, pos);
29076 }
29077 function parseTemplateExpression(isTaggedTemplate) {
29078 var pos = getNodePos();
29079 return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
29080 }
29081 function parseLiteralOfTemplateSpan(isTaggedTemplate) {
29082 if (token() === 19 /* CloseBraceToken */) {
29083 reScanTemplateToken(isTaggedTemplate);
29084 return parseTemplateMiddleOrTemplateTail();
29085 }
29086 else {
29087 // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
29088 return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
29089 }
29090 }
29091 function parseTemplateSpan(isTaggedTemplate) {
29092 var pos = getNodePos();
29093 return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
29094 }
29095 function parseLiteralNode() {
29096 return parseLiteralLikeNode(token());
29097 }
29098 function parseTemplateHead(isTaggedTemplate) {
29099 if (isTaggedTemplate) {
29100 reScanTemplateHeadOrNoSubstitutionTemplate();
29101 }
29102 var fragment = parseLiteralLikeNode(token());
29103 ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
29104 return fragment;
29105 }
29106 function parseTemplateMiddleOrTemplateTail() {
29107 var fragment = parseLiteralLikeNode(token());
29108 ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
29109 return fragment;
29110 }
29111 function getTemplateLiteralRawText(kind) {
29112 var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
29113 var tokenText = scanner.getTokenText();
29114 return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
29115 }
29116 function parseLiteralLikeNode(kind) {
29117 var pos = getNodePos();
29118 var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
29119 // Octal literals are not allowed in strict mode or ES5
29120 // Note that theoretically the following condition would hold true literals like 009,
29121 // which is not octal. But because of how the scanner separates the tokens, we would
29122 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
29123 // We also do not need to check for negatives because any prefix operator would be part of a
29124 // parent unary expression.
29125 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
29126 kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
29127 ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
29128 ts.Debug.fail();
29129 if (scanner.hasExtendedUnicodeEscape()) {
29130 node.hasExtendedUnicodeEscape = true;
29131 }
29132 if (scanner.isUnterminated()) {
29133 node.isUnterminated = true;
29134 }
29135 nextToken();
29136 return finishNode(node, pos);
29137 }
29138 // TYPES
29139 function parseEntityNameOfTypeReference() {
29140 return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
29141 }
29142 function parseTypeArgumentsOfTypeReference() {
29143 if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
29144 return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
29145 }
29146 }
29147 function parseTypeReference() {
29148 var pos = getNodePos();
29149 return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
29150 }
29151 // If true, we should abort parsing an error function.
29152 function typeHasArrowFunctionBlockingParseError(node) {
29153 switch (node.kind) {
29154 case 172 /* TypeReference */:
29155 return ts.nodeIsMissing(node.typeName);
29156 case 173 /* FunctionType */:
29157 case 174 /* ConstructorType */: {
29158 var _a = node, parameters = _a.parameters, type = _a.type;
29159 return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
29160 }
29161 case 185 /* ParenthesizedType */:
29162 return typeHasArrowFunctionBlockingParseError(node.type);
29163 default:
29164 return false;
29165 }
29166 }
29167 function parseThisTypePredicate(lhs) {
29168 nextToken();
29169 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
29170 }
29171 function parseThisTypeNode() {
29172 var pos = getNodePos();
29173 nextToken();
29174 return finishNode(factory.createThisTypeNode(), pos);
29175 }
29176 function parseJSDocAllType() {
29177 var pos = getNodePos();
29178 nextToken();
29179 return finishNode(factory.createJSDocAllType(), pos);
29180 }
29181 function parseJSDocNonNullableType() {
29182 var pos = getNodePos();
29183 nextToken();
29184 return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
29185 }
29186 function parseJSDocUnknownOrNullableType() {
29187 var pos = getNodePos();
29188 // skip the ?
29189 nextToken();
29190 // Need to lookahead to decide if this is a nullable or unknown type.
29191 // Here are cases where we'll pick the unknown type:
29192 //
29193 // Foo(?,
29194 // { a: ? }
29195 // Foo(?)
29196 // Foo<?>
29197 // Foo(?=
29198 // (?|
29199 if (token() === 27 /* CommaToken */ ||
29200 token() === 19 /* CloseBraceToken */ ||
29201 token() === 21 /* CloseParenToken */ ||
29202 token() === 31 /* GreaterThanToken */ ||
29203 token() === 62 /* EqualsToken */ ||
29204 token() === 51 /* BarToken */) {
29205 return finishNode(factory.createJSDocUnknownType(), pos);
29206 }
29207 else {
29208 return finishNode(factory.createJSDocNullableType(parseType()), pos);
29209 }
29210 }
29211 function parseJSDocFunctionType() {
29212 var pos = getNodePos();
29213 var hasJSDoc = hasPrecedingJSDocComment();
29214 if (lookAhead(nextTokenIsOpenParen)) {
29215 nextToken();
29216 var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
29217 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
29218 return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
29219 }
29220 return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
29221 }
29222 function parseJSDocParameter() {
29223 var pos = getNodePos();
29224 var name;
29225 if (token() === 107 /* ThisKeyword */ || token() === 102 /* NewKeyword */) {
29226 name = parseIdentifierName();
29227 parseExpected(58 /* ColonToken */);
29228 }
29229 return finishNode(factory.createParameterDeclaration(
29230 /*decorators*/ undefined,
29231 /*modifiers*/ undefined,
29232 /*dotDotDotToken*/ undefined,
29233 // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
29234 name,
29235 /*questionToken*/ undefined, parseJSDocType(),
29236 /*initializer*/ undefined), pos);
29237 }
29238 function parseJSDocType() {
29239 scanner.setInJSDocType(true);
29240 var pos = getNodePos();
29241 if (parseOptional(138 /* ModuleKeyword */)) {
29242 // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
29243 var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
29244 terminate: while (true) {
29245 switch (token()) {
29246 case 19 /* CloseBraceToken */:
29247 case 1 /* EndOfFileToken */:
29248 case 27 /* CommaToken */:
29249 case 5 /* WhitespaceTrivia */:
29250 break terminate;
29251 default:
29252 nextTokenJSDoc();
29253 }
29254 }
29255 scanner.setInJSDocType(false);
29256 return finishNode(moduleTag, pos);
29257 }
29258 var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
29259 var type = parseTypeOrTypePredicate();
29260 scanner.setInJSDocType(false);
29261 if (hasDotDotDot) {
29262 type = finishNode(factory.createJSDocVariadicType(type), pos);
29263 }
29264 if (token() === 62 /* EqualsToken */) {
29265 nextToken();
29266 return finishNode(factory.createJSDocOptionalType(type), pos);
29267 }
29268 return type;
29269 }
29270 function parseTypeQuery() {
29271 var pos = getNodePos();
29272 parseExpected(111 /* TypeOfKeyword */);
29273 return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
29274 }
29275 function parseTypeParameter() {
29276 var pos = getNodePos();
29277 var name = parseIdentifier();
29278 var constraint;
29279 var expression;
29280 if (parseOptional(93 /* ExtendsKeyword */)) {
29281 // It's not uncommon for people to write improper constraints to a generic. If the
29282 // user writes a constraint that is an expression and not an actual type, then parse
29283 // it out as an expression (so we can recover well), but report that a type is needed
29284 // instead.
29285 if (isStartOfType() || !isStartOfExpression()) {
29286 constraint = parseType();
29287 }
29288 else {
29289 // It was not a type, and it looked like an expression. Parse out an expression
29290 // here so we recover well. Note: it is important that we call parseUnaryExpression
29291 // and not parseExpression here. If the user has:
29292 //
29293 // <T extends "">
29294 //
29295 // We do *not* want to consume the `>` as we're consuming the expression for "".
29296 expression = parseUnaryExpressionOrHigher();
29297 }
29298 }
29299 var defaultType = parseOptional(62 /* EqualsToken */) ? parseType() : undefined;
29300 var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
29301 node.expression = expression;
29302 return finishNode(node, pos);
29303 }
29304 function parseTypeParameters() {
29305 if (token() === 29 /* LessThanToken */) {
29306 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
29307 }
29308 }
29309 function isStartOfParameter(isJSDocParameter) {
29310 return token() === 25 /* DotDotDotToken */ ||
29311 isBindingIdentifierOrPrivateIdentifierOrPattern() ||
29312 ts.isModifierKind(token()) ||
29313 token() === 59 /* AtToken */ ||
29314 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
29315 }
29316 function parseNameOfParameter(modifiers) {
29317 // FormalParameter [Yield,Await]:
29318 // BindingElement[?Yield,?Await]
29319 var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
29320 if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && ts.isModifierKind(token())) {
29321 // in cases like
29322 // 'use strict'
29323 // function foo(static)
29324 // isParameter('static') === true, because of isModifier('static')
29325 // however 'static' is not a legal identifier in a strict mode.
29326 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
29327 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
29328 // to avoid this we'll advance cursor to the next token.
29329 nextToken();
29330 }
29331 return name;
29332 }
29333 function parseParameterInOuterAwaitContext() {
29334 return parseParameterWorker(/*inOuterAwaitContext*/ true);
29335 }
29336 function parseParameter() {
29337 return parseParameterWorker(/*inOuterAwaitContext*/ false);
29338 }
29339 function parseParameterWorker(inOuterAwaitContext) {
29340 var pos = getNodePos();
29341 var hasJSDoc = hasPrecedingJSDocComment();
29342 if (token() === 107 /* ThisKeyword */) {
29343 var node_1 = factory.createParameterDeclaration(
29344 /*decorators*/ undefined,
29345 /*modifiers*/ undefined,
29346 /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true),
29347 /*questionToken*/ undefined, parseTypeAnnotation(),
29348 /*initializer*/ undefined);
29349 return withJSDoc(finishNode(node_1, pos), hasJSDoc);
29350 }
29351 // FormalParameter [Yield,Await]:
29352 // BindingElement[?Yield,?Await]
29353 // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
29354 var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
29355 var savedTopLevel = topLevel;
29356 topLevel = false;
29357 var modifiers = parseModifiers();
29358 var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
29359 topLevel = savedTopLevel;
29360 return node;
29361 }
29362 function parseReturnType(returnToken, isType) {
29363 if (shouldParseReturnType(returnToken, isType)) {
29364 return parseTypeOrTypePredicate();
29365 }
29366 }
29367 function shouldParseReturnType(returnToken, isType) {
29368 if (returnToken === 38 /* EqualsGreaterThanToken */) {
29369 parseExpected(returnToken);
29370 return true;
29371 }
29372 else if (parseOptional(58 /* ColonToken */)) {
29373 return true;
29374 }
29375 else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
29376 // This is easy to get backward, especially in type contexts, so parse the type anyway
29377 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
29378 nextToken();
29379 return true;
29380 }
29381 return false;
29382 }
29383 function parseParametersWorker(flags) {
29384 // FormalParameters [Yield,Await]: (modified)
29385 // [empty]
29386 // FormalParameterList[?Yield,Await]
29387 //
29388 // FormalParameter[Yield,Await]: (modified)
29389 // BindingElement[?Yield,Await]
29390 //
29391 // BindingElement [Yield,Await]: (modified)
29392 // SingleNameBinding[?Yield,?Await]
29393 // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
29394 //
29395 // SingleNameBinding [Yield,Await]:
29396 // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
29397 var savedYieldContext = inYieldContext();
29398 var savedAwaitContext = inAwaitContext();
29399 setYieldContext(!!(flags & 1 /* Yield */));
29400 setAwaitContext(!!(flags & 2 /* Await */));
29401 var parameters = flags & 32 /* JSDoc */ ?
29402 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
29403 parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
29404 setYieldContext(savedYieldContext);
29405 setAwaitContext(savedAwaitContext);
29406 return parameters;
29407 }
29408 function parseParameters(flags) {
29409 // FormalParameters [Yield,Await]: (modified)
29410 // [empty]
29411 // FormalParameterList[?Yield,Await]
29412 //
29413 // FormalParameter[Yield,Await]: (modified)
29414 // BindingElement[?Yield,Await]
29415 //
29416 // BindingElement [Yield,Await]: (modified)
29417 // SingleNameBinding[?Yield,?Await]
29418 // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
29419 //
29420 // SingleNameBinding [Yield,Await]:
29421 // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
29422 if (!parseExpected(20 /* OpenParenToken */)) {
29423 return createMissingList();
29424 }
29425 var parameters = parseParametersWorker(flags);
29426 parseExpected(21 /* CloseParenToken */);
29427 return parameters;
29428 }
29429 function parseTypeMemberSemicolon() {
29430 // We allow type members to be separated by commas or (possibly ASI) semicolons.
29431 // First check if it was a comma. If so, we're done with the member.
29432 if (parseOptional(27 /* CommaToken */)) {
29433 return;
29434 }
29435 // Didn't have a comma. We must have a (possible ASI) semicolon.
29436 parseSemicolon();
29437 }
29438 function parseSignatureMember(kind) {
29439 var pos = getNodePos();
29440 var hasJSDoc = hasPrecedingJSDocComment();
29441 if (kind === 169 /* ConstructSignature */) {
29442 parseExpected(102 /* NewKeyword */);
29443 }
29444 var typeParameters = parseTypeParameters();
29445 var parameters = parseParameters(4 /* Type */);
29446 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
29447 parseTypeMemberSemicolon();
29448 var node = kind === 168 /* CallSignature */
29449 ? factory.createCallSignature(typeParameters, parameters, type)
29450 : factory.createConstructSignature(typeParameters, parameters, type);
29451 return withJSDoc(finishNode(node, pos), hasJSDoc);
29452 }
29453 function isIndexSignature() {
29454 return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
29455 }
29456 function isUnambiguouslyIndexSignature() {
29457 // The only allowed sequence is:
29458 //
29459 // [id:
29460 //
29461 // However, for error recovery, we also check the following cases:
29462 //
29463 // [...
29464 // [id,
29465 // [id?,
29466 // [id?:
29467 // [id?]
29468 // [public id
29469 // [private id
29470 // [protected id
29471 // []
29472 //
29473 nextToken();
29474 if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
29475 return true;
29476 }
29477 if (ts.isModifierKind(token())) {
29478 nextToken();
29479 if (isIdentifier()) {
29480 return true;
29481 }
29482 }
29483 else if (!isIdentifier()) {
29484 return false;
29485 }
29486 else {
29487 // Skip the identifier
29488 nextToken();
29489 }
29490 // A colon signifies a well formed indexer
29491 // A comma should be a badly formed indexer because comma expressions are not allowed
29492 // in computed properties.
29493 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
29494 return true;
29495 }
29496 // Question mark could be an indexer with an optional property,
29497 // or it could be a conditional expression in a computed property.
29498 if (token() !== 57 /* QuestionToken */) {
29499 return false;
29500 }
29501 // If any of the following tokens are after the question mark, it cannot
29502 // be a conditional expression, so treat it as an indexer.
29503 nextToken();
29504 return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
29505 }
29506 function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
29507 var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
29508 var type = parseTypeAnnotation();
29509 parseTypeMemberSemicolon();
29510 var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
29511 return withJSDoc(finishNode(node, pos), hasJSDoc);
29512 }
29513 function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
29514 var name = parsePropertyName();
29515 var questionToken = parseOptionalToken(57 /* QuestionToken */);
29516 var node;
29517 if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
29518 // Method signatures don't exist in expression contexts. So they have neither
29519 // [Yield] nor [Await]
29520 var typeParameters = parseTypeParameters();
29521 var parameters = parseParameters(4 /* Type */);
29522 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
29523 node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
29524 }
29525 else {
29526 var type = parseTypeAnnotation();
29527 node = factory.createPropertySignature(modifiers, name, questionToken, type);
29528 // Although type literal properties cannot not have initializers, we attempt
29529 // to parse an initializer so we can report in the checker that an interface
29530 // property or type literal property cannot have an initializer.
29531 if (token() === 62 /* EqualsToken */)
29532 node.initializer = parseInitializer();
29533 }
29534 parseTypeMemberSemicolon();
29535 return withJSDoc(finishNode(node, pos), hasJSDoc);
29536 }
29537 function isTypeMemberStart() {
29538 // Return true if we have the start of a signature member
29539 if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
29540 return true;
29541 }
29542 var idToken = false;
29543 // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
29544 while (ts.isModifierKind(token())) {
29545 idToken = true;
29546 nextToken();
29547 }
29548 // Index signatures and computed property names are type members
29549 if (token() === 22 /* OpenBracketToken */) {
29550 return true;
29551 }
29552 // Try to get the first property-like token following all modifiers
29553 if (isLiteralPropertyName()) {
29554 idToken = true;
29555 nextToken();
29556 }
29557 // If we were able to get any potential identifier, check that it is
29558 // the start of a member declaration
29559 if (idToken) {
29560 return token() === 20 /* OpenParenToken */ ||
29561 token() === 29 /* LessThanToken */ ||
29562 token() === 57 /* QuestionToken */ ||
29563 token() === 58 /* ColonToken */ ||
29564 token() === 27 /* CommaToken */ ||
29565 canParseSemicolon();
29566 }
29567 return false;
29568 }
29569 function parseTypeMember() {
29570 if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
29571 return parseSignatureMember(168 /* CallSignature */);
29572 }
29573 if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
29574 return parseSignatureMember(169 /* ConstructSignature */);
29575 }
29576 var pos = getNodePos();
29577 var hasJSDoc = hasPrecedingJSDocComment();
29578 var modifiers = parseModifiers();
29579 if (isIndexSignature()) {
29580 return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
29581 }
29582 return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
29583 }
29584 function nextTokenIsOpenParenOrLessThan() {
29585 nextToken();
29586 return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
29587 }
29588 function nextTokenIsDot() {
29589 return nextToken() === 24 /* DotToken */;
29590 }
29591 function nextTokenIsOpenParenOrLessThanOrDot() {
29592 switch (nextToken()) {
29593 case 20 /* OpenParenToken */:
29594 case 29 /* LessThanToken */:
29595 case 24 /* DotToken */:
29596 return true;
29597 }
29598 return false;
29599 }
29600 function parseTypeLiteral() {
29601 var pos = getNodePos();
29602 return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
29603 }
29604 function parseObjectTypeMembers() {
29605 var members;
29606 if (parseExpected(18 /* OpenBraceToken */)) {
29607 members = parseList(4 /* TypeMembers */, parseTypeMember);
29608 parseExpected(19 /* CloseBraceToken */);
29609 }
29610 else {
29611 members = createMissingList();
29612 }
29613 return members;
29614 }
29615 function isStartOfMappedType() {
29616 nextToken();
29617 if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
29618 return nextToken() === 141 /* ReadonlyKeyword */;
29619 }
29620 if (token() === 141 /* ReadonlyKeyword */) {
29621 nextToken();
29622 }
29623 return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 100 /* InKeyword */;
29624 }
29625 function parseMappedTypeParameter() {
29626 var pos = getNodePos();
29627 var name = parseIdentifierName();
29628 parseExpected(100 /* InKeyword */);
29629 var type = parseType();
29630 return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
29631 }
29632 function parseMappedType() {
29633 var pos = getNodePos();
29634 parseExpected(18 /* OpenBraceToken */);
29635 var readonlyToken;
29636 if (token() === 141 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
29637 readonlyToken = parseTokenNode();
29638 if (readonlyToken.kind !== 141 /* ReadonlyKeyword */) {
29639 parseExpected(141 /* ReadonlyKeyword */);
29640 }
29641 }
29642 parseExpected(22 /* OpenBracketToken */);
29643 var typeParameter = parseMappedTypeParameter();
29644 parseExpected(23 /* CloseBracketToken */);
29645 var questionToken;
29646 if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
29647 questionToken = parseTokenNode();
29648 if (questionToken.kind !== 57 /* QuestionToken */) {
29649 parseExpected(57 /* QuestionToken */);
29650 }
29651 }
29652 var type = parseTypeAnnotation();
29653 parseSemicolon();
29654 parseExpected(19 /* CloseBraceToken */);
29655 return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), pos);
29656 }
29657 function parseTupleElementType() {
29658 var pos = getNodePos();
29659 if (parseOptional(25 /* DotDotDotToken */)) {
29660 return finishNode(factory.createRestTypeNode(parseType()), pos);
29661 }
29662 var type = parseType();
29663 if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
29664 var node = factory.createOptionalTypeNode(type.type);
29665 ts.setTextRange(node, type);
29666 node.flags = type.flags;
29667 return node;
29668 }
29669 return type;
29670 }
29671 function isNextTokenColonOrQuestionColon() {
29672 return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
29673 }
29674 function isTupleElementName() {
29675 if (token() === 25 /* DotDotDotToken */) {
29676 return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
29677 }
29678 return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
29679 }
29680 function parseTupleElementNameOrTupleElementType() {
29681 if (lookAhead(isTupleElementName)) {
29682 var pos = getNodePos();
29683 var hasJSDoc = hasPrecedingJSDocComment();
29684 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
29685 var name = parseIdentifierName();
29686 var questionToken = parseOptionalToken(57 /* QuestionToken */);
29687 parseExpected(58 /* ColonToken */);
29688 var type = parseTupleElementType();
29689 var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
29690 return withJSDoc(finishNode(node, pos), hasJSDoc);
29691 }
29692 return parseTupleElementType();
29693 }
29694 function parseTupleType() {
29695 var pos = getNodePos();
29696 return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
29697 }
29698 function parseParenthesizedType() {
29699 var pos = getNodePos();
29700 parseExpected(20 /* OpenParenToken */);
29701 var type = parseType();
29702 parseExpected(21 /* CloseParenToken */);
29703 return finishNode(factory.createParenthesizedType(type), pos);
29704 }
29705 function parseFunctionOrConstructorType() {
29706 var pos = getNodePos();
29707 var hasJSDoc = hasPrecedingJSDocComment();
29708 var isConstructorType = parseOptional(102 /* NewKeyword */);
29709 var typeParameters = parseTypeParameters();
29710 var parameters = parseParameters(4 /* Type */);
29711 var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
29712 var node = isConstructorType
29713 ? factory.createConstructorTypeNode(typeParameters, parameters, type)
29714 : factory.createFunctionTypeNode(typeParameters, parameters, type);
29715 return withJSDoc(finishNode(node, pos), hasJSDoc);
29716 }
29717 function parseKeywordAndNoDot() {
29718 var node = parseTokenNode();
29719 return token() === 24 /* DotToken */ ? undefined : node;
29720 }
29721 function parseLiteralTypeNode(negative) {
29722 var pos = getNodePos();
29723 if (negative) {
29724 nextToken();
29725 }
29726 var expression = token() === 109 /* TrueKeyword */ || token() === 94 /* FalseKeyword */ || token() === 103 /* NullKeyword */ ?
29727 parseTokenNode() :
29728 parseLiteralLikeNode(token());
29729 if (negative) {
29730 expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
29731 }
29732 return finishNode(factory.createLiteralTypeNode(expression), pos);
29733 }
29734 function isStartOfTypeOfImportType() {
29735 nextToken();
29736 return token() === 99 /* ImportKeyword */;
29737 }
29738 function parseImportType() {
29739 sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
29740 var pos = getNodePos();
29741 var isTypeOf = parseOptional(111 /* TypeOfKeyword */);
29742 parseExpected(99 /* ImportKeyword */);
29743 parseExpected(20 /* OpenParenToken */);
29744 var type = parseType();
29745 parseExpected(21 /* CloseParenToken */);
29746 var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
29747 var typeArguments = parseTypeArgumentsOfTypeReference();
29748 return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
29749 }
29750 function nextTokenIsNumericOrBigIntLiteral() {
29751 nextToken();
29752 return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
29753 }
29754 function parseNonArrayType() {
29755 switch (token()) {
29756 case 128 /* AnyKeyword */:
29757 case 151 /* UnknownKeyword */:
29758 case 146 /* StringKeyword */:
29759 case 143 /* NumberKeyword */:
29760 case 154 /* BigIntKeyword */:
29761 case 147 /* SymbolKeyword */:
29762 case 131 /* BooleanKeyword */:
29763 case 149 /* UndefinedKeyword */:
29764 case 140 /* NeverKeyword */:
29765 case 144 /* ObjectKeyword */:
29766 // If these are followed by a dot, then parse these out as a dotted type reference instead.
29767 return tryParse(parseKeywordAndNoDot) || parseTypeReference();
29768 case 65 /* AsteriskEqualsToken */:
29769 // If there is '*=', treat it as * followed by postfix =
29770 scanner.reScanAsteriskEqualsToken();
29771 // falls through
29772 case 41 /* AsteriskToken */:
29773 return parseJSDocAllType();
29774 case 60 /* QuestionQuestionToken */:
29775 // If there is '??', treat it as prefix-'?' in JSDoc type.
29776 scanner.reScanQuestionToken();
29777 // falls through
29778 case 57 /* QuestionToken */:
29779 return parseJSDocUnknownOrNullableType();
29780 case 97 /* FunctionKeyword */:
29781 return parseJSDocFunctionType();
29782 case 53 /* ExclamationToken */:
29783 return parseJSDocNonNullableType();
29784 case 14 /* NoSubstitutionTemplateLiteral */:
29785 case 10 /* StringLiteral */:
29786 case 8 /* NumericLiteral */:
29787 case 9 /* BigIntLiteral */:
29788 case 109 /* TrueKeyword */:
29789 case 94 /* FalseKeyword */:
29790 case 103 /* NullKeyword */:
29791 return parseLiteralTypeNode();
29792 case 40 /* MinusToken */:
29793 return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
29794 case 113 /* VoidKeyword */:
29795 return parseTokenNode();
29796 case 107 /* ThisKeyword */: {
29797 var thisKeyword = parseThisTypeNode();
29798 if (token() === 136 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
29799 return parseThisTypePredicate(thisKeyword);
29800 }
29801 else {
29802 return thisKeyword;
29803 }
29804 }
29805 case 111 /* TypeOfKeyword */:
29806 return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
29807 case 18 /* OpenBraceToken */:
29808 return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
29809 case 22 /* OpenBracketToken */:
29810 return parseTupleType();
29811 case 20 /* OpenParenToken */:
29812 return parseParenthesizedType();
29813 case 99 /* ImportKeyword */:
29814 return parseImportType();
29815 case 127 /* AssertsKeyword */:
29816 return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
29817 default:
29818 return parseTypeReference();
29819 }
29820 }
29821 function isStartOfType(inStartOfParameter) {
29822 switch (token()) {
29823 case 128 /* AnyKeyword */:
29824 case 151 /* UnknownKeyword */:
29825 case 146 /* StringKeyword */:
29826 case 143 /* NumberKeyword */:
29827 case 154 /* BigIntKeyword */:
29828 case 131 /* BooleanKeyword */:
29829 case 141 /* ReadonlyKeyword */:
29830 case 147 /* SymbolKeyword */:
29831 case 150 /* UniqueKeyword */:
29832 case 113 /* VoidKeyword */:
29833 case 149 /* UndefinedKeyword */:
29834 case 103 /* NullKeyword */:
29835 case 107 /* ThisKeyword */:
29836 case 111 /* TypeOfKeyword */:
29837 case 140 /* NeverKeyword */:
29838 case 18 /* OpenBraceToken */:
29839 case 22 /* OpenBracketToken */:
29840 case 29 /* LessThanToken */:
29841 case 51 /* BarToken */:
29842 case 50 /* AmpersandToken */:
29843 case 102 /* NewKeyword */:
29844 case 10 /* StringLiteral */:
29845 case 8 /* NumericLiteral */:
29846 case 9 /* BigIntLiteral */:
29847 case 109 /* TrueKeyword */:
29848 case 94 /* FalseKeyword */:
29849 case 144 /* ObjectKeyword */:
29850 case 41 /* AsteriskToken */:
29851 case 57 /* QuestionToken */:
29852 case 53 /* ExclamationToken */:
29853 case 25 /* DotDotDotToken */:
29854 case 135 /* InferKeyword */:
29855 case 99 /* ImportKeyword */:
29856 case 127 /* AssertsKeyword */:
29857 return true;
29858 case 97 /* FunctionKeyword */:
29859 return !inStartOfParameter;
29860 case 40 /* MinusToken */:
29861 return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
29862 case 20 /* OpenParenToken */:
29863 // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
29864 // or something that starts a type. We don't want to consider things like '(1)' a type.
29865 return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
29866 default:
29867 return isIdentifier();
29868 }
29869 }
29870 function isStartOfParenthesizedOrFunctionType() {
29871 nextToken();
29872 return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
29873 }
29874 function parsePostfixTypeOrHigher() {
29875 var pos = getNodePos();
29876 var type = parseNonArrayType();
29877 while (!scanner.hasPrecedingLineBreak()) {
29878 switch (token()) {
29879 case 53 /* ExclamationToken */:
29880 nextToken();
29881 type = finishNode(factory.createJSDocNonNullableType(type), pos);
29882 break;
29883 case 57 /* QuestionToken */:
29884 // If next token is start of a type we have a conditional type
29885 if (lookAhead(nextTokenIsStartOfType)) {
29886 return type;
29887 }
29888 nextToken();
29889 type = finishNode(factory.createJSDocNullableType(type), pos);
29890 break;
29891 case 22 /* OpenBracketToken */:
29892 parseExpected(22 /* OpenBracketToken */);
29893 if (isStartOfType()) {
29894 var indexType = parseType();
29895 parseExpected(23 /* CloseBracketToken */);
29896 type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
29897 }
29898 else {
29899 parseExpected(23 /* CloseBracketToken */);
29900 type = finishNode(factory.createArrayTypeNode(type), pos);
29901 }
29902 break;
29903 default:
29904 return type;
29905 }
29906 }
29907 return type;
29908 }
29909 function parseTypeOperator(operator) {
29910 var pos = getNodePos();
29911 parseExpected(operator);
29912 return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
29913 }
29914 function parseTypeParameterOfInferType() {
29915 var pos = getNodePos();
29916 return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(),
29917 /*constraint*/ undefined,
29918 /*defaultType*/ undefined), pos);
29919 }
29920 function parseInferType() {
29921 var pos = getNodePos();
29922 parseExpected(135 /* InferKeyword */);
29923 return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
29924 }
29925 function parseTypeOperatorOrHigher() {
29926 var operator = token();
29927 switch (operator) {
29928 case 137 /* KeyOfKeyword */:
29929 case 150 /* UniqueKeyword */:
29930 case 141 /* ReadonlyKeyword */:
29931 return parseTypeOperator(operator);
29932 case 135 /* InferKeyword */:
29933 return parseInferType();
29934 }
29935 return parsePostfixTypeOrHigher();
29936 }
29937 function parseFunctionOrConstructorTypeToError(isInUnionType) {
29938 // the function type and constructor type shorthand notation
29939 // are not allowed directly in unions and intersections, but we'll
29940 // try to parse them gracefully and issue a helpful message.
29941 if (isStartOfFunctionTypeOrConstructorType()) {
29942 var type = parseFunctionOrConstructorType();
29943 var diagnostic = void 0;
29944 if (ts.isFunctionTypeNode(type)) {
29945 diagnostic = isInUnionType
29946 ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
29947 : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
29948 }
29949 else {
29950 diagnostic = isInUnionType
29951 ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
29952 : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
29953 }
29954 parseErrorAtRange(type, diagnostic);
29955 return type;
29956 }
29957 return undefined;
29958 }
29959 function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
29960 var pos = getNodePos();
29961 var isUnionType = operator === 51 /* BarToken */;
29962 var hasLeadingOperator = parseOptional(operator);
29963 var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
29964 || parseConstituentType();
29965 if (token() === operator || hasLeadingOperator) {
29966 var types = [type];
29967 while (parseOptional(operator)) {
29968 types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
29969 }
29970 type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
29971 }
29972 return type;
29973 }
29974 function parseIntersectionTypeOrHigher() {
29975 return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
29976 }
29977 function parseUnionTypeOrHigher() {
29978 return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
29979 }
29980 function isStartOfFunctionTypeOrConstructorType() {
29981 if (token() === 29 /* LessThanToken */) {
29982 return true;
29983 }
29984 if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
29985 return true;
29986 }
29987 return token() === 102 /* NewKeyword */;
29988 }
29989 function skipParameterStart() {
29990 if (ts.isModifierKind(token())) {
29991 // Skip modifiers
29992 parseModifiers();
29993 }
29994 if (isIdentifier() || token() === 107 /* ThisKeyword */) {
29995 nextToken();
29996 return true;
29997 }
29998 if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
29999 // Return true if we can parse an array or object binding pattern with no errors
30000 var previousErrorCount = parseDiagnostics.length;
30001 parseIdentifierOrPattern();
30002 return previousErrorCount === parseDiagnostics.length;
30003 }
30004 return false;
30005 }
30006 function isUnambiguouslyStartOfFunctionType() {
30007 nextToken();
30008 if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
30009 // ( )
30010 // ( ...
30011 return true;
30012 }
30013 if (skipParameterStart()) {
30014 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
30015 // now see if we have something that indicates a parameter declaration
30016 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
30017 token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
30018 // ( xxx :
30019 // ( xxx ,
30020 // ( xxx ?
30021 // ( xxx =
30022 return true;
30023 }
30024 if (token() === 21 /* CloseParenToken */) {
30025 nextToken();
30026 if (token() === 38 /* EqualsGreaterThanToken */) {
30027 // ( xxx ) =>
30028 return true;
30029 }
30030 }
30031 }
30032 return false;
30033 }
30034 function parseTypeOrTypePredicate() {
30035 var pos = getNodePos();
30036 var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
30037 var type = parseType();
30038 if (typePredicateVariable) {
30039 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
30040 }
30041 else {
30042 return type;
30043 }
30044 }
30045 function parseTypePredicatePrefix() {
30046 var id = parseIdentifier();
30047 if (token() === 136 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
30048 nextToken();
30049 return id;
30050 }
30051 }
30052 function parseAssertsTypePredicate() {
30053 var pos = getNodePos();
30054 var assertsModifier = parseExpectedToken(127 /* AssertsKeyword */);
30055 var parameterName = token() === 107 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
30056 var type = parseOptional(136 /* IsKeyword */) ? parseType() : undefined;
30057 return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
30058 }
30059 function parseType() {
30060 // The rules about 'yield' only apply to actual code/expression contexts. They don't
30061 // apply to 'type' contexts. So we disable these parameters here before moving on.
30062 return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
30063 }
30064 function parseTypeWorker(noConditionalTypes) {
30065 if (isStartOfFunctionTypeOrConstructorType()) {
30066 return parseFunctionOrConstructorType();
30067 }
30068 var pos = getNodePos();
30069 var type = parseUnionTypeOrHigher();
30070 if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(93 /* ExtendsKeyword */)) {
30071 // The type following 'extends' is not permitted to be another conditional type
30072 var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
30073 parseExpected(57 /* QuestionToken */);
30074 var trueType = parseTypeWorker();
30075 parseExpected(58 /* ColonToken */);
30076 var falseType = parseTypeWorker();
30077 return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
30078 }
30079 return type;
30080 }
30081 function parseTypeAnnotation() {
30082 return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
30083 }
30084 // EXPRESSIONS
30085 function isStartOfLeftHandSideExpression() {
30086 switch (token()) {
30087 case 107 /* ThisKeyword */:
30088 case 105 /* SuperKeyword */:
30089 case 103 /* NullKeyword */:
30090 case 109 /* TrueKeyword */:
30091 case 94 /* FalseKeyword */:
30092 case 8 /* NumericLiteral */:
30093 case 9 /* BigIntLiteral */:
30094 case 10 /* StringLiteral */:
30095 case 14 /* NoSubstitutionTemplateLiteral */:
30096 case 15 /* TemplateHead */:
30097 case 20 /* OpenParenToken */:
30098 case 22 /* OpenBracketToken */:
30099 case 18 /* OpenBraceToken */:
30100 case 97 /* FunctionKeyword */:
30101 case 83 /* ClassKeyword */:
30102 case 102 /* NewKeyword */:
30103 case 43 /* SlashToken */:
30104 case 67 /* SlashEqualsToken */:
30105 case 78 /* Identifier */:
30106 return true;
30107 case 99 /* ImportKeyword */:
30108 return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
30109 default:
30110 return isIdentifier();
30111 }
30112 }
30113 function isStartOfExpression() {
30114 if (isStartOfLeftHandSideExpression()) {
30115 return true;
30116 }
30117 switch (token()) {
30118 case 39 /* PlusToken */:
30119 case 40 /* MinusToken */:
30120 case 54 /* TildeToken */:
30121 case 53 /* ExclamationToken */:
30122 case 88 /* DeleteKeyword */:
30123 case 111 /* TypeOfKeyword */:
30124 case 113 /* VoidKeyword */:
30125 case 45 /* PlusPlusToken */:
30126 case 46 /* MinusMinusToken */:
30127 case 29 /* LessThanToken */:
30128 case 130 /* AwaitKeyword */:
30129 case 124 /* YieldKeyword */:
30130 case 79 /* PrivateIdentifier */:
30131 // Yield/await always starts an expression. Either it is an identifier (in which case
30132 // it is definitely an expression). Or it's a keyword (either because we're in
30133 // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
30134 return true;
30135 default:
30136 // Error tolerance. If we see the start of some binary operator, we consider
30137 // that the start of an expression. That way we'll parse out a missing identifier,
30138 // give a good message about an identifier being missing, and then consume the
30139 // rest of the binary expression.
30140 if (isBinaryOperator()) {
30141 return true;
30142 }
30143 return isIdentifier();
30144 }
30145 }
30146 function isStartOfExpressionStatement() {
30147 // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
30148 return token() !== 18 /* OpenBraceToken */ &&
30149 token() !== 97 /* FunctionKeyword */ &&
30150 token() !== 83 /* ClassKeyword */ &&
30151 token() !== 59 /* AtToken */ &&
30152 isStartOfExpression();
30153 }
30154 function parseExpression() {
30155 // Expression[in]:
30156 // AssignmentExpression[in]
30157 // Expression[in] , AssignmentExpression[in]
30158 // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
30159 var saveDecoratorContext = inDecoratorContext();
30160 if (saveDecoratorContext) {
30161 setDecoratorContext(/*val*/ false);
30162 }
30163 var pos = getNodePos();
30164 var expr = parseAssignmentExpressionOrHigher();
30165 var operatorToken;
30166 while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
30167 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
30168 }
30169 if (saveDecoratorContext) {
30170 setDecoratorContext(/*val*/ true);
30171 }
30172 return expr;
30173 }
30174 function parseInitializer() {
30175 return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
30176 }
30177 function parseAssignmentExpressionOrHigher() {
30178 // AssignmentExpression[in,yield]:
30179 // 1) ConditionalExpression[?in,?yield]
30180 // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
30181 // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
30182 // 4) ArrowFunctionExpression[?in,?yield]
30183 // 5) AsyncArrowFunctionExpression[in,yield,await]
30184 // 6) [+Yield] YieldExpression[?In]
30185 //
30186 // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
30187 // (i.e. they're both BinaryExpressions with an assignment operator in it).
30188 // First, do the simple check if we have a YieldExpression (production '6').
30189 if (isYieldExpression()) {
30190 return parseYieldExpression();
30191 }
30192 // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
30193 // parameter list or is an async arrow function.
30194 // AsyncArrowFunctionExpression:
30195 // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
30196 // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
30197 // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
30198 // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
30199 //
30200 // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
30201 // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
30202 // with AssignmentExpression if we see one.
30203 var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
30204 if (arrowExpression) {
30205 return arrowExpression;
30206 }
30207 // Now try to see if we're in production '1', '2' or '3'. A conditional expression can
30208 // start with a LogicalOrExpression, while the assignment productions can only start with
30209 // LeftHandSideExpressions.
30210 //
30211 // So, first, we try to just parse out a BinaryExpression. If we get something that is a
30212 // LeftHandSide or higher, then we can try to parse out the assignment expression part.
30213 // Otherwise, we try to parse out the conditional expression bit. We want to allow any
30214 // binary expression here, so we pass in the 'lowest' precedence here so that it matches
30215 // and consumes anything.
30216 var pos = getNodePos();
30217 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
30218 // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
30219 // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
30220 // identifier and the current token is an arrow.
30221 if (expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
30222 return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
30223 }
30224 // Now see if we might be in cases '2' or '3'.
30225 // If the expression was a LHS expression, and we have an assignment operator, then
30226 // we're in '2' or '3'. Consume the assignment and return.
30227 //
30228 // Note: we call reScanGreaterToken so that we get an appropriately merged token
30229 // for cases like `> > =` becoming `>>=`
30230 if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
30231 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos);
30232 }
30233 // It wasn't an assignment or a lambda. This is a conditional expression:
30234 return parseConditionalExpressionRest(expr, pos);
30235 }
30236 function isYieldExpression() {
30237 if (token() === 124 /* YieldKeyword */) {
30238 // If we have a 'yield' keyword, and this is a context where yield expressions are
30239 // allowed, then definitely parse out a yield expression.
30240 if (inYieldContext()) {
30241 return true;
30242 }
30243 // We're in a context where 'yield expr' is not allowed. However, if we can
30244 // definitely tell that the user was trying to parse a 'yield expr' and not
30245 // just a normal expr that start with a 'yield' identifier, then parse out
30246 // a 'yield expr'. We can then report an error later that they are only
30247 // allowed in generator expressions.
30248 //
30249 // for example, if we see 'yield(foo)', then we'll have to treat that as an
30250 // invocation expression of something called 'yield'. However, if we have
30251 // 'yield foo' then that is not legal as a normal expression, so we can
30252 // definitely recognize this as a yield expression.
30253 //
30254 // for now we just check if the next token is an identifier. More heuristics
30255 // can be added here later as necessary. We just need to make sure that we
30256 // don't accidentally consume something legal.
30257 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
30258 }
30259 return false;
30260 }
30261 function nextTokenIsIdentifierOnSameLine() {
30262 nextToken();
30263 return !scanner.hasPrecedingLineBreak() && isIdentifier();
30264 }
30265 function parseYieldExpression() {
30266 var pos = getNodePos();
30267 // YieldExpression[In] :
30268 // yield
30269 // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
30270 // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
30271 nextToken();
30272 if (!scanner.hasPrecedingLineBreak() &&
30273 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
30274 return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
30275 }
30276 else {
30277 // if the next token is not on the same line as yield. or we don't have an '*' or
30278 // the start of an expression, then this is just a simple "yield" expression.
30279 return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
30280 }
30281 }
30282 function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
30283 ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
30284 var parameter = factory.createParameterDeclaration(
30285 /*decorators*/ undefined,
30286 /*modifiers*/ undefined,
30287 /*dotDotDotToken*/ undefined, identifier,
30288 /*questionToken*/ undefined,
30289 /*type*/ undefined,
30290 /*initializer*/ undefined);
30291 finishNode(parameter, identifier.pos);
30292 var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
30293 var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
30294 var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
30295 var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
30296 return addJSDocComment(finishNode(node, pos));
30297 }
30298 function tryParseParenthesizedArrowFunctionExpression() {
30299 var triState = isParenthesizedArrowFunctionExpression();
30300 if (triState === 0 /* False */) {
30301 // It's definitely not a parenthesized arrow function expression.
30302 return undefined;
30303 }
30304 // If we definitely have an arrow function, then we can just parse one, not requiring a
30305 // following => or { token. Otherwise, we *might* have an arrow function. Try to parse
30306 // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
30307 // expression instead.
30308 return triState === 1 /* True */ ?
30309 parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
30310 tryParse(parsePossibleParenthesizedArrowFunctionExpression);
30311 }
30312 // True -> We definitely expect a parenthesized arrow function here.
30313 // False -> There *cannot* be a parenthesized arrow function here.
30314 // Unknown -> There *might* be a parenthesized arrow function here.
30315 // Speculatively look ahead to be sure, and rollback if not.
30316 function isParenthesizedArrowFunctionExpression() {
30317 if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 129 /* AsyncKeyword */) {
30318 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
30319 }
30320 if (token() === 38 /* EqualsGreaterThanToken */) {
30321 // ERROR RECOVERY TWEAK:
30322 // If we see a standalone => try to parse it as an arrow function expression as that's
30323 // likely what the user intended to write.
30324 return 1 /* True */;
30325 }
30326 // Definitely not a parenthesized arrow function.
30327 return 0 /* False */;
30328 }
30329 function isParenthesizedArrowFunctionExpressionWorker() {
30330 if (token() === 129 /* AsyncKeyword */) {
30331 nextToken();
30332 if (scanner.hasPrecedingLineBreak()) {
30333 return 0 /* False */;
30334 }
30335 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
30336 return 0 /* False */;
30337 }
30338 }
30339 var first = token();
30340 var second = nextToken();
30341 if (first === 20 /* OpenParenToken */) {
30342 if (second === 21 /* CloseParenToken */) {
30343 // Simple cases: "() =>", "(): ", and "() {".
30344 // This is an arrow function with no parameters.
30345 // The last one is not actually an arrow function,
30346 // but this is probably what the user intended.
30347 var third = nextToken();
30348 switch (third) {
30349 case 38 /* EqualsGreaterThanToken */:
30350 case 58 /* ColonToken */:
30351 case 18 /* OpenBraceToken */:
30352 return 1 /* True */;
30353 default:
30354 return 0 /* False */;
30355 }
30356 }
30357 // If encounter "([" or "({", this could be the start of a binding pattern.
30358 // Examples:
30359 // ([ x ]) => { }
30360 // ({ x }) => { }
30361 // ([ x ])
30362 // ({ x })
30363 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
30364 return 2 /* Unknown */;
30365 }
30366 // Simple case: "(..."
30367 // This is an arrow function with a rest parameter.
30368 if (second === 25 /* DotDotDotToken */) {
30369 return 1 /* True */;
30370 }
30371 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
30372 // isn't actually allowed, but we want to treat it as a lambda so we can provide
30373 // a good error message.
30374 if (ts.isModifierKind(second) && second !== 129 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
30375 return 1 /* True */;
30376 }
30377 // If we had "(" followed by something that's not an identifier,
30378 // then this definitely doesn't look like a lambda. "this" is not
30379 // valid, but we want to parse it and then give a semantic error.
30380 if (!isIdentifier() && second !== 107 /* ThisKeyword */) {
30381 return 0 /* False */;
30382 }
30383 switch (nextToken()) {
30384 case 58 /* ColonToken */:
30385 // If we have something like "(a:", then we must have a
30386 // type-annotated parameter in an arrow function expression.
30387 return 1 /* True */;
30388 case 57 /* QuestionToken */:
30389 nextToken();
30390 // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
30391 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
30392 return 1 /* True */;
30393 }
30394 // Otherwise it is definitely not a lambda.
30395 return 0 /* False */;
30396 case 27 /* CommaToken */:
30397 case 62 /* EqualsToken */:
30398 case 21 /* CloseParenToken */:
30399 // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
30400 return 2 /* Unknown */;
30401 }
30402 // It is definitely not an arrow function
30403 return 0 /* False */;
30404 }
30405 else {
30406 ts.Debug.assert(first === 29 /* LessThanToken */);
30407 // If we have "<" not followed by an identifier,
30408 // then this definitely is not an arrow function.
30409 if (!isIdentifier()) {
30410 return 0 /* False */;
30411 }
30412 // JSX overrides
30413 if (languageVariant === 1 /* JSX */) {
30414 var isArrowFunctionInJsx = lookAhead(function () {
30415 var third = nextToken();
30416 if (third === 93 /* ExtendsKeyword */) {
30417 var fourth = nextToken();
30418 switch (fourth) {
30419 case 62 /* EqualsToken */:
30420 case 31 /* GreaterThanToken */:
30421 return false;
30422 default:
30423 return true;
30424 }
30425 }
30426 else if (third === 27 /* CommaToken */) {
30427 return true;
30428 }
30429 return false;
30430 });
30431 if (isArrowFunctionInJsx) {
30432 return 1 /* True */;
30433 }
30434 return 0 /* False */;
30435 }
30436 // This *could* be a parenthesized arrow function.
30437 return 2 /* Unknown */;
30438 }
30439 }
30440 function parsePossibleParenthesizedArrowFunctionExpression() {
30441 var tokenPos = scanner.getTokenPos();
30442 if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
30443 return undefined;
30444 }
30445 var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
30446 if (!result) {
30447 (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
30448 }
30449 return result;
30450 }
30451 function tryParseAsyncSimpleArrowFunctionExpression() {
30452 // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
30453 if (token() === 129 /* AsyncKeyword */) {
30454 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
30455 var pos = getNodePos();
30456 var asyncModifier = parseModifiersForArrowFunction();
30457 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
30458 return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
30459 }
30460 }
30461 return undefined;
30462 }
30463 function isUnParenthesizedAsyncArrowFunctionWorker() {
30464 // AsyncArrowFunctionExpression:
30465 // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
30466 // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
30467 if (token() === 129 /* AsyncKeyword */) {
30468 nextToken();
30469 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
30470 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
30471 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
30472 return 0 /* False */;
30473 }
30474 // Check for un-parenthesized AsyncArrowFunction
30475 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
30476 if (!scanner.hasPrecedingLineBreak() && expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
30477 return 1 /* True */;
30478 }
30479 }
30480 return 0 /* False */;
30481 }
30482 function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
30483 var pos = getNodePos();
30484 var hasJSDoc = hasPrecedingJSDocComment();
30485 var modifiers = parseModifiersForArrowFunction();
30486 var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
30487 // Arrow functions are never generators.
30488 //
30489 // If we're speculatively parsing a signature for a parenthesized arrow function, then
30490 // we have to have a complete parameter list. Otherwise we might see something like
30491 // a => (b => c)
30492 // And think that "(b =>" was actually a parenthesized arrow function with a missing
30493 // close paren.
30494 var typeParameters = parseTypeParameters();
30495 var parameters;
30496 if (!parseExpected(20 /* OpenParenToken */)) {
30497 if (!allowAmbiguity) {
30498 return undefined;
30499 }
30500 parameters = createMissingList();
30501 }
30502 else {
30503 parameters = parseParametersWorker(isAsync);
30504 if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
30505 return undefined;
30506 }
30507 }
30508 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
30509 if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
30510 return undefined;
30511 }
30512 // Parsing a signature isn't enough.
30513 // Parenthesized arrow signatures often look like other valid expressions.
30514 // For instance:
30515 // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
30516 // - "(x,y)" is a comma expression parsed as a signature with two parameters.
30517 // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
30518 // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
30519 //
30520 // So we need just a bit of lookahead to ensure that it can only be a signature.
30521 var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
30522 if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
30523 // Returning undefined here will cause our caller to rewind to where we started from.
30524 return undefined;
30525 }
30526 // If we have an arrow, then try to parse the body. Even if not, try to parse if we
30527 // have an opening brace, just in case we're in an error state.
30528 var lastToken = token();
30529 var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
30530 var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
30531 ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
30532 : parseIdentifier();
30533 var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
30534 return withJSDoc(finishNode(node, pos), hasJSDoc);
30535 }
30536 function parseArrowFunctionExpressionBody(isAsync) {
30537 if (token() === 18 /* OpenBraceToken */) {
30538 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
30539 }
30540 if (token() !== 26 /* SemicolonToken */ &&
30541 token() !== 97 /* FunctionKeyword */ &&
30542 token() !== 83 /* ClassKeyword */ &&
30543 isStartOfStatement() &&
30544 !isStartOfExpressionStatement()) {
30545 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
30546 //
30547 // Here we try to recover from a potential error situation in the case where the
30548 // user meant to supply a block. For example, if the user wrote:
30549 //
30550 // a =>
30551 // let v = 0;
30552 // }
30553 //
30554 // they may be missing an open brace. Check to see if that's the case so we can
30555 // try to recover better. If we don't do this, then the next close curly we see may end
30556 // up preemptively closing the containing construct.
30557 //
30558 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
30559 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
30560 }
30561 var savedTopLevel = topLevel;
30562 topLevel = false;
30563 var node = isAsync
30564 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
30565 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
30566 topLevel = savedTopLevel;
30567 return node;
30568 }
30569 function parseConditionalExpressionRest(leftOperand, pos) {
30570 // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
30571 var questionToken = parseOptionalToken(57 /* QuestionToken */);
30572 if (!questionToken) {
30573 return leftOperand;
30574 }
30575 // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
30576 // we do not that for the 'whenFalse' part.
30577 var colonToken;
30578 return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
30579 ? parseAssignmentExpressionOrHigher()
30580 : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
30581 }
30582 function parseBinaryExpressionOrHigher(precedence) {
30583 var pos = getNodePos();
30584 var leftOperand = parseUnaryExpressionOrHigher();
30585 return parseBinaryExpressionRest(precedence, leftOperand, pos);
30586 }
30587 function isInOrOfKeyword(t) {
30588 return t === 100 /* InKeyword */ || t === 155 /* OfKeyword */;
30589 }
30590 function parseBinaryExpressionRest(precedence, leftOperand, pos) {
30591 while (true) {
30592 // We either have a binary operator here, or we're finished. We call
30593 // reScanGreaterToken so that we merge token sequences like > and = into >=
30594 reScanGreaterToken();
30595 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
30596 // Check the precedence to see if we should "take" this operator
30597 // - For left associative operator (all operator but **), consume the operator,
30598 // recursively call the function below, and parse binaryExpression as a rightOperand
30599 // of the caller if the new precedence of the operator is greater then or equal to the current precedence.
30600 // For example:
30601 // a - b - c;
30602 // ^token; leftOperand = b. Return b to the caller as a rightOperand
30603 // a * b - c
30604 // ^token; leftOperand = b. Return b to the caller as a rightOperand
30605 // a - b * c;
30606 // ^token; leftOperand = b. Return b * c to the caller as a rightOperand
30607 // - For right associative operator (**), consume the operator, recursively call the function
30608 // and parse binaryExpression as a rightOperand of the caller if the new precedence of
30609 // the operator is strictly grater than the current precedence
30610 // For example:
30611 // a ** b ** c;
30612 // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
30613 // a - b ** c;
30614 // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
30615 // a ** b - c
30616 // ^token; leftOperand = b. Return b to the caller as a rightOperand
30617 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
30618 newPrecedence >= precedence :
30619 newPrecedence > precedence;
30620 if (!consumeCurrentOperator) {
30621 break;
30622 }
30623 if (token() === 100 /* InKeyword */ && inDisallowInContext()) {
30624 break;
30625 }
30626 if (token() === 126 /* AsKeyword */) {
30627 // Make sure we *do* perform ASI for constructs like this:
30628 // var x = foo
30629 // as (Bar)
30630 // This should be parsed as an initialized variable, followed
30631 // by a function call to 'as' with the argument 'Bar'
30632 if (scanner.hasPrecedingLineBreak()) {
30633 break;
30634 }
30635 else {
30636 nextToken();
30637 leftOperand = makeAsExpression(leftOperand, parseType());
30638 }
30639 }
30640 else {
30641 leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
30642 }
30643 }
30644 return leftOperand;
30645 }
30646 function isBinaryOperator() {
30647 if (inDisallowInContext() && token() === 100 /* InKeyword */) {
30648 return false;
30649 }
30650 return ts.getBinaryOperatorPrecedence(token()) > 0;
30651 }
30652 function makeBinaryExpression(left, operatorToken, right, pos) {
30653 return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
30654 }
30655 function makeAsExpression(left, right) {
30656 return finishNode(factory.createAsExpression(left, right), left.pos);
30657 }
30658 function parsePrefixUnaryExpression() {
30659 var pos = getNodePos();
30660 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
30661 }
30662 function parseDeleteExpression() {
30663 var pos = getNodePos();
30664 return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
30665 }
30666 function parseTypeOfExpression() {
30667 var pos = getNodePos();
30668 return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
30669 }
30670 function parseVoidExpression() {
30671 var pos = getNodePos();
30672 return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
30673 }
30674 function isAwaitExpression() {
30675 if (token() === 130 /* AwaitKeyword */) {
30676 if (inAwaitContext()) {
30677 return true;
30678 }
30679 // here we are using similar heuristics as 'isYieldExpression'
30680 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
30681 }
30682 return false;
30683 }
30684 function parseAwaitExpression() {
30685 var pos = getNodePos();
30686 return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
30687 }
30688 /**
30689 * Parse ES7 exponential expression and await expression
30690 *
30691 * ES7 ExponentiationExpression:
30692 * 1) UnaryExpression[?Yield]
30693 * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
30694 *
30695 */
30696 function parseUnaryExpressionOrHigher() {
30697 /**
30698 * ES7 UpdateExpression:
30699 * 1) LeftHandSideExpression[?Yield]
30700 * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++
30701 * 3) LeftHandSideExpression[?Yield][no LineTerminator here]--
30702 * 4) ++UnaryExpression[?Yield]
30703 * 5) --UnaryExpression[?Yield]
30704 */
30705 if (isUpdateExpression()) {
30706 var pos = getNodePos();
30707 var updateExpression = parseUpdateExpression();
30708 return token() === 42 /* AsteriskAsteriskToken */ ?
30709 parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
30710 updateExpression;
30711 }
30712 /**
30713 * ES7 UnaryExpression:
30714 * 1) UpdateExpression[?yield]
30715 * 2) delete UpdateExpression[?yield]
30716 * 3) void UpdateExpression[?yield]
30717 * 4) typeof UpdateExpression[?yield]
30718 * 5) + UpdateExpression[?yield]
30719 * 6) - UpdateExpression[?yield]
30720 * 7) ~ UpdateExpression[?yield]
30721 * 8) ! UpdateExpression[?yield]
30722 */
30723 var unaryOperator = token();
30724 var simpleUnaryExpression = parseSimpleUnaryExpression();
30725 if (token() === 42 /* AsteriskAsteriskToken */) {
30726 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
30727 var end = simpleUnaryExpression.end;
30728 if (simpleUnaryExpression.kind === 203 /* TypeAssertionExpression */) {
30729 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);
30730 }
30731 else {
30732 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));
30733 }
30734 }
30735 return simpleUnaryExpression;
30736 }
30737 /**
30738 * Parse ES7 simple-unary expression or higher:
30739 *
30740 * ES7 UnaryExpression:
30741 * 1) UpdateExpression[?yield]
30742 * 2) delete UnaryExpression[?yield]
30743 * 3) void UnaryExpression[?yield]
30744 * 4) typeof UnaryExpression[?yield]
30745 * 5) + UnaryExpression[?yield]
30746 * 6) - UnaryExpression[?yield]
30747 * 7) ~ UnaryExpression[?yield]
30748 * 8) ! UnaryExpression[?yield]
30749 * 9) [+Await] await UnaryExpression[?yield]
30750 */
30751 function parseSimpleUnaryExpression() {
30752 switch (token()) {
30753 case 39 /* PlusToken */:
30754 case 40 /* MinusToken */:
30755 case 54 /* TildeToken */:
30756 case 53 /* ExclamationToken */:
30757 return parsePrefixUnaryExpression();
30758 case 88 /* DeleteKeyword */:
30759 return parseDeleteExpression();
30760 case 111 /* TypeOfKeyword */:
30761 return parseTypeOfExpression();
30762 case 113 /* VoidKeyword */:
30763 return parseVoidExpression();
30764 case 29 /* LessThanToken */:
30765 // This is modified UnaryExpression grammar in TypeScript
30766 // UnaryExpression (modified):
30767 // < type > UnaryExpression
30768 return parseTypeAssertion();
30769 case 130 /* AwaitKeyword */:
30770 if (isAwaitExpression()) {
30771 return parseAwaitExpression();
30772 }
30773 // falls through
30774 default:
30775 return parseUpdateExpression();
30776 }
30777 }
30778 /**
30779 * Check if the current token can possibly be an ES7 increment expression.
30780 *
30781 * ES7 UpdateExpression:
30782 * LeftHandSideExpression[?Yield]
30783 * LeftHandSideExpression[?Yield][no LineTerminator here]++
30784 * LeftHandSideExpression[?Yield][no LineTerminator here]--
30785 * ++LeftHandSideExpression[?Yield]
30786 * --LeftHandSideExpression[?Yield]
30787 */
30788 function isUpdateExpression() {
30789 // This function is called inside parseUnaryExpression to decide
30790 // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
30791 switch (token()) {
30792 case 39 /* PlusToken */:
30793 case 40 /* MinusToken */:
30794 case 54 /* TildeToken */:
30795 case 53 /* ExclamationToken */:
30796 case 88 /* DeleteKeyword */:
30797 case 111 /* TypeOfKeyword */:
30798 case 113 /* VoidKeyword */:
30799 case 130 /* AwaitKeyword */:
30800 return false;
30801 case 29 /* LessThanToken */:
30802 // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
30803 if (languageVariant !== 1 /* JSX */) {
30804 return false;
30805 }
30806 // We are in JSX context and the token is part of JSXElement.
30807 // falls through
30808 default:
30809 return true;
30810 }
30811 }
30812 /**
30813 * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
30814 *
30815 * ES7 UpdateExpression[yield]:
30816 * 1) LeftHandSideExpression[?yield]
30817 * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
30818 * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
30819 * 4) ++LeftHandSideExpression[?yield]
30820 * 5) --LeftHandSideExpression[?yield]
30821 * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
30822 */
30823 function parseUpdateExpression() {
30824 if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
30825 var pos = getNodePos();
30826 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
30827 }
30828 else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
30829 // JSXElement is part of primaryExpression
30830 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
30831 }
30832 var expression = parseLeftHandSideExpressionOrHigher();
30833 ts.Debug.assert(ts.isLeftHandSideExpression(expression));
30834 if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
30835 var operator = token();
30836 nextToken();
30837 return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
30838 }
30839 return expression;
30840 }
30841 function parseLeftHandSideExpressionOrHigher() {
30842 // Original Ecma:
30843 // LeftHandSideExpression: See 11.2
30844 // NewExpression
30845 // CallExpression
30846 //
30847 // Our simplification:
30848 //
30849 // LeftHandSideExpression: See 11.2
30850 // MemberExpression
30851 // CallExpression
30852 //
30853 // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
30854 // MemberExpression to make our lives easier.
30855 //
30856 // to best understand the below code, it's important to see how CallExpression expands
30857 // out into its own productions:
30858 //
30859 // CallExpression:
30860 // MemberExpression Arguments
30861 // CallExpression Arguments
30862 // CallExpression[Expression]
30863 // CallExpression.IdentifierName
30864 // import (AssignmentExpression)
30865 // super Arguments
30866 // super.IdentifierName
30867 //
30868 // Because of the recursion in these calls, we need to bottom out first. There are three
30869 // bottom out states we can run into: 1) We see 'super' which must start either of
30870 // the last two CallExpression productions. 2) We see 'import' which must start import call.
30871 // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
30872 // or starts the beginning of the first four CallExpression productions.
30873 var pos = getNodePos();
30874 var expression;
30875 if (token() === 99 /* ImportKeyword */) {
30876 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
30877 // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
30878 // For example:
30879 // var foo3 = require("subfolder
30880 // import * as foo1 from "module-from-node
30881 // We want this import to be a statement rather than import call expression
30882 sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
30883 expression = parseTokenNode();
30884 }
30885 else if (lookAhead(nextTokenIsDot)) {
30886 // This is an 'import.*' metaproperty (i.e. 'import.meta')
30887 nextToken(); // advance past the 'import'
30888 nextToken(); // advance past the dot
30889 expression = finishNode(factory.createMetaProperty(99 /* ImportKeyword */, parseIdentifierName()), pos);
30890 sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
30891 }
30892 else {
30893 expression = parseMemberExpressionOrHigher();
30894 }
30895 }
30896 else {
30897 expression = token() === 105 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
30898 }
30899 // Now, we *may* be complete. However, we might have consumed the start of a
30900 // CallExpression or OptionalExpression. As such, we need to consume the rest
30901 // of it here to be complete.
30902 return parseCallExpressionRest(pos, expression);
30903 }
30904 function parseMemberExpressionOrHigher() {
30905 // Note: to make our lives simpler, we decompose the NewExpression productions and
30906 // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
30907 // like so:
30908 //
30909 // PrimaryExpression : See 11.1
30910 // this
30911 // Identifier
30912 // Literal
30913 // ArrayLiteral
30914 // ObjectLiteral
30915 // (Expression)
30916 // FunctionExpression
30917 // new MemberExpression Arguments?
30918 //
30919 // MemberExpression : See 11.2
30920 // PrimaryExpression
30921 // MemberExpression[Expression]
30922 // MemberExpression.IdentifierName
30923 //
30924 // CallExpression : See 11.2
30925 // MemberExpression
30926 // CallExpression Arguments
30927 // CallExpression[Expression]
30928 // CallExpression.IdentifierName
30929 //
30930 // Technically this is ambiguous. i.e. CallExpression defines:
30931 //
30932 // CallExpression:
30933 // CallExpression Arguments
30934 //
30935 // If you see: "new Foo()"
30936 //
30937 // Then that could be treated as a single ObjectCreationExpression, or it could be
30938 // treated as the invocation of "new Foo". We disambiguate that in code (to match
30939 // the original grammar) by making sure that if we see an ObjectCreationExpression
30940 // we always consume arguments if they are there. So we treat "new Foo()" as an
30941 // object creation only, and not at all as an invocation. Another way to think
30942 // about this is that for every "new" that we see, we will consume an argument list if
30943 // it is there as part of the *associated* object creation node. Any additional
30944 // argument lists we see, will become invocation expressions.
30945 //
30946 // Because there are no other places in the grammar now that refer to FunctionExpression
30947 // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
30948 // production.
30949 //
30950 // Because CallExpression and MemberExpression are left recursive, we need to bottom out
30951 // of the recursion immediately. So we parse out a primary expression to start with.
30952 var pos = getNodePos();
30953 var expression = parsePrimaryExpression();
30954 return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
30955 }
30956 function parseSuperExpression() {
30957 var pos = getNodePos();
30958 var expression = parseTokenNode();
30959 if (token() === 29 /* LessThanToken */) {
30960 var startPos = getNodePos();
30961 var typeArguments = tryParse(parseTypeArgumentsInExpression);
30962 if (typeArguments !== undefined) {
30963 parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
30964 }
30965 }
30966 if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
30967 return expression;
30968 }
30969 // If we have seen "super" it must be followed by '(' or '.'.
30970 // If it wasn't then just try to parse out a '.' and report an error.
30971 parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
30972 // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
30973 return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
30974 }
30975 function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition) {
30976 var pos = getNodePos();
30977 var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
30978 var result;
30979 if (opening.kind === 272 /* JsxOpeningElement */) {
30980 var children = parseJsxChildren(opening);
30981 var closingElement = parseJsxClosingElement(inExpressionContext);
30982 if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
30983 parseErrorAtRange(closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
30984 }
30985 result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
30986 }
30987 else if (opening.kind === 275 /* JsxOpeningFragment */) {
30988 result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
30989 }
30990 else {
30991 ts.Debug.assert(opening.kind === 271 /* JsxSelfClosingElement */);
30992 // Nothing else to do for self-closing elements
30993 result = opening;
30994 }
30995 // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
30996 // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag
30997 // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
30998 // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
30999 // does less damage and we can report a better error.
31000 // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
31001 // of one sort or another.
31002 if (inExpressionContext && token() === 29 /* LessThanToken */) {
31003 var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
31004 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
31005 if (invalidElement) {
31006 var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
31007 ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
31008 parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
31009 return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
31010 }
31011 }
31012 return result;
31013 }
31014 function parseJsxText() {
31015 var pos = getNodePos();
31016 var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
31017 currentToken = scanner.scanJsxToken();
31018 return finishNode(node, pos);
31019 }
31020 function parseJsxChild(openingTag, token) {
31021 switch (token) {
31022 case 1 /* EndOfFileToken */:
31023 // If we hit EOF, issue the error at the tag that lacks the closing element
31024 // rather than at the end of the file (which is useless)
31025 if (ts.isJsxOpeningFragment(openingTag)) {
31026 parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
31027 }
31028 else {
31029 // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
31030 // or to cover only 'Foo' in < Foo >
31031 var tag = openingTag.tagName;
31032 var start = ts.skipTrivia(sourceText, tag.pos);
31033 parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
31034 }
31035 return undefined;
31036 case 30 /* LessThanSlashToken */:
31037 case 7 /* ConflictMarkerTrivia */:
31038 return undefined;
31039 case 11 /* JsxText */:
31040 case 12 /* JsxTextAllWhiteSpaces */:
31041 return parseJsxText();
31042 case 18 /* OpenBraceToken */:
31043 return parseJsxExpression(/*inExpressionContext*/ false);
31044 case 29 /* LessThanToken */:
31045 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
31046 default:
31047 return ts.Debug.assertNever(token);
31048 }
31049 }
31050 function parseJsxChildren(openingTag) {
31051 var list = [];
31052 var listPos = getNodePos();
31053 var saveParsingContext = parsingContext;
31054 parsingContext |= 1 << 14 /* JsxChildren */;
31055 while (true) {
31056 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
31057 if (!child)
31058 break;
31059 list.push(child);
31060 }
31061 parsingContext = saveParsingContext;
31062 return createNodeArray(list, listPos);
31063 }
31064 function parseJsxAttributes() {
31065 var pos = getNodePos();
31066 return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
31067 }
31068 function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
31069 var pos = getNodePos();
31070 parseExpected(29 /* LessThanToken */);
31071 if (token() === 31 /* GreaterThanToken */) {
31072 // See below for explanation of scanJsxText
31073 scanJsxText();
31074 return finishNode(factory.createJsxOpeningFragment(), pos);
31075 }
31076 var tagName = parseJsxElementName();
31077 var typeArguments = tryParseTypeArguments();
31078 var attributes = parseJsxAttributes();
31079 var node;
31080 if (token() === 31 /* GreaterThanToken */) {
31081 // Closing tag, so scan the immediately-following text with the JSX scanning instead
31082 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
31083 // scanning errors
31084 scanJsxText();
31085 node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
31086 }
31087 else {
31088 parseExpected(43 /* SlashToken */);
31089 if (inExpressionContext) {
31090 parseExpected(31 /* GreaterThanToken */);
31091 }
31092 else {
31093 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
31094 scanJsxText();
31095 }
31096 node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
31097 }
31098 return finishNode(node, pos);
31099 }
31100 function parseJsxElementName() {
31101 var pos = getNodePos();
31102 scanJsxIdentifier();
31103 // JsxElement can have name in the form of
31104 // propertyAccessExpression
31105 // primaryExpression in the form of an identifier and "this" keyword
31106 // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
31107 // We only want to consider "this" as a primaryExpression
31108 var expression = token() === 107 /* ThisKeyword */ ?
31109 parseTokenNode() : parseIdentifierName();
31110 while (parseOptional(24 /* DotToken */)) {
31111 expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
31112 }
31113 return expression;
31114 }
31115 function parseJsxExpression(inExpressionContext) {
31116 var pos = getNodePos();
31117 if (!parseExpected(18 /* OpenBraceToken */)) {
31118 return undefined;
31119 }
31120 var dotDotDotToken;
31121 var expression;
31122 if (token() !== 19 /* CloseBraceToken */) {
31123 dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
31124 // Only an AssignmentExpression is valid here per the JSX spec,
31125 // but we can unambiguously parse a comma sequence and provide
31126 // a better error message in grammar checking.
31127 expression = parseExpression();
31128 }
31129 if (inExpressionContext) {
31130 parseExpected(19 /* CloseBraceToken */);
31131 }
31132 else {
31133 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
31134 scanJsxText();
31135 }
31136 }
31137 return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
31138 }
31139 function parseJsxAttribute() {
31140 if (token() === 18 /* OpenBraceToken */) {
31141 return parseJsxSpreadAttribute();
31142 }
31143 scanJsxIdentifier();
31144 var pos = getNodePos();
31145 return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 62 /* EqualsToken */ ? undefined :
31146 scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
31147 parseJsxExpression(/*inExpressionContext*/ true)), pos);
31148 }
31149 function parseJsxSpreadAttribute() {
31150 var pos = getNodePos();
31151 parseExpected(18 /* OpenBraceToken */);
31152 parseExpected(25 /* DotDotDotToken */);
31153 var expression = parseExpression();
31154 parseExpected(19 /* CloseBraceToken */);
31155 return finishNode(factory.createJsxSpreadAttribute(expression), pos);
31156 }
31157 function parseJsxClosingElement(inExpressionContext) {
31158 var pos = getNodePos();
31159 parseExpected(30 /* LessThanSlashToken */);
31160 var tagName = parseJsxElementName();
31161 if (inExpressionContext) {
31162 parseExpected(31 /* GreaterThanToken */);
31163 }
31164 else {
31165 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
31166 scanJsxText();
31167 }
31168 return finishNode(factory.createJsxClosingElement(tagName), pos);
31169 }
31170 function parseJsxClosingFragment(inExpressionContext) {
31171 var pos = getNodePos();
31172 parseExpected(30 /* LessThanSlashToken */);
31173 if (ts.tokenIsIdentifierOrKeyword(token())) {
31174 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
31175 }
31176 if (inExpressionContext) {
31177 parseExpected(31 /* GreaterThanToken */);
31178 }
31179 else {
31180 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
31181 scanJsxText();
31182 }
31183 return finishNode(factory.createJsxJsxClosingFragment(), pos);
31184 }
31185 function parseTypeAssertion() {
31186 var pos = getNodePos();
31187 parseExpected(29 /* LessThanToken */);
31188 var type = parseType();
31189 parseExpected(31 /* GreaterThanToken */);
31190 var expression = parseSimpleUnaryExpression();
31191 return finishNode(factory.createTypeAssertion(type, expression), pos);
31192 }
31193 function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
31194 nextToken();
31195 return ts.tokenIsIdentifierOrKeyword(token())
31196 || token() === 22 /* OpenBracketToken */
31197 || isTemplateStartOfTaggedTemplate();
31198 }
31199 function isStartOfOptionalPropertyOrElementAccessChain() {
31200 return token() === 28 /* QuestionDotToken */
31201 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
31202 }
31203 function tryReparseOptionalChain(node) {
31204 if (node.flags & 32 /* OptionalChain */) {
31205 return true;
31206 }
31207 // check for an optional chain in a non-null expression
31208 if (ts.isNonNullExpression(node)) {
31209 var expr = node.expression;
31210 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
31211 expr = expr.expression;
31212 }
31213 if (expr.flags & 32 /* OptionalChain */) {
31214 // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
31215 while (ts.isNonNullExpression(node)) {
31216 node.flags |= 32 /* OptionalChain */;
31217 node = node.expression;
31218 }
31219 return true;
31220 }
31221 }
31222 return false;
31223 }
31224 function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
31225 var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
31226 var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
31227 var propertyAccess = isOptionalChain ?
31228 factory.createPropertyAccessChain(expression, questionDotToken, name) :
31229 factory.createPropertyAccessExpression(expression, name);
31230 if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
31231 parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
31232 }
31233 return finishNode(propertyAccess, pos);
31234 }
31235 function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
31236 var argumentExpression;
31237 if (token() === 23 /* CloseBracketToken */) {
31238 argumentExpression = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
31239 }
31240 else {
31241 var argument = allowInAnd(parseExpression);
31242 if (ts.isStringOrNumericLiteralLike(argument)) {
31243 argument.text = internIdentifier(argument.text);
31244 }
31245 argumentExpression = argument;
31246 }
31247 parseExpected(23 /* CloseBracketToken */);
31248 var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
31249 factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
31250 factory.createElementAccessExpression(expression, argumentExpression);
31251 return finishNode(indexedAccess, pos);
31252 }
31253 function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
31254 while (true) {
31255 var questionDotToken = void 0;
31256 var isPropertyAccess = false;
31257 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
31258 questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
31259 isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
31260 }
31261 else {
31262 isPropertyAccess = parseOptional(24 /* DotToken */);
31263 }
31264 if (isPropertyAccess) {
31265 expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
31266 continue;
31267 }
31268 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
31269 nextToken();
31270 expression = finishNode(factory.createNonNullExpression(expression), pos);
31271 continue;
31272 }
31273 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
31274 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
31275 expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
31276 continue;
31277 }
31278 if (isTemplateStartOfTaggedTemplate()) {
31279 expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
31280 continue;
31281 }
31282 return expression;
31283 }
31284 }
31285 function isTemplateStartOfTaggedTemplate() {
31286 return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
31287 }
31288 function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
31289 var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
31290 (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
31291 parseTemplateExpression(/*isTaggedTemplate*/ true));
31292 if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
31293 tagExpression.flags |= 32 /* OptionalChain */;
31294 }
31295 tagExpression.questionDotToken = questionDotToken;
31296 return finishNode(tagExpression, pos);
31297 }
31298 function parseCallExpressionRest(pos, expression) {
31299 while (true) {
31300 expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
31301 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
31302 // handle 'foo<<T>()'
31303 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
31304 // See if this is the start of a generic invocation. If so, consume it and
31305 // keep checking for postfix expressions. Otherwise, it's just a '<' that's
31306 // part of an arithmetic expression. Break out so we consume it higher in the
31307 // stack.
31308 var typeArguments = tryParse(parseTypeArgumentsInExpression);
31309 if (typeArguments) {
31310 if (isTemplateStartOfTaggedTemplate()) {
31311 expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
31312 continue;
31313 }
31314 var argumentList = parseArgumentList();
31315 var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
31316 factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
31317 factory.createCallExpression(expression, typeArguments, argumentList);
31318 expression = finishNode(callExpr, pos);
31319 continue;
31320 }
31321 }
31322 else if (token() === 20 /* OpenParenToken */) {
31323 var argumentList = parseArgumentList();
31324 var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
31325 factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
31326 factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
31327 expression = finishNode(callExpr, pos);
31328 continue;
31329 }
31330 if (questionDotToken) {
31331 // We failed to parse anything, so report a missing identifier here.
31332 var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
31333 expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
31334 }
31335 break;
31336 }
31337 return expression;
31338 }
31339 function parseArgumentList() {
31340 parseExpected(20 /* OpenParenToken */);
31341 var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
31342 parseExpected(21 /* CloseParenToken */);
31343 return result;
31344 }
31345 function parseTypeArgumentsInExpression() {
31346 if (reScanLessThanToken() !== 29 /* LessThanToken */) {
31347 return undefined;
31348 }
31349 nextToken();
31350 var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
31351 if (!parseExpected(31 /* GreaterThanToken */)) {
31352 // If it doesn't have the closing `>` then it's definitely not an type argument list.
31353 return undefined;
31354 }
31355 // If we have a '<', then only parse this as a argument list if the type arguments
31356 // are complete and we have an open paren. if we don't, rewind and return nothing.
31357 return typeArguments && canFollowTypeArgumentsInExpression()
31358 ? typeArguments
31359 : undefined;
31360 }
31361 function canFollowTypeArgumentsInExpression() {
31362 switch (token()) {
31363 case 20 /* OpenParenToken */: // foo<x>(
31364 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
31365 case 15 /* TemplateHead */: // foo<T> `...${100}...`
31366 // these are the only tokens can legally follow a type argument
31367 // list. So we definitely want to treat them as type arg lists.
31368 // falls through
31369 case 24 /* DotToken */: // foo<x>.
31370 case 21 /* CloseParenToken */: // foo<x>)
31371 case 23 /* CloseBracketToken */: // foo<x>]
31372 case 58 /* ColonToken */: // foo<x>:
31373 case 26 /* SemicolonToken */: // foo<x>;
31374 case 57 /* QuestionToken */: // foo<x>?
31375 case 34 /* EqualsEqualsToken */: // foo<x> ==
31376 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
31377 case 35 /* ExclamationEqualsToken */: // foo<x> !=
31378 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
31379 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
31380 case 56 /* BarBarToken */: // foo<x> ||
31381 case 60 /* QuestionQuestionToken */: // foo<x> ??
31382 case 52 /* CaretToken */: // foo<x> ^
31383 case 50 /* AmpersandToken */: // foo<x> &
31384 case 51 /* BarToken */: // foo<x> |
31385 case 19 /* CloseBraceToken */: // foo<x> }
31386 case 1 /* EndOfFileToken */: // foo<x>
31387 // these cases can't legally follow a type arg list. However, they're not legal
31388 // expressions either. The user is probably in the middle of a generic type. So
31389 // treat it as such.
31390 return true;
31391 case 27 /* CommaToken */: // foo<x>,
31392 case 18 /* OpenBraceToken */: // foo<x> {
31393 // We don't want to treat these as type arguments. Otherwise we'll parse this
31394 // as an invocation expression. Instead, we want to parse out the expression
31395 // in isolation from the type arguments.
31396 // falls through
31397 default:
31398 // Anything else treat as an expression.
31399 return false;
31400 }
31401 }
31402 function parsePrimaryExpression() {
31403 switch (token()) {
31404 case 8 /* NumericLiteral */:
31405 case 9 /* BigIntLiteral */:
31406 case 10 /* StringLiteral */:
31407 case 14 /* NoSubstitutionTemplateLiteral */:
31408 return parseLiteralNode();
31409 case 107 /* ThisKeyword */:
31410 case 105 /* SuperKeyword */:
31411 case 103 /* NullKeyword */:
31412 case 109 /* TrueKeyword */:
31413 case 94 /* FalseKeyword */:
31414 return parseTokenNode();
31415 case 20 /* OpenParenToken */:
31416 return parseParenthesizedExpression();
31417 case 22 /* OpenBracketToken */:
31418 return parseArrayLiteralExpression();
31419 case 18 /* OpenBraceToken */:
31420 return parseObjectLiteralExpression();
31421 case 129 /* AsyncKeyword */:
31422 // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
31423 // If we encounter `async [no LineTerminator here] function` then this is an async
31424 // function; otherwise, its an identifier.
31425 if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
31426 break;
31427 }
31428 return parseFunctionExpression();
31429 case 83 /* ClassKeyword */:
31430 return parseClassExpression();
31431 case 97 /* FunctionKeyword */:
31432 return parseFunctionExpression();
31433 case 102 /* NewKeyword */:
31434 return parseNewExpressionOrNewDotTarget();
31435 case 43 /* SlashToken */:
31436 case 67 /* SlashEqualsToken */:
31437 if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
31438 return parseLiteralNode();
31439 }
31440 break;
31441 case 15 /* TemplateHead */:
31442 return parseTemplateExpression(/* isTaggedTemplate */ false);
31443 }
31444 return parseIdentifier(ts.Diagnostics.Expression_expected);
31445 }
31446 function parseParenthesizedExpression() {
31447 var pos = getNodePos();
31448 var hasJSDoc = hasPrecedingJSDocComment();
31449 parseExpected(20 /* OpenParenToken */);
31450 var expression = allowInAnd(parseExpression);
31451 parseExpected(21 /* CloseParenToken */);
31452 return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
31453 }
31454 function parseSpreadElement() {
31455 var pos = getNodePos();
31456 parseExpected(25 /* DotDotDotToken */);
31457 var expression = parseAssignmentExpressionOrHigher();
31458 return finishNode(factory.createSpreadElement(expression), pos);
31459 }
31460 function parseArgumentOrArrayLiteralElement() {
31461 return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
31462 token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
31463 parseAssignmentExpressionOrHigher();
31464 }
31465 function parseArgumentExpression() {
31466 return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
31467 }
31468 function parseArrayLiteralExpression() {
31469 var pos = getNodePos();
31470 parseExpected(22 /* OpenBracketToken */);
31471 var multiLine = scanner.hasPrecedingLineBreak();
31472 var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
31473 parseExpected(23 /* CloseBracketToken */);
31474 return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
31475 }
31476 function parseObjectLiteralElement() {
31477 var pos = getNodePos();
31478 var hasJSDoc = hasPrecedingJSDocComment();
31479 if (parseOptionalToken(25 /* DotDotDotToken */)) {
31480 var expression = parseAssignmentExpressionOrHigher();
31481 return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
31482 }
31483 var decorators = parseDecorators();
31484 var modifiers = parseModifiers();
31485 if (parseContextualModifier(134 /* GetKeyword */)) {
31486 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 166 /* GetAccessor */);
31487 }
31488 if (parseContextualModifier(145 /* SetKeyword */)) {
31489 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* SetAccessor */);
31490 }
31491 var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
31492 var tokenIsIdentifier = isIdentifier();
31493 var name = parsePropertyName();
31494 // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
31495 var questionToken = parseOptionalToken(57 /* QuestionToken */);
31496 var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
31497 if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
31498 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
31499 }
31500 // check if it is short-hand property assignment or normal property assignment
31501 // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
31502 // CoverInitializedName[Yield] :
31503 // IdentifierReference[?Yield] Initializer[In, ?Yield]
31504 // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
31505 var node;
31506 var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
31507 if (isShorthandPropertyAssignment) {
31508 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
31509 var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
31510 node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
31511 // Save equals token for error reporting.
31512 // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
31513 node.equalsToken = equalsToken;
31514 }
31515 else {
31516 parseExpected(58 /* ColonToken */);
31517 var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
31518 node = factory.createPropertyAssignment(name, initializer);
31519 }
31520 // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
31521 node.decorators = decorators;
31522 node.modifiers = modifiers;
31523 node.questionToken = questionToken;
31524 node.exclamationToken = exclamationToken;
31525 return withJSDoc(finishNode(node, pos), hasJSDoc);
31526 }
31527 function parseObjectLiteralExpression() {
31528 var pos = getNodePos();
31529 var openBracePosition = scanner.getTokenPos();
31530 parseExpected(18 /* OpenBraceToken */);
31531 var multiLine = scanner.hasPrecedingLineBreak();
31532 var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
31533 if (!parseExpected(19 /* CloseBraceToken */)) {
31534 var lastError = ts.lastOrUndefined(parseDiagnostics);
31535 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
31536 ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
31537 }
31538 }
31539 return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
31540 }
31541 function parseFunctionExpression() {
31542 // GeneratorExpression:
31543 // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
31544 //
31545 // FunctionExpression:
31546 // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
31547 var saveDecoratorContext = inDecoratorContext();
31548 if (saveDecoratorContext) {
31549 setDecoratorContext(/*val*/ false);
31550 }
31551 var pos = getNodePos();
31552 var hasJSDoc = hasPrecedingJSDocComment();
31553 var modifiers = parseModifiers();
31554 parseExpected(97 /* FunctionKeyword */);
31555 var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
31556 var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
31557 var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
31558 var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
31559 isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
31560 isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
31561 parseOptionalBindingIdentifier();
31562 var typeParameters = parseTypeParameters();
31563 var parameters = parseParameters(isGenerator | isAsync);
31564 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
31565 var body = parseFunctionBlock(isGenerator | isAsync);
31566 if (saveDecoratorContext) {
31567 setDecoratorContext(/*val*/ true);
31568 }
31569 var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
31570 return withJSDoc(finishNode(node, pos), hasJSDoc);
31571 }
31572 function parseOptionalBindingIdentifier() {
31573 return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
31574 }
31575 function parseNewExpressionOrNewDotTarget() {
31576 var pos = getNodePos();
31577 parseExpected(102 /* NewKeyword */);
31578 if (parseOptional(24 /* DotToken */)) {
31579 var name = parseIdentifierName();
31580 return finishNode(factory.createMetaProperty(102 /* NewKeyword */, name), pos);
31581 }
31582 var expressionPos = getNodePos();
31583 var expression = parsePrimaryExpression();
31584 var typeArguments;
31585 while (true) {
31586 expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
31587 typeArguments = tryParse(parseTypeArgumentsInExpression);
31588 if (isTemplateStartOfTaggedTemplate()) {
31589 ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
31590 expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
31591 typeArguments = undefined;
31592 }
31593 break;
31594 }
31595 var argumentsArray;
31596 if (token() === 20 /* OpenParenToken */) {
31597 argumentsArray = parseArgumentList();
31598 }
31599 else if (typeArguments) {
31600 parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
31601 }
31602 return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
31603 }
31604 // STATEMENTS
31605 function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
31606 var pos = getNodePos();
31607 var openBracePosition = scanner.getTokenPos();
31608 if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
31609 var multiLine = scanner.hasPrecedingLineBreak();
31610 var statements = parseList(1 /* BlockStatements */, parseStatement);
31611 if (!parseExpected(19 /* CloseBraceToken */)) {
31612 var lastError = ts.lastOrUndefined(parseDiagnostics);
31613 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
31614 ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
31615 }
31616 }
31617 return finishNode(factory.createBlock(statements, multiLine), pos);
31618 }
31619 else {
31620 var statements = createMissingList();
31621 return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos);
31622 }
31623 }
31624 function parseFunctionBlock(flags, diagnosticMessage) {
31625 var savedYieldContext = inYieldContext();
31626 setYieldContext(!!(flags & 1 /* Yield */));
31627 var savedAwaitContext = inAwaitContext();
31628 setAwaitContext(!!(flags & 2 /* Await */));
31629 var savedTopLevel = topLevel;
31630 topLevel = false;
31631 // We may be in a [Decorator] context when parsing a function expression or
31632 // arrow function. The body of the function is not in [Decorator] context.
31633 var saveDecoratorContext = inDecoratorContext();
31634 if (saveDecoratorContext) {
31635 setDecoratorContext(/*val*/ false);
31636 }
31637 var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
31638 if (saveDecoratorContext) {
31639 setDecoratorContext(/*val*/ true);
31640 }
31641 topLevel = savedTopLevel;
31642 setYieldContext(savedYieldContext);
31643 setAwaitContext(savedAwaitContext);
31644 return block;
31645 }
31646 function parseEmptyStatement() {
31647 var pos = getNodePos();
31648 parseExpected(26 /* SemicolonToken */);
31649 return finishNode(factory.createEmptyStatement(), pos);
31650 }
31651 function parseIfStatement() {
31652 var pos = getNodePos();
31653 parseExpected(98 /* IfKeyword */);
31654 parseExpected(20 /* OpenParenToken */);
31655 var expression = allowInAnd(parseExpression);
31656 parseExpected(21 /* CloseParenToken */);
31657 var thenStatement = parseStatement();
31658 var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined;
31659 return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos);
31660 }
31661 function parseDoStatement() {
31662 var pos = getNodePos();
31663 parseExpected(89 /* DoKeyword */);
31664 var statement = parseStatement();
31665 parseExpected(114 /* WhileKeyword */);
31666 parseExpected(20 /* OpenParenToken */);
31667 var expression = allowInAnd(parseExpression);
31668 parseExpected(21 /* CloseParenToken */);
31669 // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
31670 // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
31671 // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
31672 // do;while(0)x will have a semicolon inserted before x.
31673 parseOptional(26 /* SemicolonToken */);
31674 return finishNode(factory.createDoStatement(statement, expression), pos);
31675 }
31676 function parseWhileStatement() {
31677 var pos = getNodePos();
31678 parseExpected(114 /* WhileKeyword */);
31679 parseExpected(20 /* OpenParenToken */);
31680 var expression = allowInAnd(parseExpression);
31681 parseExpected(21 /* CloseParenToken */);
31682 var statement = parseStatement();
31683 return finishNode(factory.createWhileStatement(expression, statement), pos);
31684 }
31685 function parseForOrForInOrForOfStatement() {
31686 var pos = getNodePos();
31687 parseExpected(96 /* ForKeyword */);
31688 var awaitToken = parseOptionalToken(130 /* AwaitKeyword */);
31689 parseExpected(20 /* OpenParenToken */);
31690 var initializer;
31691 if (token() !== 26 /* SemicolonToken */) {
31692 if (token() === 112 /* VarKeyword */ || token() === 118 /* LetKeyword */ || token() === 84 /* ConstKeyword */) {
31693 initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
31694 }
31695 else {
31696 initializer = disallowInAnd(parseExpression);
31697 }
31698 }
31699 var node;
31700 if (awaitToken ? parseExpected(155 /* OfKeyword */) : parseOptional(155 /* OfKeyword */)) {
31701 var expression = allowInAnd(parseAssignmentExpressionOrHigher);
31702 parseExpected(21 /* CloseParenToken */);
31703 node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
31704 }
31705 else if (parseOptional(100 /* InKeyword */)) {
31706 var expression = allowInAnd(parseExpression);
31707 parseExpected(21 /* CloseParenToken */);
31708 node = factory.createForInStatement(initializer, expression, parseStatement());
31709 }
31710 else {
31711 parseExpected(26 /* SemicolonToken */);
31712 var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
31713 ? allowInAnd(parseExpression)
31714 : undefined;
31715 parseExpected(26 /* SemicolonToken */);
31716 var incrementor = token() !== 21 /* CloseParenToken */
31717 ? allowInAnd(parseExpression)
31718 : undefined;
31719 parseExpected(21 /* CloseParenToken */);
31720 node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
31721 }
31722 return finishNode(node, pos);
31723 }
31724 function parseBreakOrContinueStatement(kind) {
31725 var pos = getNodePos();
31726 parseExpected(kind === 238 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */);
31727 var label = canParseSemicolon() ? undefined : parseIdentifier();
31728 parseSemicolon();
31729 var node = kind === 238 /* BreakStatement */
31730 ? factory.createBreakStatement(label)
31731 : factory.createContinueStatement(label);
31732 return finishNode(node, pos);
31733 }
31734 function parseReturnStatement() {
31735 var pos = getNodePos();
31736 parseExpected(104 /* ReturnKeyword */);
31737 var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
31738 parseSemicolon();
31739 return finishNode(factory.createReturnStatement(expression), pos);
31740 }
31741 function parseWithStatement() {
31742 var pos = getNodePos();
31743 parseExpected(115 /* WithKeyword */);
31744 parseExpected(20 /* OpenParenToken */);
31745 var expression = allowInAnd(parseExpression);
31746 parseExpected(21 /* CloseParenToken */);
31747 var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
31748 return finishNode(factory.createWithStatement(expression, statement), pos);
31749 }
31750 function parseCaseClause() {
31751 var pos = getNodePos();
31752 parseExpected(81 /* CaseKeyword */);
31753 var expression = allowInAnd(parseExpression);
31754 parseExpected(58 /* ColonToken */);
31755 var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
31756 return finishNode(factory.createCaseClause(expression, statements), pos);
31757 }
31758 function parseDefaultClause() {
31759 var pos = getNodePos();
31760 parseExpected(87 /* DefaultKeyword */);
31761 parseExpected(58 /* ColonToken */);
31762 var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
31763 return finishNode(factory.createDefaultClause(statements), pos);
31764 }
31765 function parseCaseOrDefaultClause() {
31766 return token() === 81 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
31767 }
31768 function parseCaseBlock() {
31769 var pos = getNodePos();
31770 parseExpected(18 /* OpenBraceToken */);
31771 var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
31772 parseExpected(19 /* CloseBraceToken */);
31773 return finishNode(factory.createCaseBlock(clauses), pos);
31774 }
31775 function parseSwitchStatement() {
31776 var pos = getNodePos();
31777 parseExpected(106 /* SwitchKeyword */);
31778 parseExpected(20 /* OpenParenToken */);
31779 var expression = allowInAnd(parseExpression);
31780 parseExpected(21 /* CloseParenToken */);
31781 var caseBlock = parseCaseBlock();
31782 return finishNode(factory.createSwitchStatement(expression, caseBlock), pos);
31783 }
31784 function parseThrowStatement() {
31785 // ThrowStatement[Yield] :
31786 // throw [no LineTerminator here]Expression[In, ?Yield];
31787 var pos = getNodePos();
31788 parseExpected(108 /* ThrowKeyword */);
31789 // Because of automatic semicolon insertion, we need to report error if this
31790 // throw could be terminated with a semicolon. Note: we can't call 'parseExpression'
31791 // directly as that might consume an expression on the following line.
31792 // Instead, we create a "missing" identifier, but don't report an error. The actual error
31793 // will be reported in the grammar walker.
31794 var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
31795 if (expression === undefined) {
31796 identifierCount++;
31797 expression = finishNode(factory.createIdentifier(""), getNodePos());
31798 }
31799 parseSemicolon();
31800 return finishNode(factory.createThrowStatement(expression), pos);
31801 }
31802 // TODO: Review for error recovery
31803 function parseTryStatement() {
31804 var pos = getNodePos();
31805 parseExpected(110 /* TryKeyword */);
31806 var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
31807 var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined;
31808 // If we don't have a catch clause, then we must have a finally clause. Try to parse
31809 // one out no matter what.
31810 var finallyBlock;
31811 if (!catchClause || token() === 95 /* FinallyKeyword */) {
31812 parseExpected(95 /* FinallyKeyword */);
31813 finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
31814 }
31815 return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos);
31816 }
31817 function parseCatchClause() {
31818 var pos = getNodePos();
31819 parseExpected(82 /* CatchKeyword */);
31820 var variableDeclaration;
31821 if (parseOptional(20 /* OpenParenToken */)) {
31822 variableDeclaration = parseVariableDeclaration();
31823 parseExpected(21 /* CloseParenToken */);
31824 }
31825 else {
31826 // Keep shape of node to avoid degrading performance.
31827 variableDeclaration = undefined;
31828 }
31829 var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
31830 return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
31831 }
31832 function parseDebuggerStatement() {
31833 var pos = getNodePos();
31834 parseExpected(86 /* DebuggerKeyword */);
31835 parseSemicolon();
31836 return finishNode(factory.createDebuggerStatement(), pos);
31837 }
31838 function parseExpressionOrLabeledStatement() {
31839 // Avoiding having to do the lookahead for a labeled statement by just trying to parse
31840 // out an expression, seeing if it is identifier and then seeing if it is followed by
31841 // a colon.
31842 var pos = getNodePos();
31843 var hasJSDoc = hasPrecedingJSDocComment();
31844 var node;
31845 var hasParen = token() === 20 /* OpenParenToken */;
31846 var expression = allowInAnd(parseExpression);
31847 if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
31848 node = factory.createLabeledStatement(expression, parseStatement());
31849 }
31850 else {
31851 parseSemicolon();
31852 node = factory.createExpressionStatement(expression);
31853 if (hasParen) {
31854 // do not parse the same jsdoc twice
31855 hasJSDoc = false;
31856 }
31857 }
31858 return withJSDoc(finishNode(node, pos), hasJSDoc);
31859 }
31860 function nextTokenIsIdentifierOrKeywordOnSameLine() {
31861 nextToken();
31862 return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
31863 }
31864 function nextTokenIsClassKeywordOnSameLine() {
31865 nextToken();
31866 return token() === 83 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
31867 }
31868 function nextTokenIsFunctionKeywordOnSameLine() {
31869 nextToken();
31870 return token() === 97 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
31871 }
31872 function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
31873 nextToken();
31874 return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
31875 }
31876 function isDeclaration() {
31877 while (true) {
31878 switch (token()) {
31879 case 112 /* VarKeyword */:
31880 case 118 /* LetKeyword */:
31881 case 84 /* ConstKeyword */:
31882 case 97 /* FunctionKeyword */:
31883 case 83 /* ClassKeyword */:
31884 case 91 /* EnumKeyword */:
31885 return true;
31886 // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
31887 // however, an identifier cannot be followed by another identifier on the same line. This is what we
31888 // count on to parse out the respective declarations. For instance, we exploit this to say that
31889 //
31890 // namespace n
31891 //
31892 // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
31893 //
31894 // namespace
31895 // n
31896 //
31897 // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
31898 // We need to look one token ahead to see if it permissible to try parsing a declaration.
31899 //
31900 // *Note*: 'interface' is actually a strict mode reserved word. So while
31901 //
31902 // "use strict"
31903 // interface
31904 // I {}
31905 //
31906 // could be legal, it would add complexity for very little gain.
31907 case 117 /* InterfaceKeyword */:
31908 case 148 /* TypeKeyword */:
31909 return nextTokenIsIdentifierOnSameLine();
31910 case 138 /* ModuleKeyword */:
31911 case 139 /* NamespaceKeyword */:
31912 return nextTokenIsIdentifierOrStringLiteralOnSameLine();
31913 case 125 /* AbstractKeyword */:
31914 case 129 /* AsyncKeyword */:
31915 case 133 /* DeclareKeyword */:
31916 case 120 /* PrivateKeyword */:
31917 case 121 /* ProtectedKeyword */:
31918 case 122 /* PublicKeyword */:
31919 case 141 /* ReadonlyKeyword */:
31920 nextToken();
31921 // ASI takes effect for this modifier.
31922 if (scanner.hasPrecedingLineBreak()) {
31923 return false;
31924 }
31925 continue;
31926 case 153 /* GlobalKeyword */:
31927 nextToken();
31928 return token() === 18 /* OpenBraceToken */ || token() === 78 /* Identifier */ || token() === 92 /* ExportKeyword */;
31929 case 99 /* ImportKeyword */:
31930 nextToken();
31931 return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
31932 token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
31933 case 92 /* ExportKeyword */:
31934 var currentToken_1 = nextToken();
31935 if (currentToken_1 === 148 /* TypeKeyword */) {
31936 currentToken_1 = lookAhead(nextToken);
31937 }
31938 if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
31939 currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 87 /* DefaultKeyword */ ||
31940 currentToken_1 === 126 /* AsKeyword */) {
31941 return true;
31942 }
31943 continue;
31944 case 123 /* StaticKeyword */:
31945 nextToken();
31946 continue;
31947 default:
31948 return false;
31949 }
31950 }
31951 }
31952 function isStartOfDeclaration() {
31953 return lookAhead(isDeclaration);
31954 }
31955 function isStartOfStatement() {
31956 switch (token()) {
31957 case 59 /* AtToken */:
31958 case 26 /* SemicolonToken */:
31959 case 18 /* OpenBraceToken */:
31960 case 112 /* VarKeyword */:
31961 case 118 /* LetKeyword */:
31962 case 97 /* FunctionKeyword */:
31963 case 83 /* ClassKeyword */:
31964 case 91 /* EnumKeyword */:
31965 case 98 /* IfKeyword */:
31966 case 89 /* DoKeyword */:
31967 case 114 /* WhileKeyword */:
31968 case 96 /* ForKeyword */:
31969 case 85 /* ContinueKeyword */:
31970 case 80 /* BreakKeyword */:
31971 case 104 /* ReturnKeyword */:
31972 case 115 /* WithKeyword */:
31973 case 106 /* SwitchKeyword */:
31974 case 108 /* ThrowKeyword */:
31975 case 110 /* TryKeyword */:
31976 case 86 /* DebuggerKeyword */:
31977 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
31978 // however, we say they are here so that we may gracefully parse them and error later.
31979 // falls through
31980 case 82 /* CatchKeyword */:
31981 case 95 /* FinallyKeyword */:
31982 return true;
31983 case 99 /* ImportKeyword */:
31984 return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
31985 case 84 /* ConstKeyword */:
31986 case 92 /* ExportKeyword */:
31987 return isStartOfDeclaration();
31988 case 129 /* AsyncKeyword */:
31989 case 133 /* DeclareKeyword */:
31990 case 117 /* InterfaceKeyword */:
31991 case 138 /* ModuleKeyword */:
31992 case 139 /* NamespaceKeyword */:
31993 case 148 /* TypeKeyword */:
31994 case 153 /* GlobalKeyword */:
31995 // When these don't start a declaration, they're an identifier in an expression statement
31996 return true;
31997 case 122 /* PublicKeyword */:
31998 case 120 /* PrivateKeyword */:
31999 case 121 /* ProtectedKeyword */:
32000 case 123 /* StaticKeyword */:
32001 case 141 /* ReadonlyKeyword */:
32002 // When these don't start a declaration, they may be the start of a class member if an identifier
32003 // immediately follows. Otherwise they're an identifier in an expression statement.
32004 return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
32005 default:
32006 return isStartOfExpression();
32007 }
32008 }
32009 function nextTokenIsIdentifierOrStartOfDestructuring() {
32010 nextToken();
32011 return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
32012 }
32013 function isLetDeclaration() {
32014 // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
32015 // or [.
32016 return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
32017 }
32018 function parseStatement() {
32019 switch (token()) {
32020 case 26 /* SemicolonToken */:
32021 return parseEmptyStatement();
32022 case 18 /* OpenBraceToken */:
32023 return parseBlock(/*ignoreMissingOpenBrace*/ false);
32024 case 112 /* VarKeyword */:
32025 return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32026 case 118 /* LetKeyword */:
32027 if (isLetDeclaration()) {
32028 return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32029 }
32030 break;
32031 case 97 /* FunctionKeyword */:
32032 return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32033 case 83 /* ClassKeyword */:
32034 return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32035 case 98 /* IfKeyword */:
32036 return parseIfStatement();
32037 case 89 /* DoKeyword */:
32038 return parseDoStatement();
32039 case 114 /* WhileKeyword */:
32040 return parseWhileStatement();
32041 case 96 /* ForKeyword */:
32042 return parseForOrForInOrForOfStatement();
32043 case 85 /* ContinueKeyword */:
32044 return parseBreakOrContinueStatement(237 /* ContinueStatement */);
32045 case 80 /* BreakKeyword */:
32046 return parseBreakOrContinueStatement(238 /* BreakStatement */);
32047 case 104 /* ReturnKeyword */:
32048 return parseReturnStatement();
32049 case 115 /* WithKeyword */:
32050 return parseWithStatement();
32051 case 106 /* SwitchKeyword */:
32052 return parseSwitchStatement();
32053 case 108 /* ThrowKeyword */:
32054 return parseThrowStatement();
32055 case 110 /* TryKeyword */:
32056 // Include 'catch' and 'finally' for error recovery.
32057 // falls through
32058 case 82 /* CatchKeyword */:
32059 case 95 /* FinallyKeyword */:
32060 return parseTryStatement();
32061 case 86 /* DebuggerKeyword */:
32062 return parseDebuggerStatement();
32063 case 59 /* AtToken */:
32064 return parseDeclaration();
32065 case 129 /* AsyncKeyword */:
32066 case 117 /* InterfaceKeyword */:
32067 case 148 /* TypeKeyword */:
32068 case 138 /* ModuleKeyword */:
32069 case 139 /* NamespaceKeyword */:
32070 case 133 /* DeclareKeyword */:
32071 case 84 /* ConstKeyword */:
32072 case 91 /* EnumKeyword */:
32073 case 92 /* ExportKeyword */:
32074 case 99 /* ImportKeyword */:
32075 case 120 /* PrivateKeyword */:
32076 case 121 /* ProtectedKeyword */:
32077 case 122 /* PublicKeyword */:
32078 case 125 /* AbstractKeyword */:
32079 case 123 /* StaticKeyword */:
32080 case 141 /* ReadonlyKeyword */:
32081 case 153 /* GlobalKeyword */:
32082 if (isStartOfDeclaration()) {
32083 return parseDeclaration();
32084 }
32085 break;
32086 }
32087 return parseExpressionOrLabeledStatement();
32088 }
32089 function isDeclareModifier(modifier) {
32090 return modifier.kind === 133 /* DeclareKeyword */;
32091 }
32092 function parseDeclaration() {
32093 // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
32094 // if we can't reuse the declaration, so that we don't do this work twice?
32095 //
32096 // `parseListElement` attempted to get the reused node at this position,
32097 // but the ambient context flag was not yet set, so the node appeared
32098 // not reusable in that context.
32099 var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
32100 if (isAmbient) {
32101 var node = tryReuseAmbientDeclaration();
32102 if (node) {
32103 return node;
32104 }
32105 }
32106 var pos = getNodePos();
32107 var hasJSDoc = hasPrecedingJSDocComment();
32108 var decorators = parseDecorators();
32109 var modifiers = parseModifiers();
32110 if (isAmbient) {
32111 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
32112 var m = _a[_i];
32113 m.flags |= 8388608 /* Ambient */;
32114 }
32115 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
32116 }
32117 else {
32118 return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
32119 }
32120 }
32121 function tryReuseAmbientDeclaration() {
32122 return doInsideOfContext(8388608 /* Ambient */, function () {
32123 var node = currentNode(parsingContext);
32124 if (node) {
32125 return consumeNode(node);
32126 }
32127 });
32128 }
32129 function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
32130 switch (token()) {
32131 case 112 /* VarKeyword */:
32132 case 118 /* LetKeyword */:
32133 case 84 /* ConstKeyword */:
32134 return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
32135 case 97 /* FunctionKeyword */:
32136 return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
32137 case 83 /* ClassKeyword */:
32138 return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
32139 case 117 /* InterfaceKeyword */:
32140 return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
32141 case 148 /* TypeKeyword */:
32142 return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
32143 case 91 /* EnumKeyword */:
32144 return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
32145 case 153 /* GlobalKeyword */:
32146 case 138 /* ModuleKeyword */:
32147 case 139 /* NamespaceKeyword */:
32148 return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
32149 case 99 /* ImportKeyword */:
32150 return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
32151 case 92 /* ExportKeyword */:
32152 nextToken();
32153 switch (token()) {
32154 case 87 /* DefaultKeyword */:
32155 case 62 /* EqualsToken */:
32156 return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
32157 case 126 /* AsKeyword */:
32158 return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
32159 default:
32160 return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
32161 }
32162 default:
32163 if (decorators || modifiers) {
32164 // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
32165 // would follow. For recovery and error reporting purposes, return an incomplete declaration.
32166 var missing = createMissingNode(268 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
32167 ts.setTextRangePos(missing, pos);
32168 missing.decorators = decorators;
32169 missing.modifiers = modifiers;
32170 return missing;
32171 }
32172 return undefined; // TODO: GH#18217
32173 }
32174 }
32175 function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
32176 nextToken();
32177 return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
32178 }
32179 function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
32180 if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
32181 parseSemicolon();
32182 return;
32183 }
32184 return parseFunctionBlock(flags, diagnosticMessage);
32185 }
32186 // DECLARATIONS
32187 function parseArrayBindingElement() {
32188 var pos = getNodePos();
32189 if (token() === 27 /* CommaToken */) {
32190 return finishNode(factory.createOmittedExpression(), pos);
32191 }
32192 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
32193 var name = parseIdentifierOrPattern();
32194 var initializer = parseInitializer();
32195 return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
32196 }
32197 function parseObjectBindingElement() {
32198 var pos = getNodePos();
32199 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
32200 var tokenIsIdentifier = isBindingIdentifier();
32201 var propertyName = parsePropertyName();
32202 var name;
32203 if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
32204 name = propertyName;
32205 propertyName = undefined;
32206 }
32207 else {
32208 parseExpected(58 /* ColonToken */);
32209 name = parseIdentifierOrPattern();
32210 }
32211 var initializer = parseInitializer();
32212 return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
32213 }
32214 function parseObjectBindingPattern() {
32215 var pos = getNodePos();
32216 parseExpected(18 /* OpenBraceToken */);
32217 var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
32218 parseExpected(19 /* CloseBraceToken */);
32219 return finishNode(factory.createObjectBindingPattern(elements), pos);
32220 }
32221 function parseArrayBindingPattern() {
32222 var pos = getNodePos();
32223 parseExpected(22 /* OpenBracketToken */);
32224 var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
32225 parseExpected(23 /* CloseBracketToken */);
32226 return finishNode(factory.createArrayBindingPattern(elements), pos);
32227 }
32228 function isBindingIdentifierOrPrivateIdentifierOrPattern() {
32229 return token() === 18 /* OpenBraceToken */
32230 || token() === 22 /* OpenBracketToken */
32231 || token() === 79 /* PrivateIdentifier */
32232 || isBindingIdentifier();
32233 }
32234 function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
32235 if (token() === 22 /* OpenBracketToken */) {
32236 return parseArrayBindingPattern();
32237 }
32238 if (token() === 18 /* OpenBraceToken */) {
32239 return parseObjectBindingPattern();
32240 }
32241 return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
32242 }
32243 function parseVariableDeclarationAllowExclamation() {
32244 return parseVariableDeclaration(/*allowExclamation*/ true);
32245 }
32246 function parseVariableDeclaration(allowExclamation) {
32247 var pos = getNodePos();
32248 var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
32249 var exclamationToken;
32250 if (allowExclamation && name.kind === 78 /* Identifier */ &&
32251 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
32252 exclamationToken = parseTokenNode();
32253 }
32254 var type = parseTypeAnnotation();
32255 var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
32256 var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
32257 return finishNode(node, pos);
32258 }
32259 function parseVariableDeclarationList(inForStatementInitializer) {
32260 var pos = getNodePos();
32261 var flags = 0;
32262 switch (token()) {
32263 case 112 /* VarKeyword */:
32264 break;
32265 case 118 /* LetKeyword */:
32266 flags |= 1 /* Let */;
32267 break;
32268 case 84 /* ConstKeyword */:
32269 flags |= 2 /* Const */;
32270 break;
32271 default:
32272 ts.Debug.fail();
32273 }
32274 nextToken();
32275 // The user may have written the following:
32276 //
32277 // for (let of X) { }
32278 //
32279 // In this case, we want to parse an empty declaration list, and then parse 'of'
32280 // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
32281 // So we need to look ahead to determine if 'of' should be treated as a keyword in
32282 // this context.
32283 // The checker will then give an error that there is an empty declaration list.
32284 var declarations;
32285 if (token() === 155 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
32286 declarations = createMissingList();
32287 }
32288 else {
32289 var savedDisallowIn = inDisallowInContext();
32290 setDisallowInContext(inForStatementInitializer);
32291 declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
32292 setDisallowInContext(savedDisallowIn);
32293 }
32294 return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
32295 }
32296 function canFollowContextualOfKeyword() {
32297 return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
32298 }
32299 function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
32300 var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
32301 parseSemicolon();
32302 var node = factory.createVariableStatement(modifiers, declarationList);
32303 // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
32304 node.decorators = decorators;
32305 return withJSDoc(finishNode(node, pos), hasJSDoc);
32306 }
32307 function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
32308 var savedAwaitContext = inAwaitContext();
32309 var modifierFlags = ts.modifiersToFlags(modifiers);
32310 parseExpected(97 /* FunctionKeyword */);
32311 var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32312 // We don't parse the name here in await context, instead we will report a grammar error in the checker.
32313 var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
32314 var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
32315 var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
32316 var typeParameters = parseTypeParameters();
32317 if (modifierFlags & 1 /* Export */)
32318 setAwaitContext(/*value*/ true);
32319 var parameters = parseParameters(isGenerator | isAsync);
32320 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32321 var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
32322 setAwaitContext(savedAwaitContext);
32323 var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
32324 return withJSDoc(finishNode(node, pos), hasJSDoc);
32325 }
32326 function parseConstructorName() {
32327 if (token() === 132 /* ConstructorKeyword */) {
32328 return parseExpected(132 /* ConstructorKeyword */);
32329 }
32330 if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
32331 return tryParse(function () {
32332 var literalNode = parseLiteralNode();
32333 return literalNode.text === "constructor" ? literalNode : undefined;
32334 });
32335 }
32336 }
32337 function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
32338 return tryParse(function () {
32339 if (parseConstructorName()) {
32340 var typeParameters = parseTypeParameters();
32341 var parameters = parseParameters(0 /* None */);
32342 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32343 var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
32344 var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
32345 // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
32346 node.typeParameters = typeParameters;
32347 node.type = type;
32348 return withJSDoc(finishNode(node, pos), hasJSDoc);
32349 }
32350 });
32351 }
32352 function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
32353 var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
32354 var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
32355 var typeParameters = parseTypeParameters();
32356 var parameters = parseParameters(isGenerator | isAsync);
32357 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32358 var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
32359 var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
32360 // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
32361 node.exclamationToken = exclamationToken;
32362 return withJSDoc(finishNode(node, pos), hasJSDoc);
32363 }
32364 function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
32365 var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
32366 var type = parseTypeAnnotation();
32367 var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
32368 parseSemicolon();
32369 var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
32370 return withJSDoc(finishNode(node, pos), hasJSDoc);
32371 }
32372 function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
32373 var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32374 var name = parsePropertyName();
32375 // Note: this is not legal as per the grammar. But we allow it in the parser and
32376 // report an error in the grammar checker.
32377 var questionToken = parseOptionalToken(57 /* QuestionToken */);
32378 if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32379 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
32380 }
32381 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
32382 }
32383 function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
32384 var name = parsePropertyName();
32385 var typeParameters = parseTypeParameters();
32386 var parameters = parseParameters(0 /* None */);
32387 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32388 var body = parseFunctionBlockOrSemicolon(0 /* None */);
32389 var node = kind === 166 /* GetAccessor */
32390 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
32391 : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
32392 // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
32393 node.typeParameters = typeParameters;
32394 if (type && node.kind === 167 /* SetAccessor */)
32395 node.type = type;
32396 return withJSDoc(finishNode(node, pos), hasJSDoc);
32397 }
32398 function isClassMemberStart() {
32399 var idToken;
32400 if (token() === 59 /* AtToken */) {
32401 return true;
32402 }
32403 // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
32404 while (ts.isModifierKind(token())) {
32405 idToken = token();
32406 // If the idToken is a class modifier (protected, private, public, and static), it is
32407 // certain that we are starting to parse class member. This allows better error recovery
32408 // Example:
32409 // public foo() ... // true
32410 // public @dec blah ... // true; we will then report an error later
32411 // export public ... // true; we will then report an error later
32412 if (ts.isClassMemberModifier(idToken)) {
32413 return true;
32414 }
32415 nextToken();
32416 }
32417 if (token() === 41 /* AsteriskToken */) {
32418 return true;
32419 }
32420 // Try to get the first property-like token following all modifiers.
32421 // This can either be an identifier or the 'get' or 'set' keywords.
32422 if (isLiteralPropertyName()) {
32423 idToken = token();
32424 nextToken();
32425 }
32426 // Index signatures and computed properties are class members; we can parse.
32427 if (token() === 22 /* OpenBracketToken */) {
32428 return true;
32429 }
32430 // If we were able to get any potential identifier...
32431 if (idToken !== undefined) {
32432 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
32433 if (!ts.isKeyword(idToken) || idToken === 145 /* SetKeyword */ || idToken === 134 /* GetKeyword */) {
32434 return true;
32435 }
32436 // If it *is* a keyword, but not an accessor, check a little farther along
32437 // to see if it should actually be parsed as a class member.
32438 switch (token()) {
32439 case 20 /* OpenParenToken */: // Method declaration
32440 case 29 /* LessThanToken */: // Generic Method declaration
32441 case 53 /* ExclamationToken */: // Non-null assertion on property name
32442 case 58 /* ColonToken */: // Type Annotation for declaration
32443 case 62 /* EqualsToken */: // Initializer for declaration
32444 case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
32445 return true;
32446 default:
32447 // Covers
32448 // - Semicolons (declaration termination)
32449 // - Closing braces (end-of-class, must be declaration)
32450 // - End-of-files (not valid, but permitted so that it gets caught later on)
32451 // - Line-breaks (enabling *automatic semicolon insertion*)
32452 return canParseSemicolon();
32453 }
32454 }
32455 return false;
32456 }
32457 function parseDecoratorExpression() {
32458 if (inAwaitContext() && token() === 130 /* AwaitKeyword */) {
32459 // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
32460 // This simply parses the missing identifier and moves on.
32461 var pos = getNodePos();
32462 var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
32463 nextToken();
32464 var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
32465 return parseCallExpressionRest(pos, memberExpression);
32466 }
32467 return parseLeftHandSideExpressionOrHigher();
32468 }
32469 function tryParseDecorator() {
32470 var pos = getNodePos();
32471 if (!parseOptional(59 /* AtToken */)) {
32472 return undefined;
32473 }
32474 var expression = doInDecoratorContext(parseDecoratorExpression);
32475 return finishNode(factory.createDecorator(expression), pos);
32476 }
32477 function parseDecorators() {
32478 var pos = getNodePos();
32479 var list, decorator;
32480 while (decorator = tryParseDecorator()) {
32481 list = ts.append(list, decorator);
32482 }
32483 return list && createNodeArray(list, pos);
32484 }
32485 function tryParseModifier(permitInvalidConstAsModifier) {
32486 var pos = getNodePos();
32487 var kind = token();
32488 if (token() === 84 /* ConstKeyword */ && permitInvalidConstAsModifier) {
32489 // We need to ensure that any subsequent modifiers appear on the same line
32490 // so that when 'const' is a standalone declaration, we don't issue an error.
32491 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
32492 return undefined;
32493 }
32494 }
32495 else {
32496 if (!parseAnyContextualModifier()) {
32497 return undefined;
32498 }
32499 }
32500 return finishNode(factory.createToken(kind), pos);
32501 }
32502 /*
32503 * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
32504 * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
32505 * and turns it into a standalone declaration), then it is better to parse it and report an error later.
32506 *
32507 * In such situations, 'permitInvalidConstAsModifier' should be set to true.
32508 */
32509 function parseModifiers(permitInvalidConstAsModifier) {
32510 var pos = getNodePos();
32511 var list, modifier;
32512 while (modifier = tryParseModifier(permitInvalidConstAsModifier)) {
32513 list = ts.append(list, modifier);
32514 }
32515 return list && createNodeArray(list, pos);
32516 }
32517 function parseModifiersForArrowFunction() {
32518 var modifiers;
32519 if (token() === 129 /* AsyncKeyword */) {
32520 var pos = getNodePos();
32521 nextToken();
32522 var modifier = finishNode(factory.createToken(129 /* AsyncKeyword */), pos);
32523 modifiers = createNodeArray([modifier], pos);
32524 }
32525 return modifiers;
32526 }
32527 function parseClassElement() {
32528 var pos = getNodePos();
32529 if (token() === 26 /* SemicolonToken */) {
32530 nextToken();
32531 return finishNode(factory.createSemicolonClassElement(), pos);
32532 }
32533 var hasJSDoc = hasPrecedingJSDocComment();
32534 var decorators = parseDecorators();
32535 var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
32536 if (parseContextualModifier(134 /* GetKeyword */)) {
32537 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 166 /* GetAccessor */);
32538 }
32539 if (parseContextualModifier(145 /* SetKeyword */)) {
32540 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* SetAccessor */);
32541 }
32542 if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
32543 var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
32544 if (constructorDeclaration) {
32545 return constructorDeclaration;
32546 }
32547 }
32548 if (isIndexSignature()) {
32549 return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
32550 }
32551 // It is very important that we check this *after* checking indexers because
32552 // the [ token can start an index signature or a computed property name
32553 if (ts.tokenIsIdentifierOrKeyword(token()) ||
32554 token() === 10 /* StringLiteral */ ||
32555 token() === 8 /* NumericLiteral */ ||
32556 token() === 41 /* AsteriskToken */ ||
32557 token() === 22 /* OpenBracketToken */) {
32558 var isAmbient = ts.some(modifiers, isDeclareModifier);
32559 if (isAmbient) {
32560 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
32561 var m = _a[_i];
32562 m.flags |= 8388608 /* Ambient */;
32563 }
32564 return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
32565 }
32566 else {
32567 return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
32568 }
32569 }
32570 if (decorators || modifiers) {
32571 // treat this as a property declaration with a missing name.
32572 var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
32573 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
32574 }
32575 // 'isClassMemberStart' should have hinted not to attempt parsing.
32576 return ts.Debug.fail("Should not have attempted to parse class member declaration.");
32577 }
32578 function parseClassExpression() {
32579 return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 218 /* ClassExpression */);
32580 }
32581 function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
32582 return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 249 /* ClassDeclaration */);
32583 }
32584 function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
32585 var savedAwaitContext = inAwaitContext();
32586 parseExpected(83 /* ClassKeyword */);
32587 // We don't parse the name here in await context, instead we will report a grammar error in the checker.
32588 var name = parseNameOfClassDeclarationOrExpression();
32589 var typeParameters = parseTypeParameters();
32590 if (ts.some(modifiers, ts.isExportModifier))
32591 setAwaitContext(/*value*/ true);
32592 var heritageClauses = parseHeritageClauses();
32593 var members;
32594 if (parseExpected(18 /* OpenBraceToken */)) {
32595 // ClassTail[Yield,Await] : (Modified) See 14.5
32596 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
32597 members = parseClassMembers();
32598 parseExpected(19 /* CloseBraceToken */);
32599 }
32600 else {
32601 members = createMissingList();
32602 }
32603 setAwaitContext(savedAwaitContext);
32604 var node = kind === 249 /* ClassDeclaration */
32605 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
32606 : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
32607 return withJSDoc(finishNode(node, pos), hasJSDoc);
32608 }
32609 function parseNameOfClassDeclarationOrExpression() {
32610 // implements is a future reserved word so
32611 // 'class implements' might mean either
32612 // - class expression with omitted name, 'implements' starts heritage clause
32613 // - class with name 'implements'
32614 // 'isImplementsClause' helps to disambiguate between these two cases
32615 return isBindingIdentifier() && !isImplementsClause()
32616 ? createIdentifier(isBindingIdentifier())
32617 : undefined;
32618 }
32619 function isImplementsClause() {
32620 return token() === 116 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
32621 }
32622 function parseHeritageClauses() {
32623 // ClassTail[Yield,Await] : (Modified) See 14.5
32624 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
32625 if (isHeritageClause()) {
32626 return parseList(22 /* HeritageClauses */, parseHeritageClause);
32627 }
32628 return undefined;
32629 }
32630 function parseHeritageClause() {
32631 var pos = getNodePos();
32632 var tok = token();
32633 ts.Debug.assert(tok === 93 /* ExtendsKeyword */ || tok === 116 /* ImplementsKeyword */); // isListElement() should ensure this.
32634 nextToken();
32635 var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
32636 return finishNode(factory.createHeritageClause(tok, types), pos);
32637 }
32638 function parseExpressionWithTypeArguments() {
32639 var pos = getNodePos();
32640 var expression = parseLeftHandSideExpressionOrHigher();
32641 var typeArguments = tryParseTypeArguments();
32642 return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
32643 }
32644 function tryParseTypeArguments() {
32645 return token() === 29 /* LessThanToken */ ?
32646 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
32647 }
32648 function isHeritageClause() {
32649 return token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
32650 }
32651 function parseClassMembers() {
32652 return parseList(5 /* ClassMembers */, parseClassElement);
32653 }
32654 function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
32655 parseExpected(117 /* InterfaceKeyword */);
32656 var name = parseIdentifier();
32657 var typeParameters = parseTypeParameters();
32658 var heritageClauses = parseHeritageClauses();
32659 var members = parseObjectTypeMembers();
32660 var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
32661 return withJSDoc(finishNode(node, pos), hasJSDoc);
32662 }
32663 function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
32664 parseExpected(148 /* TypeKeyword */);
32665 var name = parseIdentifier();
32666 var typeParameters = parseTypeParameters();
32667 parseExpected(62 /* EqualsToken */);
32668 var type = parseType();
32669 parseSemicolon();
32670 var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
32671 return withJSDoc(finishNode(node, pos), hasJSDoc);
32672 }
32673 // In an ambient declaration, the grammar only allows integer literals as initializers.
32674 // In a non-ambient declaration, the grammar allows uninitialized members only in a
32675 // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
32676 // or any time an integer literal initializer is encountered.
32677 function parseEnumMember() {
32678 var pos = getNodePos();
32679 var hasJSDoc = hasPrecedingJSDocComment();
32680 var name = parsePropertyName();
32681 var initializer = allowInAnd(parseInitializer);
32682 return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
32683 }
32684 function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
32685 parseExpected(91 /* EnumKeyword */);
32686 var name = parseIdentifier();
32687 var members;
32688 if (parseExpected(18 /* OpenBraceToken */)) {
32689 members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
32690 parseExpected(19 /* CloseBraceToken */);
32691 }
32692 else {
32693 members = createMissingList();
32694 }
32695 var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
32696 return withJSDoc(finishNode(node, pos), hasJSDoc);
32697 }
32698 function parseModuleBlock() {
32699 var pos = getNodePos();
32700 var statements;
32701 if (parseExpected(18 /* OpenBraceToken */)) {
32702 statements = parseList(1 /* BlockStatements */, parseStatement);
32703 parseExpected(19 /* CloseBraceToken */);
32704 }
32705 else {
32706 statements = createMissingList();
32707 }
32708 return finishNode(factory.createModuleBlock(statements), pos);
32709 }
32710 function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
32711 // If we are parsing a dotted namespace name, we want to
32712 // propagate the 'Namespace' flag across the names if set.
32713 var namespaceFlag = flags & 16 /* Namespace */;
32714 var name = parseIdentifier();
32715 var body = parseOptional(24 /* DotToken */)
32716 ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
32717 : parseModuleBlock();
32718 var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
32719 return withJSDoc(finishNode(node, pos), hasJSDoc);
32720 }
32721 function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
32722 var flags = 0;
32723 var name;
32724 if (token() === 153 /* GlobalKeyword */) {
32725 // parse 'global' as name of global scope augmentation
32726 name = parseIdentifier();
32727 flags |= 1024 /* GlobalAugmentation */;
32728 }
32729 else {
32730 name = parseLiteralNode();
32731 name.text = internIdentifier(name.text);
32732 }
32733 var body;
32734 if (token() === 18 /* OpenBraceToken */) {
32735 body = parseModuleBlock();
32736 }
32737 else {
32738 parseSemicolon();
32739 }
32740 var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
32741 return withJSDoc(finishNode(node, pos), hasJSDoc);
32742 }
32743 function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
32744 var flags = 0;
32745 if (token() === 153 /* GlobalKeyword */) {
32746 // global augmentation
32747 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
32748 }
32749 else if (parseOptional(139 /* NamespaceKeyword */)) {
32750 flags |= 16 /* Namespace */;
32751 }
32752 else {
32753 parseExpected(138 /* ModuleKeyword */);
32754 if (token() === 10 /* StringLiteral */) {
32755 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
32756 }
32757 }
32758 return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
32759 }
32760 function isExternalModuleReference() {
32761 return token() === 142 /* RequireKeyword */ &&
32762 lookAhead(nextTokenIsOpenParen);
32763 }
32764 function nextTokenIsOpenParen() {
32765 return nextToken() === 20 /* OpenParenToken */;
32766 }
32767 function nextTokenIsSlash() {
32768 return nextToken() === 43 /* SlashToken */;
32769 }
32770 function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
32771 parseExpected(126 /* AsKeyword */);
32772 parseExpected(139 /* NamespaceKeyword */);
32773 var name = parseIdentifier();
32774 parseSemicolon();
32775 var node = factory.createNamespaceExportDeclaration(name);
32776 // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
32777 node.decorators = decorators;
32778 node.modifiers = modifiers;
32779 return withJSDoc(finishNode(node, pos), hasJSDoc);
32780 }
32781 function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
32782 parseExpected(99 /* ImportKeyword */);
32783 var afterImportPos = scanner.getStartPos();
32784 // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
32785 var identifier;
32786 if (isIdentifier()) {
32787 identifier = parseIdentifier();
32788 }
32789 var isTypeOnly = false;
32790 if (token() !== 152 /* FromKeyword */ &&
32791 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
32792 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
32793 isTypeOnly = true;
32794 identifier = isIdentifier() ? parseIdentifier() : undefined;
32795 }
32796 if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
32797 return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
32798 }
32799 // ImportDeclaration:
32800 // import ImportClause from ModuleSpecifier ;
32801 // import ModuleSpecifier;
32802 var importClause;
32803 if (identifier || // import id
32804 token() === 41 /* AsteriskToken */ || // import *
32805 token() === 18 /* OpenBraceToken */ // import {
32806 ) {
32807 importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
32808 parseExpected(152 /* FromKeyword */);
32809 }
32810 var moduleSpecifier = parseModuleSpecifier();
32811 parseSemicolon();
32812 var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier);
32813 return withJSDoc(finishNode(node, pos), hasJSDoc);
32814 }
32815 function tokenAfterImportDefinitelyProducesImportDeclaration() {
32816 return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
32817 }
32818 function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
32819 // In `import id ___`, the current token decides whether to produce
32820 // an ImportDeclaration or ImportEqualsDeclaration.
32821 return token() === 27 /* CommaToken */ || token() === 152 /* FromKeyword */;
32822 }
32823 function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
32824 parseExpected(62 /* EqualsToken */);
32825 var moduleReference = parseModuleReference();
32826 parseSemicolon();
32827 var node = factory.createImportEqualsDeclaration(decorators, modifiers, identifier, moduleReference);
32828 var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
32829 if (isTypeOnly) {
32830 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
32831 }
32832 return finished;
32833 }
32834 function parseImportClause(identifier, pos, isTypeOnly) {
32835 // ImportClause:
32836 // ImportedDefaultBinding
32837 // NameSpaceImport
32838 // NamedImports
32839 // ImportedDefaultBinding, NameSpaceImport
32840 // ImportedDefaultBinding, NamedImports
32841 // If there was no default import or if there is comma token after default import
32842 // parse namespace or named imports
32843 var namedBindings;
32844 if (!identifier ||
32845 parseOptional(27 /* CommaToken */)) {
32846 namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(261 /* NamedImports */);
32847 }
32848 return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
32849 }
32850 function parseModuleReference() {
32851 return isExternalModuleReference()
32852 ? parseExternalModuleReference()
32853 : parseEntityName(/*allowReservedWords*/ false);
32854 }
32855 function parseExternalModuleReference() {
32856 var pos = getNodePos();
32857 parseExpected(142 /* RequireKeyword */);
32858 parseExpected(20 /* OpenParenToken */);
32859 var expression = parseModuleSpecifier();
32860 parseExpected(21 /* CloseParenToken */);
32861 return finishNode(factory.createExternalModuleReference(expression), pos);
32862 }
32863 function parseModuleSpecifier() {
32864 if (token() === 10 /* StringLiteral */) {
32865 var result = parseLiteralNode();
32866 result.text = internIdentifier(result.text);
32867 return result;
32868 }
32869 else {
32870 // We allow arbitrary expressions here, even though the grammar only allows string
32871 // literals. We check to ensure that it is only a string literal later in the grammar
32872 // check pass.
32873 return parseExpression();
32874 }
32875 }
32876 function parseNamespaceImport() {
32877 // NameSpaceImport:
32878 // * as ImportedBinding
32879 var pos = getNodePos();
32880 parseExpected(41 /* AsteriskToken */);
32881 parseExpected(126 /* AsKeyword */);
32882 var name = parseIdentifier();
32883 return finishNode(factory.createNamespaceImport(name), pos);
32884 }
32885 function parseNamedImportsOrExports(kind) {
32886 var pos = getNodePos();
32887 // NamedImports:
32888 // { }
32889 // { ImportsList }
32890 // { ImportsList, }
32891 // ImportsList:
32892 // ImportSpecifier
32893 // ImportsList, ImportSpecifier
32894 var node = kind === 261 /* NamedImports */
32895 ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
32896 : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
32897 return finishNode(node, pos);
32898 }
32899 function parseExportSpecifier() {
32900 return parseImportOrExportSpecifier(267 /* ExportSpecifier */);
32901 }
32902 function parseImportSpecifier() {
32903 return parseImportOrExportSpecifier(262 /* ImportSpecifier */);
32904 }
32905 function parseImportOrExportSpecifier(kind) {
32906 var pos = getNodePos();
32907 // ImportSpecifier:
32908 // BindingIdentifier
32909 // IdentifierName as BindingIdentifier
32910 // ExportSpecifier:
32911 // IdentifierName
32912 // IdentifierName as IdentifierName
32913 var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
32914 var checkIdentifierStart = scanner.getTokenPos();
32915 var checkIdentifierEnd = scanner.getTextPos();
32916 var identifierName = parseIdentifierName();
32917 var propertyName;
32918 var name;
32919 if (token() === 126 /* AsKeyword */) {
32920 propertyName = identifierName;
32921 parseExpected(126 /* AsKeyword */);
32922 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
32923 checkIdentifierStart = scanner.getTokenPos();
32924 checkIdentifierEnd = scanner.getTextPos();
32925 name = parseIdentifierName();
32926 }
32927 else {
32928 name = identifierName;
32929 }
32930 if (kind === 262 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
32931 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
32932 }
32933 var node = kind === 262 /* ImportSpecifier */
32934 ? factory.createImportSpecifier(propertyName, name)
32935 : factory.createExportSpecifier(propertyName, name);
32936 return finishNode(node, pos);
32937 }
32938 function parseNamespaceExport(pos) {
32939 return finishNode(factory.createNamespaceExport(parseIdentifier()), pos);
32940 }
32941 function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
32942 var savedAwaitContext = inAwaitContext();
32943 setAwaitContext(/*value*/ true);
32944 var exportClause;
32945 var moduleSpecifier;
32946 var isTypeOnly = parseOptional(148 /* TypeKeyword */);
32947 var namespaceExportPos = getNodePos();
32948 if (parseOptional(41 /* AsteriskToken */)) {
32949 if (parseOptional(126 /* AsKeyword */)) {
32950 exportClause = parseNamespaceExport(namespaceExportPos);
32951 }
32952 parseExpected(152 /* FromKeyword */);
32953 moduleSpecifier = parseModuleSpecifier();
32954 }
32955 else {
32956 exportClause = parseNamedImportsOrExports(265 /* NamedExports */);
32957 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
32958 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
32959 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
32960 if (token() === 152 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
32961 parseExpected(152 /* FromKeyword */);
32962 moduleSpecifier = parseModuleSpecifier();
32963 }
32964 }
32965 parseSemicolon();
32966 setAwaitContext(savedAwaitContext);
32967 var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
32968 return withJSDoc(finishNode(node, pos), hasJSDoc);
32969 }
32970 function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
32971 var savedAwaitContext = inAwaitContext();
32972 setAwaitContext(/*value*/ true);
32973 var isExportEquals;
32974 if (parseOptional(62 /* EqualsToken */)) {
32975 isExportEquals = true;
32976 }
32977 else {
32978 parseExpected(87 /* DefaultKeyword */);
32979 }
32980 var expression = parseAssignmentExpressionOrHigher();
32981 parseSemicolon();
32982 setAwaitContext(savedAwaitContext);
32983 var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
32984 return withJSDoc(finishNode(node, pos), hasJSDoc);
32985 }
32986 function setExternalModuleIndicator(sourceFile) {
32987 // Try to use the first top-level import/export when available, then
32988 // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
32989 sourceFile.externalModuleIndicator =
32990 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
32991 getImportMetaIfNecessary(sourceFile);
32992 }
32993 function isAnExternalModuleIndicatorNode(node) {
32994 return hasModifierOfKind(node, 92 /* ExportKeyword */)
32995 || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
32996 || ts.isImportDeclaration(node)
32997 || ts.isExportAssignment(node)
32998 || ts.isExportDeclaration(node) ? node : undefined;
32999 }
33000 function getImportMetaIfNecessary(sourceFile) {
33001 return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
33002 walkTreeForExternalModuleIndicators(sourceFile) :
33003 undefined;
33004 }
33005 function walkTreeForExternalModuleIndicators(node) {
33006 return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
33007 }
33008 /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
33009 function hasModifierOfKind(node, kind) {
33010 return ts.some(node.modifiers, function (m) { return m.kind === kind; });
33011 }
33012 function isImportMeta(node) {
33013 return ts.isMetaProperty(node) && node.keywordToken === 99 /* ImportKeyword */ && node.name.escapedText === "meta";
33014 }
33015 var ParsingContext;
33016 (function (ParsingContext) {
33017 ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
33018 ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
33019 ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
33020 ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
33021 ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
33022 ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
33023 ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
33024 ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
33025 ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
33026 ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
33027 ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
33028 ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
33029 ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
33030 ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
33031 ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
33032 ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
33033 ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
33034 ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
33035 ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
33036 ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
33037 ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
33038 ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
33039 ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
33040 ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
33041 ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
33042 })(ParsingContext || (ParsingContext = {}));
33043 var Tristate;
33044 (function (Tristate) {
33045 Tristate[Tristate["False"] = 0] = "False";
33046 Tristate[Tristate["True"] = 1] = "True";
33047 Tristate[Tristate["Unknown"] = 2] = "Unknown";
33048 })(Tristate || (Tristate = {}));
33049 var JSDocParser;
33050 (function (JSDocParser) {
33051 function parseJSDocTypeExpressionForTests(content, start, length) {
33052 initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33053 scanner.setText(content, start, length);
33054 currentToken = scanner.scan();
33055 var jsDocTypeExpression = parseJSDocTypeExpression();
33056 var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
33057 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33058 if (jsDocDiagnostics) {
33059 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
33060 }
33061 clearState();
33062 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
33063 }
33064 JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
33065 // Parses out a JSDoc type expression.
33066 function parseJSDocTypeExpression(mayOmitBraces) {
33067 var pos = getNodePos();
33068 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
33069 var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
33070 if (!mayOmitBraces || hasBrace) {
33071 parseExpectedJSDoc(19 /* CloseBraceToken */);
33072 }
33073 var result = factory.createJSDocTypeExpression(type);
33074 fixupParentReferences(result);
33075 return finishNode(result, pos);
33076 }
33077 JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
33078 function parseIsolatedJSDocComment(content, start, length) {
33079 initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33080 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33081 var sourceFile = { languageVariant: 0 /* Standard */, text: content };
33082 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33083 clearState();
33084 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
33085 }
33086 JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
33087 function parseJSDocComment(parent, start, length) {
33088 var saveToken = currentToken;
33089 var saveParseDiagnosticsLength = parseDiagnostics.length;
33090 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
33091 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33092 ts.setParent(comment, parent);
33093 if (contextFlags & 131072 /* JavaScriptFile */) {
33094 if (!jsDocDiagnostics) {
33095 jsDocDiagnostics = [];
33096 }
33097 jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
33098 }
33099 currentToken = saveToken;
33100 parseDiagnostics.length = saveParseDiagnosticsLength;
33101 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
33102 return comment;
33103 }
33104 JSDocParser.parseJSDocComment = parseJSDocComment;
33105 var JSDocState;
33106 (function (JSDocState) {
33107 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
33108 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
33109 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
33110 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
33111 })(JSDocState || (JSDocState = {}));
33112 var PropertyLikeParse;
33113 (function (PropertyLikeParse) {
33114 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
33115 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
33116 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
33117 })(PropertyLikeParse || (PropertyLikeParse = {}));
33118 function parseJSDocCommentWorker(start, length) {
33119 if (start === void 0) { start = 0; }
33120 var content = sourceText;
33121 var end = length === undefined ? content.length : start + length;
33122 length = end - start;
33123 ts.Debug.assert(start >= 0);
33124 ts.Debug.assert(start <= end);
33125 ts.Debug.assert(end <= content.length);
33126 // Check for /** (JSDoc opening part)
33127 if (!isJSDocLikeText(content, start)) {
33128 return undefined;
33129 }
33130 var tags;
33131 var tagsPos;
33132 var tagsEnd;
33133 var comments = [];
33134 // + 3 for leading /**, - 5 in total for /** */
33135 return scanner.scanRange(start + 3, length - 5, function () {
33136 // Initially we can parse out a tag. We also have seen a starting asterisk.
33137 // This is so that /** * @type */ doesn't parse.
33138 var state = 1 /* SawAsterisk */;
33139 var margin;
33140 // + 4 for leading '/** '
33141 var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
33142 function pushComment(text) {
33143 if (!margin) {
33144 margin = indent;
33145 }
33146 comments.push(text);
33147 indent += text.length;
33148 }
33149 nextTokenJSDoc();
33150 while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
33151 ;
33152 if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
33153 state = 0 /* BeginningOfLine */;
33154 indent = 0;
33155 }
33156 loop: while (true) {
33157 switch (token()) {
33158 case 59 /* AtToken */:
33159 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
33160 removeTrailingWhitespace(comments);
33161 addTag(parseTag(indent));
33162 // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
33163 // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
33164 // for malformed examples like `/** @param {string} x @returns {number} the length */`
33165 state = 0 /* BeginningOfLine */;
33166 margin = undefined;
33167 }
33168 else {
33169 pushComment(scanner.getTokenText());
33170 }
33171 break;
33172 case 4 /* NewLineTrivia */:
33173 comments.push(scanner.getTokenText());
33174 state = 0 /* BeginningOfLine */;
33175 indent = 0;
33176 break;
33177 case 41 /* AsteriskToken */:
33178 var asterisk = scanner.getTokenText();
33179 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
33180 // If we've already seen an asterisk, then we can no longer parse a tag on this line
33181 state = 2 /* SavingComments */;
33182 pushComment(asterisk);
33183 }
33184 else {
33185 // Ignore the first asterisk on a line
33186 state = 1 /* SawAsterisk */;
33187 indent += asterisk.length;
33188 }
33189 break;
33190 case 5 /* WhitespaceTrivia */:
33191 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
33192 var whitespace = scanner.getTokenText();
33193 if (state === 2 /* SavingComments */) {
33194 comments.push(whitespace);
33195 }
33196 else if (margin !== undefined && indent + whitespace.length > margin) {
33197 comments.push(whitespace.slice(margin - indent - 1));
33198 }
33199 indent += whitespace.length;
33200 break;
33201 case 1 /* EndOfFileToken */:
33202 break loop;
33203 default:
33204 // Anything else is doc comment text. We just save it. Because it
33205 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
33206 // line break.
33207 state = 2 /* SavingComments */;
33208 pushComment(scanner.getTokenText());
33209 break;
33210 }
33211 nextTokenJSDoc();
33212 }
33213 removeLeadingNewlines(comments);
33214 removeTrailingWhitespace(comments);
33215 return createJSDocComment();
33216 });
33217 function removeLeadingNewlines(comments) {
33218 while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
33219 comments.shift();
33220 }
33221 }
33222 function removeTrailingWhitespace(comments) {
33223 while (comments.length && comments[comments.length - 1].trim() === "") {
33224 comments.pop();
33225 }
33226 }
33227 function createJSDocComment() {
33228 var comment = comments.length ? comments.join("") : undefined;
33229 var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
33230 return finishNode(factory.createJSDocComment(comment, tagsArray), start, end);
33231 }
33232 function isNextNonwhitespaceTokenEndOfFile() {
33233 // We must use infinite lookahead, as there could be any number of newlines :(
33234 while (true) {
33235 nextTokenJSDoc();
33236 if (token() === 1 /* EndOfFileToken */) {
33237 return true;
33238 }
33239 if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
33240 return false;
33241 }
33242 }
33243 }
33244 function skipWhitespace() {
33245 if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
33246 if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
33247 return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
33248 }
33249 }
33250 while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
33251 nextTokenJSDoc();
33252 }
33253 }
33254 function skipWhitespaceOrAsterisk() {
33255 if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
33256 if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
33257 return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
33258 }
33259 }
33260 var precedingLineBreak = scanner.hasPrecedingLineBreak();
33261 var seenLineBreak = false;
33262 var indentText = "";
33263 while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
33264 indentText += scanner.getTokenText();
33265 if (token() === 4 /* NewLineTrivia */) {
33266 precedingLineBreak = true;
33267 seenLineBreak = true;
33268 indentText = "";
33269 }
33270 else if (token() === 41 /* AsteriskToken */) {
33271 precedingLineBreak = false;
33272 }
33273 nextTokenJSDoc();
33274 }
33275 return seenLineBreak ? indentText : "";
33276 }
33277 function parseTag(margin) {
33278 ts.Debug.assert(token() === 59 /* AtToken */);
33279 var start = scanner.getTokenPos();
33280 nextTokenJSDoc();
33281 var tagName = parseJSDocIdentifierName(/*message*/ undefined);
33282 var indentText = skipWhitespaceOrAsterisk();
33283 var tag;
33284 switch (tagName.escapedText) {
33285 case "author":
33286 tag = parseAuthorTag(start, tagName, margin, indentText);
33287 break;
33288 case "implements":
33289 tag = parseImplementsTag(start, tagName, margin, indentText);
33290 break;
33291 case "augments":
33292 case "extends":
33293 tag = parseAugmentsTag(start, tagName, margin, indentText);
33294 break;
33295 case "class":
33296 case "constructor":
33297 tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
33298 break;
33299 case "public":
33300 tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
33301 break;
33302 case "private":
33303 tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
33304 break;
33305 case "protected":
33306 tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
33307 break;
33308 case "readonly":
33309 tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
33310 break;
33311 case "deprecated":
33312 hasDeprecatedTag = true;
33313 tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
33314 break;
33315 case "this":
33316 tag = parseThisTag(start, tagName, margin, indentText);
33317 break;
33318 case "enum":
33319 tag = parseEnumTag(start, tagName, margin, indentText);
33320 break;
33321 case "arg":
33322 case "argument":
33323 case "param":
33324 return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
33325 case "return":
33326 case "returns":
33327 tag = parseReturnTag(start, tagName, margin, indentText);
33328 break;
33329 case "template":
33330 tag = parseTemplateTag(start, tagName, margin, indentText);
33331 break;
33332 case "type":
33333 tag = parseTypeTag(start, tagName, margin, indentText);
33334 break;
33335 case "typedef":
33336 tag = parseTypedefTag(start, tagName, margin, indentText);
33337 break;
33338 case "callback":
33339 tag = parseCallbackTag(start, tagName, margin, indentText);
33340 break;
33341 default:
33342 tag = parseUnknownTag(start, tagName, margin, indentText);
33343 break;
33344 }
33345 return tag;
33346 }
33347 function parseTrailingTagComments(pos, end, margin, indentText) {
33348 // some tags, like typedef and callback, have already parsed their comments earlier
33349 if (!indentText) {
33350 margin += end - pos;
33351 }
33352 return parseTagComments(margin, indentText.slice(margin));
33353 }
33354 function parseTagComments(indent, initialMargin) {
33355 var comments = [];
33356 var state = 0 /* BeginningOfLine */;
33357 var margin;
33358 function pushComment(text) {
33359 if (!margin) {
33360 margin = indent;
33361 }
33362 comments.push(text);
33363 indent += text.length;
33364 }
33365 if (initialMargin !== undefined) {
33366 // jump straight to saving comments if there is some initial indentation
33367 if (initialMargin !== "") {
33368 pushComment(initialMargin);
33369 }
33370 state = 1 /* SawAsterisk */;
33371 }
33372 var tok = token();
33373 loop: while (true) {
33374 switch (tok) {
33375 case 4 /* NewLineTrivia */:
33376 state = 0 /* BeginningOfLine */;
33377 // don't use pushComment here because we want to keep the margin unchanged
33378 comments.push(scanner.getTokenText());
33379 indent = 0;
33380 break;
33381 case 59 /* AtToken */:
33382 if (state === 3 /* SavingBackticks */) {
33383 comments.push(scanner.getTokenText());
33384 break;
33385 }
33386 scanner.setTextPos(scanner.getTextPos() - 1);
33387 // falls through
33388 case 1 /* EndOfFileToken */:
33389 // Done
33390 break loop;
33391 case 5 /* WhitespaceTrivia */:
33392 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
33393 pushComment(scanner.getTokenText());
33394 }
33395 else {
33396 var whitespace = scanner.getTokenText();
33397 // if the whitespace crosses the margin, take only the whitespace that passes the margin
33398 if (margin !== undefined && indent + whitespace.length > margin) {
33399 comments.push(whitespace.slice(margin - indent));
33400 }
33401 indent += whitespace.length;
33402 }
33403 break;
33404 case 18 /* OpenBraceToken */:
33405 state = 2 /* SavingComments */;
33406 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
33407 pushComment(scanner.getTokenText());
33408 nextTokenJSDoc();
33409 pushComment(scanner.getTokenText());
33410 nextTokenJSDoc();
33411 }
33412 pushComment(scanner.getTokenText());
33413 break;
33414 case 61 /* BacktickToken */:
33415 if (state === 3 /* SavingBackticks */) {
33416 state = 2 /* SavingComments */;
33417 }
33418 else {
33419 state = 3 /* SavingBackticks */;
33420 }
33421 pushComment(scanner.getTokenText());
33422 break;
33423 case 41 /* AsteriskToken */:
33424 if (state === 0 /* BeginningOfLine */) {
33425 // leading asterisks start recording on the *next* (non-whitespace) token
33426 state = 1 /* SawAsterisk */;
33427 indent += 1;
33428 break;
33429 }
33430 // record the * as a comment
33431 // falls through
33432 default:
33433 if (state !== 3 /* SavingBackticks */) {
33434 state = 2 /* SavingComments */; // leading identifiers start recording as well
33435 }
33436 pushComment(scanner.getTokenText());
33437 break;
33438 }
33439 tok = nextTokenJSDoc();
33440 }
33441 removeLeadingNewlines(comments);
33442 removeTrailingWhitespace(comments);
33443 return comments.length === 0 ? undefined : comments.join("");
33444 }
33445 function parseUnknownTag(start, tagName, indent, indentText) {
33446 var end = getNodePos();
33447 return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end);
33448 }
33449 function addTag(tag) {
33450 if (!tag) {
33451 return;
33452 }
33453 if (!tags) {
33454 tags = [tag];
33455 tagsPos = tag.pos;
33456 }
33457 else {
33458 tags.push(tag);
33459 }
33460 tagsEnd = tag.end;
33461 }
33462 function tryParseTypeExpression() {
33463 skipWhitespaceOrAsterisk();
33464 return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
33465 }
33466 function parseBracketNameInPropertyAndParamTag() {
33467 // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
33468 var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
33469 if (isBracketed) {
33470 skipWhitespace();
33471 }
33472 // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
33473 var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
33474 var name = parseJSDocEntityName();
33475 if (isBackquoted) {
33476 parseExpectedTokenJSDoc(61 /* BacktickToken */);
33477 }
33478 if (isBracketed) {
33479 skipWhitespace();
33480 // May have an optional default, e.g. '[foo = 42]'
33481 if (parseOptionalToken(62 /* EqualsToken */)) {
33482 parseExpression();
33483 }
33484 parseExpected(23 /* CloseBracketToken */);
33485 }
33486 return { name: name, isBracketed: isBracketed };
33487 }
33488 function isObjectOrObjectArrayTypeReference(node) {
33489 switch (node.kind) {
33490 case 144 /* ObjectKeyword */:
33491 return true;
33492 case 177 /* ArrayType */:
33493 return isObjectOrObjectArrayTypeReference(node.elementType);
33494 default:
33495 return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
33496 }
33497 }
33498 function parseParameterOrPropertyTag(start, tagName, target, indent) {
33499 var typeExpression = tryParseTypeExpression();
33500 var isNameFirst = !typeExpression;
33501 skipWhitespaceOrAsterisk();
33502 var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
33503 skipWhitespace();
33504 if (isNameFirst) {
33505 typeExpression = tryParseTypeExpression();
33506 }
33507 var comment = parseTagComments(indent + scanner.getStartPos() - start);
33508 var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
33509 if (nestedTypeLiteral) {
33510 typeExpression = nestedTypeLiteral;
33511 isNameFirst = true;
33512 }
33513 var result = target === 1 /* Property */
33514 ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
33515 : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
33516 return finishNode(result, start);
33517 }
33518 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
33519 if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
33520 var pos = getNodePos();
33521 var child = void 0;
33522 var children = void 0;
33523 while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
33524 if (child.kind === 322 /* JSDocParameterTag */ || child.kind === 328 /* JSDocPropertyTag */) {
33525 children = ts.append(children, child);
33526 }
33527 }
33528 if (children) {
33529 var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 177 /* ArrayType */), pos);
33530 return finishNode(factory.createJSDocTypeExpression(literal), pos);
33531 }
33532 }
33533 }
33534 function parseReturnTag(start, tagName, indent, indentText) {
33535 if (ts.some(tags, ts.isJSDocReturnTag)) {
33536 parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
33537 }
33538 var typeExpression = tryParseTypeExpression();
33539 var end = getNodePos();
33540 return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end);
33541 }
33542 function parseTypeTag(start, tagName, indent, indentText) {
33543 if (ts.some(tags, ts.isJSDocTypeTag)) {
33544 parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
33545 }
33546 var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
33547 var end = getNodePos();
33548 var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
33549 return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end);
33550 }
33551 function parseAuthorTag(start, tagName, indent, indentText) {
33552 var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
33553 if (!authorInfoWithEmail) {
33554 var end_1 = getNodePos();
33555 return finishNode(factory.createJSDocAuthorTag(tagName, parseTrailingTagComments(start, end_1, indent, indentText)), start, end_1);
33556 }
33557 var comments = authorInfoWithEmail;
33558 if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
33559 var comment = parseTagComments(indent);
33560 if (comment) {
33561 comments += comment;
33562 }
33563 }
33564 return finishNode(factory.createJSDocAuthorTag(tagName, comments), start);
33565 }
33566 function tryParseAuthorNameAndEmail() {
33567 var comments = [];
33568 var seenLessThan = false;
33569 var seenGreaterThan = false;
33570 var token = scanner.getToken();
33571 loop: while (true) {
33572 switch (token) {
33573 case 78 /* Identifier */:
33574 case 5 /* WhitespaceTrivia */:
33575 case 24 /* DotToken */:
33576 case 59 /* AtToken */:
33577 comments.push(scanner.getTokenText());
33578 break;
33579 case 29 /* LessThanToken */:
33580 if (seenLessThan || seenGreaterThan) {
33581 return;
33582 }
33583 seenLessThan = true;
33584 comments.push(scanner.getTokenText());
33585 break;
33586 case 31 /* GreaterThanToken */:
33587 if (!seenLessThan || seenGreaterThan) {
33588 return;
33589 }
33590 seenGreaterThan = true;
33591 comments.push(scanner.getTokenText());
33592 scanner.setTextPos(scanner.getTokenPos() + 1);
33593 break loop;
33594 case 4 /* NewLineTrivia */:
33595 case 1 /* EndOfFileToken */:
33596 break loop;
33597 }
33598 token = nextTokenJSDoc();
33599 }
33600 if (seenLessThan && seenGreaterThan) {
33601 return comments.length === 0 ? undefined : comments.join("");
33602 }
33603 }
33604 function parseImplementsTag(start, tagName, margin, indentText) {
33605 var className = parseExpressionWithTypeArgumentsForAugments();
33606 var end = getNodePos();
33607 return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
33608 }
33609 function parseAugmentsTag(start, tagName, margin, indentText) {
33610 var className = parseExpressionWithTypeArgumentsForAugments();
33611 var end = getNodePos();
33612 return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
33613 }
33614 function parseExpressionWithTypeArgumentsForAugments() {
33615 var usedBrace = parseOptional(18 /* OpenBraceToken */);
33616 var pos = getNodePos();
33617 var expression = parsePropertyAccessEntityNameExpression();
33618 var typeArguments = tryParseTypeArguments();
33619 var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
33620 var res = finishNode(node, pos);
33621 if (usedBrace) {
33622 parseExpected(19 /* CloseBraceToken */);
33623 }
33624 return res;
33625 }
33626 function parsePropertyAccessEntityNameExpression() {
33627 var pos = getNodePos();
33628 var node = parseJSDocIdentifierName();
33629 while (parseOptional(24 /* DotToken */)) {
33630 var name = parseJSDocIdentifierName();
33631 node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
33632 }
33633 return node;
33634 }
33635 function parseSimpleTag(start, createTag, tagName, margin, indentText) {
33636 var end = getNodePos();
33637 return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end);
33638 }
33639 function parseThisTag(start, tagName, margin, indentText) {
33640 var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
33641 skipWhitespace();
33642 var end = getNodePos();
33643 return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
33644 }
33645 function parseEnumTag(start, tagName, margin, indentText) {
33646 var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
33647 skipWhitespace();
33648 var end = getNodePos();
33649 return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
33650 }
33651 function parseTypedefTag(start, tagName, indent, indentText) {
33652 var _a;
33653 var typeExpression = tryParseTypeExpression();
33654 skipWhitespaceOrAsterisk();
33655 var fullName = parseJSDocTypeNameWithNamespace();
33656 skipWhitespace();
33657 var comment = parseTagComments(indent);
33658 var end;
33659 if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
33660 var child = void 0;
33661 var childTypeTag = void 0;
33662 var jsDocPropertyTags = void 0;
33663 var hasChildren = false;
33664 while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
33665 hasChildren = true;
33666 if (child.kind === 325 /* JSDocTypeTag */) {
33667 if (childTypeTag) {
33668 parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
33669 var lastError = ts.lastOrUndefined(parseDiagnostics);
33670 if (lastError) {
33671 ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
33672 }
33673 break;
33674 }
33675 else {
33676 childTypeTag = child;
33677 }
33678 }
33679 else {
33680 jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
33681 }
33682 }
33683 if (hasChildren) {
33684 var isArrayType = typeExpression && typeExpression.type.kind === 177 /* ArrayType */;
33685 var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
33686 typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
33687 childTypeTag.typeExpression :
33688 finishNode(jsdocTypeLiteral, start);
33689 end = typeExpression.end;
33690 }
33691 }
33692 // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
33693 end = end || comment !== undefined ?
33694 getNodePos() :
33695 ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
33696 if (!comment) {
33697 comment = parseTrailingTagComments(start, end, indent, indentText);
33698 }
33699 var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
33700 return finishNode(typedefTag, start, end);
33701 }
33702 function parseJSDocTypeNameWithNamespace(nested) {
33703 var pos = scanner.getTokenPos();
33704 if (!ts.tokenIsIdentifierOrKeyword(token())) {
33705 return undefined;
33706 }
33707 var typeNameOrNamespaceName = parseJSDocIdentifierName();
33708 if (parseOptional(24 /* DotToken */)) {
33709 var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
33710 var jsDocNamespaceNode = factory.createModuleDeclaration(
33711 /*decorators*/ undefined,
33712 /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
33713 return finishNode(jsDocNamespaceNode, pos);
33714 }
33715 if (nested) {
33716 typeNameOrNamespaceName.isInJSDocNamespace = true;
33717 }
33718 return typeNameOrNamespaceName;
33719 }
33720 function parseCallbackTagParameters(indent) {
33721 var pos = getNodePos();
33722 var child;
33723 var parameters;
33724 while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
33725 parameters = ts.append(parameters, child);
33726 }
33727 return createNodeArray(parameters || [], pos);
33728 }
33729 function parseCallbackTag(start, tagName, indent, indentText) {
33730 var fullName = parseJSDocTypeNameWithNamespace();
33731 skipWhitespace();
33732 var comment = parseTagComments(indent);
33733 var parameters = parseCallbackTagParameters(indent);
33734 var returnTag = tryParse(function () {
33735 if (parseOptionalJsdoc(59 /* AtToken */)) {
33736 var tag = parseTag(indent);
33737 if (tag && tag.kind === 323 /* JSDocReturnTag */) {
33738 return tag;
33739 }
33740 }
33741 });
33742 var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
33743 var end = getNodePos();
33744 if (!comment) {
33745 comment = parseTrailingTagComments(start, end, indent, indentText);
33746 }
33747 return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end);
33748 }
33749 function escapedTextsEqual(a, b) {
33750 while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
33751 if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
33752 a = a.left;
33753 b = b.left;
33754 }
33755 else {
33756 return false;
33757 }
33758 }
33759 return a.escapedText === b.escapedText;
33760 }
33761 function parseChildPropertyTag(indent) {
33762 return parseChildParameterOrPropertyTag(1 /* Property */, indent);
33763 }
33764 function parseChildParameterOrPropertyTag(target, indent, name) {
33765 var canParseTag = true;
33766 var seenAsterisk = false;
33767 while (true) {
33768 switch (nextTokenJSDoc()) {
33769 case 59 /* AtToken */:
33770 if (canParseTag) {
33771 var child = tryParseChildTag(target, indent);
33772 if (child && (child.kind === 322 /* JSDocParameterTag */ || child.kind === 328 /* JSDocPropertyTag */) &&
33773 target !== 4 /* CallbackParameter */ &&
33774 name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
33775 return false;
33776 }
33777 return child;
33778 }
33779 seenAsterisk = false;
33780 break;
33781 case 4 /* NewLineTrivia */:
33782 canParseTag = true;
33783 seenAsterisk = false;
33784 break;
33785 case 41 /* AsteriskToken */:
33786 if (seenAsterisk) {
33787 canParseTag = false;
33788 }
33789 seenAsterisk = true;
33790 break;
33791 case 78 /* Identifier */:
33792 canParseTag = false;
33793 break;
33794 case 1 /* EndOfFileToken */:
33795 return false;
33796 }
33797 }
33798 }
33799 function tryParseChildTag(target, indent) {
33800 ts.Debug.assert(token() === 59 /* AtToken */);
33801 var start = scanner.getStartPos();
33802 nextTokenJSDoc();
33803 var tagName = parseJSDocIdentifierName();
33804 skipWhitespace();
33805 var t;
33806 switch (tagName.escapedText) {
33807 case "type":
33808 return target === 1 /* Property */ && parseTypeTag(start, tagName);
33809 case "prop":
33810 case "property":
33811 t = 1 /* Property */;
33812 break;
33813 case "arg":
33814 case "argument":
33815 case "param":
33816 t = 2 /* Parameter */ | 4 /* CallbackParameter */;
33817 break;
33818 default:
33819 return false;
33820 }
33821 if (!(target & t)) {
33822 return false;
33823 }
33824 return parseParameterOrPropertyTag(start, tagName, target, indent);
33825 }
33826 function parseTemplateTagTypeParameter() {
33827 var typeParameterPos = getNodePos();
33828 var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
33829 return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos);
33830 }
33831 function parseTemplateTagTypeParameters() {
33832 var pos = getNodePos();
33833 var typeParameters = [];
33834 do {
33835 skipWhitespace();
33836 typeParameters.push(parseTemplateTagTypeParameter());
33837 skipWhitespaceOrAsterisk();
33838 } while (parseOptionalJsdoc(27 /* CommaToken */));
33839 return createNodeArray(typeParameters, pos);
33840 }
33841 function parseTemplateTag(start, tagName, indent, indentText) {
33842 // The template tag looks like one of the following:
33843 // @template T,U,V
33844 // @template {Constraint} T
33845 //
33846 // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
33847 // > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
33848 // > type bound they must be declared on separate lines.
33849 //
33850 // TODO: Determine whether we should enforce this in the checker.
33851 // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
33852 // TODO: Consider only parsing a single type parameter if there is a constraint.
33853 var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
33854 var typeParameters = parseTemplateTagTypeParameters();
33855 var end = getNodePos();
33856 return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end);
33857 }
33858 function parseOptionalJsdoc(t) {
33859 if (token() === t) {
33860 nextTokenJSDoc();
33861 return true;
33862 }
33863 return false;
33864 }
33865 function parseJSDocEntityName() {
33866 var entity = parseJSDocIdentifierName();
33867 if (parseOptional(22 /* OpenBracketToken */)) {
33868 parseExpected(23 /* CloseBracketToken */);
33869 // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
33870 // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
33871 // but it's not worth it to enforce that restriction.
33872 }
33873 while (parseOptional(24 /* DotToken */)) {
33874 var name = parseJSDocIdentifierName();
33875 if (parseOptional(22 /* OpenBracketToken */)) {
33876 parseExpected(23 /* CloseBracketToken */);
33877 }
33878 entity = createQualifiedName(entity, name);
33879 }
33880 return entity;
33881 }
33882 function parseJSDocIdentifierName(message) {
33883 if (!ts.tokenIsIdentifierOrKeyword(token())) {
33884 return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
33885 }
33886 identifierCount++;
33887 var pos = scanner.getTokenPos();
33888 var end = scanner.getTextPos();
33889 var originalKeywordKind = token();
33890 var text = internIdentifier(scanner.getTokenValue());
33891 var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
33892 nextTokenJSDoc();
33893 return result;
33894 }
33895 }
33896 })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
33897 })(Parser || (Parser = {}));
33898 var IncrementalParser;
33899 (function (IncrementalParser) {
33900 function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
33901 aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
33902 checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
33903 if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
33904 // if the text didn't change, then we can just return our current source file as-is.
33905 return sourceFile;
33906 }
33907 if (sourceFile.statements.length === 0) {
33908 // If we don't have any statements in the current source file, then there's no real
33909 // way to incrementally parse. So just do a full parse instead.
33910 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
33911 }
33912 // Make sure we're not trying to incrementally update a source file more than once. Once
33913 // we do an update the original source file is considered unusable from that point onwards.
33914 //
33915 // This is because we do incremental parsing in-place. i.e. we take nodes from the old
33916 // tree and give them new positions and parents. From that point on, trusting the old
33917 // tree at all is not possible as far too much of it may violate invariants.
33918 var incrementalSourceFile = sourceFile;
33919 ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
33920 incrementalSourceFile.hasBeenIncrementallyParsed = true;
33921 Parser.fixupParentReferences(incrementalSourceFile);
33922 var oldText = sourceFile.text;
33923 var syntaxCursor = createSyntaxCursor(sourceFile);
33924 // Make the actual change larger so that we know to reparse anything whose lookahead
33925 // might have intersected the change.
33926 var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
33927 checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
33928 // Ensure that extending the affected range only moved the start of the change range
33929 // earlier in the file.
33930 ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
33931 ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
33932 ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
33933 // The is the amount the nodes after the edit range need to be adjusted. It can be
33934 // positive (if the edit added characters), negative (if the edit deleted characters)
33935 // or zero (if this was a pure overwrite with nothing added/removed).
33936 var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
33937 // If we added or removed characters during the edit, then we need to go and adjust all
33938 // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they
33939 // may move backward (if we deleted chars).
33940 //
33941 // Doing this helps us out in two ways. First, it means that any nodes/tokens we want
33942 // to reuse are already at the appropriate position in the new text. That way when we
33943 // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
33944 // it very easy to determine if we can reuse a node. If the node's position is at where
33945 // we are in the text, then we can reuse it. Otherwise we can't. If the node's position
33946 // is ahead of us, then we'll need to rescan tokens. If the node's position is behind
33947 // us, then we'll need to skip it or crumble it as appropriate
33948 //
33949 // We will also adjust the positions of nodes that intersect the change range as well.
33950 // By doing this, we ensure that all the positions in the old tree are consistent, not
33951 // just the positions of nodes entirely before/after the change range. By being
33952 // consistent, we can then easily map from positions to nodes in the old tree easily.
33953 //
33954 // Also, mark any syntax elements that intersect the changed span. We know, up front,
33955 // that we cannot reuse these elements.
33956 updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
33957 // Now that we've set up our internal incremental state just proceed and parse the
33958 // source file in the normal fashion. When possible the parser will retrieve and
33959 // reuse nodes from the old tree.
33960 //
33961 // Note: passing in 'true' for setNodeParents is very important. When incrementally
33962 // parsing, we will be reusing nodes from the old tree, and placing it into new
33963 // parents. If we don't set the parents now, we'll end up with an observably
33964 // inconsistent tree. Setting the parents on the new tree should be very fast. We
33965 // will immediately bail out of walking any subtrees when we can see that their parents
33966 // are already correct.
33967 var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
33968 result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
33969 return result;
33970 }
33971 IncrementalParser.updateSourceFile = updateSourceFile;
33972 function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
33973 if (!oldDirectives)
33974 return newDirectives;
33975 var commentDirectives;
33976 var addedNewlyScannedDirectives = false;
33977 for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
33978 var directive = oldDirectives_1[_i];
33979 var range = directive.range, type = directive.type;
33980 // Range before the change
33981 if (range.end < changeStart) {
33982 commentDirectives = ts.append(commentDirectives, directive);
33983 }
33984 else if (range.pos > changeRangeOldEnd) {
33985 addNewlyScannedDirectives();
33986 // Node is entirely past the change range. We need to move both its pos and
33987 // end, forward or backward appropriately.
33988 var updatedDirective = {
33989 range: { pos: range.pos + delta, end: range.end + delta },
33990 type: type
33991 };
33992 commentDirectives = ts.append(commentDirectives, updatedDirective);
33993 if (aggressiveChecks) {
33994 ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
33995 }
33996 }
33997 // Ignore ranges that fall in change range
33998 }
33999 addNewlyScannedDirectives();
34000 return commentDirectives;
34001 function addNewlyScannedDirectives() {
34002 if (addedNewlyScannedDirectives)
34003 return;
34004 addedNewlyScannedDirectives = true;
34005 if (!commentDirectives) {
34006 commentDirectives = newDirectives;
34007 }
34008 else if (newDirectives) {
34009 commentDirectives.push.apply(commentDirectives, newDirectives);
34010 }
34011 }
34012 }
34013 function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
34014 if (isArray) {
34015 visitArray(element);
34016 }
34017 else {
34018 visitNode(element);
34019 }
34020 return;
34021 function visitNode(node) {
34022 var text = "";
34023 if (aggressiveChecks && shouldCheckNode(node)) {
34024 text = oldText.substring(node.pos, node.end);
34025 }
34026 // Ditch any existing LS children we may have created. This way we can avoid
34027 // moving them forward.
34028 if (node._children) {
34029 node._children = undefined;
34030 }
34031 ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
34032 if (aggressiveChecks && shouldCheckNode(node)) {
34033 ts.Debug.assert(text === newText.substring(node.pos, node.end));
34034 }
34035 forEachChild(node, visitNode, visitArray);
34036 if (ts.hasJSDocNodes(node)) {
34037 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
34038 var jsDocComment = _a[_i];
34039 visitNode(jsDocComment);
34040 }
34041 }
34042 checkNodePositions(node, aggressiveChecks);
34043 }
34044 function visitArray(array) {
34045 array._children = undefined;
34046 ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
34047 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
34048 var node = array_8[_i];
34049 visitNode(node);
34050 }
34051 }
34052 }
34053 function shouldCheckNode(node) {
34054 switch (node.kind) {
34055 case 10 /* StringLiteral */:
34056 case 8 /* NumericLiteral */:
34057 case 78 /* Identifier */:
34058 return true;
34059 }
34060 return false;
34061 }
34062 function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
34063 ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
34064 ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
34065 ts.Debug.assert(element.pos <= element.end);
34066 // We have an element that intersects the change range in some way. It may have its
34067 // start, or its end (or both) in the changed range. We want to adjust any part
34068 // that intersects such that the final tree is in a consistent state. i.e. all
34069 // children have spans within the span of their parent, and all siblings are ordered
34070 // properly.
34071 // We may need to update both the 'pos' and the 'end' of the element.
34072 // If the 'pos' is before the start of the change, then we don't need to touch it.
34073 // If it isn't, then the 'pos' must be inside the change. How we update it will
34074 // depend if delta is positive or negative. If delta is positive then we have
34075 // something like:
34076 //
34077 // -------------------AAA-----------------
34078 // -------------------BBBCCCCCCC-----------------
34079 //
34080 // In this case, we consider any node that started in the change range to still be
34081 // starting at the same position.
34082 //
34083 // however, if the delta is negative, then we instead have something like this:
34084 //
34085 // -------------------XXXYYYYYYY-----------------
34086 // -------------------ZZZ-----------------
34087 //
34088 // In this case, any element that started in the 'X' range will keep its position.
34089 // However any element that started after that will have their pos adjusted to be
34090 // at the end of the new range. i.e. any node that started in the 'Y' range will
34091 // be adjusted to have their start at the end of the 'Z' range.
34092 //
34093 // The element will keep its position if possible. Or Move backward to the new-end
34094 // if it's in the 'Y' range.
34095 var pos = Math.min(element.pos, changeRangeNewEnd);
34096 // If the 'end' is after the change range, then we always adjust it by the delta
34097 // amount. However, if the end is in the change range, then how we adjust it
34098 // will depend on if delta is positive or negative. If delta is positive then we
34099 // have something like:
34100 //
34101 // -------------------AAA-----------------
34102 // -------------------BBBCCCCCCC-----------------
34103 //
34104 // In this case, we consider any node that ended inside the change range to keep its
34105 // end position.
34106 //
34107 // however, if the delta is negative, then we instead have something like this:
34108 //
34109 // -------------------XXXYYYYYYY-----------------
34110 // -------------------ZZZ-----------------
34111 //
34112 // In this case, any element that ended in the 'X' range will keep its position.
34113 // However any element that ended after that will have their pos adjusted to be
34114 // at the end of the new range. i.e. any node that ended in the 'Y' range will
34115 // be adjusted to have their end at the end of the 'Z' range.
34116 var end = element.end >= changeRangeOldEnd ?
34117 // Element ends after the change range. Always adjust the end pos.
34118 element.end + delta :
34119 // Element ends in the change range. The element will keep its position if
34120 // possible. Or Move backward to the new-end if it's in the 'Y' range.
34121 Math.min(element.end, changeRangeNewEnd);
34122 ts.Debug.assert(pos <= end);
34123 if (element.parent) {
34124 ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
34125 ts.Debug.assertLessThanOrEqual(end, element.parent.end);
34126 }
34127 ts.setTextRangePosEnd(element, pos, end);
34128 }
34129 function checkNodePositions(node, aggressiveChecks) {
34130 if (aggressiveChecks) {
34131 var pos_2 = node.pos;
34132 var visitNode_1 = function (child) {
34133 ts.Debug.assert(child.pos >= pos_2);
34134 pos_2 = child.end;
34135 };
34136 if (ts.hasJSDocNodes(node)) {
34137 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
34138 var jsDocComment = _a[_i];
34139 visitNode_1(jsDocComment);
34140 }
34141 }
34142 forEachChild(node, visitNode_1);
34143 ts.Debug.assert(pos_2 <= node.end);
34144 }
34145 }
34146 function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
34147 visitNode(sourceFile);
34148 return;
34149 function visitNode(child) {
34150 ts.Debug.assert(child.pos <= child.end);
34151 if (child.pos > changeRangeOldEnd) {
34152 // Node is entirely past the change range. We need to move both its pos and
34153 // end, forward or backward appropriately.
34154 moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
34155 return;
34156 }
34157 // Check if the element intersects the change range. If it does, then it is not
34158 // reusable. Also, we'll need to recurse to see what constituent portions we may
34159 // be able to use.
34160 var fullEnd = child.end;
34161 if (fullEnd >= changeStart) {
34162 child.intersectsChange = true;
34163 child._children = undefined;
34164 // Adjust the pos or end (or both) of the intersecting element accordingly.
34165 adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
34166 forEachChild(child, visitNode, visitArray);
34167 if (ts.hasJSDocNodes(child)) {
34168 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
34169 var jsDocComment = _a[_i];
34170 visitNode(jsDocComment);
34171 }
34172 }
34173 checkNodePositions(child, aggressiveChecks);
34174 return;
34175 }
34176 // Otherwise, the node is entirely before the change range. No need to do anything with it.
34177 ts.Debug.assert(fullEnd < changeStart);
34178 }
34179 function visitArray(array) {
34180 ts.Debug.assert(array.pos <= array.end);
34181 if (array.pos > changeRangeOldEnd) {
34182 // Array is entirely after the change range. We need to move it, and move any of
34183 // its children.
34184 moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
34185 return;
34186 }
34187 // Check if the element intersects the change range. If it does, then it is not
34188 // reusable. Also, we'll need to recurse to see what constituent portions we may
34189 // be able to use.
34190 var fullEnd = array.end;
34191 if (fullEnd >= changeStart) {
34192 array.intersectsChange = true;
34193 array._children = undefined;
34194 // Adjust the pos or end (or both) of the intersecting array accordingly.
34195 adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
34196 for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
34197 var node = array_9[_i];
34198 visitNode(node);
34199 }
34200 return;
34201 }
34202 // Otherwise, the array is entirely before the change range. No need to do anything with it.
34203 ts.Debug.assert(fullEnd < changeStart);
34204 }
34205 }
34206 function extendToAffectedRange(sourceFile, changeRange) {
34207 // Consider the following code:
34208 // void foo() { /; }
34209 //
34210 // If the text changes with an insertion of / just before the semicolon then we end up with:
34211 // void foo() { //; }
34212 //
34213 // If we were to just use the changeRange a is, then we would not rescan the { token
34214 // (as it does not intersect the actual original change range). Because an edit may
34215 // change the token touching it, we actually need to look back *at least* one token so
34216 // that the prior token sees that change.
34217 var maxLookahead = 1;
34218 var start = changeRange.span.start;
34219 // the first iteration aligns us with the change start. subsequent iteration move us to
34220 // the left by maxLookahead tokens. We only need to do this as long as we're not at the
34221 // start of the tree.
34222 for (var i = 0; start > 0 && i <= maxLookahead; i++) {
34223 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
34224 ts.Debug.assert(nearestNode.pos <= start);
34225 var position = nearestNode.pos;
34226 start = Math.max(0, position - 1);
34227 }
34228 var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
34229 var finalLength = changeRange.newLength + (changeRange.span.start - start);
34230 return ts.createTextChangeRange(finalSpan, finalLength);
34231 }
34232 function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
34233 var bestResult = sourceFile;
34234 var lastNodeEntirelyBeforePosition;
34235 forEachChild(sourceFile, visit);
34236 if (lastNodeEntirelyBeforePosition) {
34237 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
34238 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
34239 bestResult = lastChildOfLastEntireNodeBeforePosition;
34240 }
34241 }
34242 return bestResult;
34243 function getLastDescendant(node) {
34244 while (true) {
34245 var lastChild = ts.getLastChild(node);
34246 if (lastChild) {
34247 node = lastChild;
34248 }
34249 else {
34250 return node;
34251 }
34252 }
34253 }
34254 function visit(child) {
34255 if (ts.nodeIsMissing(child)) {
34256 // Missing nodes are effectively invisible to us. We never even consider them
34257 // When trying to find the nearest node before us.
34258 return;
34259 }
34260 // If the child intersects this position, then this node is currently the nearest
34261 // node that starts before the position.
34262 if (child.pos <= position) {
34263 if (child.pos >= bestResult.pos) {
34264 // This node starts before the position, and is closer to the position than
34265 // the previous best node we found. It is now the new best node.
34266 bestResult = child;
34267 }
34268 // Now, the node may overlap the position, or it may end entirely before the
34269 // position. If it overlaps with the position, then either it, or one of its
34270 // children must be the nearest node before the position. So we can just
34271 // recurse into this child to see if we can find something better.
34272 if (position < child.end) {
34273 // The nearest node is either this child, or one of the children inside
34274 // of it. We've already marked this child as the best so far. Recurse
34275 // in case one of the children is better.
34276 forEachChild(child, visit);
34277 // Once we look at the children of this node, then there's no need to
34278 // continue any further.
34279 return true;
34280 }
34281 else {
34282 ts.Debug.assert(child.end <= position);
34283 // The child ends entirely before this position. Say you have the following
34284 // (where $ is the position)
34285 //
34286 // <complex expr 1> ? <complex expr 2> $ : <...> <...>
34287 //
34288 // We would want to find the nearest preceding node in "complex expr 2".
34289 // To support that, we keep track of this node, and once we're done searching
34290 // for a best node, we recurse down this node to see if we can find a good
34291 // result in it.
34292 //
34293 // This approach allows us to quickly skip over nodes that are entirely
34294 // before the position, while still allowing us to find any nodes in the
34295 // last one that might be what we want.
34296 lastNodeEntirelyBeforePosition = child;
34297 }
34298 }
34299 else {
34300 ts.Debug.assert(child.pos > position);
34301 // We're now at a node that is entirely past the position we're searching for.
34302 // This node (and all following nodes) could never contribute to the result,
34303 // so just skip them by returning 'true' here.
34304 return true;
34305 }
34306 }
34307 }
34308 function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
34309 var oldText = sourceFile.text;
34310 if (textChangeRange) {
34311 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
34312 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
34313 var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
34314 var newTextPrefix = newText.substr(0, textChangeRange.span.start);
34315 ts.Debug.assert(oldTextPrefix === newTextPrefix);
34316 var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
34317 var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
34318 ts.Debug.assert(oldTextSuffix === newTextSuffix);
34319 }
34320 }
34321 }
34322 function createSyntaxCursor(sourceFile) {
34323 var currentArray = sourceFile.statements;
34324 var currentArrayIndex = 0;
34325 ts.Debug.assert(currentArrayIndex < currentArray.length);
34326 var current = currentArray[currentArrayIndex];
34327 var lastQueriedPosition = -1 /* Value */;
34328 return {
34329 currentNode: function (position) {
34330 // Only compute the current node if the position is different than the last time
34331 // we were asked. The parser commonly asks for the node at the same position
34332 // twice. Once to know if can read an appropriate list element at a certain point,
34333 // and then to actually read and consume the node.
34334 if (position !== lastQueriedPosition) {
34335 // Much of the time the parser will need the very next node in the array that
34336 // we just returned a node from.So just simply check for that case and move
34337 // forward in the array instead of searching for the node again.
34338 if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
34339 currentArrayIndex++;
34340 current = currentArray[currentArrayIndex];
34341 }
34342 // If we don't have a node, or the node we have isn't in the right position,
34343 // then try to find a viable node at the position requested.
34344 if (!current || current.pos !== position) {
34345 findHighestListElementThatStartsAtPosition(position);
34346 }
34347 }
34348 // Cache this query so that we don't do any extra work if the parser calls back
34349 // into us. Note: this is very common as the parser will make pairs of calls like
34350 // 'isListElement -> parseListElement'. If we were unable to find a node when
34351 // called with 'isListElement', we don't want to redo the work when parseListElement
34352 // is called immediately after.
34353 lastQueriedPosition = position;
34354 // Either we don'd have a node, or we have a node at the position being asked for.
34355 ts.Debug.assert(!current || current.pos === position);
34356 return current;
34357 }
34358 };
34359 // Finds the highest element in the tree we can find that starts at the provided position.
34360 // The element must be a direct child of some node list in the tree. This way after we
34361 // return it, we can easily return its next sibling in the list.
34362 function findHighestListElementThatStartsAtPosition(position) {
34363 // Clear out any cached state about the last node we found.
34364 currentArray = undefined;
34365 currentArrayIndex = -1 /* Value */;
34366 current = undefined;
34367 // Recurse into the source file to find the highest node at this position.
34368 forEachChild(sourceFile, visitNode, visitArray);
34369 return;
34370 function visitNode(node) {
34371 if (position >= node.pos && position < node.end) {
34372 // Position was within this node. Keep searching deeper to find the node.
34373 forEachChild(node, visitNode, visitArray);
34374 // don't proceed any further in the search.
34375 return true;
34376 }
34377 // position wasn't in this node, have to keep searching.
34378 return false;
34379 }
34380 function visitArray(array) {
34381 if (position >= array.pos && position < array.end) {
34382 // position was in this array. Search through this array to see if we find a
34383 // viable element.
34384 for (var i = 0; i < array.length; i++) {
34385 var child = array[i];
34386 if (child) {
34387 if (child.pos === position) {
34388 // Found the right node. We're done.
34389 currentArray = array;
34390 currentArrayIndex = i;
34391 current = child;
34392 return true;
34393 }
34394 else {
34395 if (child.pos < position && position < child.end) {
34396 // Position in somewhere within this child. Search in it and
34397 // stop searching in this array.
34398 forEachChild(child, visitNode, visitArray);
34399 return true;
34400 }
34401 }
34402 }
34403 }
34404 }
34405 // position wasn't in this array, have to keep searching.
34406 return false;
34407 }
34408 }
34409 }
34410 IncrementalParser.createSyntaxCursor = createSyntaxCursor;
34411 var InvalidPosition;
34412 (function (InvalidPosition) {
34413 InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
34414 })(InvalidPosition || (InvalidPosition = {}));
34415 })(IncrementalParser || (IncrementalParser = {}));
34416 /** @internal */
34417 function isDeclarationFileName(fileName) {
34418 return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
34419 }
34420 ts.isDeclarationFileName = isDeclarationFileName;
34421 /*@internal*/
34422 function processCommentPragmas(context, sourceText) {
34423 var pragmas = [];
34424 for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
34425 var range = _a[_i];
34426 var comment = sourceText.substring(range.pos, range.end);
34427 extractPragmas(pragmas, range, comment);
34428 }
34429 context.pragmas = new ts.Map();
34430 for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
34431 var pragma = pragmas_1[_b];
34432 if (context.pragmas.has(pragma.name)) {
34433 var currentValue = context.pragmas.get(pragma.name);
34434 if (currentValue instanceof Array) {
34435 currentValue.push(pragma.args);
34436 }
34437 else {
34438 context.pragmas.set(pragma.name, [currentValue, pragma.args]);
34439 }
34440 continue;
34441 }
34442 context.pragmas.set(pragma.name, pragma.args);
34443 }
34444 }
34445 ts.processCommentPragmas = processCommentPragmas;
34446 /*@internal*/
34447 function processPragmasIntoFields(context, reportDiagnostic) {
34448 context.checkJsDirective = undefined;
34449 context.referencedFiles = [];
34450 context.typeReferenceDirectives = [];
34451 context.libReferenceDirectives = [];
34452 context.amdDependencies = [];
34453 context.hasNoDefaultLib = false;
34454 context.pragmas.forEach(function (entryOrList, key) {
34455 // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
34456 // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
34457 switch (key) {
34458 case "reference": {
34459 var referencedFiles_1 = context.referencedFiles;
34460 var typeReferenceDirectives_1 = context.typeReferenceDirectives;
34461 var libReferenceDirectives_1 = context.libReferenceDirectives;
34462 ts.forEach(ts.toArray(entryOrList), function (arg) {
34463 var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
34464 if (arg.arguments["no-default-lib"]) {
34465 context.hasNoDefaultLib = true;
34466 }
34467 else if (types) {
34468 typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
34469 }
34470 else if (lib) {
34471 libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
34472 }
34473 else if (path) {
34474 referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
34475 }
34476 else {
34477 reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
34478 }
34479 });
34480 break;
34481 }
34482 case "amd-dependency": {
34483 context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
34484 break;
34485 }
34486 case "amd-module": {
34487 if (entryOrList instanceof Array) {
34488 for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
34489 var entry = entryOrList_1[_i];
34490 if (context.moduleName) {
34491 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
34492 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
34493 }
34494 context.moduleName = entry.arguments.name;
34495 }
34496 }
34497 else {
34498 context.moduleName = entryOrList.arguments.name;
34499 }
34500 break;
34501 }
34502 case "ts-nocheck":
34503 case "ts-check": {
34504 // _last_ of either nocheck or check in a file is the "winner"
34505 ts.forEach(ts.toArray(entryOrList), function (entry) {
34506 if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
34507 context.checkJsDirective = {
34508 enabled: key === "ts-check",
34509 end: entry.range.end,
34510 pos: entry.range.pos
34511 };
34512 }
34513 });
34514 break;
34515 }
34516 case "jsx":
34517 case "jsxfrag":
34518 return; // Accessed directly
34519 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
34520 }
34521 });
34522 }
34523 ts.processPragmasIntoFields = processPragmasIntoFields;
34524 var namedArgRegExCache = new ts.Map();
34525 function getNamedArgRegEx(name) {
34526 if (namedArgRegExCache.has(name)) {
34527 return namedArgRegExCache.get(name);
34528 }
34529 var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
34530 namedArgRegExCache.set(name, result);
34531 return result;
34532 }
34533 var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
34534 var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
34535 function extractPragmas(pragmas, range, text) {
34536 var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
34537 if (tripleSlash) {
34538 var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
34539 var pragma = ts.commentPragmas[name];
34540 if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
34541 return;
34542 }
34543 if (pragma.args) {
34544 var argument = {};
34545 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
34546 var arg = _a[_i];
34547 var matcher = getNamedArgRegEx(arg.name);
34548 var matchResult = matcher.exec(text);
34549 if (!matchResult && !arg.optional) {
34550 return; // Missing required argument, don't parse
34551 }
34552 else if (matchResult) {
34553 if (arg.captureSpan) {
34554 var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
34555 argument[arg.name] = {
34556 value: matchResult[3],
34557 pos: startPos,
34558 end: startPos + matchResult[3].length
34559 };
34560 }
34561 else {
34562 argument[arg.name] = matchResult[3];
34563 }
34564 }
34565 }
34566 pragmas.push({ name: name, args: { arguments: argument, range: range } });
34567 }
34568 else {
34569 pragmas.push({ name: name, args: { arguments: {}, range: range } });
34570 }
34571 return;
34572 }
34573 var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
34574 if (singleLine) {
34575 return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
34576 }
34577 if (range.kind === 3 /* MultiLineCommentTrivia */) {
34578 var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
34579 var multiLineMatch = void 0;
34580 while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
34581 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
34582 }
34583 }
34584 }
34585 function addPragmaForMatch(pragmas, range, kind, match) {
34586 if (!match)
34587 return;
34588 var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
34589 var pragma = ts.commentPragmas[name];
34590 if (!pragma || !(pragma.kind & kind)) {
34591 return;
34592 }
34593 var args = match[2]; // Split on spaces and match up positionally with definition
34594 var argument = getNamedPragmaArguments(pragma, args);
34595 if (argument === "fail")
34596 return; // Missing required argument, fail to parse it
34597 pragmas.push({ name: name, args: { arguments: argument, range: range } });
34598 return;
34599 }
34600 function getNamedPragmaArguments(pragma, text) {
34601 if (!text)
34602 return {};
34603 if (!pragma.args)
34604 return {};
34605 var args = text.split(/\s+/);
34606 var argMap = {};
34607 for (var i = 0; i < pragma.args.length; i++) {
34608 var argument = pragma.args[i];
34609 if (!args[i] && !argument.optional) {
34610 return "fail";
34611 }
34612 if (argument.captureSpan) {
34613 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
34614 }
34615 argMap[argument.name] = args[i];
34616 }
34617 return argMap;
34618 }
34619 /** @internal */
34620 function tagNamesAreEquivalent(lhs, rhs) {
34621 if (lhs.kind !== rhs.kind) {
34622 return false;
34623 }
34624 if (lhs.kind === 78 /* Identifier */) {
34625 return lhs.escapedText === rhs.escapedText;
34626 }
34627 if (lhs.kind === 107 /* ThisKeyword */) {
34628 return true;
34629 }
34630 // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
34631 // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
34632 // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
34633 return lhs.name.escapedText === rhs.name.escapedText &&
34634 tagNamesAreEquivalent(lhs.expression, rhs.expression);
34635 }
34636 ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
34637})(ts || (ts = {}));
34638var ts;
34639(function (ts) {
34640 /* @internal */
34641 ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
34642 // NOTE: The order here is important to default lib ordering as entries will have the same
34643 // order in the generated program (see `getDefaultLibPriority` in program.ts). This
34644 // order also affects overload resolution when a type declared in one lib is
34645 // augmented in another lib.
34646 var libEntries = [
34647 // JavaScript only
34648 ["es5", "lib.es5.d.ts"],
34649 ["es6", "lib.es2015.d.ts"],
34650 ["es2015", "lib.es2015.d.ts"],
34651 ["es7", "lib.es2016.d.ts"],
34652 ["es2016", "lib.es2016.d.ts"],
34653 ["es2017", "lib.es2017.d.ts"],
34654 ["es2018", "lib.es2018.d.ts"],
34655 ["es2019", "lib.es2019.d.ts"],
34656 ["es2020", "lib.es2020.d.ts"],
34657 ["esnext", "lib.esnext.d.ts"],
34658 // Host only
34659 ["dom", "lib.dom.d.ts"],
34660 ["dom.iterable", "lib.dom.iterable.d.ts"],
34661 ["webworker", "lib.webworker.d.ts"],
34662 ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
34663 ["scripthost", "lib.scripthost.d.ts"],
34664 // ES2015 Or ESNext By-feature options
34665 ["es2015.core", "lib.es2015.core.d.ts"],
34666 ["es2015.collection", "lib.es2015.collection.d.ts"],
34667 ["es2015.generator", "lib.es2015.generator.d.ts"],
34668 ["es2015.iterable", "lib.es2015.iterable.d.ts"],
34669 ["es2015.promise", "lib.es2015.promise.d.ts"],
34670 ["es2015.proxy", "lib.es2015.proxy.d.ts"],
34671 ["es2015.reflect", "lib.es2015.reflect.d.ts"],
34672 ["es2015.symbol", "lib.es2015.symbol.d.ts"],
34673 ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
34674 ["es2016.array.include", "lib.es2016.array.include.d.ts"],
34675 ["es2017.object", "lib.es2017.object.d.ts"],
34676 ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
34677 ["es2017.string", "lib.es2017.string.d.ts"],
34678 ["es2017.intl", "lib.es2017.intl.d.ts"],
34679 ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
34680 ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
34681 ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
34682 ["es2018.intl", "lib.es2018.intl.d.ts"],
34683 ["es2018.promise", "lib.es2018.promise.d.ts"],
34684 ["es2018.regexp", "lib.es2018.regexp.d.ts"],
34685 ["es2019.array", "lib.es2019.array.d.ts"],
34686 ["es2019.object", "lib.es2019.object.d.ts"],
34687 ["es2019.string", "lib.es2019.string.d.ts"],
34688 ["es2019.symbol", "lib.es2019.symbol.d.ts"],
34689 ["es2020.bigint", "lib.es2020.bigint.d.ts"],
34690 ["es2020.promise", "lib.es2020.promise.d.ts"],
34691 ["es2020.string", "lib.es2020.string.d.ts"],
34692 ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
34693 ["es2020.intl", "lib.es2020.intl.d.ts"],
34694 ["esnext.array", "lib.es2019.array.d.ts"],
34695 ["esnext.symbol", "lib.es2019.symbol.d.ts"],
34696 ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
34697 ["esnext.intl", "lib.esnext.intl.d.ts"],
34698 ["esnext.bigint", "lib.es2020.bigint.d.ts"],
34699 ["esnext.string", "lib.esnext.string.d.ts"],
34700 ["esnext.promise", "lib.esnext.promise.d.ts"]
34701 ];
34702 /**
34703 * An array of supported "lib" reference file names used to determine the order for inclusion
34704 * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
34705 * overload resolution when a type declared in one lib is extended by another.
34706 */
34707 /* @internal */
34708 ts.libs = libEntries.map(function (entry) { return entry[0]; });
34709 /**
34710 * A map of lib names to lib files. This map is used both for parsing the "lib" command line
34711 * option as well as for resolving lib reference directives.
34712 */
34713 /* @internal */
34714 ts.libMap = new ts.Map(libEntries);
34715 // Watch related options
34716 /* @internal */
34717 ts.optionsForWatch = [
34718 {
34719 name: "watchFile",
34720 type: new ts.Map(ts.getEntries({
34721 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
34722 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
34723 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
34724 usefsevents: ts.WatchFileKind.UseFsEvents,
34725 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
34726 })),
34727 category: ts.Diagnostics.Advanced_Options,
34728 description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
34729 },
34730 {
34731 name: "watchDirectory",
34732 type: new ts.Map(ts.getEntries({
34733 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
34734 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
34735 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
34736 })),
34737 category: ts.Diagnostics.Advanced_Options,
34738 description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
34739 },
34740 {
34741 name: "fallbackPolling",
34742 type: new ts.Map(ts.getEntries({
34743 fixedinterval: ts.PollingWatchKind.FixedInterval,
34744 priorityinterval: ts.PollingWatchKind.PriorityInterval,
34745 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
34746 })),
34747 category: ts.Diagnostics.Advanced_Options,
34748 description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
34749 },
34750 {
34751 name: "synchronousWatchDirectory",
34752 type: "boolean",
34753 category: ts.Diagnostics.Advanced_Options,
34754 description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
34755 },
34756 ];
34757 /* @internal */
34758 ts.commonOptionsWithBuild = [
34759 {
34760 name: "help",
34761 shortName: "h",
34762 type: "boolean",
34763 showInSimplifiedHelpView: true,
34764 category: ts.Diagnostics.Command_line_Options,
34765 description: ts.Diagnostics.Print_this_message,
34766 },
34767 {
34768 name: "help",
34769 shortName: "?",
34770 type: "boolean"
34771 },
34772 {
34773 name: "watch",
34774 shortName: "w",
34775 type: "boolean",
34776 showInSimplifiedHelpView: true,
34777 category: ts.Diagnostics.Command_line_Options,
34778 description: ts.Diagnostics.Watch_input_files,
34779 },
34780 {
34781 name: "preserveWatchOutput",
34782 type: "boolean",
34783 showInSimplifiedHelpView: false,
34784 category: ts.Diagnostics.Command_line_Options,
34785 description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
34786 },
34787 {
34788 name: "listFiles",
34789 type: "boolean",
34790 category: ts.Diagnostics.Advanced_Options,
34791 description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
34792 },
34793 {
34794 name: "listEmittedFiles",
34795 type: "boolean",
34796 category: ts.Diagnostics.Advanced_Options,
34797 description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
34798 },
34799 {
34800 name: "pretty",
34801 type: "boolean",
34802 showInSimplifiedHelpView: true,
34803 category: ts.Diagnostics.Command_line_Options,
34804 description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
34805 },
34806 {
34807 name: "traceResolution",
34808 type: "boolean",
34809 category: ts.Diagnostics.Advanced_Options,
34810 description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
34811 },
34812 {
34813 name: "diagnostics",
34814 type: "boolean",
34815 category: ts.Diagnostics.Advanced_Options,
34816 description: ts.Diagnostics.Show_diagnostic_information
34817 },
34818 {
34819 name: "extendedDiagnostics",
34820 type: "boolean",
34821 category: ts.Diagnostics.Advanced_Options,
34822 description: ts.Diagnostics.Show_verbose_diagnostic_information
34823 },
34824 {
34825 name: "generateCpuProfile",
34826 type: "string",
34827 isFilePath: true,
34828 paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
34829 category: ts.Diagnostics.Advanced_Options,
34830 description: ts.Diagnostics.Generates_a_CPU_profile
34831 },
34832 {
34833 name: "incremental",
34834 shortName: "i",
34835 type: "boolean",
34836 category: ts.Diagnostics.Basic_Options,
34837 description: ts.Diagnostics.Enable_incremental_compilation,
34838 transpileOptionValue: undefined
34839 },
34840 {
34841 name: "assumeChangesOnlyAffectDirectDependencies",
34842 type: "boolean",
34843 affectsSemanticDiagnostics: true,
34844 affectsEmit: true,
34845 category: ts.Diagnostics.Advanced_Options,
34846 description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
34847 },
34848 {
34849 name: "locale",
34850 type: "string",
34851 category: ts.Diagnostics.Advanced_Options,
34852 description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
34853 },
34854 ];
34855 /* @internal */
34856 ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
34857 {
34858 name: "all",
34859 type: "boolean",
34860 showInSimplifiedHelpView: true,
34861 category: ts.Diagnostics.Command_line_Options,
34862 description: ts.Diagnostics.Show_all_compiler_options,
34863 },
34864 {
34865 name: "version",
34866 shortName: "v",
34867 type: "boolean",
34868 showInSimplifiedHelpView: true,
34869 category: ts.Diagnostics.Command_line_Options,
34870 description: ts.Diagnostics.Print_the_compiler_s_version,
34871 },
34872 {
34873 name: "init",
34874 type: "boolean",
34875 showInSimplifiedHelpView: true,
34876 category: ts.Diagnostics.Command_line_Options,
34877 description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
34878 },
34879 {
34880 name: "project",
34881 shortName: "p",
34882 type: "string",
34883 isFilePath: true,
34884 showInSimplifiedHelpView: true,
34885 category: ts.Diagnostics.Command_line_Options,
34886 paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
34887 description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
34888 },
34889 {
34890 name: "build",
34891 type: "boolean",
34892 shortName: "b",
34893 showInSimplifiedHelpView: true,
34894 category: ts.Diagnostics.Command_line_Options,
34895 description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
34896 },
34897 {
34898 name: "showConfig",
34899 type: "boolean",
34900 category: ts.Diagnostics.Command_line_Options,
34901 isCommandLineOnly: true,
34902 description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
34903 },
34904 {
34905 name: "listFilesOnly",
34906 type: "boolean",
34907 category: ts.Diagnostics.Command_line_Options,
34908 affectsSemanticDiagnostics: true,
34909 affectsEmit: true,
34910 isCommandLineOnly: true,
34911 description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
34912 },
34913 // Basic
34914 {
34915 name: "target",
34916 shortName: "t",
34917 type: new ts.Map(ts.getEntries({
34918 es3: 0 /* ES3 */,
34919 es5: 1 /* ES5 */,
34920 es6: 2 /* ES2015 */,
34921 es2015: 2 /* ES2015 */,
34922 es2016: 3 /* ES2016 */,
34923 es2017: 4 /* ES2017 */,
34924 es2018: 5 /* ES2018 */,
34925 es2019: 6 /* ES2019 */,
34926 es2020: 7 /* ES2020 */,
34927 esnext: 99 /* ESNext */,
34928 })),
34929 affectsSourceFile: true,
34930 affectsModuleResolution: true,
34931 affectsEmit: true,
34932 paramType: ts.Diagnostics.VERSION,
34933 showInSimplifiedHelpView: true,
34934 category: ts.Diagnostics.Basic_Options,
34935 description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
34936 },
34937 {
34938 name: "module",
34939 shortName: "m",
34940 type: new ts.Map(ts.getEntries({
34941 none: ts.ModuleKind.None,
34942 commonjs: ts.ModuleKind.CommonJS,
34943 amd: ts.ModuleKind.AMD,
34944 system: ts.ModuleKind.System,
34945 umd: ts.ModuleKind.UMD,
34946 es6: ts.ModuleKind.ES2015,
34947 es2015: ts.ModuleKind.ES2015,
34948 es2020: ts.ModuleKind.ES2020,
34949 esnext: ts.ModuleKind.ESNext
34950 })),
34951 affectsModuleResolution: true,
34952 affectsEmit: true,
34953 paramType: ts.Diagnostics.KIND,
34954 showInSimplifiedHelpView: true,
34955 category: ts.Diagnostics.Basic_Options,
34956 description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
34957 },
34958 {
34959 name: "lib",
34960 type: "list",
34961 element: {
34962 name: "lib",
34963 type: ts.libMap
34964 },
34965 affectsModuleResolution: true,
34966 showInSimplifiedHelpView: true,
34967 category: ts.Diagnostics.Basic_Options,
34968 description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
34969 transpileOptionValue: undefined
34970 },
34971 {
34972 name: "allowJs",
34973 type: "boolean",
34974 affectsModuleResolution: true,
34975 showInSimplifiedHelpView: true,
34976 category: ts.Diagnostics.Basic_Options,
34977 description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
34978 },
34979 {
34980 name: "checkJs",
34981 type: "boolean",
34982 category: ts.Diagnostics.Basic_Options,
34983 description: ts.Diagnostics.Report_errors_in_js_files
34984 },
34985 {
34986 name: "jsx",
34987 type: new ts.Map(ts.getEntries({
34988 "preserve": 1 /* Preserve */,
34989 "react-native": 3 /* ReactNative */,
34990 "react": 2 /* React */
34991 })),
34992 affectsSourceFile: true,
34993 paramType: ts.Diagnostics.KIND,
34994 showInSimplifiedHelpView: true,
34995 category: ts.Diagnostics.Basic_Options,
34996 description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
34997 },
34998 {
34999 name: "declaration",
35000 shortName: "d",
35001 type: "boolean",
35002 affectsEmit: true,
35003 showInSimplifiedHelpView: true,
35004 category: ts.Diagnostics.Basic_Options,
35005 description: ts.Diagnostics.Generates_corresponding_d_ts_file,
35006 transpileOptionValue: undefined
35007 },
35008 {
35009 name: "declarationMap",
35010 type: "boolean",
35011 affectsEmit: true,
35012 showInSimplifiedHelpView: true,
35013 category: ts.Diagnostics.Basic_Options,
35014 description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
35015 transpileOptionValue: undefined
35016 },
35017 {
35018 name: "emitDeclarationOnly",
35019 type: "boolean",
35020 affectsEmit: true,
35021 category: ts.Diagnostics.Advanced_Options,
35022 description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
35023 transpileOptionValue: undefined
35024 },
35025 {
35026 name: "sourceMap",
35027 type: "boolean",
35028 affectsEmit: true,
35029 showInSimplifiedHelpView: true,
35030 category: ts.Diagnostics.Basic_Options,
35031 description: ts.Diagnostics.Generates_corresponding_map_file,
35032 },
35033 {
35034 name: "outFile",
35035 type: "string",
35036 affectsEmit: true,
35037 isFilePath: true,
35038 paramType: ts.Diagnostics.FILE,
35039 showInSimplifiedHelpView: true,
35040 category: ts.Diagnostics.Basic_Options,
35041 description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
35042 transpileOptionValue: undefined
35043 },
35044 {
35045 name: "outDir",
35046 type: "string",
35047 affectsEmit: true,
35048 isFilePath: true,
35049 paramType: ts.Diagnostics.DIRECTORY,
35050 showInSimplifiedHelpView: true,
35051 category: ts.Diagnostics.Basic_Options,
35052 description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
35053 },
35054 {
35055 name: "rootDir",
35056 type: "string",
35057 affectsEmit: true,
35058 isFilePath: true,
35059 paramType: ts.Diagnostics.LOCATION,
35060 category: ts.Diagnostics.Basic_Options,
35061 description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
35062 },
35063 {
35064 name: "composite",
35065 type: "boolean",
35066 affectsEmit: true,
35067 isTSConfigOnly: true,
35068 category: ts.Diagnostics.Basic_Options,
35069 description: ts.Diagnostics.Enable_project_compilation,
35070 transpileOptionValue: undefined
35071 },
35072 {
35073 name: "tsBuildInfoFile",
35074 type: "string",
35075 affectsEmit: true,
35076 isFilePath: true,
35077 paramType: ts.Diagnostics.FILE,
35078 category: ts.Diagnostics.Basic_Options,
35079 description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
35080 transpileOptionValue: undefined
35081 },
35082 {
35083 name: "removeComments",
35084 type: "boolean",
35085 affectsEmit: true,
35086 showInSimplifiedHelpView: true,
35087 category: ts.Diagnostics.Basic_Options,
35088 description: ts.Diagnostics.Do_not_emit_comments_to_output,
35089 },
35090 {
35091 name: "noEmit",
35092 type: "boolean",
35093 showInSimplifiedHelpView: true,
35094 category: ts.Diagnostics.Basic_Options,
35095 description: ts.Diagnostics.Do_not_emit_outputs,
35096 transpileOptionValue: undefined
35097 },
35098 {
35099 name: "importHelpers",
35100 type: "boolean",
35101 affectsEmit: true,
35102 category: ts.Diagnostics.Basic_Options,
35103 description: ts.Diagnostics.Import_emit_helpers_from_tslib
35104 },
35105 {
35106 name: "importsNotUsedAsValues",
35107 type: new ts.Map(ts.getEntries({
35108 remove: 0 /* Remove */,
35109 preserve: 1 /* Preserve */,
35110 error: 2 /* Error */
35111 })),
35112 affectsEmit: true,
35113 affectsSemanticDiagnostics: true,
35114 category: ts.Diagnostics.Advanced_Options,
35115 description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
35116 },
35117 {
35118 name: "downlevelIteration",
35119 type: "boolean",
35120 affectsEmit: true,
35121 category: ts.Diagnostics.Basic_Options,
35122 description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
35123 },
35124 {
35125 name: "isolatedModules",
35126 type: "boolean",
35127 category: ts.Diagnostics.Basic_Options,
35128 description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
35129 transpileOptionValue: true
35130 },
35131 // Strict Type Checks
35132 {
35133 name: "strict",
35134 type: "boolean",
35135 showInSimplifiedHelpView: true,
35136 category: ts.Diagnostics.Strict_Type_Checking_Options,
35137 description: ts.Diagnostics.Enable_all_strict_type_checking_options
35138 },
35139 {
35140 name: "noImplicitAny",
35141 type: "boolean",
35142 affectsSemanticDiagnostics: true,
35143 strictFlag: true,
35144 showInSimplifiedHelpView: true,
35145 category: ts.Diagnostics.Strict_Type_Checking_Options,
35146 description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
35147 },
35148 {
35149 name: "strictNullChecks",
35150 type: "boolean",
35151 affectsSemanticDiagnostics: true,
35152 strictFlag: true,
35153 showInSimplifiedHelpView: true,
35154 category: ts.Diagnostics.Strict_Type_Checking_Options,
35155 description: ts.Diagnostics.Enable_strict_null_checks
35156 },
35157 {
35158 name: "strictFunctionTypes",
35159 type: "boolean",
35160 affectsSemanticDiagnostics: true,
35161 strictFlag: true,
35162 showInSimplifiedHelpView: true,
35163 category: ts.Diagnostics.Strict_Type_Checking_Options,
35164 description: ts.Diagnostics.Enable_strict_checking_of_function_types
35165 },
35166 {
35167 name: "strictBindCallApply",
35168 type: "boolean",
35169 strictFlag: true,
35170 showInSimplifiedHelpView: true,
35171 category: ts.Diagnostics.Strict_Type_Checking_Options,
35172 description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
35173 },
35174 {
35175 name: "strictPropertyInitialization",
35176 type: "boolean",
35177 affectsSemanticDiagnostics: true,
35178 strictFlag: true,
35179 showInSimplifiedHelpView: true,
35180 category: ts.Diagnostics.Strict_Type_Checking_Options,
35181 description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
35182 },
35183 {
35184 name: "noImplicitThis",
35185 type: "boolean",
35186 affectsSemanticDiagnostics: true,
35187 strictFlag: true,
35188 showInSimplifiedHelpView: true,
35189 category: ts.Diagnostics.Strict_Type_Checking_Options,
35190 description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
35191 },
35192 {
35193 name: "alwaysStrict",
35194 type: "boolean",
35195 affectsSourceFile: true,
35196 strictFlag: true,
35197 showInSimplifiedHelpView: true,
35198 category: ts.Diagnostics.Strict_Type_Checking_Options,
35199 description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
35200 },
35201 // Additional Checks
35202 {
35203 name: "noUnusedLocals",
35204 type: "boolean",
35205 affectsSemanticDiagnostics: true,
35206 showInSimplifiedHelpView: true,
35207 category: ts.Diagnostics.Additional_Checks,
35208 description: ts.Diagnostics.Report_errors_on_unused_locals,
35209 },
35210 {
35211 name: "noUnusedParameters",
35212 type: "boolean",
35213 affectsSemanticDiagnostics: true,
35214 showInSimplifiedHelpView: true,
35215 category: ts.Diagnostics.Additional_Checks,
35216 description: ts.Diagnostics.Report_errors_on_unused_parameters,
35217 },
35218 {
35219 name: "noImplicitReturns",
35220 type: "boolean",
35221 affectsSemanticDiagnostics: true,
35222 showInSimplifiedHelpView: true,
35223 category: ts.Diagnostics.Additional_Checks,
35224 description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
35225 },
35226 {
35227 name: "noFallthroughCasesInSwitch",
35228 type: "boolean",
35229 affectsBindDiagnostics: true,
35230 affectsSemanticDiagnostics: true,
35231 showInSimplifiedHelpView: true,
35232 category: ts.Diagnostics.Additional_Checks,
35233 description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
35234 },
35235 // Module Resolution
35236 {
35237 name: "moduleResolution",
35238 type: new ts.Map(ts.getEntries({
35239 node: ts.ModuleResolutionKind.NodeJs,
35240 classic: ts.ModuleResolutionKind.Classic,
35241 })),
35242 affectsModuleResolution: true,
35243 paramType: ts.Diagnostics.STRATEGY,
35244 category: ts.Diagnostics.Module_Resolution_Options,
35245 description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
35246 },
35247 {
35248 name: "baseUrl",
35249 type: "string",
35250 affectsModuleResolution: true,
35251 isFilePath: true,
35252 category: ts.Diagnostics.Module_Resolution_Options,
35253 description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
35254 },
35255 {
35256 // this option can only be specified in tsconfig.json
35257 // use type = object to copy the value as-is
35258 name: "paths",
35259 type: "object",
35260 affectsModuleResolution: true,
35261 isTSConfigOnly: true,
35262 category: ts.Diagnostics.Module_Resolution_Options,
35263 description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
35264 transpileOptionValue: undefined
35265 },
35266 {
35267 // this option can only be specified in tsconfig.json
35268 // use type = object to copy the value as-is
35269 name: "rootDirs",
35270 type: "list",
35271 isTSConfigOnly: true,
35272 element: {
35273 name: "rootDirs",
35274 type: "string",
35275 isFilePath: true
35276 },
35277 affectsModuleResolution: true,
35278 category: ts.Diagnostics.Module_Resolution_Options,
35279 description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
35280 transpileOptionValue: undefined
35281 },
35282 {
35283 name: "typeRoots",
35284 type: "list",
35285 element: {
35286 name: "typeRoots",
35287 type: "string",
35288 isFilePath: true
35289 },
35290 affectsModuleResolution: true,
35291 category: ts.Diagnostics.Module_Resolution_Options,
35292 description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
35293 },
35294 {
35295 name: "types",
35296 type: "list",
35297 element: {
35298 name: "types",
35299 type: "string"
35300 },
35301 affectsModuleResolution: true,
35302 showInSimplifiedHelpView: true,
35303 category: ts.Diagnostics.Module_Resolution_Options,
35304 description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
35305 transpileOptionValue: undefined
35306 },
35307 {
35308 name: "allowSyntheticDefaultImports",
35309 type: "boolean",
35310 affectsSemanticDiagnostics: true,
35311 category: ts.Diagnostics.Module_Resolution_Options,
35312 description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
35313 },
35314 {
35315 name: "esModuleInterop",
35316 type: "boolean",
35317 affectsSemanticDiagnostics: true,
35318 affectsEmit: true,
35319 showInSimplifiedHelpView: true,
35320 category: ts.Diagnostics.Module_Resolution_Options,
35321 description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
35322 },
35323 {
35324 name: "preserveSymlinks",
35325 type: "boolean",
35326 category: ts.Diagnostics.Module_Resolution_Options,
35327 description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
35328 },
35329 {
35330 name: "allowUmdGlobalAccess",
35331 type: "boolean",
35332 affectsSemanticDiagnostics: true,
35333 category: ts.Diagnostics.Module_Resolution_Options,
35334 description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
35335 },
35336 // Source Maps
35337 {
35338 name: "sourceRoot",
35339 type: "string",
35340 affectsEmit: true,
35341 paramType: ts.Diagnostics.LOCATION,
35342 category: ts.Diagnostics.Source_Map_Options,
35343 description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
35344 },
35345 {
35346 name: "mapRoot",
35347 type: "string",
35348 affectsEmit: true,
35349 paramType: ts.Diagnostics.LOCATION,
35350 category: ts.Diagnostics.Source_Map_Options,
35351 description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
35352 },
35353 {
35354 name: "inlineSourceMap",
35355 type: "boolean",
35356 affectsEmit: true,
35357 category: ts.Diagnostics.Source_Map_Options,
35358 description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
35359 },
35360 {
35361 name: "inlineSources",
35362 type: "boolean",
35363 affectsEmit: true,
35364 category: ts.Diagnostics.Source_Map_Options,
35365 description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
35366 },
35367 // Experimental
35368 {
35369 name: "experimentalDecorators",
35370 type: "boolean",
35371 affectsSemanticDiagnostics: true,
35372 category: ts.Diagnostics.Experimental_Options,
35373 description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
35374 },
35375 {
35376 name: "emitDecoratorMetadata",
35377 type: "boolean",
35378 affectsSemanticDiagnostics: true,
35379 affectsEmit: true,
35380 category: ts.Diagnostics.Experimental_Options,
35381 description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
35382 },
35383 // Advanced
35384 {
35385 name: "jsxFactory",
35386 type: "string",
35387 category: ts.Diagnostics.Advanced_Options,
35388 description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
35389 },
35390 {
35391 name: "jsxFragmentFactory",
35392 type: "string",
35393 category: ts.Diagnostics.Advanced_Options,
35394 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
35395 },
35396 {
35397 name: "resolveJsonModule",
35398 type: "boolean",
35399 affectsModuleResolution: true,
35400 category: ts.Diagnostics.Advanced_Options,
35401 description: ts.Diagnostics.Include_modules_imported_with_json_extension
35402 },
35403 {
35404 name: "out",
35405 type: "string",
35406 affectsEmit: true,
35407 isFilePath: false,
35408 // for correct behaviour, please use outFile
35409 category: ts.Diagnostics.Advanced_Options,
35410 paramType: ts.Diagnostics.FILE,
35411 description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
35412 transpileOptionValue: undefined
35413 },
35414 {
35415 name: "reactNamespace",
35416 type: "string",
35417 affectsEmit: true,
35418 category: ts.Diagnostics.Advanced_Options,
35419 description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
35420 },
35421 {
35422 name: "skipDefaultLibCheck",
35423 type: "boolean",
35424 category: ts.Diagnostics.Advanced_Options,
35425 description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
35426 },
35427 {
35428 name: "charset",
35429 type: "string",
35430 category: ts.Diagnostics.Advanced_Options,
35431 description: ts.Diagnostics.The_character_set_of_the_input_files
35432 },
35433 {
35434 name: "emitBOM",
35435 type: "boolean",
35436 affectsEmit: true,
35437 category: ts.Diagnostics.Advanced_Options,
35438 description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
35439 },
35440 {
35441 name: "newLine",
35442 type: new ts.Map(ts.getEntries({
35443 crlf: 0 /* CarriageReturnLineFeed */,
35444 lf: 1 /* LineFeed */
35445 })),
35446 affectsEmit: true,
35447 paramType: ts.Diagnostics.NEWLINE,
35448 category: ts.Diagnostics.Advanced_Options,
35449 description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
35450 },
35451 {
35452 name: "noErrorTruncation",
35453 type: "boolean",
35454 affectsSemanticDiagnostics: true,
35455 category: ts.Diagnostics.Advanced_Options,
35456 description: ts.Diagnostics.Do_not_truncate_error_messages
35457 },
35458 {
35459 name: "noLib",
35460 type: "boolean",
35461 affectsModuleResolution: true,
35462 category: ts.Diagnostics.Advanced_Options,
35463 description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
35464 // We are not returning a sourceFile for lib file when asked by the program,
35465 // so pass --noLib to avoid reporting a file not found error.
35466 transpileOptionValue: true
35467 },
35468 {
35469 name: "noResolve",
35470 type: "boolean",
35471 affectsModuleResolution: true,
35472 category: ts.Diagnostics.Advanced_Options,
35473 description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
35474 // We are not doing a full typecheck, we are not resolving the whole context,
35475 // so pass --noResolve to avoid reporting missing file errors.
35476 transpileOptionValue: true
35477 },
35478 {
35479 name: "stripInternal",
35480 type: "boolean",
35481 affectsEmit: true,
35482 category: ts.Diagnostics.Advanced_Options,
35483 description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
35484 },
35485 {
35486 name: "disableSizeLimit",
35487 type: "boolean",
35488 affectsSourceFile: true,
35489 category: ts.Diagnostics.Advanced_Options,
35490 description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
35491 },
35492 {
35493 name: "disableSourceOfProjectReferenceRedirect",
35494 type: "boolean",
35495 isTSConfigOnly: true,
35496 category: ts.Diagnostics.Advanced_Options,
35497 description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
35498 },
35499 {
35500 name: "disableSolutionSearching",
35501 type: "boolean",
35502 isTSConfigOnly: true,
35503 category: ts.Diagnostics.Advanced_Options,
35504 description: ts.Diagnostics.Disable_solution_searching_for_this_project
35505 },
35506 {
35507 name: "disableReferencedProjectLoad",
35508 type: "boolean",
35509 isTSConfigOnly: true,
35510 category: ts.Diagnostics.Advanced_Options,
35511 description: ts.Diagnostics.Disable_loading_referenced_projects
35512 },
35513 {
35514 name: "noImplicitUseStrict",
35515 type: "boolean",
35516 affectsSemanticDiagnostics: true,
35517 category: ts.Diagnostics.Advanced_Options,
35518 description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
35519 },
35520 {
35521 name: "noEmitHelpers",
35522 type: "boolean",
35523 affectsEmit: true,
35524 category: ts.Diagnostics.Advanced_Options,
35525 description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
35526 },
35527 {
35528 name: "noEmitOnError",
35529 type: "boolean",
35530 affectsEmit: true,
35531 category: ts.Diagnostics.Advanced_Options,
35532 description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
35533 transpileOptionValue: undefined
35534 },
35535 {
35536 name: "preserveConstEnums",
35537 type: "boolean",
35538 affectsEmit: true,
35539 category: ts.Diagnostics.Advanced_Options,
35540 description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
35541 },
35542 {
35543 name: "declarationDir",
35544 type: "string",
35545 affectsEmit: true,
35546 isFilePath: true,
35547 paramType: ts.Diagnostics.DIRECTORY,
35548 category: ts.Diagnostics.Advanced_Options,
35549 description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
35550 transpileOptionValue: undefined
35551 },
35552 {
35553 name: "skipLibCheck",
35554 type: "boolean",
35555 category: ts.Diagnostics.Advanced_Options,
35556 description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
35557 },
35558 {
35559 name: "allowUnusedLabels",
35560 type: "boolean",
35561 affectsBindDiagnostics: true,
35562 affectsSemanticDiagnostics: true,
35563 category: ts.Diagnostics.Advanced_Options,
35564 description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
35565 },
35566 {
35567 name: "allowUnreachableCode",
35568 type: "boolean",
35569 affectsBindDiagnostics: true,
35570 affectsSemanticDiagnostics: true,
35571 category: ts.Diagnostics.Advanced_Options,
35572 description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
35573 },
35574 {
35575 name: "suppressExcessPropertyErrors",
35576 type: "boolean",
35577 affectsSemanticDiagnostics: true,
35578 category: ts.Diagnostics.Advanced_Options,
35579 description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
35580 },
35581 {
35582 name: "suppressImplicitAnyIndexErrors",
35583 type: "boolean",
35584 affectsSemanticDiagnostics: true,
35585 category: ts.Diagnostics.Advanced_Options,
35586 description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
35587 },
35588 {
35589 name: "forceConsistentCasingInFileNames",
35590 type: "boolean",
35591 affectsModuleResolution: true,
35592 category: ts.Diagnostics.Advanced_Options,
35593 description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
35594 },
35595 {
35596 name: "maxNodeModuleJsDepth",
35597 type: "number",
35598 affectsModuleResolution: true,
35599 category: ts.Diagnostics.Advanced_Options,
35600 description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
35601 },
35602 {
35603 name: "noStrictGenericChecks",
35604 type: "boolean",
35605 affectsSemanticDiagnostics: true,
35606 category: ts.Diagnostics.Advanced_Options,
35607 description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
35608 },
35609 {
35610 name: "useDefineForClassFields",
35611 type: "boolean",
35612 affectsSemanticDiagnostics: true,
35613 affectsEmit: true,
35614 category: ts.Diagnostics.Advanced_Options,
35615 description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
35616 },
35617 {
35618 name: "keyofStringsOnly",
35619 type: "boolean",
35620 category: ts.Diagnostics.Advanced_Options,
35621 description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
35622 },
35623 {
35624 // A list of plugins to load in the language service
35625 name: "plugins",
35626 type: "list",
35627 isTSConfigOnly: true,
35628 element: {
35629 name: "plugin",
35630 type: "object"
35631 },
35632 description: ts.Diagnostics.List_of_language_service_plugins
35633 },
35634 ]);
35635 /* @internal */
35636 ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
35637 /* @internal */
35638 ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
35639 /* @internal */
35640 ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
35641 /* @internal */
35642 ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
35643 return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
35644 });
35645 /* @internal */
35646 ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
35647 return ts.hasProperty(option, "transpileOptionValue");
35648 });
35649 /* @internal */
35650 ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
35651 {
35652 name: "verbose",
35653 shortName: "v",
35654 category: ts.Diagnostics.Command_line_Options,
35655 description: ts.Diagnostics.Enable_verbose_logging,
35656 type: "boolean"
35657 },
35658 {
35659 name: "dry",
35660 shortName: "d",
35661 category: ts.Diagnostics.Command_line_Options,
35662 description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
35663 type: "boolean"
35664 },
35665 {
35666 name: "force",
35667 shortName: "f",
35668 category: ts.Diagnostics.Command_line_Options,
35669 description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
35670 type: "boolean"
35671 },
35672 {
35673 name: "clean",
35674 category: ts.Diagnostics.Command_line_Options,
35675 description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
35676 type: "boolean"
35677 }
35678 ]);
35679 /* @internal */
35680 ts.typeAcquisitionDeclarations = [
35681 {
35682 /* @deprecated typingOptions.enableAutoDiscovery
35683 * Use typeAcquisition.enable instead.
35684 */
35685 name: "enableAutoDiscovery",
35686 type: "boolean",
35687 },
35688 {
35689 name: "enable",
35690 type: "boolean",
35691 },
35692 {
35693 name: "include",
35694 type: "list",
35695 element: {
35696 name: "include",
35697 type: "string"
35698 }
35699 },
35700 {
35701 name: "exclude",
35702 type: "list",
35703 element: {
35704 name: "exclude",
35705 type: "string"
35706 }
35707 }
35708 ];
35709 /*@internal*/
35710 function createOptionNameMap(optionDeclarations) {
35711 var optionsNameMap = new ts.Map();
35712 var shortOptionNames = new ts.Map();
35713 ts.forEach(optionDeclarations, function (option) {
35714 optionsNameMap.set(option.name.toLowerCase(), option);
35715 if (option.shortName) {
35716 shortOptionNames.set(option.shortName, option.name);
35717 }
35718 });
35719 return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
35720 }
35721 ts.createOptionNameMap = createOptionNameMap;
35722 var optionsNameMapCache;
35723 /* @internal */
35724 function getOptionsNameMap() {
35725 return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
35726 }
35727 ts.getOptionsNameMap = getOptionsNameMap;
35728 /* @internal */
35729 ts.defaultInitCompilerOptions = {
35730 module: ts.ModuleKind.CommonJS,
35731 target: 1 /* ES5 */,
35732 strict: true,
35733 esModuleInterop: true,
35734 forceConsistentCasingInFileNames: true,
35735 skipLibCheck: true
35736 };
35737 /* @internal */
35738 function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
35739 // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
35740 if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
35741 return {
35742 enable: typeAcquisition.enableAutoDiscovery,
35743 include: typeAcquisition.include || [],
35744 exclude: typeAcquisition.exclude || []
35745 };
35746 }
35747 return typeAcquisition;
35748 }
35749 ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
35750 /* @internal */
35751 function createCompilerDiagnosticForInvalidCustomType(opt) {
35752 return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
35753 }
35754 ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
35755 function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
35756 var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
35757 return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
35758 }
35759 /* @internal */
35760 function parseCustomTypeOption(opt, value, errors) {
35761 return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
35762 }
35763 ts.parseCustomTypeOption = parseCustomTypeOption;
35764 /* @internal */
35765 function parseListTypeOption(opt, value, errors) {
35766 if (value === void 0) { value = ""; }
35767 value = trimString(value);
35768 if (ts.startsWith(value, "-")) {
35769 return undefined;
35770 }
35771 if (value === "") {
35772 return [];
35773 }
35774 var values = value.split(",");
35775 switch (opt.element.type) {
35776 case "number":
35777 return ts.map(values, parseInt);
35778 case "string":
35779 return ts.map(values, function (v) { return v || ""; });
35780 default:
35781 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
35782 }
35783 }
35784 ts.parseListTypeOption = parseListTypeOption;
35785 function getOptionName(option) {
35786 return option.name;
35787 }
35788 function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
35789 var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
35790 return possibleOption ?
35791 createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
35792 createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
35793 }
35794 /*@internal*/
35795 function parseCommandLineWorker(diagnostics, commandLine, readFile) {
35796 var options = {};
35797 var watchOptions;
35798 var fileNames = [];
35799 var errors = [];
35800 parseStrings(commandLine);
35801 return {
35802 options: options,
35803 watchOptions: watchOptions,
35804 fileNames: fileNames,
35805 errors: errors
35806 };
35807 function parseStrings(args) {
35808 var i = 0;
35809 while (i < args.length) {
35810 var s = args[i];
35811 i++;
35812 if (s.charCodeAt(0) === 64 /* at */) {
35813 parseResponseFile(s.slice(1));
35814 }
35815 else if (s.charCodeAt(0) === 45 /* minus */) {
35816 var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
35817 var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
35818 if (opt) {
35819 i = parseOptionValue(args, i, diagnostics, opt, options, errors);
35820 }
35821 else {
35822 var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
35823 if (watchOpt) {
35824 i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
35825 }
35826 else {
35827 errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
35828 }
35829 }
35830 }
35831 else {
35832 fileNames.push(s);
35833 }
35834 }
35835 }
35836 function parseResponseFile(fileName) {
35837 var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
35838 if (!ts.isString(text)) {
35839 errors.push(text);
35840 return;
35841 }
35842 var args = [];
35843 var pos = 0;
35844 while (true) {
35845 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
35846 pos++;
35847 if (pos >= text.length)
35848 break;
35849 var start = pos;
35850 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
35851 pos++;
35852 while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
35853 pos++;
35854 if (pos < text.length) {
35855 args.push(text.substring(start + 1, pos));
35856 pos++;
35857 }
35858 else {
35859 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
35860 }
35861 }
35862 else {
35863 while (text.charCodeAt(pos) > 32 /* space */)
35864 pos++;
35865 args.push(text.substring(start, pos));
35866 }
35867 }
35868 parseStrings(args);
35869 }
35870 }
35871 ts.parseCommandLineWorker = parseCommandLineWorker;
35872 function parseOptionValue(args, i, diagnostics, opt, options, errors) {
35873 if (opt.isTSConfigOnly) {
35874 var optValue = args[i];
35875 if (optValue === "null") {
35876 options[opt.name] = undefined;
35877 i++;
35878 }
35879 else if (opt.type === "boolean") {
35880 if (optValue === "false") {
35881 options[opt.name] = false;
35882 i++;
35883 }
35884 else {
35885 if (optValue === "true")
35886 i++;
35887 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));
35888 }
35889 }
35890 else {
35891 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));
35892 if (optValue && !ts.startsWith(optValue, "-"))
35893 i++;
35894 }
35895 }
35896 else {
35897 // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
35898 if (!args[i] && opt.type !== "boolean") {
35899 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
35900 }
35901 if (args[i] !== "null") {
35902 switch (opt.type) {
35903 case "number":
35904 options[opt.name] = parseInt(args[i]);
35905 i++;
35906 break;
35907 case "boolean":
35908 // boolean flag has optional value true, false, others
35909 var optValue = args[i];
35910 options[opt.name] = optValue !== "false";
35911 // consume next argument as boolean flag value
35912 if (optValue === "false" || optValue === "true") {
35913 i++;
35914 }
35915 break;
35916 case "string":
35917 options[opt.name] = args[i] || "";
35918 i++;
35919 break;
35920 case "list":
35921 var result = parseListTypeOption(opt, args[i], errors);
35922 options[opt.name] = result || [];
35923 if (result) {
35924 i++;
35925 }
35926 break;
35927 // If not a primitive, the possible types are specified in what is effectively a map of options.
35928 default:
35929 options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
35930 i++;
35931 break;
35932 }
35933 }
35934 else {
35935 options[opt.name] = undefined;
35936 i++;
35937 }
35938 }
35939 return i;
35940 }
35941 /*@internal*/
35942 ts.compilerOptionsDidYouMeanDiagnostics = {
35943 getOptionsNameMap: getOptionsNameMap,
35944 optionDeclarations: ts.optionDeclarations,
35945 unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
35946 unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
35947 optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
35948 };
35949 function parseCommandLine(commandLine, readFile) {
35950 return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
35951 }
35952 ts.parseCommandLine = parseCommandLine;
35953 /** @internal */
35954 function getOptionFromName(optionName, allowShort) {
35955 return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
35956 }
35957 ts.getOptionFromName = getOptionFromName;
35958 function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
35959 if (allowShort === void 0) { allowShort = false; }
35960 optionName = optionName.toLowerCase();
35961 var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
35962 // Try to translate short option names to their full equivalents.
35963 if (allowShort) {
35964 var short = shortOptionNames.get(optionName);
35965 if (short !== undefined) {
35966 optionName = short;
35967 }
35968 }
35969 return optionsNameMap.get(optionName);
35970 }
35971 var buildOptionsNameMapCache;
35972 function getBuildOptionsNameMap() {
35973 return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
35974 }
35975 var buildOptionsDidYouMeanDiagnostics = {
35976 getOptionsNameMap: getBuildOptionsNameMap,
35977 optionDeclarations: ts.buildOpts,
35978 unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
35979 unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
35980 optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
35981 };
35982 /*@internal*/
35983 function parseBuildCommand(args) {
35984 var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
35985 var buildOptions = options;
35986 if (projects.length === 0) {
35987 // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
35988 projects.push(".");
35989 }
35990 // Nonsensical combinations
35991 if (buildOptions.clean && buildOptions.force) {
35992 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
35993 }
35994 if (buildOptions.clean && buildOptions.verbose) {
35995 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
35996 }
35997 if (buildOptions.clean && buildOptions.watch) {
35998 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
35999 }
36000 if (buildOptions.watch && buildOptions.dry) {
36001 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
36002 }
36003 return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
36004 }
36005 ts.parseBuildCommand = parseBuildCommand;
36006 /* @internal */
36007 function getDiagnosticText(_message) {
36008 var _args = [];
36009 for (var _i = 1; _i < arguments.length; _i++) {
36010 _args[_i - 1] = arguments[_i];
36011 }
36012 var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
36013 return diagnostic.messageText;
36014 }
36015 ts.getDiagnosticText = getDiagnosticText;
36016 /**
36017 * Reads the config file, reports errors if any and exits if the config file cannot be found
36018 */
36019 function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
36020 var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
36021 if (!ts.isString(configFileText)) {
36022 host.onUnRecoverableConfigFileDiagnostic(configFileText);
36023 return undefined;
36024 }
36025 var result = ts.parseJsonText(configFileName, configFileText);
36026 var cwd = host.getCurrentDirectory();
36027 result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
36028 result.resolvedPath = result.path;
36029 result.originalFileName = result.fileName;
36030 return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd),
36031 /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
36032 }
36033 ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
36034 /**
36035 * Read tsconfig.json file
36036 * @param fileName The path to the config file
36037 */
36038 function readConfigFile(fileName, readFile) {
36039 var textOrDiagnostic = tryReadFile(fileName, readFile);
36040 return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
36041 }
36042 ts.readConfigFile = readConfigFile;
36043 /**
36044 * Parse the text of the tsconfig.json file
36045 * @param fileName The path to the config file
36046 * @param jsonText The text of the config file
36047 */
36048 function parseConfigFileTextToJson(fileName, jsonText) {
36049 var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
36050 return {
36051 config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
36052 error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
36053 };
36054 }
36055 ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
36056 /**
36057 * Read tsconfig.json file
36058 * @param fileName The path to the config file
36059 */
36060 function readJsonConfigFile(fileName, readFile) {
36061 var textOrDiagnostic = tryReadFile(fileName, readFile);
36062 return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
36063 }
36064 ts.readJsonConfigFile = readJsonConfigFile;
36065 /*@internal*/
36066 function tryReadFile(fileName, readFile) {
36067 var text;
36068 try {
36069 text = readFile(fileName);
36070 }
36071 catch (e) {
36072 return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
36073 }
36074 return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
36075 }
36076 ts.tryReadFile = tryReadFile;
36077 function commandLineOptionsToMap(options) {
36078 return ts.arrayToMap(options, getOptionName);
36079 }
36080 var typeAcquisitionDidYouMeanDiagnostics = {
36081 optionDeclarations: ts.typeAcquisitionDeclarations,
36082 unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
36083 unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
36084 };
36085 var watchOptionsNameMapCache;
36086 function getWatchOptionsNameMap() {
36087 return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
36088 }
36089 var watchOptionsDidYouMeanDiagnostics = {
36090 getOptionsNameMap: getWatchOptionsNameMap,
36091 optionDeclarations: ts.optionsForWatch,
36092 unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
36093 unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
36094 optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
36095 };
36096 var commandLineCompilerOptionsMapCache;
36097 function getCommandLineCompilerOptionsMap() {
36098 return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
36099 }
36100 var commandLineWatchOptionsMapCache;
36101 function getCommandLineWatchOptionsMap() {
36102 return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
36103 }
36104 var commandLineTypeAcquisitionMapCache;
36105 function getCommandLineTypeAcquisitionMap() {
36106 return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
36107 }
36108 var _tsconfigRootOptions;
36109 function getTsconfigRootOptionsMap() {
36110 if (_tsconfigRootOptions === undefined) {
36111 _tsconfigRootOptions = {
36112 name: undefined,
36113 type: "object",
36114 elementOptions: commandLineOptionsToMap([
36115 {
36116 name: "compilerOptions",
36117 type: "object",
36118 elementOptions: getCommandLineCompilerOptionsMap(),
36119 extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
36120 },
36121 {
36122 name: "watchOptions",
36123 type: "object",
36124 elementOptions: getCommandLineWatchOptionsMap(),
36125 extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
36126 },
36127 {
36128 name: "typingOptions",
36129 type: "object",
36130 elementOptions: getCommandLineTypeAcquisitionMap(),
36131 extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
36132 },
36133 {
36134 name: "typeAcquisition",
36135 type: "object",
36136 elementOptions: getCommandLineTypeAcquisitionMap(),
36137 extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
36138 },
36139 {
36140 name: "extends",
36141 type: "string"
36142 },
36143 {
36144 name: "references",
36145 type: "list",
36146 element: {
36147 name: "references",
36148 type: "object"
36149 }
36150 },
36151 {
36152 name: "files",
36153 type: "list",
36154 element: {
36155 name: "files",
36156 type: "string"
36157 }
36158 },
36159 {
36160 name: "include",
36161 type: "list",
36162 element: {
36163 name: "include",
36164 type: "string"
36165 }
36166 },
36167 {
36168 name: "exclude",
36169 type: "list",
36170 element: {
36171 name: "exclude",
36172 type: "string"
36173 }
36174 },
36175 ts.compileOnSaveCommandLineOption
36176 ])
36177 };
36178 }
36179 return _tsconfigRootOptions;
36180 }
36181 /**
36182 * Convert the json syntax tree into the json value
36183 */
36184 function convertToObject(sourceFile, errors) {
36185 return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
36186 }
36187 ts.convertToObject = convertToObject;
36188 /**
36189 * Convert the json syntax tree into the json value and report errors
36190 * This returns the json value (apart from checking errors) only if returnValue provided is true.
36191 * Otherwise it just checks the errors and returns undefined
36192 */
36193 /*@internal*/
36194 function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
36195 if (!sourceFile.statements.length) {
36196 return returnValue ? {} : undefined;
36197 }
36198 return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
36199 function isRootOptionMap(knownOptions) {
36200 return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
36201 }
36202 function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
36203 var result = returnValue ? {} : undefined;
36204 var _loop_4 = function (element) {
36205 if (element.kind !== 285 /* PropertyAssignment */) {
36206 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
36207 return "continue";
36208 }
36209 if (element.questionToken) {
36210 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
36211 }
36212 if (!isDoubleQuotedString(element.name)) {
36213 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
36214 }
36215 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
36216 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
36217 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
36218 if (keyText && extraKeyDiagnostics && !option) {
36219 if (knownOptions) {
36220 errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
36221 }
36222 else {
36223 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
36224 }
36225 }
36226 var value = convertPropertyValueToJson(element.initializer, option);
36227 if (typeof keyText !== "undefined") {
36228 if (returnValue) {
36229 result[keyText] = value;
36230 }
36231 // Notify key value set, if user asked for it
36232 if (jsonConversionNotifier &&
36233 // Current callbacks are only on known parent option or if we are setting values in the root
36234 (parentOption || isRootOptionMap(knownOptions))) {
36235 var isValidOptionValue = isCompilerOptionsValue(option, value);
36236 if (parentOption) {
36237 if (isValidOptionValue) {
36238 // Notify option set in the parent if its a valid option value
36239 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
36240 }
36241 }
36242 else if (isRootOptionMap(knownOptions)) {
36243 if (isValidOptionValue) {
36244 // Notify about the valid root key value being set
36245 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
36246 }
36247 else if (!option) {
36248 // Notify about the unknown root key value being set
36249 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
36250 }
36251 }
36252 }
36253 }
36254 };
36255 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
36256 var element = _a[_i];
36257 _loop_4(element);
36258 }
36259 return result;
36260 }
36261 function convertArrayLiteralExpressionToJson(elements, elementOption) {
36262 if (!returnValue) {
36263 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
36264 }
36265 // Filter out invalid values
36266 return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
36267 }
36268 function convertPropertyValueToJson(valueExpression, option) {
36269 switch (valueExpression.kind) {
36270 case 109 /* TrueKeyword */:
36271 reportInvalidOptionValue(option && option.type !== "boolean");
36272 return true;
36273 case 94 /* FalseKeyword */:
36274 reportInvalidOptionValue(option && option.type !== "boolean");
36275 return false;
36276 case 103 /* NullKeyword */:
36277 reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
36278 return null; // eslint-disable-line no-null/no-null
36279 case 10 /* StringLiteral */:
36280 if (!isDoubleQuotedString(valueExpression)) {
36281 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
36282 }
36283 reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
36284 var text = valueExpression.text;
36285 if (option && !ts.isString(option.type)) {
36286 var customOption = option;
36287 // Validate custom option type
36288 if (!customOption.type.has(text.toLowerCase())) {
36289 errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
36290 }
36291 }
36292 return text;
36293 case 8 /* NumericLiteral */:
36294 reportInvalidOptionValue(option && option.type !== "number");
36295 return Number(valueExpression.text);
36296 case 211 /* PrefixUnaryExpression */:
36297 if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
36298 break; // not valid JSON syntax
36299 }
36300 reportInvalidOptionValue(option && option.type !== "number");
36301 return -Number(valueExpression.operand.text);
36302 case 197 /* ObjectLiteralExpression */:
36303 reportInvalidOptionValue(option && option.type !== "object");
36304 var objectLiteralExpression = valueExpression;
36305 // Currently having element option declaration in the tsconfig with type "object"
36306 // determines if it needs onSetValidOptionKeyValueInParent callback or not
36307 // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
36308 // that satifies it and need it to modify options set in them (for normalizing file paths)
36309 // vs what we set in the json
36310 // If need arises, we can modify this interface and callbacks as needed
36311 if (option) {
36312 var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
36313 return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
36314 }
36315 else {
36316 return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
36317 /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
36318 }
36319 case 196 /* ArrayLiteralExpression */:
36320 reportInvalidOptionValue(option && option.type !== "list");
36321 return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
36322 }
36323 // Not in expected format
36324 if (option) {
36325 reportInvalidOptionValue(/*isError*/ true);
36326 }
36327 else {
36328 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));
36329 }
36330 return undefined;
36331 function reportInvalidOptionValue(isError) {
36332 if (isError) {
36333 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
36334 }
36335 }
36336 }
36337 function isDoubleQuotedString(node) {
36338 return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
36339 }
36340 }
36341 ts.convertToObjectWorker = convertToObjectWorker;
36342 function getCompilerOptionValueTypeString(option) {
36343 return option.type === "list" ?
36344 "Array" :
36345 ts.isString(option.type) ? option.type : "string";
36346 }
36347 function isCompilerOptionsValue(option, value) {
36348 if (option) {
36349 if (isNullOrUndefined(value))
36350 return true; // All options are undefinable/nullable
36351 if (option.type === "list") {
36352 return ts.isArray(value);
36353 }
36354 var expectedType = ts.isString(option.type) ? option.type : "string";
36355 return typeof value === expectedType;
36356 }
36357 return false;
36358 }
36359 /**
36360 * Generate an uncommented, complete tsconfig for use with "--showConfig"
36361 * @param configParseResult options to be generated into tsconfig.json
36362 * @param configFileName name of the parsed config file - output paths will be generated relative to this
36363 * @param host provides current directory and case sensitivity services
36364 */
36365 /** @internal */
36366 function convertToTSConfig(configParseResult, configFileName, host) {
36367 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
36368 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); });
36369 var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
36370 var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
36371 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 ? {
36372 include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
36373 exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
36374 } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
36375 return config;
36376 }
36377 ts.convertToTSConfig = convertToTSConfig;
36378 function optionMapToObject(optionMap) {
36379 return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
36380 var _a;
36381 return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
36382 }, {}));
36383 }
36384 function filterSameAsDefaultInclude(specs) {
36385 if (!ts.length(specs))
36386 return undefined;
36387 if (ts.length(specs) !== 1)
36388 return specs;
36389 if (specs[0] === "**/*")
36390 return undefined;
36391 return specs;
36392 }
36393 function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
36394 if (!includeSpecs)
36395 return function (_) { return true; };
36396 var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
36397 var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
36398 var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
36399 if (includeRe) {
36400 if (excludeRe) {
36401 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
36402 }
36403 return function (path) { return !includeRe.test(path); };
36404 }
36405 if (excludeRe) {
36406 return function (path) { return excludeRe.test(path); };
36407 }
36408 return function (_) { return true; };
36409 }
36410 function getCustomTypeMapOfCommandLineOption(optionDefinition) {
36411 if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
36412 // this is of a type CommandLineOptionOfPrimitiveType
36413 return undefined;
36414 }
36415 else if (optionDefinition.type === "list") {
36416 return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
36417 }
36418 else {
36419 return optionDefinition.type;
36420 }
36421 }
36422 function getNameOfCompilerOptionValue(value, customTypeMap) {
36423 // There is a typeMap associated with this command-line option so use it to map value back to its name
36424 return ts.forEachEntry(customTypeMap, function (mapValue, key) {
36425 if (mapValue === value) {
36426 return key;
36427 }
36428 });
36429 }
36430 function serializeCompilerOptions(options, pathOptions) {
36431 return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
36432 }
36433 function serializeWatchOptions(options) {
36434 return serializeOptionBaseObject(options, getWatchOptionsNameMap());
36435 }
36436 function serializeOptionBaseObject(options, _a, pathOptions) {
36437 var optionsNameMap = _a.optionsNameMap;
36438 var result = new ts.Map();
36439 var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
36440 var _loop_5 = function (name) {
36441 if (ts.hasProperty(options, name)) {
36442 // tsconfig only options cannot be specified via command line,
36443 // so we can assume that only types that can appear here string | number | boolean
36444 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
36445 return "continue";
36446 }
36447 var value = options[name];
36448 var optionDefinition = optionsNameMap.get(name.toLowerCase());
36449 if (optionDefinition) {
36450 var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
36451 if (!customTypeMap_1) {
36452 // There is no map associated with this compiler option then use the value as-is
36453 // This is the case if the value is expect to be string, number, boolean or list of string
36454 if (pathOptions && optionDefinition.isFilePath) {
36455 result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
36456 }
36457 else {
36458 result.set(name, value);
36459 }
36460 }
36461 else {
36462 if (optionDefinition.type === "list") {
36463 result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
36464 }
36465 else {
36466 // There is a typeMap associated with this command-line option so use it to map value back to its name
36467 result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
36468 }
36469 }
36470 }
36471 }
36472 };
36473 for (var name in options) {
36474 _loop_5(name);
36475 }
36476 return result;
36477 }
36478 /**
36479 * Generate tsconfig configuration when running command line "--init"
36480 * @param options commandlineOptions to be generated into tsconfig.json
36481 * @param fileNames array of filenames to be generated into tsconfig.json
36482 */
36483 /* @internal */
36484 function generateTSConfig(options, fileNames, newLine) {
36485 var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
36486 var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
36487 return writeConfigurations();
36488 function getDefaultValueForOption(option) {
36489 switch (option.type) {
36490 case "number":
36491 return 1;
36492 case "boolean":
36493 return true;
36494 case "string":
36495 return option.isFilePath ? "./" : "";
36496 case "list":
36497 return [];
36498 case "object":
36499 return {};
36500 default:
36501 var iterResult = option.type.keys().next();
36502 if (!iterResult.done)
36503 return iterResult.value;
36504 return ts.Debug.fail("Expected 'option.type' to have entries.");
36505 }
36506 }
36507 function makePadding(paddingLength) {
36508 return Array(paddingLength + 1).join(" ");
36509 }
36510 function isAllowedOption(_a) {
36511 var category = _a.category, name = _a.name;
36512 // Skip options which do not have a category or have category `Command_line_Options`
36513 // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
36514 return category !== undefined
36515 && category !== ts.Diagnostics.Command_line_Options
36516 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
36517 }
36518 function writeConfigurations() {
36519 // Filter applicable options to place in the file
36520 var categorizedOptions = ts.createMultiMap();
36521 for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
36522 var option = optionDeclarations_1[_i];
36523 var category = option.category;
36524 if (isAllowedOption(option)) {
36525 categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
36526 }
36527 }
36528 // Serialize all options and their descriptions
36529 var marginLength = 0;
36530 var seenKnownKeys = 0;
36531 var entries = [];
36532 categorizedOptions.forEach(function (options, category) {
36533 if (entries.length !== 0) {
36534 entries.push({ value: "" });
36535 }
36536 entries.push({ value: "/* " + category + " */" });
36537 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
36538 var option = options_1[_i];
36539 var optionName = void 0;
36540 if (compilerOptionsMap.has(option.name)) {
36541 optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
36542 }
36543 else {
36544 optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
36545 }
36546 entries.push({
36547 value: optionName,
36548 description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
36549 });
36550 marginLength = Math.max(optionName.length, marginLength);
36551 }
36552 });
36553 // Write the output
36554 var tab = makePadding(2);
36555 var result = [];
36556 result.push("{");
36557 result.push(tab + "\"compilerOptions\": {");
36558 result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
36559 result.push("");
36560 // Print out each row, aligning all the descriptions on the same column.
36561 for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
36562 var entry = entries_2[_a];
36563 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
36564 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
36565 }
36566 if (fileNames.length) {
36567 result.push(tab + "},");
36568 result.push(tab + "\"files\": [");
36569 for (var i = 0; i < fileNames.length; i++) {
36570 result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
36571 }
36572 result.push(tab + "]");
36573 }
36574 else {
36575 result.push(tab + "}");
36576 }
36577 result.push("}");
36578 return result.join(newLine) + newLine;
36579 }
36580 }
36581 ts.generateTSConfig = generateTSConfig;
36582 /* @internal */
36583 function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
36584 var result = {};
36585 var optionsNameMap = getOptionsNameMap().optionsNameMap;
36586 for (var name in options) {
36587 if (ts.hasProperty(options, name)) {
36588 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
36589 }
36590 }
36591 if (result.configFilePath) {
36592 result.configFilePath = toAbsolutePath(result.configFilePath);
36593 }
36594 return result;
36595 }
36596 ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
36597 function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
36598 if (option && !isNullOrUndefined(value)) {
36599 if (option.type === "list") {
36600 var values = value;
36601 if (option.element.isFilePath && values.length) {
36602 return values.map(toAbsolutePath);
36603 }
36604 }
36605 else if (option.isFilePath) {
36606 return toAbsolutePath(value);
36607 }
36608 }
36609 return value;
36610 }
36611 /**
36612 * Parse the contents of a config file (tsconfig.json).
36613 * @param json The contents of the config file to parse
36614 * @param host Instance of ParseConfigHost used to enumerate files in folder.
36615 * @param basePath A root directory to resolve relative path entries in the config
36616 * file to. e.g. outDir
36617 */
36618 function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
36619 return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
36620 }
36621 ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
36622 /**
36623 * Parse the contents of a config file (tsconfig.json).
36624 * @param jsonNode The contents of the config file to parse
36625 * @param host Instance of ParseConfigHost used to enumerate files in folder.
36626 * @param basePath A root directory to resolve relative path entries in the config
36627 * file to. e.g. outDir
36628 */
36629 function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
36630 return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
36631 }
36632 ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
36633 /*@internal*/
36634 function setConfigFileInOptions(options, configFile) {
36635 if (configFile) {
36636 Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
36637 }
36638 }
36639 ts.setConfigFileInOptions = setConfigFileInOptions;
36640 function isNullOrUndefined(x) {
36641 return x === undefined || x === null; // eslint-disable-line no-null/no-null
36642 }
36643 function directoryOfCombinedPath(fileName, basePath) {
36644 // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
36645 // until consistent casing errors are reported
36646 return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
36647 }
36648 /**
36649 * Parse the contents of a config file from json or json source file (tsconfig.json).
36650 * @param json The contents of the config file to parse
36651 * @param sourceFile sourceFile corresponding to the Json
36652 * @param host Instance of ParseConfigHost used to enumerate files in folder.
36653 * @param basePath A root directory to resolve relative path entries in the config
36654 * file to. e.g. outDir
36655 * @param resolutionStack Only present for backwards-compatibility. Should be empty.
36656 */
36657 function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
36658 if (existingOptions === void 0) { existingOptions = {}; }
36659 if (resolutionStack === void 0) { resolutionStack = []; }
36660 if (extraFileExtensions === void 0) { extraFileExtensions = []; }
36661 ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
36662 var errors = [];
36663 var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
36664 var raw = parsedConfig.raw;
36665 var options = ts.extend(existingOptions, parsedConfig.options || {});
36666 var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
36667 ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
36668 parsedConfig.watchOptions || existingWatchOptions;
36669 options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
36670 setConfigFileInOptions(options, sourceFile);
36671 var projectReferences;
36672 var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
36673 return {
36674 options: options,
36675 watchOptions: watchOptions,
36676 fileNames: fileNames,
36677 projectReferences: projectReferences,
36678 typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
36679 raw: raw,
36680 errors: errors,
36681 wildcardDirectories: wildcardDirectories,
36682 compileOnSave: !!raw.compileOnSave,
36683 configFileSpecs: spec
36684 };
36685 function getFileNames() {
36686 var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
36687 if (ts.isArray(referencesOfRaw)) {
36688 for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
36689 var ref = referencesOfRaw_1[_i];
36690 if (typeof ref.path !== "string") {
36691 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
36692 }
36693 else {
36694 (projectReferences || (projectReferences = [])).push({
36695 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
36696 originalPath: ref.path,
36697 prepend: ref.prepend,
36698 circular: ref.circular
36699 });
36700 }
36701 }
36702 }
36703 var filesSpecs = toPropValue(getSpecsFromRaw("files"));
36704 if (filesSpecs) {
36705 var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
36706 var hasExtends = ts.hasProperty(raw, "extends");
36707 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
36708 if (sourceFile) {
36709 var fileName = configFileName || "tsconfig.json";
36710 var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
36711 var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
36712 var error = nodeValue
36713 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
36714 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
36715 errors.push(error);
36716 }
36717 else {
36718 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
36719 }
36720 }
36721 }
36722 var includeSpecs = toPropValue(getSpecsFromRaw("include"));
36723 var excludeOfRaw = getSpecsFromRaw("exclude");
36724 var excludeSpecs = toPropValue(excludeOfRaw);
36725 if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
36726 var outDir = raw.compilerOptions.outDir;
36727 var declarationDir = raw.compilerOptions.declarationDir;
36728 if (outDir || declarationDir) {
36729 excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
36730 }
36731 }
36732 if (filesSpecs === undefined && includeSpecs === undefined) {
36733 includeSpecs = ["**/*"];
36734 }
36735 var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
36736 if (shouldReportNoInputFiles(result, canJsonReportNoInputFiles(raw), resolutionStack)) {
36737 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
36738 }
36739 return result;
36740 }
36741 function toPropValue(specResult) {
36742 return ts.isArray(specResult) ? specResult : undefined;
36743 }
36744 function getSpecsFromRaw(prop) {
36745 return getPropFromRaw(prop, ts.isString, "string");
36746 }
36747 function getPropFromRaw(prop, validateElement, elementTypeName) {
36748 if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
36749 if (ts.isArray(raw[prop])) {
36750 var result = raw[prop];
36751 if (!sourceFile && !ts.every(result, validateElement)) {
36752 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
36753 }
36754 return result;
36755 }
36756 else {
36757 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
36758 return "not-array";
36759 }
36760 }
36761 return "no-prop";
36762 }
36763 function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
36764 if (!sourceFile) {
36765 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
36766 }
36767 }
36768 }
36769 function isErrorNoInputFiles(error) {
36770 return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
36771 }
36772 function getErrorForNoInputFiles(_a, configFileName) {
36773 var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
36774 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 || []));
36775 }
36776 function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
36777 return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
36778 }
36779 /*@internal*/
36780 function canJsonReportNoInputFiles(raw) {
36781 return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
36782 }
36783 ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
36784 /*@internal*/
36785 function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
36786 var existingErrors = configParseDiagnostics.length;
36787 if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
36788 configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
36789 }
36790 else {
36791 ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
36792 }
36793 return existingErrors !== configParseDiagnostics.length;
36794 }
36795 ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
36796 function isSuccessfulParsedTsconfig(value) {
36797 return !!value.options;
36798 }
36799 /**
36800 * This *just* extracts options/include/exclude/files out of a config file.
36801 * It does *not* resolve the included files.
36802 */
36803 function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
36804 basePath = ts.normalizeSlashes(basePath);
36805 var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
36806 if (resolutionStack.indexOf(resolvedPath) >= 0) {
36807 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
36808 return { raw: json || convertToObject(sourceFile, errors) };
36809 }
36810 var ownConfig = json ?
36811 parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
36812 parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
36813 if (ownConfig.extendedConfigPath) {
36814 // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
36815 resolutionStack = resolutionStack.concat([resolvedPath]);
36816 var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
36817 if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
36818 var baseRaw_1 = extendedConfig.raw;
36819 var raw_1 = ownConfig.raw;
36820 var setPropertyInRawIfNotUndefined = function (propertyName) {
36821 var value = raw_1[propertyName] || baseRaw_1[propertyName];
36822 if (value) {
36823 raw_1[propertyName] = value;
36824 }
36825 };
36826 setPropertyInRawIfNotUndefined("include");
36827 setPropertyInRawIfNotUndefined("exclude");
36828 setPropertyInRawIfNotUndefined("files");
36829 if (raw_1.compileOnSave === undefined) {
36830 raw_1.compileOnSave = baseRaw_1.compileOnSave;
36831 }
36832 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
36833 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
36834 ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
36835 ownConfig.watchOptions || extendedConfig.watchOptions;
36836 // TODO extend type typeAcquisition
36837 }
36838 }
36839 return ownConfig;
36840 }
36841 function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
36842 if (ts.hasProperty(json, "excludes")) {
36843 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
36844 }
36845 var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
36846 // typingOptions has been deprecated and is only supported for backward compatibility purposes.
36847 // It should be removed in future releases - use typeAcquisition instead.
36848 var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
36849 var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
36850 json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
36851 var extendedConfigPath;
36852 if (json.extends) {
36853 if (!ts.isString(json.extends)) {
36854 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
36855 }
36856 else {
36857 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
36858 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
36859 }
36860 }
36861 return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
36862 }
36863 function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
36864 var options = getDefaultCompilerOptions(configFileName);
36865 var typeAcquisition, typingOptionstypeAcquisition;
36866 var watchOptions;
36867 var extendedConfigPath;
36868 var optionsIterator = {
36869 onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
36870 var currentOption;
36871 switch (parentOption) {
36872 case "compilerOptions":
36873 currentOption = options;
36874 break;
36875 case "watchOptions":
36876 currentOption = (watchOptions || (watchOptions = {}));
36877 break;
36878 case "typeAcquisition":
36879 currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
36880 break;
36881 case "typingOptions":
36882 currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
36883 break;
36884 default:
36885 ts.Debug.fail("Unknown option");
36886 }
36887 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
36888 },
36889 onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
36890 switch (key) {
36891 case "extends":
36892 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
36893 extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
36894 return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
36895 });
36896 return;
36897 }
36898 },
36899 onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
36900 if (key === "excludes") {
36901 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
36902 }
36903 }
36904 };
36905 var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
36906 if (!typeAcquisition) {
36907 if (typingOptionstypeAcquisition) {
36908 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
36909 {
36910 enable: typingOptionstypeAcquisition.enableAutoDiscovery,
36911 include: typingOptionstypeAcquisition.include,
36912 exclude: typingOptionstypeAcquisition.exclude
36913 } :
36914 typingOptionstypeAcquisition;
36915 }
36916 else {
36917 typeAcquisition = getDefaultTypeAcquisition(configFileName);
36918 }
36919 }
36920 return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
36921 }
36922 function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
36923 extendedConfig = ts.normalizeSlashes(extendedConfig);
36924 if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
36925 var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
36926 if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
36927 extendedConfigPath = extendedConfigPath + ".json";
36928 if (!host.fileExists(extendedConfigPath)) {
36929 errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
36930 return undefined;
36931 }
36932 }
36933 return extendedConfigPath;
36934 }
36935 // If the path isn't a rooted or relative path, resolve like a module
36936 var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
36937 if (resolved.resolvedModule) {
36938 return resolved.resolvedModule.resolvedFileName;
36939 }
36940 errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
36941 return undefined;
36942 }
36943 function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
36944 var _a;
36945 var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
36946 var value;
36947 var extendedResult;
36948 var extendedConfig;
36949 if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
36950 (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
36951 }
36952 else {
36953 extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
36954 if (!extendedResult.parseDiagnostics.length) {
36955 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
36956 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
36957 if (isSuccessfulParsedTsconfig(extendedConfig)) {
36958 // Update the paths to reflect base path
36959 var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
36960 var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
36961 var mapPropertiesInRawIfNotUndefined = function (propertyName) {
36962 if (raw_2[propertyName]) {
36963 raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
36964 }
36965 };
36966 var raw_2 = extendedConfig.raw;
36967 mapPropertiesInRawIfNotUndefined("include");
36968 mapPropertiesInRawIfNotUndefined("exclude");
36969 mapPropertiesInRawIfNotUndefined("files");
36970 }
36971 }
36972 if (extendedConfigCache) {
36973 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
36974 }
36975 }
36976 if (sourceFile) {
36977 sourceFile.extendedSourceFiles = [extendedResult.fileName];
36978 if (extendedResult.extendedSourceFiles) {
36979 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
36980 }
36981 }
36982 if (extendedResult.parseDiagnostics.length) {
36983 errors.push.apply(errors, extendedResult.parseDiagnostics);
36984 return undefined;
36985 }
36986 return extendedConfig;
36987 }
36988 function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
36989 if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
36990 return false;
36991 }
36992 var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
36993 return typeof result === "boolean" && result;
36994 }
36995 function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
36996 var errors = [];
36997 var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
36998 return { options: options, errors: errors };
36999 }
37000 ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
37001 function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
37002 var errors = [];
37003 var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
37004 return { options: options, errors: errors };
37005 }
37006 ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
37007 function getDefaultCompilerOptions(configFileName) {
37008 var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
37009 ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
37010 : {};
37011 return options;
37012 }
37013 function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37014 var options = getDefaultCompilerOptions(configFileName);
37015 convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
37016 if (configFileName) {
37017 options.configFilePath = ts.normalizeSlashes(configFileName);
37018 }
37019 return options;
37020 }
37021 function getDefaultTypeAcquisition(configFileName) {
37022 return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
37023 }
37024 function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37025 var options = getDefaultTypeAcquisition(configFileName);
37026 var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
37027 convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
37028 return options;
37029 }
37030 function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
37031 return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
37032 }
37033 function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
37034 if (!jsonOptions) {
37035 return;
37036 }
37037 for (var id in jsonOptions) {
37038 var opt = optionsNameMap.get(id);
37039 if (opt) {
37040 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
37041 }
37042 else {
37043 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
37044 }
37045 }
37046 return defaultOptions;
37047 }
37048 function convertJsonOption(opt, value, basePath, errors) {
37049 if (isCompilerOptionsValue(opt, value)) {
37050 var optType = opt.type;
37051 if (optType === "list" && ts.isArray(value)) {
37052 return convertJsonOptionOfListType(opt, value, basePath, errors);
37053 }
37054 else if (!ts.isString(optType)) {
37055 return convertJsonOptionOfCustomType(opt, value, errors);
37056 }
37057 return normalizeNonListOptionValue(opt, basePath, value);
37058 }
37059 else {
37060 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
37061 }
37062 }
37063 function normalizeOptionValue(option, basePath, value) {
37064 if (isNullOrUndefined(value))
37065 return undefined;
37066 if (option.type === "list") {
37067 var listOption_1 = option;
37068 if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
37069 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
37070 }
37071 return value;
37072 }
37073 else if (!ts.isString(option.type)) {
37074 return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
37075 }
37076 return normalizeNonListOptionValue(option, basePath, value);
37077 }
37078 function normalizeNonListOptionValue(option, basePath, value) {
37079 if (option.isFilePath) {
37080 value = ts.getNormalizedAbsolutePath(value, basePath);
37081 if (value === "") {
37082 value = ".";
37083 }
37084 }
37085 return value;
37086 }
37087 function convertJsonOptionOfCustomType(opt, value, errors) {
37088 if (isNullOrUndefined(value))
37089 return undefined;
37090 var key = value.toLowerCase();
37091 var val = opt.type.get(key);
37092 if (val !== undefined) {
37093 return val;
37094 }
37095 else {
37096 errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
37097 }
37098 }
37099 function convertJsonOptionOfListType(option, values, basePath, errors) {
37100 return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
37101 }
37102 function trimString(s) {
37103 return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
37104 }
37105 /**
37106 * Tests for a path that ends in a recursive directory wildcard.
37107 * Matches **, \**, **\, and \**\, but not a**b.
37108 *
37109 * NOTE: used \ in place of / above to avoid issues with multiline comments.
37110 *
37111 * Breakdown:
37112 * (^|\/) # matches either the beginning of the string or a directory separator.
37113 * \*\* # matches the recursive directory wildcard "**".
37114 * \/?$ # matches an optional trailing directory separator at the end of the string.
37115 */
37116 var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
37117 /**
37118 * Tests for a path where .. appears after a recursive directory wildcard.
37119 * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
37120 *
37121 * NOTE: used \ in place of / above to avoid issues with multiline comments.
37122 *
37123 * Breakdown:
37124 * (^|\/) # matches either the beginning of the string or a directory separator.
37125 * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator.
37126 * (.*\/)? # optionally matches any number of characters followed by a directory separator.
37127 * \.\. # matches a parent directory path component ".."
37128 * ($|\/) # matches either the end of the string or a directory separator.
37129 */
37130 var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
37131 /**
37132 * Tests for a path containing a wildcard character in a directory component of the path.
37133 * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
37134 *
37135 * NOTE: used \ in place of / above to avoid issues with multiline comments.
37136 *
37137 * Breakdown:
37138 * \/ # matches a directory separator.
37139 * [^/]*? # matches any number of characters excluding directory separators (non-greedy).
37140 * [*?] # matches either a wildcard character (* or ?)
37141 * [^/]* # matches any number of characters excluding directory separators (greedy).
37142 * \/ # matches a directory separator.
37143 */
37144 var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
37145 /**
37146 * Matches the portion of a wildcard path that does not contain wildcards.
37147 * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
37148 *
37149 * NOTE: used \ in place of / above to avoid issues with multiline comments.
37150 *
37151 * Breakdown:
37152 * ^ # matches the beginning of the string
37153 * [^*?]* # matches any number of non-wildcard characters
37154 * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by
37155 * # a path component that contains at least one wildcard character (* or ?).
37156 */
37157 var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
37158 /**
37159 * Expands an array of file specifications.
37160 *
37161 * @param filesSpecs The literal file names to include.
37162 * @param includeSpecs The wildcard file specifications to include.
37163 * @param excludeSpecs The wildcard file specifications to exclude.
37164 * @param basePath The base path for any relative file specifications.
37165 * @param options Compiler options.
37166 * @param host The host used to resolve files and directories.
37167 * @param errors An array for diagnostic reporting.
37168 */
37169 function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
37170 basePath = ts.normalizePath(basePath);
37171 var validatedIncludeSpecs, validatedExcludeSpecs;
37172 // The exclude spec list is converted into a regular expression, which allows us to quickly
37173 // test whether a file or directory should be excluded before recursively traversing the
37174 // file system.
37175 if (includeSpecs) {
37176 validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
37177 }
37178 if (excludeSpecs) {
37179 validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
37180 }
37181 // Wildcard directories (provided as part of a wildcard path) are stored in a
37182 // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
37183 // or a recursive directory. This information is used by filesystem watchers to monitor for
37184 // new entries in these paths.
37185 var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
37186 var spec = {
37187 filesSpecs: filesSpecs,
37188 includeSpecs: includeSpecs,
37189 excludeSpecs: excludeSpecs,
37190 validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
37191 validatedIncludeSpecs: validatedIncludeSpecs,
37192 validatedExcludeSpecs: validatedExcludeSpecs,
37193 wildcardDirectories: wildcardDirectories
37194 };
37195 return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
37196 }
37197 /**
37198 * Gets the file names from the provided config file specs that contain, files, include, exclude and
37199 * other properties needed to resolve the file names
37200 * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
37201 * @param basePath The base path for any relative file specifications.
37202 * @param options Compiler options.
37203 * @param host The host used to resolve files and directories.
37204 * @param extraFileExtensions optionaly file extra file extension information from host
37205 */
37206 /* @internal */
37207 function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
37208 if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
37209 basePath = ts.normalizePath(basePath);
37210 var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
37211 // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
37212 // file map with a possibly case insensitive key. We use this map later when when including
37213 // wildcard paths.
37214 var literalFileMap = new ts.Map();
37215 // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
37216 // file map with a possibly case insensitive key. We use this map to store paths matched
37217 // via wildcard, and to handle extension priority.
37218 var wildcardFileMap = new ts.Map();
37219 // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
37220 // file map with a possibly case insensitive key. We use this map to store paths matched
37221 // via wildcard of *.json kind
37222 var wildCardJsonFileMap = new ts.Map();
37223 var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
37224 // Rather than requery this for each file and filespec, we query the supported extensions
37225 // once and store it on the expansion context.
37226 var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
37227 var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
37228 // Literal files are always included verbatim. An "include" or "exclude" specification cannot
37229 // remove a literal file.
37230 if (validatedFilesSpec) {
37231 for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
37232 var fileName = validatedFilesSpec_1[_i];
37233 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
37234 literalFileMap.set(keyMapper(file), file);
37235 }
37236 }
37237 var jsonOnlyIncludeRegexes;
37238 if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
37239 var _loop_6 = function (file) {
37240 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
37241 // Valid only if *.json specified
37242 if (!jsonOnlyIncludeRegexes) {
37243 var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
37244 var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
37245 jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
37246 }
37247 var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
37248 if (includeIndex !== -1) {
37249 var key_1 = keyMapper(file);
37250 if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
37251 wildCardJsonFileMap.set(key_1, file);
37252 }
37253 }
37254 return "continue";
37255 }
37256 // If we have already included a literal or wildcard path with a
37257 // higher priority extension, we should skip this file.
37258 //
37259 // This handles cases where we may encounter both <file>.ts and
37260 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
37261 // directory when they are compilation outputs.
37262 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
37263 return "continue";
37264 }
37265 // We may have included a wildcard path with a lower priority
37266 // extension due to the user-defined order of entries in the
37267 // "include" array. If there is a lower priority extension in the
37268 // same directory, we should remove it.
37269 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
37270 var key = keyMapper(file);
37271 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
37272 wildcardFileMap.set(key, file);
37273 }
37274 };
37275 for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
37276 var file = _b[_a];
37277 _loop_6(file);
37278 }
37279 }
37280 var literalFiles = ts.arrayFrom(literalFileMap.values());
37281 var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
37282 return {
37283 fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
37284 wildcardDirectories: wildcardDirectories,
37285 spec: spec
37286 };
37287 }
37288 ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
37289 /* @internal */
37290 function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
37291 var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
37292 if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
37293 return false;
37294 basePath = ts.normalizePath(basePath);
37295 var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
37296 if (validatedFilesSpec) {
37297 for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
37298 var fileName = validatedFilesSpec_2[_i];
37299 if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
37300 return false;
37301 }
37302 }
37303 var excludePattern = ts.getRegularExpressionForWildcard(validatedExcludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
37304 var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
37305 if (!excludeRegex)
37306 return false;
37307 if (excludeRegex.test(pathToCheck))
37308 return true;
37309 return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
37310 }
37311 ts.isExcludedFile = isExcludedFile;
37312 function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
37313 return specs.filter(function (spec) {
37314 if (!ts.isString(spec))
37315 return false;
37316 var diag = specToDiagnostic(spec, allowTrailingRecursion);
37317 if (diag !== undefined) {
37318 errors.push(createDiagnostic(diag, spec));
37319 }
37320 return diag === undefined;
37321 });
37322 function createDiagnostic(message, spec) {
37323 var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
37324 return element ?
37325 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
37326 ts.createCompilerDiagnostic(message, spec);
37327 }
37328 }
37329 function specToDiagnostic(spec, allowTrailingRecursion) {
37330 if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
37331 return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
37332 }
37333 else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
37334 return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
37335 }
37336 }
37337 /**
37338 * Gets directories in a set of include patterns that should be watched for changes.
37339 */
37340 function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
37341 // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
37342 // of the pattern:
37343 //
37344 // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively
37345 // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
37346 // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler
37347 //
37348 // We watch a directory without recursion if it contains a wildcard in the file segment of
37349 // the pattern:
37350 //
37351 // /a/b/* - Watch /a/b directly to catch any new file
37352 // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
37353 var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
37354 var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
37355 var wildcardDirectories = {};
37356 if (include !== undefined) {
37357 var recursiveKeys = [];
37358 for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
37359 var file = include_1[_i];
37360 var spec = ts.normalizePath(ts.combinePaths(path, file));
37361 if (excludeRegex && excludeRegex.test(spec)) {
37362 continue;
37363 }
37364 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
37365 if (match) {
37366 var key = match.key, flags = match.flags;
37367 var existingFlags = wildcardDirectories[key];
37368 if (existingFlags === undefined || existingFlags < flags) {
37369 wildcardDirectories[key] = flags;
37370 if (flags === 1 /* Recursive */) {
37371 recursiveKeys.push(key);
37372 }
37373 }
37374 }
37375 }
37376 // Remove any subpaths under an existing recursively watched directory.
37377 for (var key in wildcardDirectories) {
37378 if (ts.hasProperty(wildcardDirectories, key)) {
37379 for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
37380 var recursiveKey = recursiveKeys_1[_a];
37381 if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
37382 delete wildcardDirectories[key];
37383 }
37384 }
37385 }
37386 }
37387 }
37388 return wildcardDirectories;
37389 }
37390 function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
37391 var match = wildcardDirectoryPattern.exec(spec);
37392 if (match) {
37393 return {
37394 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
37395 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
37396 };
37397 }
37398 if (ts.isImplicitGlob(spec)) {
37399 return {
37400 key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec),
37401 flags: 1 /* Recursive */
37402 };
37403 }
37404 return undefined;
37405 }
37406 /**
37407 * Determines whether a literal or wildcard file has already been included that has a higher
37408 * extension priority.
37409 *
37410 * @param file The path to the file.
37411 * @param extensionPriority The priority of the extension.
37412 * @param context The expansion context.
37413 */
37414 function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
37415 var extensionPriority = ts.getExtensionPriority(file, extensions);
37416 var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
37417 for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
37418 var higherPriorityExtension = extensions[i];
37419 var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
37420 if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
37421 return true;
37422 }
37423 }
37424 return false;
37425 }
37426 /**
37427 * Removes files included via wildcard expansion with a lower extension priority that have
37428 * already been included.
37429 *
37430 * @param file The path to the file.
37431 * @param extensionPriority The priority of the extension.
37432 * @param context The expansion context.
37433 */
37434 function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
37435 var extensionPriority = ts.getExtensionPriority(file, extensions);
37436 var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
37437 for (var i = nextExtensionPriority; i < extensions.length; i++) {
37438 var lowerPriorityExtension = extensions[i];
37439 var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
37440 wildcardFiles.delete(lowerPriorityPath);
37441 }
37442 }
37443 /**
37444 * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
37445 * Also converts enum values back to strings.
37446 */
37447 /* @internal */
37448 function convertCompilerOptionsForTelemetry(opts) {
37449 var out = {};
37450 for (var key in opts) {
37451 if (opts.hasOwnProperty(key)) {
37452 var type = getOptionFromName(key);
37453 if (type !== undefined) { // Ignore unknown options
37454 out[key] = getOptionValueWithEmptyStrings(opts[key], type);
37455 }
37456 }
37457 }
37458 return out;
37459 }
37460 ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
37461 function getOptionValueWithEmptyStrings(value, option) {
37462 switch (option.type) {
37463 case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
37464 return "";
37465 case "string": // Could be any arbitrary string -- use empty string instead.
37466 return "";
37467 case "number": // Allow numbers, but be sure to check it's actually a number.
37468 return typeof value === "number" ? value : "";
37469 case "boolean":
37470 return typeof value === "boolean" ? value : "";
37471 case "list":
37472 var elementType_1 = option.element;
37473 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
37474 default:
37475 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
37476 if (optionEnumValue === value) {
37477 return optionStringValue;
37478 }
37479 }); // TODO: GH#18217
37480 }
37481 }
37482})(ts || (ts = {}));
37483var ts;
37484(function (ts) {
37485 function trace(host) {
37486 host.trace(ts.formatMessage.apply(undefined, arguments));
37487 }
37488 ts.trace = trace;
37489 /* @internal */
37490 function isTraceEnabled(compilerOptions, host) {
37491 return !!compilerOptions.traceResolution && host.trace !== undefined;
37492 }
37493 ts.isTraceEnabled = isTraceEnabled;
37494 function withPackageId(packageInfo, r) {
37495 var packageId;
37496 if (r && packageInfo) {
37497 var packageJsonContent = packageInfo.packageJsonContent;
37498 if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
37499 packageId = {
37500 name: packageJsonContent.name,
37501 subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
37502 version: packageJsonContent.version
37503 };
37504 }
37505 }
37506 return r && { path: r.path, extension: r.ext, packageId: packageId };
37507 }
37508 function noPackageId(r) {
37509 return withPackageId(/*packageInfo*/ undefined, r);
37510 }
37511 function removeIgnoredPackageId(r) {
37512 if (r) {
37513 ts.Debug.assert(r.packageId === undefined);
37514 return { path: r.path, ext: r.extension };
37515 }
37516 }
37517 /**
37518 * Kinds of file that we are currently looking for.
37519 * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
37520 */
37521 var Extensions;
37522 (function (Extensions) {
37523 Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
37524 Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
37525 Extensions[Extensions["Json"] = 2] = "Json";
37526 Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
37527 Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
37528 })(Extensions || (Extensions = {}));
37529 /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
37530 function resolvedTypeScriptOnly(resolved) {
37531 if (!resolved) {
37532 return undefined;
37533 }
37534 ts.Debug.assert(ts.extensionIsTS(resolved.extension));
37535 return { fileName: resolved.path, packageId: resolved.packageId };
37536 }
37537 function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
37538 var _a;
37539 if (resultFromCache) {
37540 (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
37541 return resultFromCache;
37542 }
37543 return {
37544 resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
37545 failedLookupLocations: failedLookupLocations
37546 };
37547 }
37548 function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
37549 if (!ts.hasProperty(jsonContent, fieldName)) {
37550 if (state.traceEnabled) {
37551 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
37552 }
37553 return;
37554 }
37555 var value = jsonContent[fieldName];
37556 if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
37557 if (state.traceEnabled) {
37558 // eslint-disable-next-line no-null/no-null
37559 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);
37560 }
37561 return;
37562 }
37563 return value;
37564 }
37565 function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
37566 var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
37567 if (fileName === undefined) {
37568 return;
37569 }
37570 if (!fileName) {
37571 if (state.traceEnabled) {
37572 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
37573 }
37574 return;
37575 }
37576 var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
37577 if (state.traceEnabled) {
37578 trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
37579 }
37580 return path;
37581 }
37582 function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
37583 return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
37584 || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
37585 }
37586 function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
37587 return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
37588 }
37589 function readPackageJsonMainField(jsonContent, baseDirectory, state) {
37590 return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
37591 }
37592 function readPackageJsonTypesVersionsField(jsonContent, state) {
37593 var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
37594 if (typesVersions === undefined)
37595 return;
37596 if (state.traceEnabled) {
37597 trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
37598 }
37599 return typesVersions;
37600 }
37601 function readPackageJsonTypesVersionPaths(jsonContent, state) {
37602 var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
37603 if (typesVersions === undefined)
37604 return;
37605 if (state.traceEnabled) {
37606 for (var key in typesVersions) {
37607 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
37608 trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
37609 }
37610 }
37611 }
37612 var result = getPackageJsonTypesVersionsPaths(typesVersions);
37613 if (!result) {
37614 if (state.traceEnabled) {
37615 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
37616 }
37617 return;
37618 }
37619 var bestVersionKey = result.version, bestVersionPaths = result.paths;
37620 if (typeof bestVersionPaths !== "object") {
37621 if (state.traceEnabled) {
37622 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
37623 }
37624 return;
37625 }
37626 return result;
37627 }
37628 var typeScriptVersion;
37629 /* @internal */
37630 function getPackageJsonTypesVersionsPaths(typesVersions) {
37631 if (!typeScriptVersion)
37632 typeScriptVersion = new ts.Version(ts.version);
37633 for (var key in typesVersions) {
37634 if (!ts.hasProperty(typesVersions, key))
37635 continue;
37636 var keyRange = ts.VersionRange.tryParse(key);
37637 if (keyRange === undefined) {
37638 continue;
37639 }
37640 // return the first entry whose range matches the current compiler version.
37641 if (keyRange.test(typeScriptVersion)) {
37642 return { version: key, paths: typesVersions[key] };
37643 }
37644 }
37645 }
37646 ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
37647 function getEffectiveTypeRoots(options, host) {
37648 if (options.typeRoots) {
37649 return options.typeRoots;
37650 }
37651 var currentDirectory;
37652 if (options.configFilePath) {
37653 currentDirectory = ts.getDirectoryPath(options.configFilePath);
37654 }
37655 else if (host.getCurrentDirectory) {
37656 currentDirectory = host.getCurrentDirectory();
37657 }
37658 if (currentDirectory !== undefined) {
37659 return getDefaultTypeRoots(currentDirectory, host);
37660 }
37661 }
37662 ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
37663 /**
37664 * Returns the path to every node_modules/@types directory from some ancestor directory.
37665 * Returns undefined if there are none.
37666 */
37667 function getDefaultTypeRoots(currentDirectory, host) {
37668 if (!host.directoryExists) {
37669 return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
37670 // And if it doesn't exist, tough.
37671 }
37672 var typeRoots;
37673 ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
37674 var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
37675 if (host.directoryExists(atTypes)) {
37676 (typeRoots || (typeRoots = [])).push(atTypes);
37677 }
37678 return undefined;
37679 });
37680 return typeRoots;
37681 }
37682 var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
37683 /**
37684 * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
37685 * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
37686 * is assumed to be the same as root directory of the project.
37687 */
37688 function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
37689 var traceEnabled = isTraceEnabled(options, host);
37690 if (redirectedReference) {
37691 options = redirectedReference.commandLine.options;
37692 }
37693 var failedLookupLocations = [];
37694 var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
37695 var typeRoots = getEffectiveTypeRoots(options, host);
37696 if (traceEnabled) {
37697 if (containingFile === undefined) {
37698 if (typeRoots === undefined) {
37699 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
37700 }
37701 else {
37702 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
37703 }
37704 }
37705 else {
37706 if (typeRoots === undefined) {
37707 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
37708 }
37709 else {
37710 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
37711 }
37712 }
37713 if (redirectedReference) {
37714 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
37715 }
37716 }
37717 var resolved = primaryLookup();
37718 var primary = true;
37719 if (!resolved) {
37720 resolved = secondaryLookup();
37721 primary = false;
37722 }
37723 var resolvedTypeReferenceDirective;
37724 if (resolved) {
37725 var fileName = resolved.fileName, packageId = resolved.packageId;
37726 var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
37727 if (traceEnabled) {
37728 if (packageId) {
37729 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);
37730 }
37731 else {
37732 trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
37733 }
37734 }
37735 resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
37736 }
37737 return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
37738 function primaryLookup() {
37739 // Check primary library paths
37740 if (typeRoots && typeRoots.length) {
37741 if (traceEnabled) {
37742 trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
37743 }
37744 return ts.firstDefined(typeRoots, function (typeRoot) {
37745 var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
37746 var candidateDirectory = ts.getDirectoryPath(candidate);
37747 var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
37748 if (!directoryExists && traceEnabled) {
37749 trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
37750 }
37751 return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
37752 });
37753 }
37754 else {
37755 if (traceEnabled) {
37756 trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
37757 }
37758 }
37759 }
37760 function secondaryLookup() {
37761 var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
37762 if (initialLocationForSecondaryLookup !== undefined) {
37763 // check secondary locations
37764 if (traceEnabled) {
37765 trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
37766 }
37767 var result = void 0;
37768 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
37769 var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
37770 result = searchResult && searchResult.value;
37771 }
37772 else {
37773 var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
37774 result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
37775 }
37776 var resolvedFile = resolvedTypeScriptOnly(result);
37777 if (!resolvedFile && traceEnabled) {
37778 trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
37779 }
37780 return resolvedFile;
37781 }
37782 else {
37783 if (traceEnabled) {
37784 trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
37785 }
37786 }
37787 }
37788 }
37789 ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
37790 /**
37791 * Given a set of options, returns the set of type directive names
37792 * that should be included for this program automatically.
37793 * This list could either come from the config file,
37794 * or from enumerating the types root + initial secondary types lookup location.
37795 * More type directives might appear in the program later as a result of loading actual source files;
37796 * this list is only the set of defaults that are implicitly included.
37797 */
37798 function getAutomaticTypeDirectiveNames(options, host) {
37799 // Use explicit type list from tsconfig.json
37800 if (options.types) {
37801 return options.types;
37802 }
37803 // Walk the primary type lookup locations
37804 var result = [];
37805 if (host.directoryExists && host.getDirectories) {
37806 var typeRoots = getEffectiveTypeRoots(options, host);
37807 if (typeRoots) {
37808 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
37809 var root = typeRoots_1[_i];
37810 if (host.directoryExists(root)) {
37811 for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
37812 var typeDirectivePath = _b[_a];
37813 var normalized = ts.normalizePath(typeDirectivePath);
37814 var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
37815 // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
37816 // See `createNotNeededPackageJSON` in the types-publisher` repo.
37817 // eslint-disable-next-line no-null/no-null
37818 var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
37819 if (!isNotNeededPackage) {
37820 var baseFileName = ts.getBaseFileName(normalized);
37821 // At this stage, skip results with leading dot.
37822 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
37823 // Return just the type directive names
37824 result.push(baseFileName);
37825 }
37826 }
37827 }
37828 }
37829 }
37830 }
37831 }
37832 return result;
37833 }
37834 ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
37835 function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
37836 return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
37837 }
37838 ts.createModuleResolutionCache = createModuleResolutionCache;
37839 /*@internal*/
37840 function createCacheWithRedirects(options) {
37841 var ownMap = new ts.Map();
37842 var redirectsMap = new ts.Map();
37843 return {
37844 ownMap: ownMap,
37845 redirectsMap: redirectsMap,
37846 getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
37847 clear: clear,
37848 setOwnOptions: setOwnOptions,
37849 setOwnMap: setOwnMap
37850 };
37851 function setOwnOptions(newOptions) {
37852 options = newOptions;
37853 }
37854 function setOwnMap(newOwnMap) {
37855 ownMap = newOwnMap;
37856 }
37857 function getOrCreateMapOfCacheRedirects(redirectedReference) {
37858 if (!redirectedReference) {
37859 return ownMap;
37860 }
37861 var path = redirectedReference.sourceFile.path;
37862 var redirects = redirectsMap.get(path);
37863 if (!redirects) {
37864 // Reuse map if redirected reference map uses same resolution
37865 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
37866 redirectsMap.set(path, redirects);
37867 }
37868 return redirects;
37869 }
37870 function clear() {
37871 ownMap.clear();
37872 redirectsMap.clear();
37873 }
37874 }
37875 ts.createCacheWithRedirects = createCacheWithRedirects;
37876 /*@internal*/
37877 function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
37878 return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
37879 function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
37880 var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
37881 return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); });
37882 }
37883 function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
37884 ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
37885 return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
37886 }
37887 function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
37888 var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
37889 var result = cache.get(key);
37890 if (!result) {
37891 result = create();
37892 cache.set(key, result);
37893 }
37894 return result;
37895 }
37896 function createPerModuleNameCache() {
37897 var directoryPathMap = new ts.Map();
37898 return { get: get, set: set };
37899 function get(directory) {
37900 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
37901 }
37902 /**
37903 * At first this function add entry directory -> module resolution result to the table.
37904 * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
37905 * and for every parent folder in set it adds entry: parent -> module resolution. .
37906 * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
37907 * Set of parent folders that should have the same result will be:
37908 * [
37909 * /a/b/c/d, /a/b/c, /a/b
37910 * ]
37911 * this means that request for module resolution from file in any of these folder will be immediately found in cache.
37912 */
37913 function set(directory, result) {
37914 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
37915 // if entry is already in cache do nothing
37916 if (directoryPathMap.has(path)) {
37917 return;
37918 }
37919 directoryPathMap.set(path, result);
37920 var resolvedFileName = result.resolvedModule &&
37921 (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
37922 // find common prefix between directory and resolved file name
37923 // this common prefix should be the shortest path that has the same resolution
37924 // directory: /a/b/c/d/e
37925 // resolvedFileName: /a/b/foo.d.ts
37926 // commonPrefix: /a/b
37927 // for failed lookups cache the result for every directory up to root
37928 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
37929 var current = path;
37930 while (current !== commonPrefix) {
37931 var parent = ts.getDirectoryPath(current);
37932 if (parent === current || directoryPathMap.has(parent)) {
37933 break;
37934 }
37935 directoryPathMap.set(parent, result);
37936 current = parent;
37937 }
37938 }
37939 function getCommonPrefix(directory, resolution) {
37940 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
37941 // find first position where directory and resolution differs
37942 var i = 0;
37943 var limit = Math.min(directory.length, resolutionDirectory.length);
37944 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
37945 i++;
37946 }
37947 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
37948 return directory;
37949 }
37950 var rootLength = ts.getRootLength(directory);
37951 if (i < rootLength) {
37952 return undefined;
37953 }
37954 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
37955 if (sep === -1) {
37956 return undefined;
37957 }
37958 return directory.substr(0, Math.max(sep, rootLength));
37959 }
37960 }
37961 }
37962 ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
37963 function resolveModuleNameFromCache(moduleName, containingFile, cache) {
37964 var containingDirectory = ts.getDirectoryPath(containingFile);
37965 var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
37966 return perFolderCache && perFolderCache.get(moduleName);
37967 }
37968 ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
37969 function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
37970 var traceEnabled = isTraceEnabled(compilerOptions, host);
37971 if (redirectedReference) {
37972 compilerOptions = redirectedReference.commandLine.options;
37973 }
37974 if (traceEnabled) {
37975 trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
37976 if (redirectedReference) {
37977 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
37978 }
37979 }
37980 var containingDirectory = ts.getDirectoryPath(containingFile);
37981 var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
37982 var result = perFolderCache && perFolderCache.get(moduleName);
37983 if (result) {
37984 if (traceEnabled) {
37985 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
37986 }
37987 }
37988 else {
37989 var moduleResolution = compilerOptions.moduleResolution;
37990 if (moduleResolution === undefined) {
37991 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
37992 if (traceEnabled) {
37993 trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
37994 }
37995 }
37996 else {
37997 if (traceEnabled) {
37998 trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
37999 }
38000 }
38001 ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
38002 switch (moduleResolution) {
38003 case ts.ModuleResolutionKind.NodeJs:
38004 result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38005 break;
38006 case ts.ModuleResolutionKind.Classic:
38007 result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38008 break;
38009 default:
38010 return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
38011 }
38012 if (result && result.resolvedModule)
38013 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
38014 ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
38015 if (perFolderCache) {
38016 perFolderCache.set(moduleName, result);
38017 if (!ts.isExternalModuleNameRelative(moduleName)) {
38018 // put result in per-module name cache
38019 cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
38020 }
38021 }
38022 }
38023 if (traceEnabled) {
38024 if (result.resolvedModule) {
38025 if (result.resolvedModule.packageId) {
38026 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));
38027 }
38028 else {
38029 trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
38030 }
38031 }
38032 else {
38033 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
38034 }
38035 }
38036 return result;
38037 }
38038 ts.resolveModuleName = resolveModuleName;
38039 /**
38040 * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
38041 * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
38042 * can be resolved successfully by TypeScript compiler and runtime module loader.
38043 * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
38044 * fallback to standard resolution routine.
38045 *
38046 * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
38047 * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
38048 * be '/a/b/c/d'
38049 * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
38050 * will be resolved based on the content of the module name.
38051 * Structure of 'paths' compiler options
38052 * 'paths': {
38053 * pattern-1: [...substitutions],
38054 * pattern-2: [...substitutions],
38055 * ...
38056 * pattern-n: [...substitutions]
38057 * }
38058 * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
38059 * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
38060 * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
38061 * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
38062 * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
38063 * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
38064 * from the candidate location.
38065 * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
38066 * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
38067 * will be converted to absolute using baseUrl.
38068 * For example:
38069 * baseUrl: /a/b/c
38070 * "paths": {
38071 * // match all module names
38072 * "*": [
38073 * "*", // use matched name as is,
38074 * // <matched name> will be looked as /a/b/c/<matched name>
38075 *
38076 * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
38077 * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
38078 * ],
38079 * // match module names that start with 'components/'
38080 * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
38081 * // it is rooted so it will be final candidate location
38082 * }
38083 *
38084 * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
38085 * they were in the same location. For example lets say there are two files
38086 * '/local/src/content/file1.ts'
38087 * '/shared/components/contracts/src/content/protocols/file2.ts'
38088 * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
38089 * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
38090 * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
38091 * root dirs were merged together.
38092 * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
38093 * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
38094 * '/local/src/content/protocols/file2' and try to load it - failure.
38095 * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
38096 * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
38097 * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
38098 */
38099 function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
38100 var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
38101 if (resolved)
38102 return resolved.value;
38103 if (!ts.isExternalModuleNameRelative(moduleName)) {
38104 return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
38105 }
38106 else {
38107 return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
38108 }
38109 }
38110 function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
38111 var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
38112 if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
38113 if (state.traceEnabled) {
38114 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
38115 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
38116 }
38117 return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
38118 }
38119 }
38120 function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
38121 if (!state.compilerOptions.rootDirs) {
38122 return undefined;
38123 }
38124 if (state.traceEnabled) {
38125 trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
38126 }
38127 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
38128 var matchedRootDir;
38129 var matchedNormalizedPrefix;
38130 for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
38131 var rootDir = _a[_i];
38132 // rootDirs are expected to be absolute
38133 // in case of tsconfig.json this will happen automatically - compiler will expand relative names
38134 // using location of tsconfig.json as base location
38135 var normalizedRoot = ts.normalizePath(rootDir);
38136 if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
38137 normalizedRoot += ts.directorySeparator;
38138 }
38139 var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
38140 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
38141 if (state.traceEnabled) {
38142 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
38143 }
38144 if (isLongestMatchingPrefix) {
38145 matchedNormalizedPrefix = normalizedRoot;
38146 matchedRootDir = rootDir;
38147 }
38148 }
38149 if (matchedNormalizedPrefix) {
38150 if (state.traceEnabled) {
38151 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
38152 }
38153 var suffix = candidate.substr(matchedNormalizedPrefix.length);
38154 // first - try to load from a initial location
38155 if (state.traceEnabled) {
38156 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
38157 }
38158 var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
38159 if (resolvedFileName) {
38160 return resolvedFileName;
38161 }
38162 if (state.traceEnabled) {
38163 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
38164 }
38165 // then try to resolve using remaining entries in rootDirs
38166 for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
38167 var rootDir = _c[_b];
38168 if (rootDir === matchedRootDir) {
38169 // skip the initially matched entry
38170 continue;
38171 }
38172 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
38173 if (state.traceEnabled) {
38174 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
38175 }
38176 var baseDirectory = ts.getDirectoryPath(candidate_1);
38177 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
38178 if (resolvedFileName_1) {
38179 return resolvedFileName_1;
38180 }
38181 }
38182 if (state.traceEnabled) {
38183 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
38184 }
38185 }
38186 return undefined;
38187 }
38188 function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
38189 var baseUrl = state.compilerOptions.baseUrl;
38190 if (!baseUrl) {
38191 return undefined;
38192 }
38193 if (state.traceEnabled) {
38194 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
38195 }
38196 var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
38197 if (state.traceEnabled) {
38198 trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
38199 }
38200 return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
38201 }
38202 /**
38203 * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
38204 * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
38205 * Throws an error if the module can't be resolved.
38206 */
38207 /* @internal */
38208 function resolveJSModule(moduleName, initialDir, host) {
38209 var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
38210 if (!resolvedModule) {
38211 throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
38212 }
38213 return resolvedModule.resolvedFileName;
38214 }
38215 ts.resolveJSModule = resolveJSModule;
38216 /* @internal */
38217 function tryResolveJSModule(moduleName, initialDir, host) {
38218 var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
38219 return resolvedModule && resolvedModule.resolvedFileName;
38220 }
38221 ts.tryResolveJSModule = tryResolveJSModule;
38222 var jsOnlyExtensions = [Extensions.JavaScript];
38223 var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
38224 var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
38225 var tsconfigExtensions = [Extensions.TSConfig];
38226 function tryResolveJSModuleWorker(moduleName, initialDir, host) {
38227 return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
38228 }
38229 function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
38230 return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
38231 }
38232 ts.nodeModuleNameResolver = nodeModuleNameResolver;
38233 function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
38234 var _a, _b;
38235 var traceEnabled = isTraceEnabled(compilerOptions, host);
38236 var failedLookupLocations = [];
38237 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
38238 var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
38239 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);
38240 function tryResolve(extensions) {
38241 var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
38242 var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
38243 if (resolved) {
38244 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
38245 }
38246 if (!ts.isExternalModuleNameRelative(moduleName)) {
38247 if (traceEnabled) {
38248 trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
38249 }
38250 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
38251 if (!resolved_1)
38252 return undefined;
38253 var resolvedValue = resolved_1.value;
38254 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
38255 var path = realPath(resolvedValue.path, host, traceEnabled);
38256 var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
38257 resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
38258 }
38259 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
38260 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
38261 }
38262 else {
38263 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
38264 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
38265 // Treat explicit "node_modules" import as an external library import.
38266 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
38267 }
38268 }
38269 }
38270 function realPath(path, host, traceEnabled) {
38271 if (!host.realpath) {
38272 return path;
38273 }
38274 var real = ts.normalizePath(host.realpath(path));
38275 if (traceEnabled) {
38276 trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
38277 }
38278 ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
38279 return real;
38280 }
38281 function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
38282 if (state.traceEnabled) {
38283 trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
38284 }
38285 if (!ts.hasTrailingDirectorySeparator(candidate)) {
38286 if (!onlyRecordFailures) {
38287 var parentOfCandidate = ts.getDirectoryPath(candidate);
38288 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
38289 if (state.traceEnabled) {
38290 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
38291 }
38292 onlyRecordFailures = true;
38293 }
38294 }
38295 var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
38296 if (resolvedFromFile) {
38297 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
38298 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
38299 return withPackageId(packageInfo, resolvedFromFile);
38300 }
38301 }
38302 if (!onlyRecordFailures) {
38303 var candidateExists = ts.directoryProbablyExists(candidate, state.host);
38304 if (!candidateExists) {
38305 if (state.traceEnabled) {
38306 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
38307 }
38308 onlyRecordFailures = true;
38309 }
38310 }
38311 return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
38312 }
38313 /*@internal*/
38314 ts.nodeModulesPathPart = "/node_modules/";
38315 /*@internal*/
38316 function pathContainsNodeModules(path) {
38317 return ts.stringContains(path, ts.nodeModulesPathPart);
38318 }
38319 ts.pathContainsNodeModules = pathContainsNodeModules;
38320 /**
38321 * This will be called on the successfully resolved path from `loadModuleFromFile`.
38322 * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
38323 *
38324 * packageDirectory is the directory of the package itself.
38325 * For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
38326 * For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
38327 * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
38328 * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
38329 */
38330 function parseNodeModuleFromPath(resolved) {
38331 var path = ts.normalizePath(resolved.path);
38332 var idx = path.lastIndexOf(ts.nodeModulesPathPart);
38333 if (idx === -1) {
38334 return undefined;
38335 }
38336 var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
38337 var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
38338 if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
38339 indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
38340 }
38341 return path.slice(0, indexAfterPackageName);
38342 }
38343 function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
38344 var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
38345 return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
38346 }
38347 function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
38348 return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
38349 }
38350 /**
38351 * @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
38352 * 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.
38353 */
38354 function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
38355 if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
38356 var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
38357 return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
38358 }
38359 // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
38360 var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
38361 if (resolvedByAddingExtension) {
38362 return resolvedByAddingExtension;
38363 }
38364 // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
38365 // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
38366 if (ts.hasJSFileExtension(candidate)) {
38367 var extensionless = ts.removeFileExtension(candidate);
38368 if (state.traceEnabled) {
38369 var extension = candidate.substring(extensionless.length);
38370 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
38371 }
38372 return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
38373 }
38374 }
38375 /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
38376 function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
38377 if (!onlyRecordFailures) {
38378 // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
38379 var directory = ts.getDirectoryPath(candidate);
38380 if (directory) {
38381 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
38382 }
38383 }
38384 switch (extensions) {
38385 case Extensions.DtsOnly:
38386 return tryExtension(".d.ts" /* Dts */);
38387 case Extensions.TypeScript:
38388 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
38389 case Extensions.JavaScript:
38390 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
38391 case Extensions.TSConfig:
38392 case Extensions.Json:
38393 return tryExtension(".json" /* Json */);
38394 }
38395 function tryExtension(ext) {
38396 var path = tryFile(candidate + ext, onlyRecordFailures, state);
38397 return path === undefined ? undefined : { path: path, ext: ext };
38398 }
38399 }
38400 /** Return the file if it exists. */
38401 function tryFile(fileName, onlyRecordFailures, state) {
38402 if (!onlyRecordFailures) {
38403 if (state.host.fileExists(fileName)) {
38404 if (state.traceEnabled) {
38405 trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
38406 }
38407 return fileName;
38408 }
38409 else {
38410 if (state.traceEnabled) {
38411 trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
38412 }
38413 }
38414 }
38415 state.failedLookupLocations.push(fileName);
38416 return undefined;
38417 }
38418 function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
38419 if (considerPackageJson === void 0) { considerPackageJson = true; }
38420 var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
38421 var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
38422 var versionPaths = packageInfo && packageInfo.versionPaths;
38423 return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
38424 }
38425 function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
38426 var host = state.host, traceEnabled = state.traceEnabled;
38427 var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
38428 var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
38429 if (directoryExists && host.fileExists(packageJsonPath)) {
38430 var packageJsonContent = ts.readJson(packageJsonPath, host);
38431 if (traceEnabled) {
38432 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
38433 }
38434 var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
38435 return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
38436 }
38437 else {
38438 if (directoryExists && traceEnabled) {
38439 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
38440 }
38441 // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
38442 state.failedLookupLocations.push(packageJsonPath);
38443 }
38444 }
38445 function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
38446 var packageFile;
38447 if (jsonContent) {
38448 switch (extensions) {
38449 case Extensions.JavaScript:
38450 case Extensions.Json:
38451 packageFile = readPackageJsonMainField(jsonContent, candidate, state);
38452 break;
38453 case Extensions.TypeScript:
38454 // When resolving typescript modules, try resolving using main field as well
38455 packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
38456 break;
38457 case Extensions.DtsOnly:
38458 packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
38459 break;
38460 case Extensions.TSConfig:
38461 packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
38462 break;
38463 default:
38464 return ts.Debug.assertNever(extensions);
38465 }
38466 }
38467 var loader = function (extensions, candidate, onlyRecordFailures, state) {
38468 var fromFile = tryFile(candidate, onlyRecordFailures, state);
38469 if (fromFile) {
38470 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
38471 if (resolved) {
38472 return noPackageId(resolved);
38473 }
38474 if (state.traceEnabled) {
38475 trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
38476 }
38477 }
38478 // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
38479 var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
38480 // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
38481 return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
38482 };
38483 var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
38484 var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
38485 var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
38486 if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
38487 var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
38488 if (state.traceEnabled) {
38489 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);
38490 }
38491 var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
38492 if (result) {
38493 return removeIgnoredPackageId(result.value);
38494 }
38495 }
38496 // It won't have a `packageId` set, because we disabled `considerPackageJson`.
38497 var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
38498 if (packageFileResult)
38499 return packageFileResult;
38500 return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
38501 }
38502 /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
38503 function resolvedIfExtensionMatches(extensions, path) {
38504 var ext = ts.tryGetExtensionFromPath(path);
38505 return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
38506 }
38507 /** True if `extension` is one of the supported `extensions`. */
38508 function extensionIsOk(extensions, extension) {
38509 switch (extensions) {
38510 case Extensions.JavaScript:
38511 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
38512 case Extensions.TSConfig:
38513 case Extensions.Json:
38514 return extension === ".json" /* Json */;
38515 case Extensions.TypeScript:
38516 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
38517 case Extensions.DtsOnly:
38518 return extension === ".d.ts" /* Dts */;
38519 }
38520 }
38521 /* @internal */
38522 function parsePackageName(moduleName) {
38523 var idx = moduleName.indexOf(ts.directorySeparator);
38524 if (moduleName[0] === "@") {
38525 idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
38526 }
38527 return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
38528 }
38529 ts.parsePackageName = parsePackageName;
38530 function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
38531 return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
38532 }
38533 function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
38534 // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
38535 return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
38536 }
38537 function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
38538 var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
38539 return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
38540 if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
38541 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
38542 if (resolutionFromCache) {
38543 return resolutionFromCache;
38544 }
38545 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
38546 }
38547 });
38548 }
38549 function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
38550 var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
38551 var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
38552 if (!nodeModulesFolderExists && state.traceEnabled) {
38553 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
38554 }
38555 var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
38556 if (packageResult) {
38557 return packageResult;
38558 }
38559 if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
38560 var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
38561 var nodeModulesAtTypesExists = nodeModulesFolderExists;
38562 if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
38563 if (state.traceEnabled) {
38564 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
38565 }
38566 nodeModulesAtTypesExists = false;
38567 }
38568 return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
38569 }
38570 }
38571 function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
38572 var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
38573 // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
38574 var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
38575 if (packageInfo) {
38576 var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
38577 if (fromFile) {
38578 return noPackageId(fromFile);
38579 }
38580 var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
38581 return withPackageId(packageInfo, fromDirectory);
38582 }
38583 var loader = function (extensions, candidate, onlyRecordFailures, state) {
38584 var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
38585 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
38586 return withPackageId(packageInfo, pathAndExtension);
38587 };
38588 var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
38589 if (rest !== "") { // If "rest" is empty, we just did this search above.
38590 var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
38591 // 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.
38592 packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
38593 if (packageInfo && packageInfo.versionPaths) {
38594 if (state.traceEnabled) {
38595 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);
38596 }
38597 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
38598 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
38599 if (fromPaths) {
38600 return fromPaths.value;
38601 }
38602 }
38603 }
38604 return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
38605 }
38606 function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
38607 var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
38608 if (matchedPattern) {
38609 var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
38610 var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
38611 if (state.traceEnabled) {
38612 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
38613 }
38614 var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
38615 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
38616 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
38617 if (state.traceEnabled) {
38618 trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
38619 }
38620 // A path mapping may have an extension, in contrast to an import, which should omit it.
38621 var extension = ts.tryGetExtensionFromPath(candidate);
38622 if (extension !== undefined) {
38623 var path_1 = tryFile(candidate, onlyRecordFailures, state);
38624 if (path_1 !== undefined) {
38625 return noPackageId({ path: path_1, ext: extension });
38626 }
38627 }
38628 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
38629 });
38630 return { value: resolved };
38631 }
38632 }
38633 /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
38634 var mangledScopedPackageSeparator = "__";
38635 /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
38636 function mangleScopedPackageNameWithTrace(packageName, state) {
38637 var mangled = mangleScopedPackageName(packageName);
38638 if (state.traceEnabled && mangled !== packageName) {
38639 trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
38640 }
38641 return mangled;
38642 }
38643 /* @internal */
38644 function getTypesPackageName(packageName) {
38645 return "@types/" + mangleScopedPackageName(packageName);
38646 }
38647 ts.getTypesPackageName = getTypesPackageName;
38648 /* @internal */
38649 function mangleScopedPackageName(packageName) {
38650 if (ts.startsWith(packageName, "@")) {
38651 var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
38652 if (replaceSlash !== packageName) {
38653 return replaceSlash.slice(1); // Take off the "@"
38654 }
38655 }
38656 return packageName;
38657 }
38658 ts.mangleScopedPackageName = mangleScopedPackageName;
38659 /* @internal */
38660 function getPackageNameFromTypesPackageName(mangledName) {
38661 var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
38662 if (withoutAtTypePrefix !== mangledName) {
38663 return unmangleScopedPackageName(withoutAtTypePrefix);
38664 }
38665 return mangledName;
38666 }
38667 ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
38668 /* @internal */
38669 function unmangleScopedPackageName(typesPackageName) {
38670 return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
38671 "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
38672 typesPackageName;
38673 }
38674 ts.unmangleScopedPackageName = unmangleScopedPackageName;
38675 function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
38676 var result = cache && cache.get(containingDirectory);
38677 if (result) {
38678 if (state.traceEnabled) {
38679 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
38680 }
38681 state.resultFromCache = result;
38682 return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
38683 }
38684 }
38685 function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
38686 var traceEnabled = isTraceEnabled(compilerOptions, host);
38687 var failedLookupLocations = [];
38688 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
38689 var containingDirectory = ts.getDirectoryPath(containingFile);
38690 var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
38691 // No originalPath because classic resolution doesn't resolve realPath
38692 return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
38693 function tryResolve(extensions) {
38694 var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
38695 if (resolvedUsingSettings) {
38696 return { value: resolvedUsingSettings };
38697 }
38698 if (!ts.isExternalModuleNameRelative(moduleName)) {
38699 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
38700 // Climb up parent directories looking for a module.
38701 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
38702 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
38703 if (resolutionFromCache) {
38704 return resolutionFromCache;
38705 }
38706 var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
38707 return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
38708 });
38709 if (resolved_3) {
38710 return resolved_3;
38711 }
38712 if (extensions === Extensions.TypeScript) {
38713 // If we didn't find the file normally, look it up in @types.
38714 return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
38715 }
38716 }
38717 else {
38718 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
38719 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
38720 }
38721 }
38722 }
38723 ts.classicNameResolver = classicNameResolver;
38724 /**
38725 * A host may load a module from a global cache of typings.
38726 * This is the minumum code needed to expose that functionality; the rest is in the host.
38727 */
38728 /* @internal */
38729 function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
38730 var traceEnabled = isTraceEnabled(compilerOptions, host);
38731 if (traceEnabled) {
38732 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);
38733 }
38734 var failedLookupLocations = [];
38735 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
38736 var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
38737 return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
38738 }
38739 ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
38740 /**
38741 * Wraps value to SearchResult.
38742 * @returns undefined if value is undefined or { value } otherwise
38743 */
38744 function toSearchResult(value) {
38745 return value !== undefined ? { value: value } : undefined;
38746 }
38747})(ts || (ts = {}));
38748/* @internal */
38749var ts;
38750(function (ts) {
38751 var ModuleInstanceState;
38752 (function (ModuleInstanceState) {
38753 ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
38754 ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
38755 ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
38756 })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
38757 function getModuleInstanceState(node, visited) {
38758 if (node.body && !node.body.parent) {
38759 // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
38760 ts.setParent(node.body, node);
38761 ts.setParentRecursive(node.body, /*incremental*/ false);
38762 }
38763 return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
38764 }
38765 ts.getModuleInstanceState = getModuleInstanceState;
38766 function getModuleInstanceStateCached(node, visited) {
38767 if (visited === void 0) { visited = new ts.Map(); }
38768 var nodeId = ts.getNodeId(node);
38769 if (visited.has(nodeId)) {
38770 return visited.get(nodeId) || 0 /* NonInstantiated */;
38771 }
38772 visited.set(nodeId, undefined);
38773 var result = getModuleInstanceStateWorker(node, visited);
38774 visited.set(nodeId, result);
38775 return result;
38776 }
38777 function getModuleInstanceStateWorker(node, visited) {
38778 // A module is uninstantiated if it contains only
38779 switch (node.kind) {
38780 // 1. interface declarations, type alias declarations
38781 case 250 /* InterfaceDeclaration */:
38782 case 251 /* TypeAliasDeclaration */:
38783 return 0 /* NonInstantiated */;
38784 // 2. const enum declarations
38785 case 252 /* EnumDeclaration */:
38786 if (ts.isEnumConst(node)) {
38787 return 2 /* ConstEnumOnly */;
38788 }
38789 break;
38790 // 3. non-exported import declarations
38791 case 258 /* ImportDeclaration */:
38792 case 257 /* ImportEqualsDeclaration */:
38793 if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
38794 return 0 /* NonInstantiated */;
38795 }
38796 break;
38797 // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
38798 case 264 /* ExportDeclaration */:
38799 var exportDeclaration = node;
38800 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 265 /* NamedExports */) {
38801 var state = 0 /* NonInstantiated */;
38802 for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
38803 var specifier = _a[_i];
38804 var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
38805 if (specifierState > state) {
38806 state = specifierState;
38807 }
38808 if (state === 1 /* Instantiated */) {
38809 return state;
38810 }
38811 }
38812 return state;
38813 }
38814 break;
38815 // 5. other uninstantiated module declarations.
38816 case 254 /* ModuleBlock */: {
38817 var state_1 = 0 /* NonInstantiated */;
38818 ts.forEachChild(node, function (n) {
38819 var childState = getModuleInstanceStateCached(n, visited);
38820 switch (childState) {
38821 case 0 /* NonInstantiated */:
38822 // child is non-instantiated - continue searching
38823 return;
38824 case 2 /* ConstEnumOnly */:
38825 // child is const enum only - record state and continue searching
38826 state_1 = 2 /* ConstEnumOnly */;
38827 return;
38828 case 1 /* Instantiated */:
38829 // child is instantiated - record state and stop
38830 state_1 = 1 /* Instantiated */;
38831 return true;
38832 default:
38833 ts.Debug.assertNever(childState);
38834 }
38835 });
38836 return state_1;
38837 }
38838 case 253 /* ModuleDeclaration */:
38839 return getModuleInstanceState(node, visited);
38840 case 78 /* Identifier */:
38841 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
38842 // be considered the same as type alias
38843 if (node.isInJSDocNamespace) {
38844 return 0 /* NonInstantiated */;
38845 }
38846 }
38847 return 1 /* Instantiated */;
38848 }
38849 function getModuleInstanceStateForAliasTarget(specifier, visited) {
38850 var name = specifier.propertyName || specifier.name;
38851 var p = specifier.parent;
38852 while (p) {
38853 if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
38854 var statements = p.statements;
38855 var found = void 0;
38856 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
38857 var statement = statements_2[_i];
38858 if (ts.nodeHasName(statement, name)) {
38859 if (!statement.parent) {
38860 ts.setParent(statement, p);
38861 ts.setParentRecursive(statement, /*incremental*/ false);
38862 }
38863 var state = getModuleInstanceStateCached(statement, visited);
38864 if (found === undefined || state > found) {
38865 found = state;
38866 }
38867 if (found === 1 /* Instantiated */) {
38868 return found;
38869 }
38870 }
38871 }
38872 if (found !== undefined) {
38873 return found;
38874 }
38875 }
38876 p = p.parent;
38877 }
38878 return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
38879 }
38880 var ContainerFlags;
38881 (function (ContainerFlags) {
38882 // The current node is not a container, and no container manipulation should happen before
38883 // recursing into it.
38884 ContainerFlags[ContainerFlags["None"] = 0] = "None";
38885 // The current node is a container. It should be set as the current container (and block-
38886 // container) before recursing into it. The current node does not have locals. Examples:
38887 //
38888 // Classes, ObjectLiterals, TypeLiterals, Interfaces...
38889 ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
38890 // The current node is a block-scoped-container. It should be set as the current block-
38891 // container before recursing into it. Examples:
38892 //
38893 // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
38894 ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
38895 // The current node is the container of a control flow path. The current control flow should
38896 // be saved and restored, and a new control flow initialized within the container.
38897 ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
38898 ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
38899 ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
38900 ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
38901 ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
38902 ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
38903 })(ContainerFlags || (ContainerFlags = {}));
38904 function initFlowNode(node) {
38905 ts.Debug.attachFlowNodeDebugInfo(node);
38906 return node;
38907 }
38908 var binder = createBinder();
38909 function bindSourceFile(file, options) {
38910 ts.performance.mark("beforeBind");
38911 ts.perfLogger.logStartBindFile("" + file.fileName);
38912 binder(file, options);
38913 ts.perfLogger.logStopBindFile();
38914 ts.performance.mark("afterBind");
38915 ts.performance.measure("Bind", "beforeBind", "afterBind");
38916 }
38917 ts.bindSourceFile = bindSourceFile;
38918 function createBinder() {
38919 var file;
38920 var options;
38921 var languageVersion;
38922 var parent;
38923 var container;
38924 var thisParentContainer; // Container one level up
38925 var blockScopeContainer;
38926 var lastContainer;
38927 var delayedTypeAliases;
38928 var seenThisKeyword;
38929 // state used by control flow analysis
38930 var currentFlow;
38931 var currentBreakTarget;
38932 var currentContinueTarget;
38933 var currentReturnTarget;
38934 var currentTrueTarget;
38935 var currentFalseTarget;
38936 var currentExceptionTarget;
38937 var preSwitchCaseFlow;
38938 var activeLabelList;
38939 var hasExplicitReturn;
38940 // state used for emit helpers
38941 var emitFlags;
38942 // If this file is an external module, then it is automatically in strict-mode according to
38943 // ES6. If it is not an external module, then we'll determine if it is in strict mode or
38944 // not depending on if we see "use strict" in certain places or if we hit a class/namespace
38945 // or if compiler options contain alwaysStrict.
38946 var inStrictMode;
38947 var symbolCount = 0;
38948 var Symbol;
38949 var classifiableNames;
38950 var unreachableFlow = { flags: 1 /* Unreachable */ };
38951 var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
38952 /**
38953 * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
38954 * 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)
38955 * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
38956 */
38957 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
38958 return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
38959 }
38960 function bindSourceFile(f, opts) {
38961 file = f;
38962 options = opts;
38963 languageVersion = ts.getEmitScriptTarget(options);
38964 inStrictMode = bindInStrictMode(file, opts);
38965 classifiableNames = new ts.Set();
38966 symbolCount = 0;
38967 Symbol = ts.objectAllocator.getSymbolConstructor();
38968 // Attach debugging information if necessary
38969 ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
38970 ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
38971 if (!file.locals) {
38972 bind(file);
38973 file.symbolCount = symbolCount;
38974 file.classifiableNames = classifiableNames;
38975 delayedBindJSDocTypedefTag();
38976 }
38977 file = undefined;
38978 options = undefined;
38979 languageVersion = undefined;
38980 parent = undefined;
38981 container = undefined;
38982 thisParentContainer = undefined;
38983 blockScopeContainer = undefined;
38984 lastContainer = undefined;
38985 delayedTypeAliases = undefined;
38986 seenThisKeyword = false;
38987 currentFlow = undefined;
38988 currentBreakTarget = undefined;
38989 currentContinueTarget = undefined;
38990 currentReturnTarget = undefined;
38991 currentTrueTarget = undefined;
38992 currentFalseTarget = undefined;
38993 currentExceptionTarget = undefined;
38994 activeLabelList = undefined;
38995 hasExplicitReturn = false;
38996 emitFlags = 0 /* None */;
38997 }
38998 return bindSourceFile;
38999 function bindInStrictMode(file, opts) {
39000 if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
39001 // bind in strict mode source files with alwaysStrict option
39002 return true;
39003 }
39004 else {
39005 return !!file.externalModuleIndicator;
39006 }
39007 }
39008 function createSymbol(flags, name) {
39009 symbolCount++;
39010 return new Symbol(flags, name);
39011 }
39012 function addDeclarationToSymbol(symbol, node, symbolFlags) {
39013 symbol.flags |= symbolFlags;
39014 node.symbol = symbol;
39015 symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
39016 if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
39017 symbol.exports = ts.createSymbolTable();
39018 }
39019 if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
39020 symbol.members = ts.createSymbolTable();
39021 }
39022 // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
39023 if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
39024 symbol.constEnumOnlyModule = false;
39025 }
39026 if (symbolFlags & 111551 /* Value */) {
39027 ts.setValueDeclaration(symbol, node);
39028 }
39029 }
39030 // Should not be called on a declaration with a computed property name,
39031 // unless it is a well known Symbol.
39032 function getDeclarationName(node) {
39033 if (node.kind === 263 /* ExportAssignment */) {
39034 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
39035 }
39036 var name = ts.getNameOfDeclaration(node);
39037 if (name) {
39038 if (ts.isAmbientModule(node)) {
39039 var moduleName = ts.getTextOfIdentifierOrLiteral(name);
39040 return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
39041 }
39042 if (name.kind === 157 /* ComputedPropertyName */) {
39043 var nameExpression = name.expression;
39044 // treat computed property names where expression is string/numeric literal as just string/numeric literal
39045 if (ts.isStringOrNumericLiteralLike(nameExpression)) {
39046 return ts.escapeLeadingUnderscores(nameExpression.text);
39047 }
39048 if (ts.isSignedNumericLiteral(nameExpression)) {
39049 return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
39050 }
39051 ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
39052 return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
39053 }
39054 if (ts.isWellKnownSymbolSyntactically(name)) {
39055 return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
39056 }
39057 if (ts.isPrivateIdentifier(name)) {
39058 // containingClass exists because private names only allowed inside classes
39059 var containingClass = ts.getContainingClass(node);
39060 if (!containingClass) {
39061 // we can get here in cases where there is already a parse error.
39062 return undefined;
39063 }
39064 var containingClassSymbol = containingClass.symbol;
39065 return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
39066 }
39067 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
39068 }
39069 switch (node.kind) {
39070 case 165 /* Constructor */:
39071 return "__constructor" /* Constructor */;
39072 case 173 /* FunctionType */:
39073 case 168 /* CallSignature */:
39074 case 309 /* JSDocSignature */:
39075 return "__call" /* Call */;
39076 case 174 /* ConstructorType */:
39077 case 169 /* ConstructSignature */:
39078 return "__new" /* New */;
39079 case 170 /* IndexSignature */:
39080 return "__index" /* Index */;
39081 case 264 /* ExportDeclaration */:
39082 return "__export" /* ExportStar */;
39083 case 294 /* SourceFile */:
39084 // json file should behave as
39085 // module.exports = ...
39086 return "export=" /* ExportEquals */;
39087 case 213 /* BinaryExpression */:
39088 if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
39089 // module.exports = ...
39090 return "export=" /* ExportEquals */;
39091 }
39092 ts.Debug.fail("Unknown binary declaration kind");
39093 break;
39094 case 304 /* JSDocFunctionType */:
39095 return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
39096 case 159 /* Parameter */:
39097 // Parameters with names are handled at the top of this function. Parameters
39098 // without names can only come from JSDocFunctionTypes.
39099 ts.Debug.assert(node.parent.kind === 304 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
39100 var functionType = node.parent;
39101 var index = functionType.parameters.indexOf(node);
39102 return "arg" + index;
39103 }
39104 }
39105 function getDisplayName(node) {
39106 return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
39107 }
39108 /**
39109 * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
39110 * @param symbolTable - The symbol table which node will be added to.
39111 * @param parent - node's parent declaration.
39112 * @param node - The declaration to be added to the symbol table
39113 * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
39114 * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
39115 */
39116 function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
39117 ts.Debug.assert(!ts.hasDynamicName(node));
39118 var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
39119 // The exported symbol for an export default function/class node is always named "default"
39120 var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
39121 var symbol;
39122 if (name === undefined) {
39123 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
39124 }
39125 else {
39126 // Check and see if the symbol table already has a symbol with this name. If not,
39127 // create a new symbol with this name and add it to the table. Note that we don't
39128 // give the new symbol any flags *yet*. This ensures that it will not conflict
39129 // with the 'excludes' flags we pass in.
39130 //
39131 // If we do get an existing symbol, see if it conflicts with the new symbol we're
39132 // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
39133 // the same symbol table. If we have a conflict, report the issue on each
39134 // declaration we have for this symbol, and then create a new symbol for this
39135 // declaration.
39136 //
39137 // Note that when properties declared in Javascript constructors
39138 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
39139 // Always. This allows the common Javascript pattern of overwriting a prototype method
39140 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
39141 //
39142 // If we created a new symbol, either because we didn't have a symbol with this name
39143 // in the symbol table, or we conflicted with an existing symbol, then just add this
39144 // node as the sole declaration of the new symbol.
39145 //
39146 // Otherwise, we'll be merging into a compatible existing symbol (for example when
39147 // you have multiple 'vars' with the same name in the same container). In this case
39148 // just add this node into the declarations list of the symbol.
39149 symbol = symbolTable.get(name);
39150 if (includes & 2885600 /* Classifiable */) {
39151 classifiableNames.add(name);
39152 }
39153 if (!symbol) {
39154 symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
39155 if (isReplaceableByMethod)
39156 symbol.isReplaceableByMethod = true;
39157 }
39158 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
39159 // A symbol already exists, so don't add this as a declaration.
39160 return symbol;
39161 }
39162 else if (symbol.flags & excludes) {
39163 if (symbol.isReplaceableByMethod) {
39164 // Javascript constructor-declared symbols can be discarded in favor of
39165 // prototype symbols like methods.
39166 symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
39167 }
39168 else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
39169 // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
39170 if (ts.isNamedDeclaration(node)) {
39171 ts.setParent(node.name, node);
39172 }
39173 // Report errors every position with duplicate declaration
39174 // Report errors on previous encountered declarations
39175 var message_1 = symbol.flags & 2 /* BlockScopedVariable */
39176 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
39177 : ts.Diagnostics.Duplicate_identifier_0;
39178 var messageNeedsName_1 = true;
39179 if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
39180 message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
39181 messageNeedsName_1 = false;
39182 }
39183 var multipleDefaultExports_1 = false;
39184 if (ts.length(symbol.declarations)) {
39185 // If the current node is a default export of some sort, then check if
39186 // there are any other default exports that we need to error on.
39187 // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
39188 if (isDefaultExport) {
39189 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
39190 messageNeedsName_1 = false;
39191 multipleDefaultExports_1 = true;
39192 }
39193 else {
39194 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
39195 // Error on multiple export default in the following case:
39196 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
39197 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
39198 if (symbol.declarations && symbol.declarations.length &&
39199 (node.kind === 263 /* ExportAssignment */ && !node.isExportEquals)) {
39200 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
39201 messageNeedsName_1 = false;
39202 multipleDefaultExports_1 = true;
39203 }
39204 }
39205 }
39206 var relatedInformation_1 = [];
39207 if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
39208 // export type T; - may have meant export type { T }?
39209 relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
39210 }
39211 var declarationName_1 = ts.getNameOfDeclaration(node) || node;
39212 ts.forEach(symbol.declarations, function (declaration, index) {
39213 var decl = ts.getNameOfDeclaration(declaration) || declaration;
39214 var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
39215 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);
39216 if (multipleDefaultExports_1) {
39217 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
39218 }
39219 });
39220 var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
39221 file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
39222 symbol = createSymbol(0 /* None */, name);
39223 }
39224 }
39225 }
39226 addDeclarationToSymbol(symbol, node, includes);
39227 if (symbol.parent) {
39228 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
39229 }
39230 else {
39231 symbol.parent = parent;
39232 }
39233 return symbol;
39234 }
39235 function declareModuleMember(node, symbolFlags, symbolExcludes) {
39236 var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
39237 if (symbolFlags & 2097152 /* Alias */) {
39238 if (node.kind === 267 /* ExportSpecifier */ || (node.kind === 257 /* ImportEqualsDeclaration */ && hasExportModifier)) {
39239 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
39240 }
39241 else {
39242 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
39243 }
39244 }
39245 else {
39246 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
39247 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
39248 //
39249 // 1. We treat locals and exports of the same name as mutually exclusive within a container.
39250 // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
39251 // with the same name in the same container.
39252 // TODO: Make this a more specific error and decouple it from the exclusion logic.
39253 // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
39254 // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
39255 // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
39256 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
39257 // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
39258 // and this case is specially handled. Module augmentations should only be merged with original module definition
39259 // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
39260 if (ts.isJSDocTypeAlias(node))
39261 ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
39262 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
39263 if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
39264 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
39265 }
39266 var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
39267 var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
39268 local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
39269 node.localSymbol = local;
39270 return local;
39271 }
39272 else {
39273 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
39274 }
39275 }
39276 }
39277 // All container nodes are kept on a linked list in declaration order. This list is used by
39278 // the getLocalNameOfContainer function in the type checker to validate that the local name
39279 // used for a container is unique.
39280 function bindContainer(node, containerFlags) {
39281 // Before we recurse into a node's children, we first save the existing parent, container
39282 // and block-container. Then after we pop out of processing the children, we restore
39283 // these saved values.
39284 var saveContainer = container;
39285 var saveThisParentContainer = thisParentContainer;
39286 var savedBlockScopeContainer = blockScopeContainer;
39287 // Depending on what kind of node this is, we may have to adjust the current container
39288 // and block-container. If the current node is a container, then it is automatically
39289 // considered the current block-container as well. Also, for containers that we know
39290 // may contain locals, we eagerly initialize the .locals field. We do this because
39291 // it's highly likely that the .locals will be needed to place some child in (for example,
39292 // a parameter, or variable declaration).
39293 //
39294 // However, we do not proactively create the .locals for block-containers because it's
39295 // totally normal and common for block-containers to never actually have a block-scoped
39296 // variable in them. We don't want to end up allocating an object for every 'block' we
39297 // run into when most of them won't be necessary.
39298 //
39299 // Finally, if this is a block-container, then we clear out any existing .locals object
39300 // it may contain within it. This happens in incremental scenarios. Because we can be
39301 // reusing a node from a previous compilation, that node may have had 'locals' created
39302 // for it. We must clear this so we don't accidentally move any stale data forward from
39303 // a previous compilation.
39304 if (containerFlags & 1 /* IsContainer */) {
39305 if (node.kind !== 206 /* ArrowFunction */) {
39306 thisParentContainer = container;
39307 }
39308 container = blockScopeContainer = node;
39309 if (containerFlags & 32 /* HasLocals */) {
39310 container.locals = ts.createSymbolTable();
39311 }
39312 addToContainerChain(container);
39313 }
39314 else if (containerFlags & 2 /* IsBlockScopedContainer */) {
39315 blockScopeContainer = node;
39316 blockScopeContainer.locals = undefined;
39317 }
39318 if (containerFlags & 4 /* IsControlFlowContainer */) {
39319 var saveCurrentFlow = currentFlow;
39320 var saveBreakTarget = currentBreakTarget;
39321 var saveContinueTarget = currentContinueTarget;
39322 var saveReturnTarget = currentReturnTarget;
39323 var saveExceptionTarget = currentExceptionTarget;
39324 var saveActiveLabelList = activeLabelList;
39325 var saveHasExplicitReturn = hasExplicitReturn;
39326 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
39327 !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
39328 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
39329 // similarly to break statements that exit to a label just past the statement body.
39330 if (!isIIFE) {
39331 currentFlow = initFlowNode({ flags: 2 /* Start */ });
39332 if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
39333 currentFlow.node = node;
39334 }
39335 }
39336 // We create a return control flow graph for IIFEs and constructors. For constructors
39337 // we use the return control flow graph in strict property initialization checks.
39338 currentReturnTarget = isIIFE || node.kind === 165 /* Constructor */ || (ts.isInJSFile && (node.kind === 248 /* FunctionDeclaration */ || node.kind === 205 /* FunctionExpression */)) ? createBranchLabel() : undefined;
39339 currentExceptionTarget = undefined;
39340 currentBreakTarget = undefined;
39341 currentContinueTarget = undefined;
39342 activeLabelList = undefined;
39343 hasExplicitReturn = false;
39344 bindChildren(node);
39345 // Reset all reachability check related flags on node (for incremental scenarios)
39346 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
39347 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
39348 node.flags |= 256 /* HasImplicitReturn */;
39349 if (hasExplicitReturn)
39350 node.flags |= 512 /* HasExplicitReturn */;
39351 node.endFlowNode = currentFlow;
39352 }
39353 if (node.kind === 294 /* SourceFile */) {
39354 node.flags |= emitFlags;
39355 }
39356 if (currentReturnTarget) {
39357 addAntecedent(currentReturnTarget, currentFlow);
39358 currentFlow = finishFlowLabel(currentReturnTarget);
39359 if (node.kind === 165 /* Constructor */ || (ts.isInJSFile && (node.kind === 248 /* FunctionDeclaration */ || node.kind === 205 /* FunctionExpression */))) {
39360 node.returnFlowNode = currentFlow;
39361 }
39362 }
39363 if (!isIIFE) {
39364 currentFlow = saveCurrentFlow;
39365 }
39366 currentBreakTarget = saveBreakTarget;
39367 currentContinueTarget = saveContinueTarget;
39368 currentReturnTarget = saveReturnTarget;
39369 currentExceptionTarget = saveExceptionTarget;
39370 activeLabelList = saveActiveLabelList;
39371 hasExplicitReturn = saveHasExplicitReturn;
39372 }
39373 else if (containerFlags & 64 /* IsInterface */) {
39374 seenThisKeyword = false;
39375 bindChildren(node);
39376 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
39377 }
39378 else {
39379 bindChildren(node);
39380 }
39381 container = saveContainer;
39382 thisParentContainer = saveThisParentContainer;
39383 blockScopeContainer = savedBlockScopeContainer;
39384 }
39385 function bindEachFunctionsFirst(nodes) {
39386 bindEach(nodes, function (n) { return n.kind === 248 /* FunctionDeclaration */ ? bind(n) : undefined; });
39387 bindEach(nodes, function (n) { return n.kind !== 248 /* FunctionDeclaration */ ? bind(n) : undefined; });
39388 }
39389 function bindEach(nodes, bindFunction) {
39390 if (bindFunction === void 0) { bindFunction = bind; }
39391 if (nodes === undefined) {
39392 return;
39393 }
39394 ts.forEach(nodes, bindFunction);
39395 }
39396 function bindEachChild(node) {
39397 ts.forEachChild(node, bind, bindEach);
39398 }
39399 function bindChildren(node) {
39400 if (checkUnreachable(node)) {
39401 bindEachChild(node);
39402 bindJSDoc(node);
39403 return;
39404 }
39405 if (node.kind >= 229 /* FirstStatement */ && node.kind <= 245 /* LastStatement */ && !options.allowUnreachableCode) {
39406 node.flowNode = currentFlow;
39407 }
39408 switch (node.kind) {
39409 case 233 /* WhileStatement */:
39410 bindWhileStatement(node);
39411 break;
39412 case 232 /* DoStatement */:
39413 bindDoStatement(node);
39414 break;
39415 case 234 /* ForStatement */:
39416 bindForStatement(node);
39417 break;
39418 case 235 /* ForInStatement */:
39419 case 236 /* ForOfStatement */:
39420 bindForInOrForOfStatement(node);
39421 break;
39422 case 231 /* IfStatement */:
39423 bindIfStatement(node);
39424 break;
39425 case 239 /* ReturnStatement */:
39426 case 243 /* ThrowStatement */:
39427 bindReturnOrThrow(node);
39428 break;
39429 case 238 /* BreakStatement */:
39430 case 237 /* ContinueStatement */:
39431 bindBreakOrContinueStatement(node);
39432 break;
39433 case 244 /* TryStatement */:
39434 bindTryStatement(node);
39435 break;
39436 case 241 /* SwitchStatement */:
39437 bindSwitchStatement(node);
39438 break;
39439 case 255 /* CaseBlock */:
39440 bindCaseBlock(node);
39441 break;
39442 case 281 /* CaseClause */:
39443 bindCaseClause(node);
39444 break;
39445 case 230 /* ExpressionStatement */:
39446 bindExpressionStatement(node);
39447 break;
39448 case 242 /* LabeledStatement */:
39449 bindLabeledStatement(node);
39450 break;
39451 case 211 /* PrefixUnaryExpression */:
39452 bindPrefixUnaryExpressionFlow(node);
39453 break;
39454 case 212 /* PostfixUnaryExpression */:
39455 bindPostfixUnaryExpressionFlow(node);
39456 break;
39457 case 213 /* BinaryExpression */:
39458 bindBinaryExpressionFlow(node);
39459 break;
39460 case 207 /* DeleteExpression */:
39461 bindDeleteExpressionFlow(node);
39462 break;
39463 case 214 /* ConditionalExpression */:
39464 bindConditionalExpressionFlow(node);
39465 break;
39466 case 246 /* VariableDeclaration */:
39467 bindVariableDeclarationFlow(node);
39468 break;
39469 case 198 /* PropertyAccessExpression */:
39470 case 199 /* ElementAccessExpression */:
39471 bindAccessExpressionFlow(node);
39472 break;
39473 case 200 /* CallExpression */:
39474 bindCallExpressionFlow(node);
39475 break;
39476 case 222 /* NonNullExpression */:
39477 bindNonNullExpressionFlow(node);
39478 break;
39479 case 327 /* JSDocTypedefTag */:
39480 case 320 /* JSDocCallbackTag */:
39481 case 321 /* JSDocEnumTag */:
39482 bindJSDocTypeAlias(node);
39483 break;
39484 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
39485 case 294 /* SourceFile */: {
39486 bindEachFunctionsFirst(node.statements);
39487 bind(node.endOfFileToken);
39488 break;
39489 }
39490 case 227 /* Block */:
39491 case 254 /* ModuleBlock */:
39492 bindEachFunctionsFirst(node.statements);
39493 break;
39494 default:
39495 bindEachChild(node);
39496 break;
39497 }
39498 bindJSDoc(node);
39499 }
39500 function isNarrowingExpression(expr) {
39501 switch (expr.kind) {
39502 case 78 /* Identifier */:
39503 case 107 /* ThisKeyword */:
39504 case 198 /* PropertyAccessExpression */:
39505 case 199 /* ElementAccessExpression */:
39506 return containsNarrowableReference(expr);
39507 case 200 /* CallExpression */:
39508 return hasNarrowableArgument(expr);
39509 case 204 /* ParenthesizedExpression */:
39510 return isNarrowingExpression(expr.expression);
39511 case 213 /* BinaryExpression */:
39512 return isNarrowingBinaryExpression(expr);
39513 case 211 /* PrefixUnaryExpression */:
39514 return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
39515 case 208 /* TypeOfExpression */:
39516 return isNarrowingExpression(expr.expression);
39517 }
39518 return false;
39519 }
39520 function isNarrowableReference(expr) {
39521 return expr.kind === 78 /* Identifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ ||
39522 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
39523 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
39524 ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
39525 }
39526 function containsNarrowableReference(expr) {
39527 return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
39528 }
39529 function hasNarrowableArgument(expr) {
39530 if (expr.arguments) {
39531 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
39532 var argument = _a[_i];
39533 if (containsNarrowableReference(argument)) {
39534 return true;
39535 }
39536 }
39537 }
39538 if (expr.expression.kind === 198 /* PropertyAccessExpression */ &&
39539 containsNarrowableReference(expr.expression.expression)) {
39540 return true;
39541 }
39542 return false;
39543 }
39544 function isNarrowingTypeofOperands(expr1, expr2) {
39545 return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
39546 }
39547 function isNarrowableInOperands(left, right) {
39548 return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
39549 }
39550 function isNarrowingBinaryExpression(expr) {
39551 switch (expr.operatorToken.kind) {
39552 case 62 /* EqualsToken */:
39553 case 74 /* BarBarEqualsToken */:
39554 case 75 /* AmpersandAmpersandEqualsToken */:
39555 case 76 /* QuestionQuestionEqualsToken */:
39556 return containsNarrowableReference(expr.left);
39557 case 34 /* EqualsEqualsToken */:
39558 case 35 /* ExclamationEqualsToken */:
39559 case 36 /* EqualsEqualsEqualsToken */:
39560 case 37 /* ExclamationEqualsEqualsToken */:
39561 return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
39562 isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
39563 case 101 /* InstanceOfKeyword */:
39564 return isNarrowableOperand(expr.left);
39565 case 100 /* InKeyword */:
39566 return isNarrowableInOperands(expr.left, expr.right);
39567 case 27 /* CommaToken */:
39568 return isNarrowingExpression(expr.right);
39569 }
39570 return false;
39571 }
39572 function isNarrowableOperand(expr) {
39573 switch (expr.kind) {
39574 case 204 /* ParenthesizedExpression */:
39575 return isNarrowableOperand(expr.expression);
39576 case 213 /* BinaryExpression */:
39577 switch (expr.operatorToken.kind) {
39578 case 62 /* EqualsToken */:
39579 return isNarrowableOperand(expr.left);
39580 case 27 /* CommaToken */:
39581 return isNarrowableOperand(expr.right);
39582 }
39583 }
39584 return containsNarrowableReference(expr);
39585 }
39586 function createBranchLabel() {
39587 return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
39588 }
39589 function createLoopLabel() {
39590 return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
39591 }
39592 function createReduceLabel(target, antecedents, antecedent) {
39593 return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
39594 }
39595 function setFlowNodeReferenced(flow) {
39596 // On first reference we set the Referenced flag, thereafter we set the Shared flag
39597 flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
39598 }
39599 function addAntecedent(label, antecedent) {
39600 if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
39601 (label.antecedents || (label.antecedents = [])).push(antecedent);
39602 setFlowNodeReferenced(antecedent);
39603 }
39604 }
39605 function createFlowCondition(flags, antecedent, expression) {
39606 if (antecedent.flags & 1 /* Unreachable */) {
39607 return antecedent;
39608 }
39609 if (!expression) {
39610 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
39611 }
39612 if ((expression.kind === 109 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
39613 expression.kind === 94 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
39614 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
39615 return unreachableFlow;
39616 }
39617 if (!isNarrowingExpression(expression)) {
39618 return antecedent;
39619 }
39620 setFlowNodeReferenced(antecedent);
39621 return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
39622 }
39623 function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
39624 setFlowNodeReferenced(antecedent);
39625 return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
39626 }
39627 function createFlowMutation(flags, antecedent, node) {
39628 setFlowNodeReferenced(antecedent);
39629 var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
39630 if (currentExceptionTarget) {
39631 addAntecedent(currentExceptionTarget, result);
39632 }
39633 return result;
39634 }
39635 function createFlowCall(antecedent, node) {
39636 setFlowNodeReferenced(antecedent);
39637 return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
39638 }
39639 function finishFlowLabel(flow) {
39640 var antecedents = flow.antecedents;
39641 if (!antecedents) {
39642 return unreachableFlow;
39643 }
39644 if (antecedents.length === 1) {
39645 return antecedents[0];
39646 }
39647 return flow;
39648 }
39649 function isStatementCondition(node) {
39650 var parent = node.parent;
39651 switch (parent.kind) {
39652 case 231 /* IfStatement */:
39653 case 233 /* WhileStatement */:
39654 case 232 /* DoStatement */:
39655 return parent.expression === node;
39656 case 234 /* ForStatement */:
39657 case 214 /* ConditionalExpression */:
39658 return parent.condition === node;
39659 }
39660 return false;
39661 }
39662 function isLogicalExpression(node) {
39663 while (true) {
39664 if (node.kind === 204 /* ParenthesizedExpression */) {
39665 node = node.expression;
39666 }
39667 else if (node.kind === 211 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
39668 node = node.operand;
39669 }
39670 else {
39671 return node.kind === 213 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
39672 node.operatorToken.kind === 56 /* BarBarToken */ ||
39673 node.operatorToken.kind === 60 /* QuestionQuestionToken */);
39674 }
39675 }
39676 }
39677 function isLogicalAssignmentExpression(node) {
39678 node = ts.skipParentheses(node);
39679 return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
39680 }
39681 function isTopLevelLogicalExpression(node) {
39682 while (ts.isParenthesizedExpression(node.parent) ||
39683 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
39684 node = node.parent;
39685 }
39686 return !isStatementCondition(node) &&
39687 !isLogicalAssignmentExpression(node.parent) &&
39688 !isLogicalExpression(node.parent) &&
39689 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
39690 }
39691 function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
39692 var savedTrueTarget = currentTrueTarget;
39693 var savedFalseTarget = currentFalseTarget;
39694 currentTrueTarget = trueTarget;
39695 currentFalseTarget = falseTarget;
39696 action(value);
39697 currentTrueTarget = savedTrueTarget;
39698 currentFalseTarget = savedFalseTarget;
39699 }
39700 function bindCondition(node, trueTarget, falseTarget) {
39701 doWithConditionalBranches(bind, node, trueTarget, falseTarget);
39702 if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
39703 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
39704 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
39705 }
39706 }
39707 function bindIterativeStatement(node, breakTarget, continueTarget) {
39708 var saveBreakTarget = currentBreakTarget;
39709 var saveContinueTarget = currentContinueTarget;
39710 currentBreakTarget = breakTarget;
39711 currentContinueTarget = continueTarget;
39712 bind(node);
39713 currentBreakTarget = saveBreakTarget;
39714 currentContinueTarget = saveContinueTarget;
39715 }
39716 function setContinueTarget(node, target) {
39717 var label = activeLabelList;
39718 while (label && node.parent.kind === 242 /* LabeledStatement */) {
39719 label.continueTarget = target;
39720 label = label.next;
39721 node = node.parent;
39722 }
39723 return target;
39724 }
39725 function bindWhileStatement(node) {
39726 var preWhileLabel = setContinueTarget(node, createLoopLabel());
39727 var preBodyLabel = createBranchLabel();
39728 var postWhileLabel = createBranchLabel();
39729 addAntecedent(preWhileLabel, currentFlow);
39730 currentFlow = preWhileLabel;
39731 bindCondition(node.expression, preBodyLabel, postWhileLabel);
39732 currentFlow = finishFlowLabel(preBodyLabel);
39733 bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
39734 addAntecedent(preWhileLabel, currentFlow);
39735 currentFlow = finishFlowLabel(postWhileLabel);
39736 }
39737 function bindDoStatement(node) {
39738 var preDoLabel = createLoopLabel();
39739 var preConditionLabel = setContinueTarget(node, createBranchLabel());
39740 var postDoLabel = createBranchLabel();
39741 addAntecedent(preDoLabel, currentFlow);
39742 currentFlow = preDoLabel;
39743 bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
39744 addAntecedent(preConditionLabel, currentFlow);
39745 currentFlow = finishFlowLabel(preConditionLabel);
39746 bindCondition(node.expression, preDoLabel, postDoLabel);
39747 currentFlow = finishFlowLabel(postDoLabel);
39748 }
39749 function bindForStatement(node) {
39750 var preLoopLabel = setContinueTarget(node, createLoopLabel());
39751 var preBodyLabel = createBranchLabel();
39752 var postLoopLabel = createBranchLabel();
39753 bind(node.initializer);
39754 addAntecedent(preLoopLabel, currentFlow);
39755 currentFlow = preLoopLabel;
39756 bindCondition(node.condition, preBodyLabel, postLoopLabel);
39757 currentFlow = finishFlowLabel(preBodyLabel);
39758 bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
39759 bind(node.incrementor);
39760 addAntecedent(preLoopLabel, currentFlow);
39761 currentFlow = finishFlowLabel(postLoopLabel);
39762 }
39763 function bindForInOrForOfStatement(node) {
39764 var preLoopLabel = setContinueTarget(node, createLoopLabel());
39765 var postLoopLabel = createBranchLabel();
39766 bind(node.expression);
39767 addAntecedent(preLoopLabel, currentFlow);
39768 currentFlow = preLoopLabel;
39769 if (node.kind === 236 /* ForOfStatement */) {
39770 bind(node.awaitModifier);
39771 }
39772 addAntecedent(postLoopLabel, currentFlow);
39773 bind(node.initializer);
39774 if (node.initializer.kind !== 247 /* VariableDeclarationList */) {
39775 bindAssignmentTargetFlow(node.initializer);
39776 }
39777 bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
39778 addAntecedent(preLoopLabel, currentFlow);
39779 currentFlow = finishFlowLabel(postLoopLabel);
39780 }
39781 function bindIfStatement(node) {
39782 var thenLabel = createBranchLabel();
39783 var elseLabel = createBranchLabel();
39784 var postIfLabel = createBranchLabel();
39785 bindCondition(node.expression, thenLabel, elseLabel);
39786 currentFlow = finishFlowLabel(thenLabel);
39787 bind(node.thenStatement);
39788 addAntecedent(postIfLabel, currentFlow);
39789 currentFlow = finishFlowLabel(elseLabel);
39790 bind(node.elseStatement);
39791 addAntecedent(postIfLabel, currentFlow);
39792 currentFlow = finishFlowLabel(postIfLabel);
39793 }
39794 function bindReturnOrThrow(node) {
39795 bind(node.expression);
39796 if (node.kind === 239 /* ReturnStatement */) {
39797 hasExplicitReturn = true;
39798 if (currentReturnTarget) {
39799 addAntecedent(currentReturnTarget, currentFlow);
39800 }
39801 }
39802 currentFlow = unreachableFlow;
39803 }
39804 function findActiveLabel(name) {
39805 for (var label = activeLabelList; label; label = label.next) {
39806 if (label.name === name) {
39807 return label;
39808 }
39809 }
39810 return undefined;
39811 }
39812 function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
39813 var flowLabel = node.kind === 238 /* BreakStatement */ ? breakTarget : continueTarget;
39814 if (flowLabel) {
39815 addAntecedent(flowLabel, currentFlow);
39816 currentFlow = unreachableFlow;
39817 }
39818 }
39819 function bindBreakOrContinueStatement(node) {
39820 bind(node.label);
39821 if (node.label) {
39822 var activeLabel = findActiveLabel(node.label.escapedText);
39823 if (activeLabel) {
39824 activeLabel.referenced = true;
39825 bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
39826 }
39827 }
39828 else {
39829 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
39830 }
39831 }
39832 function bindTryStatement(node) {
39833 // We conservatively assume that *any* code in the try block can cause an exception, but we only need
39834 // to track code that causes mutations (because only mutations widen the possible control flow type of
39835 // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
39836 // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
39837 // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
39838 // represent exceptions that occur before any mutations.
39839 var saveReturnTarget = currentReturnTarget;
39840 var saveExceptionTarget = currentExceptionTarget;
39841 var normalExitLabel = createBranchLabel();
39842 var returnLabel = createBranchLabel();
39843 var exceptionLabel = createBranchLabel();
39844 if (node.finallyBlock) {
39845 currentReturnTarget = returnLabel;
39846 }
39847 addAntecedent(exceptionLabel, currentFlow);
39848 currentExceptionTarget = exceptionLabel;
39849 bind(node.tryBlock);
39850 addAntecedent(normalExitLabel, currentFlow);
39851 if (node.catchClause) {
39852 // Start of catch clause is the target of exceptions from try block.
39853 currentFlow = finishFlowLabel(exceptionLabel);
39854 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
39855 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
39856 // acts like a second try block.
39857 exceptionLabel = createBranchLabel();
39858 addAntecedent(exceptionLabel, currentFlow);
39859 currentExceptionTarget = exceptionLabel;
39860 bind(node.catchClause);
39861 addAntecedent(normalExitLabel, currentFlow);
39862 }
39863 currentReturnTarget = saveReturnTarget;
39864 currentExceptionTarget = saveExceptionTarget;
39865 if (node.finallyBlock) {
39866 // Possible ways control can reach the finally block:
39867 // 1) Normal completion of try block of a try-finally or try-catch-finally
39868 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
39869 // 3) Return in try or catch block of a try-finally or try-catch-finally
39870 // 4) Exception in try block of a try-finally
39871 // 5) Exception in catch block of a try-catch-finally
39872 // When analyzing a control flow graph that starts inside a finally block we want to consider all
39873 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
39874 // the finally block, we only want to consider the first two (if we're past a finally block then it
39875 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
39876 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
39877 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
39878 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
39879 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
39880 var finallyLabel = createBranchLabel();
39881 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
39882 currentFlow = finallyLabel;
39883 bind(node.finallyBlock);
39884 if (currentFlow.flags & 1 /* Unreachable */) {
39885 // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
39886 currentFlow = unreachableFlow;
39887 }
39888 else {
39889 // If we have an IIFE return target and return statements in the try or catch blocks, add a control
39890 // flow that goes back through the finally block and back through only the return statements.
39891 if (currentReturnTarget && returnLabel.antecedents) {
39892 addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
39893 }
39894 // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
39895 // control flow that goes back through the finally blok and back through each possible exception source.
39896 if (currentExceptionTarget && exceptionLabel.antecedents) {
39897 addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
39898 }
39899 // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
39900 // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
39901 // result in an unreachable current control flow.
39902 currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
39903 }
39904 }
39905 else {
39906 currentFlow = finishFlowLabel(normalExitLabel);
39907 }
39908 }
39909 function bindSwitchStatement(node) {
39910 var postSwitchLabel = createBranchLabel();
39911 bind(node.expression);
39912 var saveBreakTarget = currentBreakTarget;
39913 var savePreSwitchCaseFlow = preSwitchCaseFlow;
39914 currentBreakTarget = postSwitchLabel;
39915 preSwitchCaseFlow = currentFlow;
39916 bind(node.caseBlock);
39917 addAntecedent(postSwitchLabel, currentFlow);
39918 var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 282 /* DefaultClause */; });
39919 // We mark a switch statement as possibly exhaustive if it has no default clause and if all
39920 // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
39921 // this property in control flow analysis, it's there only for backwards compatibility.
39922 node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
39923 if (!hasDefault) {
39924 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
39925 }
39926 currentBreakTarget = saveBreakTarget;
39927 preSwitchCaseFlow = savePreSwitchCaseFlow;
39928 currentFlow = finishFlowLabel(postSwitchLabel);
39929 }
39930 function bindCaseBlock(node) {
39931 var clauses = node.clauses;
39932 var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
39933 var fallthroughFlow = unreachableFlow;
39934 for (var i = 0; i < clauses.length; i++) {
39935 var clauseStart = i;
39936 while (!clauses[i].statements.length && i + 1 < clauses.length) {
39937 bind(clauses[i]);
39938 i++;
39939 }
39940 var preCaseLabel = createBranchLabel();
39941 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
39942 addAntecedent(preCaseLabel, fallthroughFlow);
39943 currentFlow = finishFlowLabel(preCaseLabel);
39944 var clause = clauses[i];
39945 bind(clause);
39946 fallthroughFlow = currentFlow;
39947 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
39948 clause.fallthroughFlowNode = currentFlow;
39949 }
39950 }
39951 }
39952 function bindCaseClause(node) {
39953 var saveCurrentFlow = currentFlow;
39954 currentFlow = preSwitchCaseFlow;
39955 bind(node.expression);
39956 currentFlow = saveCurrentFlow;
39957 bindEach(node.statements);
39958 }
39959 function bindExpressionStatement(node) {
39960 bind(node.expression);
39961 // A top level call expression with a dotted function name and at least one argument
39962 // is potentially an assertion and is therefore included in the control flow.
39963 if (node.expression.kind === 200 /* CallExpression */) {
39964 var call = node.expression;
39965 if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) {
39966 currentFlow = createFlowCall(currentFlow, call);
39967 }
39968 }
39969 }
39970 function bindLabeledStatement(node) {
39971 var postStatementLabel = createBranchLabel();
39972 activeLabelList = {
39973 next: activeLabelList,
39974 name: node.label.escapedText,
39975 breakTarget: postStatementLabel,
39976 continueTarget: undefined,
39977 referenced: false
39978 };
39979 bind(node.label);
39980 bind(node.statement);
39981 if (!activeLabelList.referenced && !options.allowUnusedLabels) {
39982 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
39983 }
39984 activeLabelList = activeLabelList.next;
39985 addAntecedent(postStatementLabel, currentFlow);
39986 currentFlow = finishFlowLabel(postStatementLabel);
39987 }
39988 function bindDestructuringTargetFlow(node) {
39989 if (node.kind === 213 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
39990 bindAssignmentTargetFlow(node.left);
39991 }
39992 else {
39993 bindAssignmentTargetFlow(node);
39994 }
39995 }
39996 function bindAssignmentTargetFlow(node) {
39997 if (isNarrowableReference(node)) {
39998 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
39999 }
40000 else if (node.kind === 196 /* ArrayLiteralExpression */) {
40001 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
40002 var e = _a[_i];
40003 if (e.kind === 217 /* SpreadElement */) {
40004 bindAssignmentTargetFlow(e.expression);
40005 }
40006 else {
40007 bindDestructuringTargetFlow(e);
40008 }
40009 }
40010 }
40011 else if (node.kind === 197 /* ObjectLiteralExpression */) {
40012 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
40013 var p = _c[_b];
40014 if (p.kind === 285 /* PropertyAssignment */) {
40015 bindDestructuringTargetFlow(p.initializer);
40016 }
40017 else if (p.kind === 286 /* ShorthandPropertyAssignment */) {
40018 bindAssignmentTargetFlow(p.name);
40019 }
40020 else if (p.kind === 287 /* SpreadAssignment */) {
40021 bindAssignmentTargetFlow(p.expression);
40022 }
40023 }
40024 }
40025 }
40026 function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
40027 var preRightLabel = createBranchLabel();
40028 if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 75 /* AmpersandAmpersandEqualsToken */) {
40029 bindCondition(node.left, preRightLabel, falseTarget);
40030 }
40031 else {
40032 bindCondition(node.left, trueTarget, preRightLabel);
40033 }
40034 currentFlow = finishFlowLabel(preRightLabel);
40035 bind(node.operatorToken);
40036 if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
40037 doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
40038 bindAssignmentTargetFlow(node.left);
40039 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
40040 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
40041 }
40042 else {
40043 bindCondition(node.right, trueTarget, falseTarget);
40044 }
40045 }
40046 function bindPrefixUnaryExpressionFlow(node) {
40047 if (node.operator === 53 /* ExclamationToken */) {
40048 var saveTrueTarget = currentTrueTarget;
40049 currentTrueTarget = currentFalseTarget;
40050 currentFalseTarget = saveTrueTarget;
40051 bindEachChild(node);
40052 currentFalseTarget = currentTrueTarget;
40053 currentTrueTarget = saveTrueTarget;
40054 }
40055 else {
40056 bindEachChild(node);
40057 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
40058 bindAssignmentTargetFlow(node.operand);
40059 }
40060 }
40061 }
40062 function bindPostfixUnaryExpressionFlow(node) {
40063 bindEachChild(node);
40064 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
40065 bindAssignmentTargetFlow(node.operand);
40066 }
40067 }
40068 var BindBinaryExpressionFlowState;
40069 (function (BindBinaryExpressionFlowState) {
40070 BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
40071 BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
40072 BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
40073 BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
40074 BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
40075 })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
40076 function bindBinaryExpressionFlow(node) {
40077 var workStacks = {
40078 expr: [node],
40079 state: [1 /* MaybeBindLeft */],
40080 inStrictMode: [undefined],
40081 parent: [undefined],
40082 };
40083 var stackIndex = 0;
40084 while (stackIndex >= 0) {
40085 node = workStacks.expr[stackIndex];
40086 switch (workStacks.state[stackIndex]) {
40087 case 0 /* BindThenBindChildren */: {
40088 // This state is used only when recuring, to emulate the work that `bind` does before
40089 // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
40090 ts.setParent(node, parent);
40091 var saveInStrictMode = inStrictMode;
40092 bindWorker(node);
40093 var saveParent = parent;
40094 parent = node;
40095 advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent);
40096 break;
40097 }
40098 case 1 /* MaybeBindLeft */: {
40099 var operator = node.operatorToken.kind;
40100 // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
40101 // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
40102 // For now, though, since the common cases are chained `+`, leaving it recursive is fine
40103 if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ ||
40104 ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
40105 if (isTopLevelLogicalExpression(node)) {
40106 var postExpressionLabel = createBranchLabel();
40107 bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
40108 currentFlow = finishFlowLabel(postExpressionLabel);
40109 }
40110 else {
40111 bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
40112 }
40113 completeNode();
40114 }
40115 else {
40116 advanceState(2 /* BindToken */);
40117 maybeBind(node.left);
40118 }
40119 break;
40120 }
40121 case 2 /* BindToken */: {
40122 advanceState(3 /* BindRight */);
40123 maybeBind(node.operatorToken);
40124 break;
40125 }
40126 case 3 /* BindRight */: {
40127 advanceState(4 /* FinishBind */);
40128 maybeBind(node.right);
40129 break;
40130 }
40131 case 4 /* FinishBind */: {
40132 var operator = node.operatorToken.kind;
40133 if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
40134 bindAssignmentTargetFlow(node.left);
40135 if (operator === 62 /* EqualsToken */ && node.left.kind === 199 /* ElementAccessExpression */) {
40136 var elementAccess = node.left;
40137 if (isNarrowableOperand(elementAccess.expression)) {
40138 currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
40139 }
40140 }
40141 }
40142 completeNode();
40143 break;
40144 }
40145 default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
40146 }
40147 }
40148 /**
40149 * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
40150 * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
40151 */
40152 function advanceState(state, isInStrictMode, parent) {
40153 workStacks.state[stackIndex] = state;
40154 if (isInStrictMode !== undefined) {
40155 workStacks.inStrictMode[stackIndex] = isInStrictMode;
40156 }
40157 if (parent !== undefined) {
40158 workStacks.parent[stackIndex] = parent;
40159 }
40160 }
40161 function completeNode() {
40162 if (workStacks.inStrictMode[stackIndex] !== undefined) {
40163 inStrictMode = workStacks.inStrictMode[stackIndex];
40164 parent = workStacks.parent[stackIndex];
40165 }
40166 stackIndex--;
40167 }
40168 /**
40169 * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
40170 */
40171 function maybeBind(node) {
40172 if (node && ts.isBinaryExpression(node)) {
40173 stackIndex++;
40174 workStacks.expr[stackIndex] = node;
40175 workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
40176 workStacks.inStrictMode[stackIndex] = undefined;
40177 workStacks.parent[stackIndex] = undefined;
40178 }
40179 else {
40180 bind(node);
40181 }
40182 }
40183 }
40184 function bindDeleteExpressionFlow(node) {
40185 bindEachChild(node);
40186 if (node.expression.kind === 198 /* PropertyAccessExpression */) {
40187 bindAssignmentTargetFlow(node.expression);
40188 }
40189 }
40190 function bindConditionalExpressionFlow(node) {
40191 var trueLabel = createBranchLabel();
40192 var falseLabel = createBranchLabel();
40193 var postExpressionLabel = createBranchLabel();
40194 bindCondition(node.condition, trueLabel, falseLabel);
40195 currentFlow = finishFlowLabel(trueLabel);
40196 bind(node.questionToken);
40197 bind(node.whenTrue);
40198 addAntecedent(postExpressionLabel, currentFlow);
40199 currentFlow = finishFlowLabel(falseLabel);
40200 bind(node.colonToken);
40201 bind(node.whenFalse);
40202 addAntecedent(postExpressionLabel, currentFlow);
40203 currentFlow = finishFlowLabel(postExpressionLabel);
40204 }
40205 function bindInitializedVariableFlow(node) {
40206 var name = !ts.isOmittedExpression(node) ? node.name : undefined;
40207 if (ts.isBindingPattern(name)) {
40208 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
40209 var child = _a[_i];
40210 bindInitializedVariableFlow(child);
40211 }
40212 }
40213 else {
40214 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
40215 }
40216 }
40217 function bindVariableDeclarationFlow(node) {
40218 bindEachChild(node);
40219 if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
40220 bindInitializedVariableFlow(node);
40221 }
40222 }
40223 function bindJSDocTypeAlias(node) {
40224 ts.setParent(node.tagName, node);
40225 if (node.kind !== 321 /* JSDocEnumTag */ && node.fullName) {
40226 ts.setParent(node.fullName, node);
40227 ts.setParentRecursive(node.fullName, /*incremental*/ false);
40228 }
40229 }
40230 function bindJSDocClassTag(node) {
40231 bindEachChild(node);
40232 var host = ts.getHostSignatureFromJSDoc(node);
40233 if (host && host.kind !== 164 /* MethodDeclaration */) {
40234 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
40235 }
40236 }
40237 function bindOptionalExpression(node, trueTarget, falseTarget) {
40238 doWithConditionalBranches(bind, node, trueTarget, falseTarget);
40239 if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
40240 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
40241 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
40242 }
40243 }
40244 function bindOptionalChainRest(node) {
40245 switch (node.kind) {
40246 case 198 /* PropertyAccessExpression */:
40247 bind(node.questionDotToken);
40248 bind(node.name);
40249 break;
40250 case 199 /* ElementAccessExpression */:
40251 bind(node.questionDotToken);
40252 bind(node.argumentExpression);
40253 break;
40254 case 200 /* CallExpression */:
40255 bind(node.questionDotToken);
40256 bindEach(node.typeArguments);
40257 bindEach(node.arguments);
40258 break;
40259 }
40260 }
40261 function bindOptionalChain(node, trueTarget, falseTarget) {
40262 // For an optional chain, we emulate the behavior of a logical expression:
40263 //
40264 // a?.b -> a && a.b
40265 // a?.b.c -> a && a.b.c
40266 // a?.b?.c -> a && a.b && a.b.c
40267 // a?.[x = 1] -> a && a[x = 1]
40268 //
40269 // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
40270 // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
40271 // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
40272 // chain node. We then treat the entire node as the right side of the expression.
40273 var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
40274 bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
40275 if (preChainLabel) {
40276 currentFlow = finishFlowLabel(preChainLabel);
40277 }
40278 doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
40279 if (ts.isOutermostOptionalChain(node)) {
40280 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
40281 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
40282 }
40283 }
40284 function bindOptionalChainFlow(node) {
40285 if (isTopLevelLogicalExpression(node)) {
40286 var postExpressionLabel = createBranchLabel();
40287 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
40288 currentFlow = finishFlowLabel(postExpressionLabel);
40289 }
40290 else {
40291 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
40292 }
40293 }
40294 function bindNonNullExpressionFlow(node) {
40295 if (ts.isOptionalChain(node)) {
40296 bindOptionalChainFlow(node);
40297 }
40298 else {
40299 bindEachChild(node);
40300 }
40301 }
40302 function bindAccessExpressionFlow(node) {
40303 if (ts.isOptionalChain(node)) {
40304 bindOptionalChainFlow(node);
40305 }
40306 else {
40307 bindEachChild(node);
40308 }
40309 }
40310 function bindCallExpressionFlow(node) {
40311 if (ts.isOptionalChain(node)) {
40312 bindOptionalChainFlow(node);
40313 }
40314 else {
40315 // If the target of the call expression is a function expression or arrow function we have
40316 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
40317 // the current control flow (which includes evaluation of the IIFE arguments).
40318 var expr = ts.skipParentheses(node.expression);
40319 if (expr.kind === 205 /* FunctionExpression */ || expr.kind === 206 /* ArrowFunction */) {
40320 bindEach(node.typeArguments);
40321 bindEach(node.arguments);
40322 bind(node.expression);
40323 }
40324 else {
40325 bindEachChild(node);
40326 if (node.expression.kind === 105 /* SuperKeyword */) {
40327 currentFlow = createFlowCall(currentFlow, node);
40328 }
40329 }
40330 }
40331 if (node.expression.kind === 198 /* PropertyAccessExpression */) {
40332 var propertyAccess = node.expression;
40333 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
40334 currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
40335 }
40336 }
40337 }
40338 function getContainerFlags(node) {
40339 switch (node.kind) {
40340 case 218 /* ClassExpression */:
40341 case 249 /* ClassDeclaration */:
40342 case 252 /* EnumDeclaration */:
40343 case 197 /* ObjectLiteralExpression */:
40344 case 176 /* TypeLiteral */:
40345 case 308 /* JSDocTypeLiteral */:
40346 case 278 /* JsxAttributes */:
40347 return 1 /* IsContainer */;
40348 case 250 /* InterfaceDeclaration */:
40349 return 1 /* IsContainer */ | 64 /* IsInterface */;
40350 case 253 /* ModuleDeclaration */:
40351 case 251 /* TypeAliasDeclaration */:
40352 case 189 /* MappedType */:
40353 return 1 /* IsContainer */ | 32 /* HasLocals */;
40354 case 294 /* SourceFile */:
40355 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
40356 case 164 /* MethodDeclaration */:
40357 if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
40358 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
40359 }
40360 // falls through
40361 case 165 /* Constructor */:
40362 case 248 /* FunctionDeclaration */:
40363 case 163 /* MethodSignature */:
40364 case 166 /* GetAccessor */:
40365 case 167 /* SetAccessor */:
40366 case 168 /* CallSignature */:
40367 case 309 /* JSDocSignature */:
40368 case 304 /* JSDocFunctionType */:
40369 case 173 /* FunctionType */:
40370 case 169 /* ConstructSignature */:
40371 case 170 /* IndexSignature */:
40372 case 174 /* ConstructorType */:
40373 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
40374 case 205 /* FunctionExpression */:
40375 case 206 /* ArrowFunction */:
40376 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
40377 case 254 /* ModuleBlock */:
40378 return 4 /* IsControlFlowContainer */;
40379 case 162 /* PropertyDeclaration */:
40380 return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
40381 case 284 /* CatchClause */:
40382 case 234 /* ForStatement */:
40383 case 235 /* ForInStatement */:
40384 case 236 /* ForOfStatement */:
40385 case 255 /* CaseBlock */:
40386 return 2 /* IsBlockScopedContainer */;
40387 case 227 /* Block */:
40388 // do not treat blocks directly inside a function as a block-scoped-container.
40389 // Locals that reside in this block should go to the function locals. Otherwise 'x'
40390 // would not appear to be a redeclaration of a block scoped local in the following
40391 // example:
40392 //
40393 // function foo() {
40394 // var x;
40395 // let x;
40396 // }
40397 //
40398 // If we placed 'var x' into the function locals and 'let x' into the locals of
40399 // the block, then there would be no collision.
40400 //
40401 // By not creating a new block-scoped-container here, we ensure that both 'var x'
40402 // and 'let x' go into the Function-container's locals, and we do get a collision
40403 // conflict.
40404 return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
40405 }
40406 return 0 /* None */;
40407 }
40408 function addToContainerChain(next) {
40409 if (lastContainer) {
40410 lastContainer.nextContainer = next;
40411 }
40412 lastContainer = next;
40413 }
40414 function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
40415 switch (container.kind) {
40416 // Modules, source files, and classes need specialized handling for how their
40417 // members are declared (for example, a member of a class will go into a specific
40418 // symbol table depending on if it is static or not). We defer to specialized
40419 // handlers to take care of declaring these child members.
40420 case 253 /* ModuleDeclaration */:
40421 return declareModuleMember(node, symbolFlags, symbolExcludes);
40422 case 294 /* SourceFile */:
40423 return declareSourceFileMember(node, symbolFlags, symbolExcludes);
40424 case 218 /* ClassExpression */:
40425 case 249 /* ClassDeclaration */:
40426 return declareClassMember(node, symbolFlags, symbolExcludes);
40427 case 252 /* EnumDeclaration */:
40428 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40429 case 176 /* TypeLiteral */:
40430 case 308 /* JSDocTypeLiteral */:
40431 case 197 /* ObjectLiteralExpression */:
40432 case 250 /* InterfaceDeclaration */:
40433 case 278 /* JsxAttributes */:
40434 // Interface/Object-types always have their children added to the 'members' of
40435 // their container. They are only accessible through an instance of their
40436 // container, and are never in scope otherwise (even inside the body of the
40437 // object / type / interface declaring them). An exception is type parameters,
40438 // which are in scope without qualification (similar to 'locals').
40439 return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
40440 case 173 /* FunctionType */:
40441 case 174 /* ConstructorType */:
40442 case 168 /* CallSignature */:
40443 case 169 /* ConstructSignature */:
40444 case 309 /* JSDocSignature */:
40445 case 170 /* IndexSignature */:
40446 case 164 /* MethodDeclaration */:
40447 case 163 /* MethodSignature */:
40448 case 165 /* Constructor */:
40449 case 166 /* GetAccessor */:
40450 case 167 /* SetAccessor */:
40451 case 248 /* FunctionDeclaration */:
40452 case 205 /* FunctionExpression */:
40453 case 206 /* ArrowFunction */:
40454 case 304 /* JSDocFunctionType */:
40455 case 327 /* JSDocTypedefTag */:
40456 case 320 /* JSDocCallbackTag */:
40457 case 251 /* TypeAliasDeclaration */:
40458 case 189 /* MappedType */:
40459 // All the children of these container types are never visible through another
40460 // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
40461 // they're only accessed 'lexically' (i.e. from code that exists underneath
40462 // their container in the tree). To accomplish this, we simply add their declared
40463 // symbol to the 'locals' of the container. These symbols can then be found as
40464 // the type checker walks up the containers, checking them for matching names.
40465 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40466 }
40467 }
40468 function declareClassMember(node, symbolFlags, symbolExcludes) {
40469 return ts.hasSyntacticModifier(node, 32 /* Static */)
40470 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
40471 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
40472 }
40473 function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
40474 return ts.isExternalModule(file)
40475 ? declareModuleMember(node, symbolFlags, symbolExcludes)
40476 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40477 }
40478 function hasExportDeclarations(node) {
40479 var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
40480 return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
40481 }
40482 function setExportContextFlag(node) {
40483 // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
40484 // declarations with export modifiers) is an export context in which declarations are implicitly exported.
40485 if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
40486 node.flags |= 64 /* ExportContext */;
40487 }
40488 else {
40489 node.flags &= ~64 /* ExportContext */;
40490 }
40491 }
40492 function bindModuleDeclaration(node) {
40493 setExportContextFlag(node);
40494 if (ts.isAmbientModule(node)) {
40495 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
40496 errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
40497 }
40498 if (ts.isModuleAugmentationExternal(node)) {
40499 declareModuleSymbol(node);
40500 }
40501 else {
40502 var pattern = void 0;
40503 if (node.name.kind === 10 /* StringLiteral */) {
40504 var text = node.name.text;
40505 if (ts.hasZeroOrOneAsteriskCharacter(text)) {
40506 pattern = ts.tryParsePattern(text);
40507 }
40508 else {
40509 errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
40510 }
40511 }
40512 var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
40513 file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
40514 }
40515 }
40516 else {
40517 var state = declareModuleSymbol(node);
40518 if (state !== 0 /* NonInstantiated */) {
40519 var symbol = node.symbol;
40520 // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
40521 symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
40522 // Current must be `const enum` only
40523 && state === 2 /* ConstEnumOnly */
40524 // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
40525 && symbol.constEnumOnlyModule !== false;
40526 }
40527 }
40528 }
40529 function declareModuleSymbol(node) {
40530 var state = getModuleInstanceState(node);
40531 var instantiated = state !== 0 /* NonInstantiated */;
40532 declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
40533 return state;
40534 }
40535 function bindFunctionOrConstructorType(node) {
40536 // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
40537 // to the one we would get for: { <...>(...): T }
40538 //
40539 // We do that by making an anonymous type literal symbol, and then setting the function
40540 // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
40541 // from an actual type literal symbol you would have gotten had you used the long form.
40542 var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
40543 addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
40544 var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
40545 addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
40546 typeLiteralSymbol.members = ts.createSymbolTable();
40547 typeLiteralSymbol.members.set(symbol.escapedName, symbol);
40548 }
40549 function bindObjectLiteralExpression(node) {
40550 var ElementKind;
40551 (function (ElementKind) {
40552 ElementKind[ElementKind["Property"] = 1] = "Property";
40553 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
40554 })(ElementKind || (ElementKind = {}));
40555 if (inStrictMode && !ts.isAssignmentTarget(node)) {
40556 var seen = new ts.Map();
40557 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
40558 var prop = _a[_i];
40559 if (prop.kind === 287 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) {
40560 continue;
40561 }
40562 var identifier = prop.name;
40563 // ECMA-262 11.1.5 Object Initializer
40564 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
40565 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
40566 // IsDataDescriptor(propId.descriptor) is true.
40567 // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
40568 // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
40569 // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
40570 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
40571 var currentKind = prop.kind === 285 /* PropertyAssignment */ || prop.kind === 286 /* ShorthandPropertyAssignment */ || prop.kind === 164 /* MethodDeclaration */
40572 ? 1 /* Property */
40573 : 2 /* Accessor */;
40574 var existingKind = seen.get(identifier.escapedText);
40575 if (!existingKind) {
40576 seen.set(identifier.escapedText, currentKind);
40577 continue;
40578 }
40579 if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
40580 var span = ts.getErrorSpanForNode(file, identifier);
40581 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));
40582 }
40583 }
40584 }
40585 return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
40586 }
40587 function bindJsxAttributes(node) {
40588 return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
40589 }
40590 function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
40591 return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
40592 }
40593 function bindAnonymousDeclaration(node, symbolFlags, name) {
40594 var symbol = createSymbol(symbolFlags, name);
40595 if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
40596 symbol.parent = container.symbol;
40597 }
40598 addDeclarationToSymbol(symbol, node, symbolFlags);
40599 return symbol;
40600 }
40601 function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
40602 switch (blockScopeContainer.kind) {
40603 case 253 /* ModuleDeclaration */:
40604 declareModuleMember(node, symbolFlags, symbolExcludes);
40605 break;
40606 case 294 /* SourceFile */:
40607 if (ts.isExternalOrCommonJsModule(container)) {
40608 declareModuleMember(node, symbolFlags, symbolExcludes);
40609 break;
40610 }
40611 // falls through
40612 default:
40613 if (!blockScopeContainer.locals) {
40614 blockScopeContainer.locals = ts.createSymbolTable();
40615 addToContainerChain(blockScopeContainer);
40616 }
40617 declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40618 }
40619 }
40620 function delayedBindJSDocTypedefTag() {
40621 if (!delayedTypeAliases) {
40622 return;
40623 }
40624 var saveContainer = container;
40625 var saveLastContainer = lastContainer;
40626 var saveBlockScopeContainer = blockScopeContainer;
40627 var saveParent = parent;
40628 var saveCurrentFlow = currentFlow;
40629 for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
40630 var typeAlias = delayedTypeAliases_1[_i];
40631 var host = ts.getJSDocHost(typeAlias);
40632 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
40633 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
40634 currentFlow = initFlowNode({ flags: 2 /* Start */ });
40635 parent = typeAlias;
40636 bind(typeAlias.typeExpression);
40637 var declName = ts.getNameOfDeclaration(typeAlias);
40638 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
40639 // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
40640 var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
40641 if (isTopLevel) {
40642 bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
40643 var oldContainer = container;
40644 switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
40645 case 1 /* ExportsProperty */:
40646 case 2 /* ModuleExports */:
40647 if (!ts.isExternalOrCommonJsModule(file)) {
40648 container = undefined;
40649 }
40650 else {
40651 container = file;
40652 }
40653 break;
40654 case 4 /* ThisProperty */:
40655 container = declName.parent.expression;
40656 break;
40657 case 3 /* PrototypeProperty */:
40658 container = declName.parent.expression.name;
40659 break;
40660 case 5 /* Property */:
40661 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
40662 : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
40663 : declName.parent.expression;
40664 break;
40665 case 0 /* None */:
40666 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
40667 }
40668 if (container) {
40669 declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
40670 }
40671 container = oldContainer;
40672 }
40673 }
40674 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 78 /* Identifier */) {
40675 parent = typeAlias.parent;
40676 bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
40677 }
40678 else {
40679 bind(typeAlias.fullName);
40680 }
40681 }
40682 container = saveContainer;
40683 lastContainer = saveLastContainer;
40684 blockScopeContainer = saveBlockScopeContainer;
40685 parent = saveParent;
40686 currentFlow = saveCurrentFlow;
40687 }
40688 // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
40689 // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
40690 // [Yield] or [Await] contexts, respectively.
40691 function checkContextualIdentifier(node) {
40692 // Report error only if there are no parse errors in file
40693 if (!file.parseDiagnostics.length &&
40694 !(node.flags & 8388608 /* Ambient */) &&
40695 !(node.flags & 4194304 /* JSDoc */) &&
40696 !ts.isIdentifierName(node)) {
40697 // strict mode identifiers
40698 if (inStrictMode &&
40699 node.originalKeywordKind >= 116 /* FirstFutureReservedWord */ &&
40700 node.originalKeywordKind <= 124 /* LastFutureReservedWord */) {
40701 file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
40702 }
40703 else if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
40704 if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
40705 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
40706 }
40707 else if (node.flags & 32768 /* AwaitContext */) {
40708 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
40709 }
40710 }
40711 else if (node.originalKeywordKind === 124 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
40712 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
40713 }
40714 }
40715 }
40716 function getStrictModeIdentifierMessage(node) {
40717 // Provide specialized messages to help the user understand why we think they're in
40718 // strict mode.
40719 if (ts.getContainingClass(node)) {
40720 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
40721 }
40722 if (file.externalModuleIndicator) {
40723 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
40724 }
40725 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
40726 }
40727 // The binder visits every node, so this is a good place to check for
40728 // the reserved private name (there is only one)
40729 function checkPrivateIdentifier(node) {
40730 if (node.escapedText === "#constructor") {
40731 // Report error only if there are no parse errors in file
40732 if (!file.parseDiagnostics.length) {
40733 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
40734 }
40735 }
40736 }
40737 function checkStrictModeBinaryExpression(node) {
40738 if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
40739 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
40740 // Assignment operator(11.13) or of a PostfixExpression(11.3)
40741 checkStrictModeEvalOrArguments(node, node.left);
40742 }
40743 }
40744 function checkStrictModeCatchClause(node) {
40745 // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
40746 // Catch production is eval or arguments
40747 if (inStrictMode && node.variableDeclaration) {
40748 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
40749 }
40750 }
40751 function checkStrictModeDeleteExpression(node) {
40752 // Grammar checking
40753 if (inStrictMode && node.expression.kind === 78 /* Identifier */) {
40754 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
40755 // UnaryExpression is a direct reference to a variable, function argument, or function name
40756 var span = ts.getErrorSpanForNode(file, node.expression);
40757 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
40758 }
40759 }
40760 function isEvalOrArgumentsIdentifier(node) {
40761 return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
40762 }
40763 function checkStrictModeEvalOrArguments(contextNode, name) {
40764 if (name && name.kind === 78 /* Identifier */) {
40765 var identifier = name;
40766 if (isEvalOrArgumentsIdentifier(identifier)) {
40767 // We check first if the name is inside class declaration or class expression; if so give explicit message
40768 // otherwise report generic error message.
40769 var span = ts.getErrorSpanForNode(file, name);
40770 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
40771 }
40772 }
40773 }
40774 function getStrictModeEvalOrArgumentsMessage(node) {
40775 // Provide specialized messages to help the user understand why we think they're in
40776 // strict mode.
40777 if (ts.getContainingClass(node)) {
40778 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
40779 }
40780 if (file.externalModuleIndicator) {
40781 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
40782 }
40783 return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
40784 }
40785 function checkStrictModeFunctionName(node) {
40786 if (inStrictMode) {
40787 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
40788 checkStrictModeEvalOrArguments(node, node.name);
40789 }
40790 }
40791 function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
40792 // Provide specialized messages to help the user understand why we think they're in
40793 // strict mode.
40794 if (ts.getContainingClass(node)) {
40795 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;
40796 }
40797 if (file.externalModuleIndicator) {
40798 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
40799 }
40800 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
40801 }
40802 function checkStrictModeFunctionDeclaration(node) {
40803 if (languageVersion < 2 /* ES2015 */) {
40804 // Report error if function is not top level function declaration
40805 if (blockScopeContainer.kind !== 294 /* SourceFile */ &&
40806 blockScopeContainer.kind !== 253 /* ModuleDeclaration */ &&
40807 !ts.isFunctionLike(blockScopeContainer)) {
40808 // We check first if the name is inside class declaration or class expression; if so give explicit message
40809 // otherwise report generic error message.
40810 var errorSpan = ts.getErrorSpanForNode(file, node);
40811 file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
40812 }
40813 }
40814 }
40815 function checkStrictModeNumericLiteral(node) {
40816 if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
40817 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
40818 }
40819 }
40820 function checkStrictModePostfixUnaryExpression(node) {
40821 // Grammar checking
40822 // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
40823 // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
40824 // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
40825 if (inStrictMode) {
40826 checkStrictModeEvalOrArguments(node, node.operand);
40827 }
40828 }
40829 function checkStrictModePrefixUnaryExpression(node) {
40830 // Grammar checking
40831 if (inStrictMode) {
40832 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
40833 checkStrictModeEvalOrArguments(node, node.operand);
40834 }
40835 }
40836 }
40837 function checkStrictModeWithStatement(node) {
40838 // Grammar checking for withStatement
40839 if (inStrictMode) {
40840 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
40841 }
40842 }
40843 function checkStrictModeLabeledStatement(node) {
40844 // Grammar checking for labeledStatement
40845 if (inStrictMode && options.target >= 2 /* ES2015 */) {
40846 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
40847 errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
40848 }
40849 }
40850 }
40851 function errorOnFirstToken(node, message, arg0, arg1, arg2) {
40852 var span = ts.getSpanOfTokenAtPosition(file, node.pos);
40853 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
40854 }
40855 function errorOrSuggestionOnNode(isError, node, message) {
40856 errorOrSuggestionOnRange(isError, node, node, message);
40857 }
40858 function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
40859 addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
40860 }
40861 function addErrorOrSuggestionDiagnostic(isError, range, message) {
40862 var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
40863 if (isError) {
40864 file.bindDiagnostics.push(diag);
40865 }
40866 else {
40867 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
40868 }
40869 }
40870 function bind(node) {
40871 if (!node) {
40872 return;
40873 }
40874 ts.setParent(node, parent);
40875 var saveInStrictMode = inStrictMode;
40876 // Even though in the AST the jsdoc @typedef node belongs to the current node,
40877 // its symbol might be in the same scope with the current node's symbol. Consider:
40878 //
40879 // /** @typedef {string | number} MyType */
40880 // function foo();
40881 //
40882 // Here the current node is "foo", which is a container, but the scope of "MyType" should
40883 // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
40884 // and skip binding this tag later when binding all the other jsdoc tags.
40885 // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
40886 // and then potentially add the symbol to an appropriate symbol table. Possible
40887 // destination symbol tables are:
40888 //
40889 // 1) The 'exports' table of the current container's symbol.
40890 // 2) The 'members' table of the current container's symbol.
40891 // 3) The 'locals' table of the current container.
40892 //
40893 // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
40894 // (like TypeLiterals for example) will not be put in any table.
40895 bindWorker(node);
40896 // Then we recurse into the children of the node to bind them as well. For certain
40897 // symbols we do specialized work when we recurse. For example, we'll keep track of
40898 // the current 'container' node when it changes. This helps us know which symbol table
40899 // a local should go into for example. Since terminal nodes are known not to have
40900 // children, as an optimization we don't process those.
40901 if (node.kind > 155 /* LastToken */) {
40902 var saveParent = parent;
40903 parent = node;
40904 var containerFlags = getContainerFlags(node);
40905 if (containerFlags === 0 /* None */) {
40906 bindChildren(node);
40907 }
40908 else {
40909 bindContainer(node, containerFlags);
40910 }
40911 parent = saveParent;
40912 }
40913 else {
40914 var saveParent = parent;
40915 if (node.kind === 1 /* EndOfFileToken */)
40916 parent = node;
40917 bindJSDoc(node);
40918 parent = saveParent;
40919 }
40920 inStrictMode = saveInStrictMode;
40921 }
40922 function bindJSDoc(node) {
40923 if (ts.hasJSDocNodes(node)) {
40924 if (ts.isInJSFile(node)) {
40925 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
40926 var j = _a[_i];
40927 bind(j);
40928 }
40929 }
40930 else {
40931 for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
40932 var j = _c[_b];
40933 ts.setParent(j, node);
40934 ts.setParentRecursive(j, /*incremental*/ false);
40935 }
40936 }
40937 }
40938 }
40939 function updateStrictModeStatementList(statements) {
40940 if (!inStrictMode) {
40941 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
40942 var statement = statements_3[_i];
40943 if (!ts.isPrologueDirective(statement)) {
40944 return;
40945 }
40946 if (isUseStrictPrologueDirective(statement)) {
40947 inStrictMode = true;
40948 return;
40949 }
40950 }
40951 }
40952 }
40953 /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
40954 function isUseStrictPrologueDirective(node) {
40955 var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
40956 // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
40957 // string to contain unicode escapes (as per ES5).
40958 return nodeText === '"use strict"' || nodeText === "'use strict'";
40959 }
40960 function bindWorker(node) {
40961 switch (node.kind) {
40962 /* Strict mode checks */
40963 case 78 /* Identifier */:
40964 // for typedef type names with namespaces, bind the new jsdoc type symbol here
40965 // because it requires all containing namespaces to be in effect, namely the
40966 // current "blockScopeContainer" needs to be set to its immediate namespace parent.
40967 if (node.isInJSDocNamespace) {
40968 var parentNode = node.parent;
40969 while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
40970 parentNode = parentNode.parent;
40971 }
40972 bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
40973 break;
40974 }
40975 // falls through
40976 case 107 /* ThisKeyword */:
40977 if (currentFlow && (ts.isExpression(node) || parent.kind === 286 /* ShorthandPropertyAssignment */)) {
40978 node.flowNode = currentFlow;
40979 }
40980 return checkContextualIdentifier(node);
40981 case 105 /* SuperKeyword */:
40982 node.flowNode = currentFlow;
40983 break;
40984 case 79 /* PrivateIdentifier */:
40985 return checkPrivateIdentifier(node);
40986 case 198 /* PropertyAccessExpression */:
40987 case 199 /* ElementAccessExpression */:
40988 var expr = node;
40989 if (currentFlow && isNarrowableReference(expr)) {
40990 expr.flowNode = currentFlow;
40991 }
40992 if (ts.isSpecialPropertyDeclaration(expr)) {
40993 bindSpecialPropertyDeclaration(expr);
40994 }
40995 if (ts.isInJSFile(expr) &&
40996 file.commonJsModuleIndicator &&
40997 ts.isModuleExportsAccessExpression(expr) &&
40998 !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
40999 declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
41000 }
41001 break;
41002 case 213 /* BinaryExpression */:
41003 var specialKind = ts.getAssignmentDeclarationKind(node);
41004 switch (specialKind) {
41005 case 1 /* ExportsProperty */:
41006 bindExportsPropertyAssignment(node);
41007 break;
41008 case 2 /* ModuleExports */:
41009 bindModuleExportsAssignment(node);
41010 break;
41011 case 3 /* PrototypeProperty */:
41012 bindPrototypePropertyAssignment(node.left, node);
41013 break;
41014 case 6 /* Prototype */:
41015 bindPrototypeAssignment(node);
41016 break;
41017 case 4 /* ThisProperty */:
41018 bindThisPropertyAssignment(node);
41019 break;
41020 case 5 /* Property */:
41021 bindSpecialPropertyAssignment(node);
41022 break;
41023 case 0 /* None */:
41024 // Nothing to do
41025 break;
41026 default:
41027 ts.Debug.fail("Unknown binary expression special property assignment kind");
41028 }
41029 return checkStrictModeBinaryExpression(node);
41030 case 284 /* CatchClause */:
41031 return checkStrictModeCatchClause(node);
41032 case 207 /* DeleteExpression */:
41033 return checkStrictModeDeleteExpression(node);
41034 case 8 /* NumericLiteral */:
41035 return checkStrictModeNumericLiteral(node);
41036 case 212 /* PostfixUnaryExpression */:
41037 return checkStrictModePostfixUnaryExpression(node);
41038 case 211 /* PrefixUnaryExpression */:
41039 return checkStrictModePrefixUnaryExpression(node);
41040 case 240 /* WithStatement */:
41041 return checkStrictModeWithStatement(node);
41042 case 242 /* LabeledStatement */:
41043 return checkStrictModeLabeledStatement(node);
41044 case 186 /* ThisType */:
41045 seenThisKeyword = true;
41046 return;
41047 case 171 /* TypePredicate */:
41048 break; // Binding the children will handle everything
41049 case 158 /* TypeParameter */:
41050 return bindTypeParameter(node);
41051 case 159 /* Parameter */:
41052 return bindParameter(node);
41053 case 246 /* VariableDeclaration */:
41054 return bindVariableDeclarationOrBindingElement(node);
41055 case 195 /* BindingElement */:
41056 node.flowNode = currentFlow;
41057 return bindVariableDeclarationOrBindingElement(node);
41058 case 162 /* PropertyDeclaration */:
41059 case 161 /* PropertySignature */:
41060 return bindPropertyWorker(node);
41061 case 285 /* PropertyAssignment */:
41062 case 286 /* ShorthandPropertyAssignment */:
41063 return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
41064 case 288 /* EnumMember */:
41065 return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
41066 case 168 /* CallSignature */:
41067 case 169 /* ConstructSignature */:
41068 case 170 /* IndexSignature */:
41069 return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
41070 case 164 /* MethodDeclaration */:
41071 case 163 /* MethodSignature */:
41072 // If this is an ObjectLiteralExpression method, then it sits in the same space
41073 // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
41074 // so that it will conflict with any other object literal members with the same
41075 // name.
41076 return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
41077 case 248 /* FunctionDeclaration */:
41078 return bindFunctionDeclaration(node);
41079 case 165 /* Constructor */:
41080 return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
41081 case 166 /* GetAccessor */:
41082 return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
41083 case 167 /* SetAccessor */:
41084 return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
41085 case 173 /* FunctionType */:
41086 case 304 /* JSDocFunctionType */:
41087 case 309 /* JSDocSignature */:
41088 case 174 /* ConstructorType */:
41089 return bindFunctionOrConstructorType(node);
41090 case 176 /* TypeLiteral */:
41091 case 308 /* JSDocTypeLiteral */:
41092 case 189 /* MappedType */:
41093 return bindAnonymousTypeWorker(node);
41094 case 315 /* JSDocClassTag */:
41095 return bindJSDocClassTag(node);
41096 case 197 /* ObjectLiteralExpression */:
41097 return bindObjectLiteralExpression(node);
41098 case 205 /* FunctionExpression */:
41099 case 206 /* ArrowFunction */:
41100 return bindFunctionExpression(node);
41101 case 200 /* CallExpression */:
41102 var assignmentKind = ts.getAssignmentDeclarationKind(node);
41103 switch (assignmentKind) {
41104 case 7 /* ObjectDefinePropertyValue */:
41105 return bindObjectDefinePropertyAssignment(node);
41106 case 8 /* ObjectDefinePropertyExports */:
41107 return bindObjectDefinePropertyExport(node);
41108 case 9 /* ObjectDefinePrototypeProperty */:
41109 return bindObjectDefinePrototypeProperty(node);
41110 case 0 /* None */:
41111 break; // Nothing to do
41112 default:
41113 return ts.Debug.fail("Unknown call expression assignment declaration kind");
41114 }
41115 if (ts.isInJSFile(node)) {
41116 bindCallExpression(node);
41117 }
41118 break;
41119 // Members of classes, interfaces, and modules
41120 case 218 /* ClassExpression */:
41121 case 249 /* ClassDeclaration */:
41122 // All classes are automatically in strict mode in ES6.
41123 inStrictMode = true;
41124 return bindClassLikeDeclaration(node);
41125 case 250 /* InterfaceDeclaration */:
41126 return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
41127 case 251 /* TypeAliasDeclaration */:
41128 return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
41129 case 252 /* EnumDeclaration */:
41130 return bindEnumDeclaration(node);
41131 case 253 /* ModuleDeclaration */:
41132 return bindModuleDeclaration(node);
41133 // Jsx-attributes
41134 case 278 /* JsxAttributes */:
41135 return bindJsxAttributes(node);
41136 case 277 /* JsxAttribute */:
41137 return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
41138 // Imports and exports
41139 case 257 /* ImportEqualsDeclaration */:
41140 case 260 /* NamespaceImport */:
41141 case 262 /* ImportSpecifier */:
41142 case 267 /* ExportSpecifier */:
41143 return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
41144 case 256 /* NamespaceExportDeclaration */:
41145 return bindNamespaceExportDeclaration(node);
41146 case 259 /* ImportClause */:
41147 return bindImportClause(node);
41148 case 264 /* ExportDeclaration */:
41149 return bindExportDeclaration(node);
41150 case 263 /* ExportAssignment */:
41151 return bindExportAssignment(node);
41152 case 294 /* SourceFile */:
41153 updateStrictModeStatementList(node.statements);
41154 return bindSourceFileIfExternalModule();
41155 case 227 /* Block */:
41156 if (!ts.isFunctionLike(node.parent)) {
41157 return;
41158 }
41159 // falls through
41160 case 254 /* ModuleBlock */:
41161 return updateStrictModeStatementList(node.statements);
41162 case 322 /* JSDocParameterTag */:
41163 if (node.parent.kind === 309 /* JSDocSignature */) {
41164 return bindParameter(node);
41165 }
41166 if (node.parent.kind !== 308 /* JSDocTypeLiteral */) {
41167 break;
41168 }
41169 // falls through
41170 case 328 /* JSDocPropertyTag */:
41171 var propTag = node;
41172 var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 303 /* JSDocOptionalType */ ?
41173 4 /* Property */ | 16777216 /* Optional */ :
41174 4 /* Property */;
41175 return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
41176 case 327 /* JSDocTypedefTag */:
41177 case 320 /* JSDocCallbackTag */:
41178 case 321 /* JSDocEnumTag */:
41179 return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
41180 }
41181 }
41182 function bindPropertyWorker(node) {
41183 return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
41184 }
41185 function bindAnonymousTypeWorker(node) {
41186 return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
41187 }
41188 function bindSourceFileIfExternalModule() {
41189 setExportContextFlag(file);
41190 if (ts.isExternalModule(file)) {
41191 bindSourceFileAsExternalModule();
41192 }
41193 else if (ts.isJsonSourceFile(file)) {
41194 bindSourceFileAsExternalModule();
41195 // Create symbol equivalent for the module.exports = {}
41196 var originalSymbol = file.symbol;
41197 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
41198 file.symbol = originalSymbol;
41199 }
41200 }
41201 function bindSourceFileAsExternalModule() {
41202 bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
41203 }
41204 function bindExportAssignment(node) {
41205 if (!container.symbol || !container.symbol.exports) {
41206 // Export assignment in some sort of block construct
41207 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
41208 }
41209 else {
41210 var flags = ts.exportAssignmentIsAlias(node)
41211 // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
41212 ? 2097152 /* Alias */
41213 // An export default clause with any other expression exports a value
41214 : 4 /* Property */;
41215 // If there is an `export default x;` alias declaration, can't `export default` anything else.
41216 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
41217 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
41218 if (node.isExportEquals) {
41219 // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
41220 ts.setValueDeclaration(symbol, node);
41221 }
41222 }
41223 }
41224 function bindNamespaceExportDeclaration(node) {
41225 if (node.modifiers && node.modifiers.length) {
41226 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
41227 }
41228 var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
41229 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
41230 : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
41231 : undefined;
41232 if (diag) {
41233 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
41234 }
41235 else {
41236 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
41237 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
41238 }
41239 }
41240 function bindExportDeclaration(node) {
41241 if (!container.symbol || !container.symbol.exports) {
41242 // Export * in some sort of block construct
41243 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
41244 }
41245 else if (!node.exportClause) {
41246 // All export * declarations are collected in an __export symbol
41247 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
41248 }
41249 else if (ts.isNamespaceExport(node.exportClause)) {
41250 // declareSymbol walks up parents to find name text, parent _must_ be set
41251 // but won't be set by the normal binder walk until `bindChildren` later on.
41252 ts.setParent(node.exportClause, node);
41253 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
41254 }
41255 }
41256 function bindImportClause(node) {
41257 if (node.name) {
41258 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
41259 }
41260 }
41261 function setCommonJsModuleIndicator(node) {
41262 if (file.externalModuleIndicator) {
41263 return false;
41264 }
41265 if (!file.commonJsModuleIndicator) {
41266 file.commonJsModuleIndicator = node;
41267 bindSourceFileAsExternalModule();
41268 }
41269 return true;
41270 }
41271 function bindObjectDefinePropertyExport(node) {
41272 if (!setCommonJsModuleIndicator(node)) {
41273 return;
41274 }
41275 var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
41276 if (symbol) {
41277 addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
41278 }
41279 return symbol;
41280 });
41281 if (symbol) {
41282 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
41283 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
41284 }
41285 }
41286 function bindExportsPropertyAssignment(node) {
41287 // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
41288 // expression is the declaration
41289 if (!setCommonJsModuleIndicator(node)) {
41290 return;
41291 }
41292 var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
41293 if (symbol) {
41294 addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
41295 }
41296 return symbol;
41297 });
41298 if (symbol) {
41299 var flags = ts.isClassExpression(node.right) ?
41300 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
41301 4 /* Property */ | 1048576 /* ExportValue */;
41302 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
41303 }
41304 }
41305 function bindModuleExportsAssignment(node) {
41306 // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
41307 // is still pointing to 'module.exports'.
41308 // We do not want to consider this as 'export=' since a module can have only one of these.
41309 // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
41310 if (!setCommonJsModuleIndicator(node)) {
41311 return;
41312 }
41313 var assignedExpression = ts.getRightMostAssignedExpression(node.right);
41314 if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
41315 return;
41316 }
41317 // 'module.exports = expr' assignment
41318 var flags = ts.exportAssignmentIsAlias(node)
41319 ? 2097152 /* Alias */
41320 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
41321 var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
41322 ts.setValueDeclaration(symbol, node);
41323 }
41324 function bindThisPropertyAssignment(node) {
41325 ts.Debug.assert(ts.isInJSFile(node));
41326 // private identifiers *must* be declared (even in JS files)
41327 var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
41328 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
41329 if (hasPrivateIdentifier) {
41330 return;
41331 }
41332 var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
41333 switch (thisContainer.kind) {
41334 case 248 /* FunctionDeclaration */:
41335 case 205 /* FunctionExpression */:
41336 var constructorSymbol = thisContainer.symbol;
41337 // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
41338 if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
41339 var l = thisContainer.parent.left;
41340 if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
41341 constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
41342 }
41343 }
41344 if (constructorSymbol && constructorSymbol.valueDeclaration) {
41345 // Declare a 'member' if the container is an ES5 class or ES6 constructor
41346 constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
41347 // It's acceptable for multiple 'this' assignments of the same identifier to occur
41348 if (ts.hasDynamicName(node)) {
41349 bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
41350 }
41351 else {
41352 declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
41353 }
41354 addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
41355 }
41356 break;
41357 case 165 /* Constructor */:
41358 case 162 /* PropertyDeclaration */:
41359 case 164 /* MethodDeclaration */:
41360 case 166 /* GetAccessor */:
41361 case 167 /* SetAccessor */:
41362 // this.foo assignment in a JavaScript class
41363 // Bind this property to the containing class
41364 var containingClass = thisContainer.parent;
41365 var symbolTable = ts.hasSyntacticModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
41366 if (ts.hasDynamicName(node)) {
41367 bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
41368 }
41369 else {
41370 declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
41371 }
41372 break;
41373 case 294 /* SourceFile */:
41374 // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
41375 if (ts.hasDynamicName(node)) {
41376 break;
41377 }
41378 else if (thisContainer.commonJsModuleIndicator) {
41379 declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
41380 }
41381 else {
41382 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
41383 }
41384 break;
41385 default:
41386 ts.Debug.failBadSyntaxKind(thisContainer);
41387 }
41388 }
41389 function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
41390 bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
41391 addLateBoundAssignmentDeclarationToSymbol(node, symbol);
41392 }
41393 function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
41394 if (symbol) {
41395 (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
41396 }
41397 }
41398 function bindSpecialPropertyDeclaration(node) {
41399 if (node.expression.kind === 107 /* ThisKeyword */) {
41400 bindThisPropertyAssignment(node);
41401 }
41402 else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 294 /* SourceFile */) {
41403 if (ts.isPrototypeAccess(node.expression)) {
41404 bindPrototypePropertyAssignment(node, node.parent);
41405 }
41406 else {
41407 bindStaticPropertyAssignment(node);
41408 }
41409 }
41410 }
41411 /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
41412 function bindPrototypeAssignment(node) {
41413 ts.setParent(node.left, node);
41414 ts.setParent(node.right, node);
41415 bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
41416 }
41417 function bindObjectDefinePrototypeProperty(node) {
41418 var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
41419 if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
41420 // Ensure the namespace symbol becomes class-like
41421 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
41422 }
41423 bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
41424 }
41425 /**
41426 * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
41427 * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
41428 */
41429 function bindPrototypePropertyAssignment(lhs, parent) {
41430 // Look up the function in the local scope, since prototype assignments should
41431 // follow the function declaration
41432 var classPrototype = lhs.expression;
41433 var constructorFunction = classPrototype.expression;
41434 // Fix up parent pointers since we're going to use these nodes before we bind into them
41435 ts.setParent(constructorFunction, classPrototype);
41436 ts.setParent(classPrototype, lhs);
41437 ts.setParent(lhs, parent);
41438 bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
41439 }
41440 function bindObjectDefinePropertyAssignment(node) {
41441 var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
41442 var isToplevel = node.parent.parent.kind === 294 /* SourceFile */;
41443 namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
41444 bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
41445 }
41446 function bindSpecialPropertyAssignment(node) {
41447 // Class declarations in Typescript do not allow property declarations
41448 var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
41449 if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
41450 return;
41451 }
41452 // Fix up parent pointers since we're going to use these nodes before we bind into them
41453 ts.setParent(node.left, node);
41454 ts.setParent(node.right, node);
41455 if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
41456 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
41457 // var util = module.exports;
41458 // util.property = function ...
41459 bindExportsPropertyAssignment(node);
41460 }
41461 else if (ts.hasDynamicName(node)) {
41462 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
41463 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
41464 addLateBoundAssignmentDeclarationToSymbol(node, sym);
41465 }
41466 else {
41467 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
41468 }
41469 }
41470 /**
41471 * 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.
41472 * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
41473 */
41474 function bindStaticPropertyAssignment(node) {
41475 ts.Debug.assert(!ts.isIdentifier(node));
41476 ts.setParent(node.expression, node);
41477 bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
41478 }
41479 function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
41480 if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
41481 return namespaceSymbol;
41482 }
41483 if (isToplevel && !isPrototypeProperty) {
41484 // make symbols or add declarations for intermediate containers
41485 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
41486 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
41487 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
41488 if (symbol) {
41489 addDeclarationToSymbol(symbol, id, flags_1);
41490 return symbol;
41491 }
41492 else {
41493 var table = parent ? parent.exports :
41494 file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
41495 return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
41496 }
41497 });
41498 }
41499 if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
41500 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
41501 }
41502 return namespaceSymbol;
41503 }
41504 function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
41505 if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
41506 return;
41507 }
41508 // Set up the members collection if it doesn't exist already
41509 var symbolTable = isPrototypeProperty ?
41510 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
41511 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
41512 var includes = 0 /* None */;
41513 var excludes = 0 /* None */;
41514 // Method-like
41515 if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
41516 includes = 8192 /* Method */;
41517 excludes = 103359 /* MethodExcludes */;
41518 }
41519 // Maybe accessor-like
41520 else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
41521 if (ts.some(declaration.arguments[2].properties, function (p) {
41522 var id = ts.getNameOfDeclaration(p);
41523 return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
41524 })) {
41525 // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
41526 // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
41527 includes |= 65536 /* SetAccessor */ | 4 /* Property */;
41528 excludes |= 78783 /* SetAccessorExcludes */;
41529 }
41530 if (ts.some(declaration.arguments[2].properties, function (p) {
41531 var id = ts.getNameOfDeclaration(p);
41532 return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
41533 })) {
41534 includes |= 32768 /* GetAccessor */ | 4 /* Property */;
41535 excludes |= 46015 /* GetAccessorExcludes */;
41536 }
41537 }
41538 if (includes === 0 /* None */) {
41539 includes = 4 /* Property */;
41540 excludes = 0 /* PropertyExcludes */;
41541 }
41542 declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
41543 }
41544 function isTopLevelNamespaceAssignment(propertyAccess) {
41545 return ts.isBinaryExpression(propertyAccess.parent)
41546 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 294 /* SourceFile */
41547 : propertyAccess.parent.parent.kind === 294 /* SourceFile */;
41548 }
41549 function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
41550 var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
41551 var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
41552 namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
41553 bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
41554 }
41555 /**
41556 * Javascript expando values are:
41557 * - Functions
41558 * - classes
41559 * - namespaces
41560 * - variables initialized with function expressions
41561 * - with class expressions
41562 * - with empty object literals
41563 * - with non-empty object literals if assigned to the prototype property
41564 */
41565 function isExpandoSymbol(symbol) {
41566 if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
41567 return true;
41568 }
41569 var node = symbol.valueDeclaration;
41570 if (node && ts.isCallExpression(node)) {
41571 return !!ts.getAssignedExpandoInitializer(node);
41572 }
41573 var init = !node ? undefined :
41574 ts.isVariableDeclaration(node) ? node.initializer :
41575 ts.isBinaryExpression(node) ? node.right :
41576 ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
41577 undefined;
41578 init = init && ts.getRightMostAssignedExpression(init);
41579 if (init) {
41580 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
41581 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
41582 }
41583 return false;
41584 }
41585 function getParentOfBinaryExpression(expr) {
41586 while (ts.isBinaryExpression(expr.parent)) {
41587 expr = expr.parent;
41588 }
41589 return expr.parent;
41590 }
41591 function lookupSymbolForPropertyAccess(node, lookupContainer) {
41592 if (lookupContainer === void 0) { lookupContainer = container; }
41593 if (ts.isIdentifier(node)) {
41594 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
41595 }
41596 else {
41597 var symbol = lookupSymbolForPropertyAccess(node.expression);
41598 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
41599 }
41600 }
41601 function forEachIdentifierInEntityName(e, parent, action) {
41602 if (isExportsOrModuleExportsOrAlias(file, e)) {
41603 return file.symbol;
41604 }
41605 else if (ts.isIdentifier(e)) {
41606 return action(e, lookupSymbolForPropertyAccess(e), parent);
41607 }
41608 else {
41609 var s = forEachIdentifierInEntityName(e.expression, parent, action);
41610 var name = ts.getNameOrArgument(e);
41611 // unreachable
41612 if (ts.isPrivateIdentifier(name)) {
41613 ts.Debug.fail("unexpected PrivateIdentifier");
41614 }
41615 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
41616 }
41617 }
41618 function bindCallExpression(node) {
41619 // We're only inspecting call expressions to detect CommonJS modules, so we can skip
41620 // this check if we've already seen the module indicator
41621 if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
41622 setCommonJsModuleIndicator(node);
41623 }
41624 }
41625 function bindClassLikeDeclaration(node) {
41626 if (node.kind === 249 /* ClassDeclaration */) {
41627 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
41628 }
41629 else {
41630 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
41631 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
41632 // Add name of class expression into the map for semantic classifier
41633 if (node.name) {
41634 classifiableNames.add(node.name.escapedText);
41635 }
41636 }
41637 var symbol = node.symbol;
41638 // TypeScript 1.0 spec (April 2014): 8.4
41639 // Every class automatically contains a static property member named 'prototype', the
41640 // type of which is an instantiation of the class type with type Any supplied as a type
41641 // argument for each type parameter. It is an error to explicitly declare a static
41642 // property member with the name 'prototype'.
41643 //
41644 // Note: we check for this here because this class may be merging into a module. The
41645 // module might have an exported variable called 'prototype'. We can't allow that as
41646 // that would clash with the built-in 'prototype' for the class.
41647 var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
41648 var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
41649 if (symbolExport) {
41650 if (node.name) {
41651 ts.setParent(node.name, node);
41652 }
41653 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
41654 }
41655 symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
41656 prototypeSymbol.parent = symbol;
41657 }
41658 function bindEnumDeclaration(node) {
41659 return ts.isEnumConst(node)
41660 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
41661 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
41662 }
41663 function bindVariableDeclarationOrBindingElement(node) {
41664 if (inStrictMode) {
41665 checkStrictModeEvalOrArguments(node, node.name);
41666 }
41667 if (!ts.isBindingPattern(node.name)) {
41668 if (ts.isBlockOrCatchScoped(node)) {
41669 bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
41670 }
41671 else if (ts.isParameterDeclaration(node)) {
41672 // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
41673 // because its parent chain has already been set up, since parents are set before descending into children.
41674 //
41675 // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
41676 // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
41677 // For example:
41678 // function foo([a,a]) {} // Duplicate Identifier error
41679 // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
41680 // // which correctly set excluded symbols
41681 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
41682 }
41683 else {
41684 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
41685 }
41686 }
41687 }
41688 function bindParameter(node) {
41689 if (node.kind === 322 /* JSDocParameterTag */ && container.kind !== 309 /* JSDocSignature */) {
41690 return;
41691 }
41692 if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
41693 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
41694 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
41695 checkStrictModeEvalOrArguments(node, node.name);
41696 }
41697 if (ts.isBindingPattern(node.name)) {
41698 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
41699 }
41700 else {
41701 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
41702 }
41703 // If this is a property-parameter, then also declare the property symbol into the
41704 // containing class.
41705 if (ts.isParameterPropertyDeclaration(node, node.parent)) {
41706 var classDeclaration = node.parent.parent;
41707 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
41708 }
41709 }
41710 function bindFunctionDeclaration(node) {
41711 if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
41712 if (ts.isAsyncFunction(node)) {
41713 emitFlags |= 2048 /* HasAsyncFunctions */;
41714 }
41715 }
41716 checkStrictModeFunctionName(node);
41717 if (inStrictMode) {
41718 checkStrictModeFunctionDeclaration(node);
41719 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
41720 }
41721 else {
41722 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
41723 }
41724 }
41725 function bindFunctionExpression(node) {
41726 if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
41727 if (ts.isAsyncFunction(node)) {
41728 emitFlags |= 2048 /* HasAsyncFunctions */;
41729 }
41730 }
41731 if (currentFlow) {
41732 node.flowNode = currentFlow;
41733 }
41734 checkStrictModeFunctionName(node);
41735 var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
41736 return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
41737 }
41738 function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
41739 if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
41740 emitFlags |= 2048 /* HasAsyncFunctions */;
41741 }
41742 if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
41743 node.flowNode = currentFlow;
41744 }
41745 return ts.hasDynamicName(node)
41746 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
41747 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
41748 }
41749 function getInferTypeContainer(node) {
41750 var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
41751 return extendsType && extendsType.parent;
41752 }
41753 function bindTypeParameter(node) {
41754 if (ts.isJSDocTemplateTag(node.parent)) {
41755 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
41756 if (container_1) {
41757 if (!container_1.locals) {
41758 container_1.locals = ts.createSymbolTable();
41759 }
41760 declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
41761 }
41762 else {
41763 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
41764 }
41765 }
41766 else if (node.parent.kind === 184 /* InferType */) {
41767 var container_2 = getInferTypeContainer(node.parent);
41768 if (container_2) {
41769 if (!container_2.locals) {
41770 container_2.locals = ts.createSymbolTable();
41771 }
41772 declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
41773 }
41774 else {
41775 bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
41776 }
41777 }
41778 else {
41779 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
41780 }
41781 }
41782 // reachability checks
41783 function shouldReportErrorOnModuleDeclaration(node) {
41784 var instanceState = getModuleInstanceState(node);
41785 return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
41786 }
41787 function checkUnreachable(node) {
41788 if (!(currentFlow.flags & 1 /* Unreachable */)) {
41789 return false;
41790 }
41791 if (currentFlow === unreachableFlow) {
41792 var reportError =
41793 // report error on all statements except empty ones
41794 (ts.isStatementButNotDeclaration(node) && node.kind !== 228 /* EmptyStatement */) ||
41795 // report error on class declarations
41796 node.kind === 249 /* ClassDeclaration */ ||
41797 // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
41798 (node.kind === 253 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
41799 if (reportError) {
41800 currentFlow = reportedUnreachableFlow;
41801 if (!options.allowUnreachableCode) {
41802 // unreachable code is reported if
41803 // - user has explicitly asked about it AND
41804 // - statement is in not ambient context (statements in ambient context is already an error
41805 // so we should not report extras) AND
41806 // - node is not variable statement OR
41807 // - node is block scoped variable statement OR
41808 // - node is not block scoped variable statement and at least one variable declaration has initializer
41809 // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
41810 // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
41811 var isError_1 = ts.unreachableCodeIsError(options) &&
41812 !(node.flags & 8388608 /* Ambient */) &&
41813 (!ts.isVariableStatement(node) ||
41814 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
41815 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
41816 eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
41817 }
41818 }
41819 }
41820 return true;
41821 }
41822 }
41823 function eachUnreachableRange(node, cb) {
41824 if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
41825 var statements = node.parent.statements;
41826 var slice_1 = ts.sliceAfter(statements, node);
41827 ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
41828 }
41829 else {
41830 cb(node, node);
41831 }
41832 }
41833 // As opposed to a pure declaration like an `interface`
41834 function isExecutableStatement(s) {
41835 // Don't remove statements that can validly be used before they appear.
41836 return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
41837 // `var x;` may declare a variable used above
41838 !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
41839 }
41840 function isPurelyTypeDeclaration(s) {
41841 switch (s.kind) {
41842 case 250 /* InterfaceDeclaration */:
41843 case 251 /* TypeAliasDeclaration */:
41844 return true;
41845 case 253 /* ModuleDeclaration */:
41846 return getModuleInstanceState(s) !== 1 /* Instantiated */;
41847 case 252 /* EnumDeclaration */:
41848 return ts.hasSyntacticModifier(s, 2048 /* Const */);
41849 default:
41850 return false;
41851 }
41852 }
41853 function isExportsOrModuleExportsOrAlias(sourceFile, node) {
41854 var i = 0;
41855 var q = [node];
41856 while (q.length && i < 100) {
41857 i++;
41858 node = q.shift();
41859 if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
41860 return true;
41861 }
41862 else if (ts.isIdentifier(node)) {
41863 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
41864 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
41865 var init = symbol.valueDeclaration.initializer;
41866 q.push(init);
41867 if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
41868 q.push(init.left);
41869 q.push(init.right);
41870 }
41871 }
41872 }
41873 }
41874 return false;
41875 }
41876 ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
41877 function lookupSymbolForNameWorker(container, name) {
41878 var local = container.locals && container.locals.get(name);
41879 if (local) {
41880 return local.exportSymbol || local;
41881 }
41882 if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
41883 return container.jsGlobalAugmentations.get(name);
41884 }
41885 return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
41886 }
41887})(ts || (ts = {}));
41888/** @internal */
41889var ts;
41890(function (ts) {
41891 function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
41892 return getSymbolWalker;
41893 function getSymbolWalker(accept) {
41894 if (accept === void 0) { accept = function () { return true; }; }
41895 var visitedTypes = []; // Sparse array from id to type
41896 var visitedSymbols = []; // Sparse array from id to symbol
41897 return {
41898 walkType: function (type) {
41899 try {
41900 visitType(type);
41901 return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
41902 }
41903 finally {
41904 ts.clear(visitedTypes);
41905 ts.clear(visitedSymbols);
41906 }
41907 },
41908 walkSymbol: function (symbol) {
41909 try {
41910 visitSymbol(symbol);
41911 return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
41912 }
41913 finally {
41914 ts.clear(visitedTypes);
41915 ts.clear(visitedSymbols);
41916 }
41917 },
41918 };
41919 function visitType(type) {
41920 if (!type) {
41921 return;
41922 }
41923 if (visitedTypes[type.id]) {
41924 return;
41925 }
41926 visitedTypes[type.id] = type;
41927 // Reuse visitSymbol to visit the type's symbol,
41928 // but be sure to bail on recuring into the type if accept declines the symbol.
41929 var shouldBail = visitSymbol(type.symbol);
41930 if (shouldBail)
41931 return;
41932 // Visit the type's related types, if any
41933 if (type.flags & 524288 /* Object */) {
41934 var objectType = type;
41935 var objectFlags = objectType.objectFlags;
41936 if (objectFlags & 4 /* Reference */) {
41937 visitTypeReference(type);
41938 }
41939 if (objectFlags & 32 /* Mapped */) {
41940 visitMappedType(type);
41941 }
41942 if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
41943 visitInterfaceType(type);
41944 }
41945 if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
41946 visitObjectType(objectType);
41947 }
41948 }
41949 if (type.flags & 262144 /* TypeParameter */) {
41950 visitTypeParameter(type);
41951 }
41952 if (type.flags & 3145728 /* UnionOrIntersection */) {
41953 visitUnionOrIntersectionType(type);
41954 }
41955 if (type.flags & 4194304 /* Index */) {
41956 visitIndexType(type);
41957 }
41958 if (type.flags & 8388608 /* IndexedAccess */) {
41959 visitIndexedAccessType(type);
41960 }
41961 }
41962 function visitTypeReference(type) {
41963 visitType(type.target);
41964 ts.forEach(getTypeArguments(type), visitType);
41965 }
41966 function visitTypeParameter(type) {
41967 visitType(getConstraintOfTypeParameter(type));
41968 }
41969 function visitUnionOrIntersectionType(type) {
41970 ts.forEach(type.types, visitType);
41971 }
41972 function visitIndexType(type) {
41973 visitType(type.type);
41974 }
41975 function visitIndexedAccessType(type) {
41976 visitType(type.objectType);
41977 visitType(type.indexType);
41978 visitType(type.constraint);
41979 }
41980 function visitMappedType(type) {
41981 visitType(type.typeParameter);
41982 visitType(type.constraintType);
41983 visitType(type.templateType);
41984 visitType(type.modifiersType);
41985 }
41986 function visitSignature(signature) {
41987 var typePredicate = getTypePredicateOfSignature(signature);
41988 if (typePredicate) {
41989 visitType(typePredicate.type);
41990 }
41991 ts.forEach(signature.typeParameters, visitType);
41992 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
41993 var parameter = _a[_i];
41994 visitSymbol(parameter);
41995 }
41996 visitType(getRestTypeOfSignature(signature));
41997 visitType(getReturnTypeOfSignature(signature));
41998 }
41999 function visitInterfaceType(interfaceT) {
42000 visitObjectType(interfaceT);
42001 ts.forEach(interfaceT.typeParameters, visitType);
42002 ts.forEach(getBaseTypes(interfaceT), visitType);
42003 visitType(interfaceT.thisType);
42004 }
42005 function visitObjectType(type) {
42006 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
42007 visitType(stringIndexType);
42008 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
42009 visitType(numberIndexType);
42010 // The two checks above *should* have already resolved the type (if needed), so this should be cached
42011 var resolved = resolveStructuredTypeMembers(type);
42012 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
42013 var signature = _a[_i];
42014 visitSignature(signature);
42015 }
42016 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
42017 var signature = _c[_b];
42018 visitSignature(signature);
42019 }
42020 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
42021 var p = _e[_d];
42022 visitSymbol(p);
42023 }
42024 }
42025 function visitSymbol(symbol) {
42026 if (!symbol) {
42027 return false;
42028 }
42029 var symbolId = ts.getSymbolId(symbol);
42030 if (visitedSymbols[symbolId]) {
42031 return false;
42032 }
42033 visitedSymbols[symbolId] = symbol;
42034 if (!accept(symbol)) {
42035 return true;
42036 }
42037 var t = getTypeOfSymbol(symbol);
42038 visitType(t); // Should handle members on classes and such
42039 if (symbol.exports) {
42040 symbol.exports.forEach(visitSymbol);
42041 }
42042 ts.forEach(symbol.declarations, function (d) {
42043 // Type queries are too far resolved when we just visit the symbol's type
42044 // (their type resolved directly to the member deeply referenced)
42045 // So to get the intervening symbols, we need to check if there's a type
42046 // query node on any of the symbol's declarations and get symbols there
42047 if (d.type && d.type.kind === 175 /* TypeQuery */) {
42048 var query = d.type;
42049 var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
42050 visitSymbol(entity);
42051 }
42052 });
42053 return false;
42054 }
42055 }
42056 }
42057 ts.createGetSymbolWalker = createGetSymbolWalker;
42058})(ts || (ts = {}));
42059/* @internal */
42060var ts;
42061(function (ts) {
42062 var ambientModuleSymbolRegex = /^".+"$/;
42063 var anon = "(anonymous)";
42064 var nextSymbolId = 1;
42065 var nextNodeId = 1;
42066 var nextMergeId = 1;
42067 var nextFlowId = 1;
42068 var IterationUse;
42069 (function (IterationUse) {
42070 IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
42071 IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
42072 IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
42073 IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
42074 IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
42075 IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
42076 IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
42077 // Spread, Destructuring, Array element assignment
42078 IterationUse[IterationUse["Element"] = 1] = "Element";
42079 IterationUse[IterationUse["Spread"] = 33] = "Spread";
42080 IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
42081 IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
42082 IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
42083 IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
42084 IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
42085 IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
42086 IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
42087 })(IterationUse || (IterationUse = {}));
42088 var IterationTypeKind;
42089 (function (IterationTypeKind) {
42090 IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
42091 IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
42092 IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
42093 })(IterationTypeKind || (IterationTypeKind = {}));
42094 var WideningKind;
42095 (function (WideningKind) {
42096 WideningKind[WideningKind["Normal"] = 0] = "Normal";
42097 WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
42098 WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
42099 WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
42100 })(WideningKind || (WideningKind = {}));
42101 var TypeFacts;
42102 (function (TypeFacts) {
42103 TypeFacts[TypeFacts["None"] = 0] = "None";
42104 TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
42105 TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
42106 TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
42107 TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
42108 TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
42109 TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
42110 TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
42111 TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
42112 TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
42113 TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
42114 TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
42115 TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
42116 TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
42117 TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
42118 TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
42119 TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
42120 TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
42121 TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
42122 TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
42123 TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
42124 TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
42125 TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
42126 TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
42127 TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
42128 TypeFacts[TypeFacts["All"] = 16777215] = "All";
42129 // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
42130 // The presence of a particular fact means that the given test is true for some (and possibly all) values
42131 // of that kind of type.
42132 TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
42133 TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
42134 TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
42135 TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
42136 TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
42137 TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
42138 TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
42139 TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
42140 TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
42141 TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
42142 TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
42143 TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
42144 TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
42145 TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
42146 TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
42147 TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
42148 TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
42149 TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
42150 TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
42151 TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
42152 TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
42153 TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
42154 TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
42155 TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
42156 TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
42157 TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
42158 TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
42159 TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
42160 TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
42161 TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
42162 TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
42163 TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
42164 TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
42165 TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
42166 TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
42167 TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
42168 TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
42169 TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
42170 TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
42171 TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
42172 TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
42173 TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
42174 TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
42175 })(TypeFacts || (TypeFacts = {}));
42176 var typeofEQFacts = new ts.Map(ts.getEntries({
42177 string: 1 /* TypeofEQString */,
42178 number: 2 /* TypeofEQNumber */,
42179 bigint: 4 /* TypeofEQBigInt */,
42180 boolean: 8 /* TypeofEQBoolean */,
42181 symbol: 16 /* TypeofEQSymbol */,
42182 undefined: 65536 /* EQUndefined */,
42183 object: 32 /* TypeofEQObject */,
42184 function: 64 /* TypeofEQFunction */
42185 }));
42186 var typeofNEFacts = new ts.Map(ts.getEntries({
42187 string: 256 /* TypeofNEString */,
42188 number: 512 /* TypeofNENumber */,
42189 bigint: 1024 /* TypeofNEBigInt */,
42190 boolean: 2048 /* TypeofNEBoolean */,
42191 symbol: 4096 /* TypeofNESymbol */,
42192 undefined: 524288 /* NEUndefined */,
42193 object: 8192 /* TypeofNEObject */,
42194 function: 16384 /* TypeofNEFunction */
42195 }));
42196 var TypeSystemPropertyName;
42197 (function (TypeSystemPropertyName) {
42198 TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
42199 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
42200 TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
42201 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
42202 TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
42203 TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
42204 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
42205 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
42206 })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
42207 var CheckMode;
42208 (function (CheckMode) {
42209 CheckMode[CheckMode["Normal"] = 0] = "Normal";
42210 CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
42211 CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
42212 CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
42213 CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
42214 CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
42215 })(CheckMode || (CheckMode = {}));
42216 var AccessFlags;
42217 (function (AccessFlags) {
42218 AccessFlags[AccessFlags["None"] = 0] = "None";
42219 AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
42220 AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
42221 AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
42222 AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
42223 })(AccessFlags || (AccessFlags = {}));
42224 var SignatureCheckMode;
42225 (function (SignatureCheckMode) {
42226 SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
42227 SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
42228 SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
42229 SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
42230 SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
42231 })(SignatureCheckMode || (SignatureCheckMode = {}));
42232 var IntersectionState;
42233 (function (IntersectionState) {
42234 IntersectionState[IntersectionState["None"] = 0] = "None";
42235 IntersectionState[IntersectionState["Source"] = 1] = "Source";
42236 IntersectionState[IntersectionState["Target"] = 2] = "Target";
42237 IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
42238 IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
42239 })(IntersectionState || (IntersectionState = {}));
42240 var MappedTypeModifiers;
42241 (function (MappedTypeModifiers) {
42242 MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
42243 MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
42244 MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
42245 MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
42246 })(MappedTypeModifiers || (MappedTypeModifiers = {}));
42247 var ExpandingFlags;
42248 (function (ExpandingFlags) {
42249 ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
42250 ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
42251 ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
42252 ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
42253 })(ExpandingFlags || (ExpandingFlags = {}));
42254 var MembersOrExportsResolutionKind;
42255 (function (MembersOrExportsResolutionKind) {
42256 MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
42257 MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
42258 })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
42259 var UnusedKind;
42260 (function (UnusedKind) {
42261 UnusedKind[UnusedKind["Local"] = 0] = "Local";
42262 UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
42263 })(UnusedKind || (UnusedKind = {}));
42264 var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
42265 var DeclarationMeaning;
42266 (function (DeclarationMeaning) {
42267 DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
42268 DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
42269 DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
42270 DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
42271 DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
42272 DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
42273 })(DeclarationMeaning || (DeclarationMeaning = {}));
42274 var DeclarationSpaces;
42275 (function (DeclarationSpaces) {
42276 DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
42277 DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
42278 DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
42279 DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
42280 })(DeclarationSpaces || (DeclarationSpaces = {}));
42281 function SymbolLinks() {
42282 }
42283 function NodeLinks() {
42284 this.flags = 0;
42285 }
42286 function getNodeId(node) {
42287 if (!node.id) {
42288 node.id = nextNodeId;
42289 nextNodeId++;
42290 }
42291 return node.id;
42292 }
42293 ts.getNodeId = getNodeId;
42294 function getSymbolId(symbol) {
42295 if (!symbol.id) {
42296 symbol.id = nextSymbolId;
42297 nextSymbolId++;
42298 }
42299 return symbol.id;
42300 }
42301 ts.getSymbolId = getSymbolId;
42302 function isInstantiatedModule(node, preserveConstEnums) {
42303 var moduleState = ts.getModuleInstanceState(node);
42304 return moduleState === 1 /* Instantiated */ ||
42305 (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
42306 }
42307 ts.isInstantiatedModule = isInstantiatedModule;
42308 function createTypeChecker(host, produceDiagnostics) {
42309 var getPackagesSet = ts.memoize(function () {
42310 var set = new ts.Set();
42311 host.getSourceFiles().forEach(function (sf) {
42312 if (!sf.resolvedModules)
42313 return;
42314 ts.forEachEntry(sf.resolvedModules, function (r) {
42315 if (r && r.packageId)
42316 set.add(r.packageId.name);
42317 });
42318 });
42319 return set;
42320 });
42321 // Cancellation that controls whether or not we can cancel in the middle of type checking.
42322 // In general cancelling is *not* safe for the type checker. We might be in the middle of
42323 // computing something, and we will leave our internals in an inconsistent state. Callers
42324 // who set the cancellation token should catch if a cancellation exception occurs, and
42325 // should throw away and create a new TypeChecker.
42326 //
42327 // Currently we only support setting the cancellation token when getting diagnostics. This
42328 // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
42329 // they no longer need the information (for example, if the user started editing again).
42330 var cancellationToken;
42331 var requestedExternalEmitHelpers;
42332 var externalHelpersModule;
42333 var Symbol = ts.objectAllocator.getSymbolConstructor();
42334 var Type = ts.objectAllocator.getTypeConstructor();
42335 var Signature = ts.objectAllocator.getSignatureConstructor();
42336 var typeCount = 0;
42337 var symbolCount = 0;
42338 var enumCount = 0;
42339 var totalInstantiationCount = 0;
42340 var instantiationCount = 0;
42341 var instantiationDepth = 0;
42342 var constraintDepth = 0;
42343 var currentNode;
42344 var emptySymbols = ts.createSymbolTable();
42345 var arrayVariances = [1 /* Covariant */];
42346 var compilerOptions = host.getCompilerOptions();
42347 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
42348 var moduleKind = ts.getEmitModuleKind(compilerOptions);
42349 var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
42350 var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
42351 var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
42352 var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
42353 var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
42354 var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
42355 var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
42356 var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
42357 var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
42358 var emitResolver = createResolver();
42359 var nodeBuilder = createNodeBuilder();
42360 var globals = ts.createSymbolTable();
42361 var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
42362 undefinedSymbol.declarations = [];
42363 var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
42364 globalThisSymbol.exports = globals;
42365 globalThisSymbol.declarations = [];
42366 globals.set(globalThisSymbol.escapedName, globalThisSymbol);
42367 var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
42368 var requireSymbol = createSymbol(4 /* Property */, "require");
42369 /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
42370 var apparentArgumentCount;
42371 // for public members that accept a Node or one of its subtypes, we must guard against
42372 // synthetic nodes created during transformations by calling `getParseTreeNode`.
42373 // for most of these, we perform the guard only on `checker` to avoid any possible
42374 // extra cost of calling `getParseTreeNode` when calling these functions from inside the
42375 // checker.
42376 var checker = {
42377 getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
42378 getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
42379 getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
42380 getTypeCount: function () { return typeCount; },
42381 getInstantiationCount: function () { return totalInstantiationCount; },
42382 getRelationCacheSizes: function () { return ({
42383 assignable: assignableRelation.size,
42384 identity: identityRelation.size,
42385 subtype: subtypeRelation.size,
42386 strictSubtype: strictSubtypeRelation.size,
42387 }); },
42388 isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
42389 isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
42390 isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
42391 getMergedSymbol: getMergedSymbol,
42392 getDiagnostics: getDiagnostics,
42393 getGlobalDiagnostics: getGlobalDiagnostics,
42394 getTypeOfSymbolAtLocation: function (symbol, locationIn) {
42395 var location = ts.getParseTreeNode(locationIn);
42396 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
42397 },
42398 getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
42399 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
42400 if (parameter === undefined)
42401 return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
42402 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
42403 },
42404 getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
42405 getPropertiesOfType: getPropertiesOfType,
42406 getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
42407 getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
42408 var node = ts.getParseTreeNode(location);
42409 if (!node) {
42410 return undefined;
42411 }
42412 var propName = ts.escapeLeadingUnderscores(name);
42413 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
42414 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
42415 },
42416 getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
42417 getIndexInfoOfType: getIndexInfoOfType,
42418 getSignaturesOfType: getSignaturesOfType,
42419 getIndexTypeOfType: getIndexTypeOfType,
42420 getBaseTypes: getBaseTypes,
42421 getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
42422 getWidenedType: getWidenedType,
42423 getTypeFromTypeNode: function (nodeIn) {
42424 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
42425 return node ? getTypeFromTypeNode(node) : errorType;
42426 },
42427 getParameterType: getTypeAtPosition,
42428 getPromisedTypeOfPromise: getPromisedTypeOfPromise,
42429 getAwaitedType: function (type) { return getAwaitedType(type); },
42430 getReturnTypeOfSignature: getReturnTypeOfSignature,
42431 isNullableType: isNullableType,
42432 getNullableType: getNullableType,
42433 getNonNullableType: getNonNullableType,
42434 getNonOptionalType: removeOptionalTypeMarker,
42435 getTypeArguments: getTypeArguments,
42436 typeToTypeNode: nodeBuilder.typeToTypeNode,
42437 indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
42438 signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
42439 symbolToEntityName: nodeBuilder.symbolToEntityName,
42440 symbolToExpression: nodeBuilder.symbolToExpression,
42441 symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
42442 symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
42443 typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
42444 getSymbolsInScope: function (locationIn, meaning) {
42445 var location = ts.getParseTreeNode(locationIn);
42446 return location ? getSymbolsInScope(location, meaning) : [];
42447 },
42448 getSymbolAtLocation: function (nodeIn) {
42449 var node = ts.getParseTreeNode(nodeIn);
42450 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
42451 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
42452 },
42453 getShorthandAssignmentValueSymbol: function (nodeIn) {
42454 var node = ts.getParseTreeNode(nodeIn);
42455 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
42456 },
42457 getExportSpecifierLocalTargetSymbol: function (nodeIn) {
42458 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
42459 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
42460 },
42461 getExportSymbolOfSymbol: function (symbol) {
42462 return getMergedSymbol(symbol.exportSymbol || symbol);
42463 },
42464 getTypeAtLocation: function (nodeIn) {
42465 var node = ts.getParseTreeNode(nodeIn);
42466 return node ? getTypeOfNode(node) : errorType;
42467 },
42468 getTypeOfAssignmentPattern: function (nodeIn) {
42469 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
42470 return node && getTypeOfAssignmentPattern(node) || errorType;
42471 },
42472 getPropertySymbolOfDestructuringAssignment: function (locationIn) {
42473 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
42474 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
42475 },
42476 signatureToString: function (signature, enclosingDeclaration, flags, kind) {
42477 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
42478 },
42479 typeToString: function (type, enclosingDeclaration, flags) {
42480 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
42481 },
42482 symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
42483 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
42484 },
42485 typePredicateToString: function (predicate, enclosingDeclaration, flags) {
42486 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
42487 },
42488 writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
42489 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
42490 },
42491 writeType: function (type, enclosingDeclaration, flags, writer) {
42492 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
42493 },
42494 writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
42495 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
42496 },
42497 writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
42498 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
42499 },
42500 getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
42501 getRootSymbols: getRootSymbols,
42502 getContextualType: function (nodeIn, contextFlags) {
42503 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
42504 if (!node) {
42505 return undefined;
42506 }
42507 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
42508 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
42509 if (contextFlags & 4 /* Completions */ && containingCall) {
42510 var toMarkSkip = node;
42511 do {
42512 getNodeLinks(toMarkSkip).skipDirectInference = true;
42513 toMarkSkip = toMarkSkip.parent;
42514 } while (toMarkSkip && toMarkSkip !== containingCall);
42515 getNodeLinks(containingCall).resolvedSignature = undefined;
42516 }
42517 var result = getContextualType(node, contextFlags);
42518 if (contextFlags & 4 /* Completions */ && containingCall) {
42519 var toMarkSkip = node;
42520 do {
42521 getNodeLinks(toMarkSkip).skipDirectInference = undefined;
42522 toMarkSkip = toMarkSkip.parent;
42523 } while (toMarkSkip && toMarkSkip !== containingCall);
42524 getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
42525 }
42526 return result;
42527 },
42528 getContextualTypeForObjectLiteralElement: function (nodeIn) {
42529 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
42530 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
42531 },
42532 getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
42533 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
42534 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
42535 },
42536 getContextualTypeForJsxAttribute: function (nodeIn) {
42537 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
42538 return node && getContextualTypeForJsxAttribute(node);
42539 },
42540 isContextSensitive: isContextSensitive,
42541 getFullyQualifiedName: getFullyQualifiedName,
42542 getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
42543 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
42544 },
42545 getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
42546 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
42547 },
42548 getExpandedParameters: getExpandedParameters,
42549 hasEffectiveRestParameter: hasEffectiveRestParameter,
42550 getConstantValue: function (nodeIn) {
42551 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
42552 return node ? getConstantValue(node) : undefined;
42553 },
42554 isValidPropertyAccess: function (nodeIn, propertyName) {
42555 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
42556 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
42557 },
42558 isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
42559 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
42560 return !!node && isValidPropertyAccessForCompletions(node, type, property);
42561 },
42562 getSignatureFromDeclaration: function (declarationIn) {
42563 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
42564 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
42565 },
42566 isImplementationOfOverload: function (nodeIn) {
42567 var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
42568 return node ? isImplementationOfOverload(node) : undefined;
42569 },
42570 getImmediateAliasedSymbol: getImmediateAliasedSymbol,
42571 getAliasedSymbol: resolveAlias,
42572 getEmitResolver: getEmitResolver,
42573 getExportsOfModule: getExportsOfModuleAsArray,
42574 getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
42575 getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
42576 getAmbientModules: getAmbientModules,
42577 getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
42578 isOptionalParameter: function (nodeIn) {
42579 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
42580 return node ? isOptionalParameter(node) : false;
42581 },
42582 tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
42583 tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
42584 tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
42585 // we deliberately exclude augmentations
42586 // since we are only interested in declarations of the module itself
42587 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
42588 },
42589 getApparentType: getApparentType,
42590 getUnionType: getUnionType,
42591 isTypeAssignableTo: isTypeAssignableTo,
42592 createAnonymousType: createAnonymousType,
42593 createSignature: createSignature,
42594 createSymbol: createSymbol,
42595 createIndexInfo: createIndexInfo,
42596 getAnyType: function () { return anyType; },
42597 getStringType: function () { return stringType; },
42598 getNumberType: function () { return numberType; },
42599 createPromiseType: createPromiseType,
42600 createArrayType: createArrayType,
42601 getElementTypeOfArrayType: getElementTypeOfArrayType,
42602 getBooleanType: function () { return booleanType; },
42603 getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
42604 getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
42605 getVoidType: function () { return voidType; },
42606 getUndefinedType: function () { return undefinedType; },
42607 getNullType: function () { return nullType; },
42608 getESSymbolType: function () { return esSymbolType; },
42609 getNeverType: function () { return neverType; },
42610 getOptionalType: function () { return optionalType; },
42611 isSymbolAccessible: isSymbolAccessible,
42612 isArrayType: isArrayType,
42613 isTupleType: isTupleType,
42614 isArrayLikeType: isArrayLikeType,
42615 isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
42616 getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
42617 getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
42618 getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
42619 getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
42620 getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
42621 getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
42622 getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
42623 getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
42624 getBaseConstraintOfType: getBaseConstraintOfType,
42625 getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
42626 resolveName: function (name, location, meaning, excludeGlobals) {
42627 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
42628 },
42629 getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
42630 getAccessibleSymbolChain: getAccessibleSymbolChain,
42631 getTypePredicateOfSignature: getTypePredicateOfSignature,
42632 resolveExternalModuleName: function (moduleSpecifierIn) {
42633 var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
42634 return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
42635 },
42636 resolveExternalModuleSymbol: resolveExternalModuleSymbol,
42637 tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
42638 var node = ts.getParseTreeNode(nodeIn);
42639 return node && tryGetThisTypeAt(node, includeGlobalThis);
42640 },
42641 getTypeArgumentConstraint: function (nodeIn) {
42642 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
42643 return node && getTypeArgumentConstraint(node);
42644 },
42645 getSuggestionDiagnostics: function (fileIn, ct) {
42646 var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
42647 if (ts.skipTypeChecking(file, compilerOptions, host)) {
42648 return ts.emptyArray;
42649 }
42650 var diagnostics;
42651 try {
42652 // Record the cancellation token so it can be checked later on during checkSourceElement.
42653 // Do this in a finally block so we can ensure that it gets reset back to nothing after
42654 // this call is done.
42655 cancellationToken = ct;
42656 // Ensure file is type checked
42657 checkSourceFile(file);
42658 ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
42659 diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
42660 checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
42661 if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
42662 (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
42663 }
42664 });
42665 return diagnostics || ts.emptyArray;
42666 }
42667 finally {
42668 cancellationToken = undefined;
42669 }
42670 },
42671 runWithCancellationToken: function (token, callback) {
42672 try {
42673 cancellationToken = token;
42674 return callback(checker);
42675 }
42676 finally {
42677 cancellationToken = undefined;
42678 }
42679 },
42680 getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
42681 isDeclarationVisible: isDeclarationVisible,
42682 };
42683 function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
42684 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
42685 apparentArgumentCount = argumentCount;
42686 var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
42687 apparentArgumentCount = undefined;
42688 return res;
42689 }
42690 var tupleTypes = new ts.Map();
42691 var unionTypes = new ts.Map();
42692 var intersectionTypes = new ts.Map();
42693 var literalTypes = new ts.Map();
42694 var indexedAccessTypes = new ts.Map();
42695 var substitutionTypes = new ts.Map();
42696 var evolvingArrayTypes = [];
42697 var undefinedProperties = new ts.Map();
42698 var unknownSymbol = createSymbol(4 /* Property */, "unknown");
42699 var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
42700 var anyType = createIntrinsicType(1 /* Any */, "any");
42701 var autoType = createIntrinsicType(1 /* Any */, "any");
42702 var wildcardType = createIntrinsicType(1 /* Any */, "any");
42703 var errorType = createIntrinsicType(1 /* Any */, "error");
42704 var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
42705 var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
42706 var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
42707 var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
42708 var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
42709 var nullType = createIntrinsicType(65536 /* Null */, "null");
42710 var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
42711 var stringType = createIntrinsicType(4 /* String */, "string");
42712 var numberType = createIntrinsicType(8 /* Number */, "number");
42713 var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
42714 var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
42715 var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
42716 var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
42717 var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
42718 trueType.regularType = regularTrueType;
42719 trueType.freshType = trueType;
42720 regularTrueType.regularType = regularTrueType;
42721 regularTrueType.freshType = trueType;
42722 falseType.regularType = regularFalseType;
42723 falseType.freshType = falseType;
42724 regularFalseType.regularType = regularFalseType;
42725 regularFalseType.freshType = falseType;
42726 var booleanType = createBooleanType([regularFalseType, regularTrueType]);
42727 // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
42728 // (The union is cached, so simply doing the marking here is sufficient)
42729 createBooleanType([regularFalseType, trueType]);
42730 createBooleanType([falseType, regularTrueType]);
42731 createBooleanType([falseType, trueType]);
42732 var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
42733 var voidType = createIntrinsicType(16384 /* Void */, "void");
42734 var neverType = createIntrinsicType(131072 /* Never */, "never");
42735 var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
42736 var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
42737 var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
42738 var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
42739 var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
42740 var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
42741 var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
42742 var numberOrBigIntType = getUnionType([numberType, bigintType]);
42743 var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
42744 var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
42745 var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42746 var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42747 emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
42748 var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
42749 emptyTypeLiteralSymbol.members = ts.createSymbolTable();
42750 var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42751 var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42752 emptyGenericType.instantiations = new ts.Map();
42753 var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42754 // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
42755 // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
42756 anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
42757 var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42758 var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42759 var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
42760 var markerSuperType = createTypeParameter();
42761 var markerSubType = createTypeParameter();
42762 markerSubType.constraint = markerSuperType;
42763 var markerOtherType = createTypeParameter();
42764 var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
42765 var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
42766 var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
42767 var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
42768 var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
42769 var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
42770 var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
42771 var noIterationTypes = {
42772 get yieldType() { return ts.Debug.fail("Not supported"); },
42773 get returnType() { return ts.Debug.fail("Not supported"); },
42774 get nextType() { return ts.Debug.fail("Not supported"); },
42775 };
42776 var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
42777 var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
42778 var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
42779 var asyncIterationTypesResolver = {
42780 iterableCacheKey: "iterationTypesOfAsyncIterable",
42781 iteratorCacheKey: "iterationTypesOfAsyncIterator",
42782 iteratorSymbolName: "asyncIterator",
42783 getGlobalIteratorType: getGlobalAsyncIteratorType,
42784 getGlobalIterableType: getGlobalAsyncIterableType,
42785 getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
42786 getGlobalGeneratorType: getGlobalAsyncGeneratorType,
42787 resolveIterationType: getAwaitedType,
42788 mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
42789 mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
42790 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,
42791 };
42792 var syncIterationTypesResolver = {
42793 iterableCacheKey: "iterationTypesOfIterable",
42794 iteratorCacheKey: "iterationTypesOfIterator",
42795 iteratorSymbolName: "iterator",
42796 getGlobalIteratorType: getGlobalIteratorType,
42797 getGlobalIterableType: getGlobalIterableType,
42798 getGlobalIterableIteratorType: getGlobalIterableIteratorType,
42799 getGlobalGeneratorType: getGlobalGeneratorType,
42800 resolveIterationType: function (type, _errorNode) { return type; },
42801 mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
42802 mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
42803 mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
42804 };
42805 /** Key is "/path/to/a.ts|/path/to/b.ts". */
42806 var amalgamatedDuplicates;
42807 var reverseMappedCache = new ts.Map();
42808 var inInferTypeForHomomorphicMappedType = false;
42809 var ambientModulesCache;
42810 /**
42811 * List of every ambient module with a "*" wildcard.
42812 * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
42813 * This is only used if there is no exact match.
42814 */
42815 var patternAmbientModules;
42816 var patternAmbientModuleAugmentations;
42817 var globalObjectType;
42818 var globalFunctionType;
42819 var globalCallableFunctionType;
42820 var globalNewableFunctionType;
42821 var globalArrayType;
42822 var globalReadonlyArrayType;
42823 var globalStringType;
42824 var globalNumberType;
42825 var globalBooleanType;
42826 var globalRegExpType;
42827 var globalThisType;
42828 var anyArrayType;
42829 var autoArrayType;
42830 var anyReadonlyArrayType;
42831 var deferredGlobalNonNullableTypeAlias;
42832 // The library files are only loaded when the feature is used.
42833 // This allows users to just specify library files they want to used through --lib
42834 // and they will not get an error from not having unrelated library files
42835 var deferredGlobalESSymbolConstructorSymbol;
42836 var deferredGlobalESSymbolType;
42837 var deferredGlobalTypedPropertyDescriptorType;
42838 var deferredGlobalPromiseType;
42839 var deferredGlobalPromiseLikeType;
42840 var deferredGlobalPromiseConstructorSymbol;
42841 var deferredGlobalPromiseConstructorLikeType;
42842 var deferredGlobalIterableType;
42843 var deferredGlobalIteratorType;
42844 var deferredGlobalIterableIteratorType;
42845 var deferredGlobalGeneratorType;
42846 var deferredGlobalIteratorYieldResultType;
42847 var deferredGlobalIteratorReturnResultType;
42848 var deferredGlobalAsyncIterableType;
42849 var deferredGlobalAsyncIteratorType;
42850 var deferredGlobalAsyncIterableIteratorType;
42851 var deferredGlobalAsyncGeneratorType;
42852 var deferredGlobalTemplateStringsArrayType;
42853 var deferredGlobalImportMetaType;
42854 var deferredGlobalExtractSymbol;
42855 var deferredGlobalOmitSymbol;
42856 var deferredGlobalBigIntType;
42857 var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
42858 var flowLoopStart = 0;
42859 var flowLoopCount = 0;
42860 var sharedFlowCount = 0;
42861 var flowAnalysisDisabled = false;
42862 var flowInvocationCount = 0;
42863 var lastFlowNode;
42864 var lastFlowNodeReachable;
42865 var flowTypeCache;
42866 var emptyStringType = getLiteralType("");
42867 var zeroType = getLiteralType(0);
42868 var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
42869 var resolutionTargets = [];
42870 var resolutionResults = [];
42871 var resolutionPropertyNames = [];
42872 var suggestionCount = 0;
42873 var maximumSuggestionCount = 10;
42874 var mergedSymbols = [];
42875 var symbolLinks = [];
42876 var nodeLinks = [];
42877 var flowLoopCaches = [];
42878 var flowLoopNodes = [];
42879 var flowLoopKeys = [];
42880 var flowLoopTypes = [];
42881 var sharedFlowNodes = [];
42882 var sharedFlowTypes = [];
42883 var flowNodeReachable = [];
42884 var flowNodePostSuper = [];
42885 var potentialThisCollisions = [];
42886 var potentialNewTargetCollisions = [];
42887 var potentialWeakMapCollisions = [];
42888 var awaitedTypeStack = [];
42889 var diagnostics = ts.createDiagnosticCollection();
42890 var suggestionDiagnostics = ts.createDiagnosticCollection();
42891 var typeofTypesByName = new ts.Map(ts.getEntries({
42892 string: stringType,
42893 number: numberType,
42894 bigint: bigintType,
42895 boolean: booleanType,
42896 symbol: esSymbolType,
42897 undefined: undefinedType
42898 }));
42899 var typeofType = createTypeofType();
42900 var _jsxNamespace;
42901 var _jsxFactoryEntity;
42902 var outofbandVarianceMarkerHandler;
42903 var subtypeRelation = new ts.Map();
42904 var strictSubtypeRelation = new ts.Map();
42905 var assignableRelation = new ts.Map();
42906 var comparableRelation = new ts.Map();
42907 var identityRelation = new ts.Map();
42908 var enumRelation = new ts.Map();
42909 var builtinGlobals = ts.createSymbolTable();
42910 builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
42911 initializeTypeChecker();
42912 return checker;
42913 function getJsxNamespace(location) {
42914 if (location) {
42915 var file = ts.getSourceFileOfNode(location);
42916 if (file) {
42917 if (ts.isJsxOpeningFragment(location)) {
42918 if (file.localJsxFragmentNamespace) {
42919 return file.localJsxFragmentNamespace;
42920 }
42921 var jsxFragmentPragma = file.pragmas.get("jsxfrag");
42922 if (jsxFragmentPragma) {
42923 var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
42924 file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
42925 ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
42926 if (file.localJsxFragmentFactory) {
42927 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
42928 }
42929 }
42930 var entity = getJsxFragmentFactoryEntity(location);
42931 if (entity) {
42932 file.localJsxFragmentFactory = entity;
42933 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
42934 }
42935 }
42936 else {
42937 if (file.localJsxNamespace) {
42938 return file.localJsxNamespace;
42939 }
42940 var jsxPragma = file.pragmas.get("jsx");
42941 if (jsxPragma) {
42942 var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
42943 file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
42944 ts.visitNode(file.localJsxFactory, markAsSynthetic);
42945 if (file.localJsxFactory) {
42946 return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
42947 }
42948 }
42949 }
42950 }
42951 }
42952 if (!_jsxNamespace) {
42953 _jsxNamespace = "React";
42954 if (compilerOptions.jsxFactory) {
42955 _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
42956 ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
42957 if (_jsxFactoryEntity) {
42958 _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
42959 }
42960 }
42961 else if (compilerOptions.reactNamespace) {
42962 _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
42963 }
42964 }
42965 if (!_jsxFactoryEntity) {
42966 _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
42967 }
42968 return _jsxNamespace;
42969 function markAsSynthetic(node) {
42970 ts.setTextRangePosEnd(node, -1, -1);
42971 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
42972 }
42973 }
42974 function getEmitResolver(sourceFile, cancellationToken) {
42975 // Ensure we have all the type information in place for this file so that all the
42976 // emitter questions of this resolver will return the right information.
42977 getDiagnostics(sourceFile, cancellationToken);
42978 return emitResolver;
42979 }
42980 function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
42981 var diagnostic = location
42982 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
42983 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
42984 var existing = diagnostics.lookup(diagnostic);
42985 if (existing) {
42986 return existing;
42987 }
42988 else {
42989 diagnostics.add(diagnostic);
42990 return diagnostic;
42991 }
42992 }
42993 function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
42994 var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
42995 diagnostic.skippedOn = key;
42996 return diagnostic;
42997 }
42998 function error(location, message, arg0, arg1, arg2, arg3) {
42999 var diagnostic = location
43000 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
43001 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
43002 diagnostics.add(diagnostic);
43003 return diagnostic;
43004 }
43005 function addErrorOrSuggestion(isError, diagnostic) {
43006 if (isError) {
43007 diagnostics.add(diagnostic);
43008 }
43009 else {
43010 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
43011 }
43012 }
43013 function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
43014 addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
43015 }
43016 function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
43017 var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
43018 if (maybeMissingAwait) {
43019 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
43020 ts.addRelatedInfo(diagnostic, related);
43021 }
43022 return diagnostic;
43023 }
43024 function createSymbol(flags, name, checkFlags) {
43025 symbolCount++;
43026 var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
43027 symbol.checkFlags = checkFlags || 0;
43028 return symbol;
43029 }
43030 function getExcludedSymbolFlags(flags) {
43031 var result = 0;
43032 if (flags & 2 /* BlockScopedVariable */)
43033 result |= 111551 /* BlockScopedVariableExcludes */;
43034 if (flags & 1 /* FunctionScopedVariable */)
43035 result |= 111550 /* FunctionScopedVariableExcludes */;
43036 if (flags & 4 /* Property */)
43037 result |= 0 /* PropertyExcludes */;
43038 if (flags & 8 /* EnumMember */)
43039 result |= 900095 /* EnumMemberExcludes */;
43040 if (flags & 16 /* Function */)
43041 result |= 110991 /* FunctionExcludes */;
43042 if (flags & 32 /* Class */)
43043 result |= 899503 /* ClassExcludes */;
43044 if (flags & 64 /* Interface */)
43045 result |= 788872 /* InterfaceExcludes */;
43046 if (flags & 256 /* RegularEnum */)
43047 result |= 899327 /* RegularEnumExcludes */;
43048 if (flags & 128 /* ConstEnum */)
43049 result |= 899967 /* ConstEnumExcludes */;
43050 if (flags & 512 /* ValueModule */)
43051 result |= 110735 /* ValueModuleExcludes */;
43052 if (flags & 8192 /* Method */)
43053 result |= 103359 /* MethodExcludes */;
43054 if (flags & 32768 /* GetAccessor */)
43055 result |= 46015 /* GetAccessorExcludes */;
43056 if (flags & 65536 /* SetAccessor */)
43057 result |= 78783 /* SetAccessorExcludes */;
43058 if (flags & 262144 /* TypeParameter */)
43059 result |= 526824 /* TypeParameterExcludes */;
43060 if (flags & 524288 /* TypeAlias */)
43061 result |= 788968 /* TypeAliasExcludes */;
43062 if (flags & 2097152 /* Alias */)
43063 result |= 2097152 /* AliasExcludes */;
43064 return result;
43065 }
43066 function recordMergedSymbol(target, source) {
43067 if (!source.mergeId) {
43068 source.mergeId = nextMergeId;
43069 nextMergeId++;
43070 }
43071 mergedSymbols[source.mergeId] = target;
43072 }
43073 function cloneSymbol(symbol) {
43074 var result = createSymbol(symbol.flags, symbol.escapedName);
43075 result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
43076 result.parent = symbol.parent;
43077 if (symbol.valueDeclaration)
43078 result.valueDeclaration = symbol.valueDeclaration;
43079 if (symbol.constEnumOnlyModule)
43080 result.constEnumOnlyModule = true;
43081 if (symbol.members)
43082 result.members = new ts.Map(symbol.members);
43083 if (symbol.exports)
43084 result.exports = new ts.Map(symbol.exports);
43085 recordMergedSymbol(result, symbol);
43086 return result;
43087 }
43088 /**
43089 * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
43090 * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
43091 */
43092 function mergeSymbol(target, source, unidirectional) {
43093 if (unidirectional === void 0) { unidirectional = false; }
43094 if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
43095 (source.flags | target.flags) & 67108864 /* Assignment */) {
43096 if (source === target) {
43097 // This can happen when an export assigned namespace exports something also erroneously exported at the top level
43098 // See `declarationFileNoCrashOnExtraExportModifier` for an example
43099 return target;
43100 }
43101 if (!(target.flags & 33554432 /* Transient */)) {
43102 var resolvedTarget = resolveSymbol(target);
43103 if (resolvedTarget === unknownSymbol) {
43104 return source;
43105 }
43106 target = cloneSymbol(resolvedTarget);
43107 }
43108 // Javascript static-property-assignment declarations always merge, even though they are also values
43109 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
43110 // reset flag when merging instantiated module into value module that has only const enums
43111 target.constEnumOnlyModule = false;
43112 }
43113 target.flags |= source.flags;
43114 if (source.valueDeclaration) {
43115 ts.setValueDeclaration(target, source.valueDeclaration);
43116 }
43117 ts.addRange(target.declarations, source.declarations);
43118 if (source.members) {
43119 if (!target.members)
43120 target.members = ts.createSymbolTable();
43121 mergeSymbolTable(target.members, source.members, unidirectional);
43122 }
43123 if (source.exports) {
43124 if (!target.exports)
43125 target.exports = ts.createSymbolTable();
43126 mergeSymbolTable(target.exports, source.exports, unidirectional);
43127 }
43128 if (!unidirectional) {
43129 recordMergedSymbol(target, source);
43130 }
43131 }
43132 else if (target.flags & 1024 /* NamespaceModule */) {
43133 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
43134 // as we will already report a "Declaration name conflicts..." error, and this error
43135 // won't make much sense.
43136 if (target !== globalThisSymbol) {
43137 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));
43138 }
43139 }
43140 else { // error
43141 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
43142 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
43143 var message = isEitherEnum
43144 ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
43145 : isEitherBlockScoped_1
43146 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
43147 : ts.Diagnostics.Duplicate_identifier_0;
43148 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
43149 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
43150 var symbolName_1 = symbolToString(source);
43151 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
43152 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
43153 var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
43154 var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
43155 var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
43156 return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
43157 });
43158 var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
43159 return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
43160 });
43161 addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
43162 addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
43163 }
43164 else {
43165 addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
43166 addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
43167 }
43168 }
43169 return target;
43170 function addDuplicateLocations(locs, symbol) {
43171 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43172 var decl = _a[_i];
43173 ts.pushIfUnique(locs, decl);
43174 }
43175 }
43176 }
43177 function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
43178 ts.forEach(target.declarations, function (node) {
43179 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
43180 });
43181 }
43182 function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
43183 var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
43184 var err = lookupOrIssueError(errorNode, message, symbolName);
43185 var _loop_7 = function (relatedNode) {
43186 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
43187 if (adjustedNode === errorNode)
43188 return "continue";
43189 err.relatedInformation = err.relatedInformation || [];
43190 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
43191 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
43192 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 */; }))
43193 return "continue";
43194 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
43195 };
43196 for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
43197 var relatedNode = _a[_i];
43198 _loop_7(relatedNode);
43199 }
43200 }
43201 function combineSymbolTables(first, second) {
43202 if (!(first === null || first === void 0 ? void 0 : first.size))
43203 return second;
43204 if (!(second === null || second === void 0 ? void 0 : second.size))
43205 return first;
43206 var combined = ts.createSymbolTable();
43207 mergeSymbolTable(combined, first);
43208 mergeSymbolTable(combined, second);
43209 return combined;
43210 }
43211 function mergeSymbolTable(target, source, unidirectional) {
43212 if (unidirectional === void 0) { unidirectional = false; }
43213 source.forEach(function (sourceSymbol, id) {
43214 var targetSymbol = target.get(id);
43215 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
43216 });
43217 }
43218 function mergeModuleAugmentation(moduleName) {
43219 var _a, _b;
43220 var moduleAugmentation = moduleName.parent;
43221 if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
43222 // this is a combined symbol for multiple augmentations within the same file.
43223 // its symbol already has accumulated information for all declarations
43224 // so we need to add it just once - do the work only for first declaration
43225 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
43226 return;
43227 }
43228 if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
43229 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
43230 }
43231 else {
43232 // find a module that about to be augmented
43233 // do not validate names of augmentations that are defined in ambient context
43234 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
43235 ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
43236 : undefined;
43237 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
43238 if (!mainModule_1) {
43239 return;
43240 }
43241 // obtain item referenced by 'export='
43242 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
43243 if (mainModule_1.flags & 1920 /* Namespace */) {
43244 // If we're merging an augmentation to a pattern ambient module, we want to
43245 // perform the merge unidirectionally from the augmentation ('a.foo') to
43246 // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
43247 // all the exports both from the pattern and from the augmentation, but
43248 // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
43249 if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
43250 var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
43251 if (!patternAmbientModuleAugmentations) {
43252 patternAmbientModuleAugmentations = new ts.Map();
43253 }
43254 // moduleName will be a StringLiteral since this is not `declare global`.
43255 patternAmbientModuleAugmentations.set(moduleName.text, merged);
43256 }
43257 else {
43258 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)) {
43259 // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
43260 var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
43261 for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
43262 var _d = _c[_i], key = _d[0], value = _d[1];
43263 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
43264 mergeSymbol(resolvedExports.get(key), value);
43265 }
43266 }
43267 }
43268 mergeSymbol(mainModule_1, moduleAugmentation.symbol);
43269 }
43270 }
43271 else {
43272 // moduleName will be a StringLiteral since this is not `declare global`.
43273 error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
43274 }
43275 }
43276 }
43277 function addToSymbolTable(target, source, message) {
43278 source.forEach(function (sourceSymbol, id) {
43279 var targetSymbol = target.get(id);
43280 if (targetSymbol) {
43281 // Error on redeclarations
43282 ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
43283 }
43284 else {
43285 target.set(id, sourceSymbol);
43286 }
43287 });
43288 function addDeclarationDiagnostic(id, message) {
43289 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
43290 }
43291 }
43292 function getSymbolLinks(symbol) {
43293 if (symbol.flags & 33554432 /* Transient */)
43294 return symbol;
43295 var id = getSymbolId(symbol);
43296 return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
43297 }
43298 function getNodeLinks(node) {
43299 var nodeId = getNodeId(node);
43300 return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
43301 }
43302 function isGlobalSourceFile(node) {
43303 return node.kind === 294 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
43304 }
43305 function getSymbol(symbols, name, meaning) {
43306 if (meaning) {
43307 var symbol = getMergedSymbol(symbols.get(name));
43308 if (symbol) {
43309 ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
43310 if (symbol.flags & meaning) {
43311 return symbol;
43312 }
43313 if (symbol.flags & 2097152 /* Alias */) {
43314 var target = resolveAlias(symbol);
43315 // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
43316 if (target === unknownSymbol || target.flags & meaning) {
43317 return symbol;
43318 }
43319 }
43320 }
43321 }
43322 // return undefined if we can't find a symbol.
43323 }
43324 /**
43325 * Get symbols that represent parameter-property-declaration as parameter and as property declaration
43326 * @param parameter a parameterDeclaration node
43327 * @param parameterName a name of the parameter to get the symbols for.
43328 * @return a tuple of two symbols
43329 */
43330 function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
43331 var constructorDeclaration = parameter.parent;
43332 var classDeclaration = parameter.parent.parent;
43333 var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
43334 var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
43335 if (parameterSymbol && propertySymbol) {
43336 return [parameterSymbol, propertySymbol];
43337 }
43338 return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
43339 }
43340 function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
43341 var declarationFile = ts.getSourceFileOfNode(declaration);
43342 var useFile = ts.getSourceFileOfNode(usage);
43343 var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
43344 if (declarationFile !== useFile) {
43345 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
43346 (!ts.outFile(compilerOptions)) ||
43347 isInTypeQuery(usage) ||
43348 declaration.flags & 8388608 /* Ambient */) {
43349 // nodes are in different files and order cannot be determined
43350 return true;
43351 }
43352 // declaration is after usage
43353 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
43354 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
43355 return true;
43356 }
43357 var sourceFiles = host.getSourceFiles();
43358 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
43359 }
43360 if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
43361 // declaration is before usage
43362 if (declaration.kind === 195 /* BindingElement */) {
43363 // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
43364 var errorBindingElement = ts.getAncestor(usage, 195 /* BindingElement */);
43365 if (errorBindingElement) {
43366 return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
43367 declaration.pos < errorBindingElement.pos;
43368 }
43369 // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
43370 return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 246 /* VariableDeclaration */), usage);
43371 }
43372 else if (declaration.kind === 246 /* VariableDeclaration */) {
43373 // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
43374 return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
43375 }
43376 else if (ts.isClassDeclaration(declaration)) {
43377 // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
43378 return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
43379 }
43380 else if (ts.isPropertyDeclaration(declaration)) {
43381 // still might be illegal if a self-referencing property initializer (eg private x = this.x)
43382 return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
43383 }
43384 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
43385 // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
43386 return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
43387 && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
43388 && isUsedInFunctionOrInstanceProperty(usage, declaration));
43389 }
43390 return true;
43391 }
43392 // declaration is after usage, but it can still be legal if usage is deferred:
43393 // 1. inside an export specifier
43394 // 2. inside a function
43395 // 3. inside an instance property initializer, a reference to a non-instance property
43396 // (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
43397 // 4. inside a static property initializer, a reference to a static method in the same class
43398 // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
43399 // or if usage is in a type context:
43400 // 1. inside a type query (typeof in type position)
43401 // 2. inside a jsdoc comment
43402 if (usage.parent.kind === 267 /* ExportSpecifier */ || (usage.parent.kind === 263 /* ExportAssignment */ && usage.parent.isExportEquals)) {
43403 // export specifiers do not use the variable, they only make it available for use
43404 return true;
43405 }
43406 // When resolving symbols for exports, the `usage` location passed in can be the export site directly
43407 if (usage.kind === 263 /* ExportAssignment */ && usage.isExportEquals) {
43408 return true;
43409 }
43410 if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
43411 return true;
43412 }
43413 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
43414 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
43415 && ts.getContainingClass(declaration)
43416 && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
43417 return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
43418 }
43419 else {
43420 return true;
43421 }
43422 }
43423 return false;
43424 function usageInTypeDeclaration() {
43425 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
43426 }
43427 function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
43428 switch (declaration.parent.parent.kind) {
43429 case 229 /* VariableStatement */:
43430 case 234 /* ForStatement */:
43431 case 236 /* ForOfStatement */:
43432 // variable statement/for/for-of statement case,
43433 // use site should not be inside variable declaration (initializer of declaration or binding element)
43434 if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
43435 return true;
43436 }
43437 break;
43438 }
43439 // ForIn/ForOf case - use site should not be used in expression part
43440 var grandparent = declaration.parent.parent;
43441 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
43442 }
43443 function isUsedInFunctionOrInstanceProperty(usage, declaration) {
43444 return !!ts.findAncestor(usage, function (current) {
43445 if (current === declContainer) {
43446 return "quit";
43447 }
43448 if (ts.isFunctionLike(current)) {
43449 return true;
43450 }
43451 var initializerOfProperty = current.parent &&
43452 current.parent.kind === 162 /* PropertyDeclaration */ &&
43453 current.parent.initializer === current;
43454 if (initializerOfProperty) {
43455 if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) {
43456 if (declaration.kind === 164 /* MethodDeclaration */) {
43457 return true;
43458 }
43459 }
43460 else {
43461 var isDeclarationInstanceProperty = declaration.kind === 162 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */);
43462 if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
43463 return true;
43464 }
43465 }
43466 }
43467 return false;
43468 });
43469 }
43470 /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
43471 function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
43472 // always legal if usage is after declaration
43473 if (usage.end > declaration.end) {
43474 return false;
43475 }
43476 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
43477 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
43478 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
43479 if (node === declaration) {
43480 return "quit";
43481 }
43482 switch (node.kind) {
43483 case 206 /* ArrowFunction */:
43484 return true;
43485 case 162 /* PropertyDeclaration */:
43486 // even when stopping at any property declaration, they need to come from the same class
43487 return stopAtAnyPropertyDeclaration &&
43488 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
43489 || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
43490 ? "quit" : true;
43491 case 227 /* Block */:
43492 switch (node.parent.kind) {
43493 case 166 /* GetAccessor */:
43494 case 164 /* MethodDeclaration */:
43495 case 167 /* SetAccessor */:
43496 return true;
43497 default:
43498 return false;
43499 }
43500 default:
43501 return false;
43502 }
43503 });
43504 return ancestorChangingReferenceScope === undefined;
43505 }
43506 }
43507 function useOuterVariableScopeInParameter(result, location, lastLocation) {
43508 var target = ts.getEmitScriptTarget(compilerOptions);
43509 var functionLocation = location;
43510 if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
43511 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
43512 // - static field in a class expression
43513 // - optional chaining pre-es2020
43514 // - nullish coalesce pre-es2020
43515 // - spread assignment in binding pattern pre-es2017
43516 if (target >= 2 /* ES2015 */) {
43517 var links = getNodeLinks(functionLocation);
43518 if (links.declarationRequiresScopeChange === undefined) {
43519 links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
43520 }
43521 return !links.declarationRequiresScopeChange;
43522 }
43523 }
43524 return false;
43525 function requiresScopeChange(node) {
43526 return requiresScopeChangeWorker(node.name)
43527 || !!node.initializer && requiresScopeChangeWorker(node.initializer);
43528 }
43529 function requiresScopeChangeWorker(node) {
43530 switch (node.kind) {
43531 case 206 /* ArrowFunction */:
43532 case 205 /* FunctionExpression */:
43533 case 248 /* FunctionDeclaration */:
43534 case 165 /* Constructor */:
43535 // do not descend into these
43536 return false;
43537 case 164 /* MethodDeclaration */:
43538 case 166 /* GetAccessor */:
43539 case 167 /* SetAccessor */:
43540 case 285 /* PropertyAssignment */:
43541 return requiresScopeChangeWorker(node.name);
43542 case 162 /* PropertyDeclaration */:
43543 // static properties in classes introduce temporary variables
43544 if (ts.hasStaticModifier(node)) {
43545 return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
43546 }
43547 return requiresScopeChangeWorker(node.name);
43548 default:
43549 // null coalesce and optional chain pre-es2020 produce temporary variables
43550 if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
43551 return target < 7 /* ES2020 */;
43552 }
43553 if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
43554 return target < 4 /* ES2017 */;
43555 }
43556 if (ts.isTypeNode(node))
43557 return false;
43558 return ts.forEachChild(node, requiresScopeChangeWorker) || false;
43559 }
43560 }
43561 }
43562 /**
43563 * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
43564 * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
43565 * the given name can be found.
43566 *
43567 * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
43568 */
43569 function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
43570 if (excludeGlobals === void 0) { excludeGlobals = false; }
43571 return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
43572 }
43573 function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
43574 var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
43575 var result;
43576 var lastLocation;
43577 var lastSelfReferenceLocation;
43578 var propertyWithInvalidInitializer;
43579 var associatedDeclarationForContainingInitializerOrBindingName;
43580 var withinDeferredContext = false;
43581 var errorLocation = location;
43582 var grandparent;
43583 var isInExternalModule = false;
43584 loop: while (location) {
43585 // Locals of a source file are not in scope (because they get merged into the global symbol table)
43586 if (location.locals && !isGlobalSourceFile(location)) {
43587 if (result = lookup(location.locals, name, meaning)) {
43588 var useResult = true;
43589 if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
43590 // symbol lookup restrictions for function-like declarations
43591 // - Type parameters of a function are in scope in the entire function declaration, including the parameter
43592 // list and return type. However, local types are only in scope in the function body.
43593 // - parameters are only in the scope of function body
43594 // This restriction does not apply to JSDoc comment types because they are parented
43595 // at a higher level than type parameters would normally be
43596 if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 307 /* JSDocComment */) {
43597 useResult = result.flags & 262144 /* TypeParameter */
43598 // type parameters are visible in parameter list, return type and type parameter list
43599 ? lastLocation === location.type ||
43600 lastLocation.kind === 159 /* Parameter */ ||
43601 lastLocation.kind === 158 /* TypeParameter */
43602 // local types not visible outside the function body
43603 : false;
43604 }
43605 if (meaning & result.flags & 3 /* Variable */) {
43606 // expression inside parameter will lookup as normal variable scope when targeting es2015+
43607 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
43608 useResult = false;
43609 }
43610 else if (result.flags & 1 /* FunctionScopedVariable */) {
43611 // parameters are visible only inside function body, parameter list and return type
43612 // technically for parameter list case here we might mix parameters and variables declared in function,
43613 // however it is detected separately when checking initializers of parameters
43614 // to make sure that they reference no variables declared after them.
43615 useResult =
43616 lastLocation.kind === 159 /* Parameter */ ||
43617 (lastLocation === location.type &&
43618 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
43619 }
43620 }
43621 }
43622 else if (location.kind === 183 /* ConditionalType */) {
43623 // A type parameter declared using 'infer T' in a conditional type is visible only in
43624 // the true branch of the conditional type.
43625 useResult = lastLocation === location.trueType;
43626 }
43627 if (useResult) {
43628 break loop;
43629 }
43630 else {
43631 result = undefined;
43632 }
43633 }
43634 }
43635 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
43636 switch (location.kind) {
43637 case 294 /* SourceFile */:
43638 if (!ts.isExternalOrCommonJsModule(location))
43639 break;
43640 isInExternalModule = true;
43641 // falls through
43642 case 253 /* ModuleDeclaration */:
43643 var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
43644 if (location.kind === 294 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
43645 // It's an external module. First see if the module has an export default and if the local
43646 // name of that export default matches.
43647 if (result = moduleExports.get("default" /* Default */)) {
43648 var localSymbol = ts.getLocalSymbolForExportDefault(result);
43649 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
43650 break loop;
43651 }
43652 result = undefined;
43653 }
43654 // Because of module/namespace merging, a module's exports are in scope,
43655 // yet we never want to treat an export specifier as putting a member in scope.
43656 // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
43657 // Two things to note about this:
43658 // 1. We have to check this without calling getSymbol. The problem with calling getSymbol
43659 // on an export specifier is that it might find the export specifier itself, and try to
43660 // resolve it as an alias. This will cause the checker to consider the export specifier
43661 // a circular alias reference when it might not be.
43662 // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
43663 // an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
43664 // which is not the desired behavior.
43665 var moduleExport = moduleExports.get(name);
43666 if (moduleExport &&
43667 moduleExport.flags === 2097152 /* Alias */ &&
43668 (ts.getDeclarationOfKind(moduleExport, 267 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 266 /* NamespaceExport */))) {
43669 break;
43670 }
43671 }
43672 // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
43673 if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
43674 if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
43675 result = undefined;
43676 }
43677 else {
43678 break loop;
43679 }
43680 }
43681 break;
43682 case 252 /* EnumDeclaration */:
43683 if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
43684 break loop;
43685 }
43686 break;
43687 case 162 /* PropertyDeclaration */:
43688 // TypeScript 1.0 spec (April 2014): 8.4.1
43689 // Initializer expressions for instance member variables are evaluated in the scope
43690 // of the class constructor body but are not permitted to reference parameters or
43691 // local variables of the constructor. This effectively means that entities from outer scopes
43692 // by the same name as a constructor parameter or local variable are inaccessible
43693 // in initializer expressions for instance member variables.
43694 if (!ts.hasSyntacticModifier(location, 32 /* Static */)) {
43695 var ctor = findConstructorDeclaration(location.parent);
43696 if (ctor && ctor.locals) {
43697 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
43698 // Remember the property node, it will be used later to report appropriate error
43699 propertyWithInvalidInitializer = location;
43700 }
43701 }
43702 }
43703 break;
43704 case 249 /* ClassDeclaration */:
43705 case 218 /* ClassExpression */:
43706 case 250 /* InterfaceDeclaration */:
43707 // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
43708 // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
43709 // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
43710 if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
43711 if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
43712 // ignore type parameters not declared in this container
43713 result = undefined;
43714 break;
43715 }
43716 if (lastLocation && ts.hasSyntacticModifier(lastLocation, 32 /* Static */)) {
43717 // TypeScript 1.0 spec (April 2014): 3.4.1
43718 // The scope of a type parameter extends over the entire declaration with which the type
43719 // parameter list is associated, with the exception of static member declarations in classes.
43720 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
43721 return undefined;
43722 }
43723 break loop;
43724 }
43725 if (location.kind === 218 /* ClassExpression */ && meaning & 32 /* Class */) {
43726 var className = location.name;
43727 if (className && name === className.escapedText) {
43728 result = location.symbol;
43729 break loop;
43730 }
43731 }
43732 break;
43733 case 220 /* ExpressionWithTypeArguments */:
43734 // The type parameters of a class are not in scope in the base class expression.
43735 if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) {
43736 var container = location.parent.parent;
43737 if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
43738 if (nameNotFoundMessage) {
43739 error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
43740 }
43741 return undefined;
43742 }
43743 }
43744 break;
43745 // It is not legal to reference a class's own type parameters from a computed property name that
43746 // belongs to the class. For example:
43747 //
43748 // function foo<T>() { return '' }
43749 // class C<T> { // <-- Class's own type parameter T
43750 // [foo<T>()]() { } // <-- Reference to T from class's own computed property
43751 // }
43752 //
43753 case 157 /* ComputedPropertyName */:
43754 grandparent = location.parent.parent;
43755 if (ts.isClassLike(grandparent) || grandparent.kind === 250 /* InterfaceDeclaration */) {
43756 // A reference to this grandparent's type parameters would be an error
43757 if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
43758 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
43759 return undefined;
43760 }
43761 }
43762 break;
43763 case 206 /* ArrowFunction */:
43764 // when targeting ES6 or higher there is no 'arguments' in an arrow function
43765 // for lower compile targets the resolved symbol is used to emit an error
43766 if (compilerOptions.target >= 2 /* ES2015 */) {
43767 break;
43768 }
43769 // falls through
43770 case 164 /* MethodDeclaration */:
43771 case 165 /* Constructor */:
43772 case 166 /* GetAccessor */:
43773 case 167 /* SetAccessor */:
43774 case 248 /* FunctionDeclaration */:
43775 if (meaning & 3 /* Variable */ && name === "arguments") {
43776 result = argumentsSymbol;
43777 break loop;
43778 }
43779 break;
43780 case 205 /* FunctionExpression */:
43781 if (meaning & 3 /* Variable */ && name === "arguments") {
43782 result = argumentsSymbol;
43783 break loop;
43784 }
43785 if (meaning & 16 /* Function */) {
43786 var functionName = location.name;
43787 if (functionName && name === functionName.escapedText) {
43788 result = location.symbol;
43789 break loop;
43790 }
43791 }
43792 break;
43793 case 160 /* Decorator */:
43794 // Decorators are resolved at the class declaration. Resolving at the parameter
43795 // or member would result in looking up locals in the method.
43796 //
43797 // function y() {}
43798 // class C {
43799 // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
43800 // }
43801 //
43802 if (location.parent && location.parent.kind === 159 /* Parameter */) {
43803 location = location.parent;
43804 }
43805 //
43806 // function y() {}
43807 // class C {
43808 // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
43809 // }
43810 //
43811 // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
43812 //
43813 // type T = number;
43814 // declare function y(x: T): any;
43815 // @param(1 as T) // <-- T should resolve to the type alias outside of class C
43816 // class C<T> {}
43817 if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 249 /* ClassDeclaration */)) {
43818 location = location.parent;
43819 }
43820 break;
43821 case 327 /* JSDocTypedefTag */:
43822 case 320 /* JSDocCallbackTag */:
43823 case 321 /* JSDocEnumTag */:
43824 // js type aliases do not resolve names from their host, so skip past it
43825 location = ts.getJSDocHost(location);
43826 break;
43827 case 159 /* Parameter */:
43828 if (lastLocation && (lastLocation === location.initializer ||
43829 lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
43830 if (!associatedDeclarationForContainingInitializerOrBindingName) {
43831 associatedDeclarationForContainingInitializerOrBindingName = location;
43832 }
43833 }
43834 break;
43835 case 195 /* BindingElement */:
43836 if (lastLocation && (lastLocation === location.initializer ||
43837 lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
43838 var root = ts.getRootDeclaration(location);
43839 if (root.kind === 159 /* Parameter */) {
43840 if (!associatedDeclarationForContainingInitializerOrBindingName) {
43841 associatedDeclarationForContainingInitializerOrBindingName = location;
43842 }
43843 }
43844 }
43845 break;
43846 }
43847 if (isSelfReferenceLocation(location)) {
43848 lastSelfReferenceLocation = location;
43849 }
43850 lastLocation = location;
43851 location = location.parent;
43852 }
43853 // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
43854 // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
43855 // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
43856 if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
43857 result.isReferenced |= meaning;
43858 }
43859 if (!result) {
43860 if (lastLocation) {
43861 ts.Debug.assert(lastLocation.kind === 294 /* SourceFile */);
43862 if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
43863 return lastLocation.symbol;
43864 }
43865 }
43866 if (!excludeGlobals) {
43867 result = lookup(globals, name, meaning);
43868 }
43869 }
43870 if (!result) {
43871 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
43872 if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
43873 return requireSymbol;
43874 }
43875 }
43876 }
43877 if (!result) {
43878 if (nameNotFoundMessage) {
43879 if (!errorLocation ||
43880 !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
43881 !checkAndReportErrorForExtendingInterface(errorLocation) &&
43882 !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
43883 !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
43884 !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
43885 !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
43886 !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
43887 var suggestion = void 0;
43888 if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
43889 suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
43890 if (suggestion) {
43891 var suggestionName = symbolToString(suggestion);
43892 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
43893 if (suggestion.valueDeclaration) {
43894 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
43895 }
43896 }
43897 }
43898 if (!suggestion) {
43899 error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
43900 }
43901 suggestionCount++;
43902 }
43903 }
43904 return undefined;
43905 }
43906 // Perform extra checks only if error reporting was requested
43907 if (nameNotFoundMessage) {
43908 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
43909 // We have a match, but the reference occurred within a property initializer and the identifier also binds
43910 // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
43911 // with ESNext+useDefineForClassFields because the scope semantics are different.
43912 var propertyName = propertyWithInvalidInitializer.name;
43913 error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
43914 return undefined;
43915 }
43916 // Only check for block-scoped variable if we have an error location and are looking for the
43917 // name with variable meaning
43918 // For example,
43919 // declare module foo {
43920 // interface bar {}
43921 // }
43922 // const foo/*1*/: foo/*2*/.bar;
43923 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
43924 // block-scoped variable and namespace module. However, only when we
43925 // try to resolve name in /*1*/ which is used in variable position,
43926 // we want to check for block-scoped
43927 if (errorLocation &&
43928 (meaning & 2 /* BlockScopedVariable */ ||
43929 ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
43930 var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
43931 if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
43932 checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
43933 }
43934 }
43935 // If we're in an external module, we can't reference value symbols created from UMD export declarations
43936 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
43937 var merged = getMergedSymbol(result);
43938 if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
43939 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));
43940 }
43941 }
43942 // 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
43943 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
43944 var candidate = getMergedSymbol(getLateBoundSymbol(result));
43945 var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
43946 // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
43947 if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
43948 error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
43949 }
43950 // And it cannot refer to any declarations which come after it
43951 else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
43952 error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
43953 }
43954 }
43955 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
43956 checkSymbolUsageInExpressionContext(result, name, errorLocation);
43957 }
43958 }
43959 return result;
43960 }
43961 function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
43962 if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
43963 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
43964 if (typeOnlyDeclaration) {
43965 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
43966 var message = isExport
43967 ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
43968 : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
43969 var relatedMessage = isExport
43970 ? ts.Diagnostics._0_was_exported_here
43971 : ts.Diagnostics._0_was_imported_here;
43972 var unescapedName = ts.unescapeLeadingUnderscores(name);
43973 ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
43974 }
43975 }
43976 }
43977 function getIsDeferredContext(location, lastLocation) {
43978 if (location.kind !== 206 /* ArrowFunction */ && location.kind !== 205 /* FunctionExpression */) {
43979 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
43980 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
43981 (location.kind === 162 /* 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
43982 }
43983 if (lastLocation && lastLocation === location.name) {
43984 return false;
43985 }
43986 // generator functions and async functions are not inlined in control flow when immediately invoked
43987 if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
43988 return true;
43989 }
43990 return !ts.getImmediatelyInvokedFunctionExpression(location);
43991 }
43992 function isSelfReferenceLocation(node) {
43993 switch (node.kind) {
43994 case 248 /* FunctionDeclaration */:
43995 case 249 /* ClassDeclaration */:
43996 case 250 /* InterfaceDeclaration */:
43997 case 252 /* EnumDeclaration */:
43998 case 251 /* TypeAliasDeclaration */:
43999 case 253 /* ModuleDeclaration */: // For `namespace N { N; }`
44000 return true;
44001 default:
44002 return false;
44003 }
44004 }
44005 function diagnosticName(nameArg) {
44006 return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
44007 }
44008 function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
44009 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
44010 var decl = _a[_i];
44011 if (decl.kind === 158 /* TypeParameter */) {
44012 var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
44013 if (parent === container) {
44014 return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
44015 }
44016 }
44017 }
44018 return false;
44019 }
44020 function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
44021 if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
44022 return false;
44023 }
44024 var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
44025 var location = container;
44026 while (location) {
44027 if (ts.isClassLike(location.parent)) {
44028 var classSymbol = getSymbolOfNode(location.parent);
44029 if (!classSymbol) {
44030 break;
44031 }
44032 // Check to see if a static member exists.
44033 var constructorType = getTypeOfSymbol(classSymbol);
44034 if (getPropertyOfType(constructorType, name)) {
44035 error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
44036 return true;
44037 }
44038 // No static member is present.
44039 // Check if we're in an instance method and look for a relevant instance member.
44040 if (location === container && !ts.hasSyntacticModifier(location, 32 /* Static */)) {
44041 var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
44042 if (getPropertyOfType(instanceType, name)) {
44043 error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
44044 return true;
44045 }
44046 }
44047 }
44048 location = location.parent;
44049 }
44050 return false;
44051 }
44052 function checkAndReportErrorForExtendingInterface(errorLocation) {
44053 var expression = getEntityNameForExtendingInterface(errorLocation);
44054 if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
44055 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
44056 return true;
44057 }
44058 return false;
44059 }
44060 /**
44061 * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
44062 * but returns undefined if that expression is not an EntityNameExpression.
44063 */
44064 function getEntityNameForExtendingInterface(node) {
44065 switch (node.kind) {
44066 case 78 /* Identifier */:
44067 case 198 /* PropertyAccessExpression */:
44068 return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
44069 case 220 /* ExpressionWithTypeArguments */:
44070 if (ts.isEntityNameExpression(node.expression)) {
44071 return node.expression;
44072 }
44073 // falls through
44074 default:
44075 return undefined;
44076 }
44077 }
44078 function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
44079 var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
44080 if (meaning === namespaceMeaning) {
44081 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
44082 var parent = errorLocation.parent;
44083 if (symbol) {
44084 if (ts.isQualifiedName(parent)) {
44085 ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
44086 var propName = parent.right.escapedText;
44087 var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
44088 if (propType) {
44089 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));
44090 return true;
44091 }
44092 }
44093 error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
44094 return true;
44095 }
44096 }
44097 return false;
44098 }
44099 function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
44100 if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
44101 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
44102 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
44103 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));
44104 return true;
44105 }
44106 }
44107 return false;
44108 }
44109 function isPrimitiveTypeName(name) {
44110 return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
44111 }
44112 function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
44113 if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 267 /* ExportSpecifier */) {
44114 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
44115 return true;
44116 }
44117 return false;
44118 }
44119 function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
44120 if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
44121 if (isPrimitiveTypeName(name)) {
44122 error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
44123 return true;
44124 }
44125 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
44126 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
44127 var message = isES2015OrLaterConstructorName(name)
44128 ? 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
44129 : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
44130 error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
44131 return true;
44132 }
44133 }
44134 return false;
44135 }
44136 function isES2015OrLaterConstructorName(n) {
44137 switch (n) {
44138 case "Promise":
44139 case "Symbol":
44140 case "Map":
44141 case "WeakMap":
44142 case "Set":
44143 case "WeakSet":
44144 return true;
44145 }
44146 return false;
44147 }
44148 function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
44149 if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
44150 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
44151 if (symbol) {
44152 error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
44153 return true;
44154 }
44155 }
44156 else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
44157 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
44158 if (symbol) {
44159 error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
44160 return true;
44161 }
44162 }
44163 return false;
44164 }
44165 function checkResolvedBlockScopedVariable(result, errorLocation) {
44166 ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
44167 if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
44168 // constructor functions aren't block scoped
44169 return;
44170 }
44171 // Block-scoped variables cannot be used before their definition
44172 var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 252 /* EnumDeclaration */); });
44173 if (declaration === undefined)
44174 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
44175 if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
44176 var diagnosticMessage = void 0;
44177 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
44178 if (result.flags & 2 /* BlockScopedVariable */) {
44179 diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
44180 }
44181 else if (result.flags & 32 /* Class */) {
44182 diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
44183 }
44184 else if (result.flags & 256 /* RegularEnum */) {
44185 diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
44186 }
44187 else {
44188 ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
44189 if (compilerOptions.preserveConstEnums) {
44190 diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
44191 }
44192 }
44193 if (diagnosticMessage) {
44194 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
44195 }
44196 }
44197 }
44198 /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
44199 * If at any point current node is equal to 'parent' node - return true.
44200 * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
44201 */
44202 function isSameScopeDescendentOf(initial, parent, stopAt) {
44203 return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
44204 }
44205 function getAnyImportSyntax(node) {
44206 switch (node.kind) {
44207 case 257 /* ImportEqualsDeclaration */:
44208 return node;
44209 case 259 /* ImportClause */:
44210 return node.parent;
44211 case 260 /* NamespaceImport */:
44212 return node.parent.parent;
44213 case 262 /* ImportSpecifier */:
44214 return node.parent.parent.parent;
44215 default:
44216 return undefined;
44217 }
44218 }
44219 function getDeclarationOfAliasSymbol(symbol) {
44220 return ts.find(symbol.declarations, isAliasSymbolDeclaration);
44221 }
44222 /**
44223 * An alias symbol is created by one of the following declarations:
44224 * import <symbol> = ...
44225 * import <symbol> from ...
44226 * import * as <symbol> from ...
44227 * import { x as <symbol> } from ...
44228 * export { x as <symbol> } from ...
44229 * export * as ns <symbol> from ...
44230 * export = <EntityNameExpression>
44231 * export default <EntityNameExpression>
44232 * module.exports = <EntityNameExpression>
44233 * {<Identifier>}
44234 * {name: <EntityNameExpression>}
44235 */
44236 function isAliasSymbolDeclaration(node) {
44237 return node.kind === 257 /* ImportEqualsDeclaration */ ||
44238 node.kind === 256 /* NamespaceExportDeclaration */ ||
44239 node.kind === 259 /* ImportClause */ && !!node.name ||
44240 node.kind === 260 /* NamespaceImport */ ||
44241 node.kind === 266 /* NamespaceExport */ ||
44242 node.kind === 262 /* ImportSpecifier */ ||
44243 node.kind === 267 /* ExportSpecifier */ ||
44244 node.kind === 263 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
44245 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
44246 ts.isPropertyAccessExpression(node)
44247 && ts.isBinaryExpression(node.parent)
44248 && node.parent.left === node
44249 && node.parent.operatorToken.kind === 62 /* EqualsToken */
44250 && isAliasableOrJsExpression(node.parent.right) ||
44251 node.kind === 286 /* ShorthandPropertyAssignment */ ||
44252 node.kind === 285 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
44253 }
44254 function isAliasableOrJsExpression(e) {
44255 return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
44256 }
44257 function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
44258 if (node.moduleReference.kind === 269 /* ExternalModuleReference */) {
44259 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
44260 var resolved_4 = resolveExternalModuleSymbol(immediate);
44261 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
44262 return resolved_4;
44263 }
44264 var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
44265 checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
44266 return resolved;
44267 }
44268 function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
44269 if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
44270 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
44271 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
44272 var message = isExport
44273 ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
44274 : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
44275 var relatedMessage = isExport
44276 ? ts.Diagnostics._0_was_exported_here
44277 : ts.Diagnostics._0_was_imported_here;
44278 // Non-null assertion is safe because the optionality comes from ImportClause,
44279 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
44280 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
44281 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
44282 }
44283 }
44284 function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
44285 var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
44286 if (exportValue) {
44287 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
44288 }
44289 var exportSymbol = moduleSymbol.exports.get(name);
44290 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
44291 markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
44292 return resolved;
44293 }
44294 function isSyntacticDefault(node) {
44295 return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
44296 }
44297 function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
44298 if (!allowSyntheticDefaultImports) {
44299 return false;
44300 }
44301 // Declaration files (and ambient modules)
44302 if (!file || file.isDeclarationFile) {
44303 // Definitely cannot have a synthetic default if they have a syntactic default member specified
44304 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
44305 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
44306 return false;
44307 }
44308 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
44309 // So we check a bit more,
44310 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
44311 // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
44312 // it definitely is a module and does not have a synthetic default
44313 return false;
44314 }
44315 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
44316 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
44317 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
44318 return true;
44319 }
44320 // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
44321 if (!ts.isSourceFileJS(file)) {
44322 return hasExportAssignmentSymbol(moduleSymbol);
44323 }
44324 // 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
44325 return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
44326 }
44327 function getTargetOfImportClause(node, dontResolveAlias) {
44328 var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
44329 if (moduleSymbol) {
44330 var exportDefaultSymbol = void 0;
44331 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
44332 exportDefaultSymbol = moduleSymbol;
44333 }
44334 else {
44335 exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
44336 }
44337 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
44338 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
44339 if (!exportDefaultSymbol && !hasSyntheticDefault) {
44340 if (hasExportAssignmentSymbol(moduleSymbol)) {
44341 var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
44342 var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
44343 var exportAssignment = exportEqualsSymbol.valueDeclaration;
44344 var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
44345 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));
44346 }
44347 else {
44348 reportNonDefaultExport(moduleSymbol, node);
44349 }
44350 }
44351 else if (hasSyntheticDefault) {
44352 // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
44353 var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
44354 markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
44355 return resolved;
44356 }
44357 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
44358 return exportDefaultSymbol;
44359 }
44360 }
44361 function reportNonDefaultExport(moduleSymbol, node) {
44362 var _a, _b;
44363 if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
44364 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));
44365 }
44366 else {
44367 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
44368 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
44369 if (exportStar) {
44370 var defaultExport = ts.find(exportStar.declarations, function (decl) {
44371 var _a, _b;
44372 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 */)));
44373 });
44374 if (defaultExport) {
44375 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
44376 }
44377 }
44378 }
44379 }
44380 function getTargetOfNamespaceImport(node, dontResolveAlias) {
44381 var moduleSpecifier = node.parent.parent.moduleSpecifier;
44382 var immediate = resolveExternalModuleName(node, moduleSpecifier);
44383 var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
44384 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
44385 return resolved;
44386 }
44387 function getTargetOfNamespaceExport(node, dontResolveAlias) {
44388 var moduleSpecifier = node.parent.moduleSpecifier;
44389 var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
44390 var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
44391 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
44392 return resolved;
44393 }
44394 // This function creates a synthetic symbol that combines the value side of one symbol with the
44395 // type/namespace side of another symbol. Consider this example:
44396 //
44397 // declare module graphics {
44398 // interface Point {
44399 // x: number;
44400 // y: number;
44401 // }
44402 // }
44403 // declare var graphics: {
44404 // Point: new (x: number, y: number) => graphics.Point;
44405 // }
44406 // declare module "graphics" {
44407 // export = graphics;
44408 // }
44409 //
44410 // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
44411 // property with the type/namespace side interface 'Point'.
44412 function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
44413 if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
44414 return unknownSymbol;
44415 }
44416 if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
44417 return valueSymbol;
44418 }
44419 var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
44420 result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
44421 result.parent = valueSymbol.parent || typeSymbol.parent;
44422 if (valueSymbol.valueDeclaration)
44423 result.valueDeclaration = valueSymbol.valueDeclaration;
44424 if (typeSymbol.members)
44425 result.members = new ts.Map(typeSymbol.members);
44426 if (valueSymbol.exports)
44427 result.exports = new ts.Map(valueSymbol.exports);
44428 return result;
44429 }
44430 function getExportOfModule(symbol, specifier, dontResolveAlias) {
44431 var _a;
44432 if (symbol.flags & 1536 /* Module */) {
44433 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
44434 var exportSymbol = getExportsOfSymbol(symbol).get(name);
44435 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
44436 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
44437 return resolved;
44438 }
44439 }
44440 function getPropertyOfVariable(symbol, name) {
44441 if (symbol.flags & 3 /* Variable */) {
44442 var typeAnnotation = symbol.valueDeclaration.type;
44443 if (typeAnnotation) {
44444 return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
44445 }
44446 }
44447 }
44448 function getExternalModuleMember(node, specifier, dontResolveAlias) {
44449 var _a;
44450 if (dontResolveAlias === void 0) { dontResolveAlias = false; }
44451 var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
44452 var name = specifier.propertyName || specifier.name;
44453 var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
44454 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
44455 if (targetSymbol) {
44456 if (name.escapedText) {
44457 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
44458 return moduleSymbol;
44459 }
44460 var symbolFromVariable = void 0;
44461 // First check if module was specified with "export=". If so, get the member from the resolved type
44462 if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
44463 symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
44464 }
44465 else {
44466 symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
44467 }
44468 // if symbolFromVariable is export - get its final target
44469 symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
44470 var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
44471 if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
44472 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
44473 if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
44474 symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
44475 }
44476 }
44477 var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
44478 combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
44479 symbolFromModule || symbolFromVariable;
44480 if (!symbol) {
44481 var moduleName = getFullyQualifiedName(moduleSymbol, node);
44482 var declarationName = ts.declarationNameToString(name);
44483 var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
44484 if (suggestion !== undefined) {
44485 var suggestionName = symbolToString(suggestion);
44486 var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
44487 if (suggestion.valueDeclaration) {
44488 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
44489 }
44490 }
44491 else {
44492 if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
44493 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
44494 }
44495 else {
44496 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
44497 }
44498 }
44499 }
44500 return symbol;
44501 }
44502 }
44503 }
44504 function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
44505 var _a;
44506 var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
44507 var exports = moduleSymbol.exports;
44508 if (localSymbol) {
44509 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
44510 if (exportedEqualsSymbol) {
44511 getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
44512 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
44513 }
44514 else {
44515 var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
44516 var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
44517 error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
44518 ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
44519 return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
44520 })));
44521 }
44522 }
44523 else {
44524 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
44525 }
44526 }
44527 function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
44528 if (moduleKind >= ts.ModuleKind.ES2015) {
44529 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
44530 ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
44531 error(name, message, declarationName);
44532 }
44533 else {
44534 if (ts.isInJSFile(node)) {
44535 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
44536 ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
44537 error(name, message, declarationName);
44538 }
44539 else {
44540 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
44541 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;
44542 error(name, message, declarationName, declarationName, moduleName);
44543 }
44544 }
44545 }
44546 function getTargetOfImportSpecifier(node, dontResolveAlias) {
44547 var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
44548 markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
44549 return resolved;
44550 }
44551 function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
44552 var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
44553 markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
44554 return resolved;
44555 }
44556 function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
44557 var resolved = node.parent.parent.moduleSpecifier ?
44558 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
44559 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
44560 markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
44561 return resolved;
44562 }
44563 function getTargetOfExportAssignment(node, dontResolveAlias) {
44564 var expression = ts.isExportAssignment(node) ? node.expression : node.right;
44565 var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
44566 markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
44567 return resolved;
44568 }
44569 function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
44570 if (ts.isClassExpression(expression)) {
44571 return checkExpressionCached(expression).symbol;
44572 }
44573 if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
44574 return undefined;
44575 }
44576 var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
44577 if (aliasLike) {
44578 return aliasLike;
44579 }
44580 checkExpressionCached(expression);
44581 return getNodeLinks(expression).resolvedSymbol;
44582 }
44583 function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
44584 var expression = node.initializer;
44585 return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
44586 }
44587 function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
44588 if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
44589 return undefined;
44590 }
44591 return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
44592 }
44593 function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
44594 if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
44595 switch (node.kind) {
44596 case 257 /* ImportEqualsDeclaration */:
44597 return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
44598 case 259 /* ImportClause */:
44599 return getTargetOfImportClause(node, dontRecursivelyResolve);
44600 case 260 /* NamespaceImport */:
44601 return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
44602 case 266 /* NamespaceExport */:
44603 return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
44604 case 262 /* ImportSpecifier */:
44605 return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
44606 case 267 /* ExportSpecifier */:
44607 return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
44608 case 263 /* ExportAssignment */:
44609 case 213 /* BinaryExpression */:
44610 return getTargetOfExportAssignment(node, dontRecursivelyResolve);
44611 case 256 /* NamespaceExportDeclaration */:
44612 return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
44613 case 286 /* ShorthandPropertyAssignment */:
44614 return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
44615 case 285 /* PropertyAssignment */:
44616 return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
44617 case 198 /* PropertyAccessExpression */:
44618 return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
44619 default:
44620 return ts.Debug.fail();
44621 }
44622 }
44623 /**
44624 * Indicates that a symbol is an alias that does not merge with a local declaration.
44625 * OR Is a JSContainer which may merge an alias with a local declaration
44626 */
44627 function isNonLocalAlias(symbol, excludes) {
44628 if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
44629 if (!symbol)
44630 return false;
44631 return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
44632 }
44633 function resolveSymbol(symbol, dontResolveAlias) {
44634 return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
44635 }
44636 function resolveAlias(symbol) {
44637 ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
44638 var links = getSymbolLinks(symbol);
44639 if (!links.target) {
44640 links.target = resolvingSymbol;
44641 var node = getDeclarationOfAliasSymbol(symbol);
44642 if (!node)
44643 return ts.Debug.fail();
44644 var target = getTargetOfAliasDeclaration(node);
44645 if (links.target === resolvingSymbol) {
44646 links.target = target || unknownSymbol;
44647 }
44648 else {
44649 error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
44650 }
44651 }
44652 else if (links.target === resolvingSymbol) {
44653 links.target = unknownSymbol;
44654 }
44655 return links.target;
44656 }
44657 function tryResolveAlias(symbol) {
44658 var links = getSymbolLinks(symbol);
44659 if (links.target !== resolvingSymbol) {
44660 return resolveAlias(symbol);
44661 }
44662 return undefined;
44663 }
44664 /**
44665 * Marks a symbol as type-only if its declaration is syntactically type-only.
44666 * If it is not itself marked type-only, but resolves to a type-only alias
44667 * somewhere in its resolution chain, save a reference to the type-only alias declaration
44668 * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
44669 *
44670 * This function is called on each alias declaration that could be type-only or resolve to
44671 * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
44672 * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
44673 * and issue an error if so.
44674 *
44675 * @param aliasDeclaration The alias declaration not marked as type-only
44676 * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
44677 * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
44678 * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
44679 * must still be checked for a type-only marker, overwriting the previous negative result if found.
44680 * @param immediateTarget The symbol to which the alias declaration immediately resolves
44681 * @param finalTarget The symbol to which the alias declaration ultimately resolves
44682 * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
44683 */
44684 function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
44685 if (!aliasDeclaration)
44686 return false;
44687 // If the declaration itself is type-only, mark it and return.
44688 // No need to check what it resolves to.
44689 var sourceSymbol = getSymbolOfNode(aliasDeclaration);
44690 if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
44691 var links_1 = getSymbolLinks(sourceSymbol);
44692 links_1.typeOnlyDeclaration = aliasDeclaration;
44693 return true;
44694 }
44695 var links = getSymbolLinks(sourceSymbol);
44696 return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
44697 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
44698 }
44699 function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
44700 var _a, _b, _c;
44701 if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
44702 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
44703 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
44704 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
44705 }
44706 return !!aliasDeclarationLinks.typeOnlyDeclaration;
44707 }
44708 /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
44709 function getTypeOnlyAliasDeclaration(symbol) {
44710 if (!(symbol.flags & 2097152 /* Alias */)) {
44711 return undefined;
44712 }
44713 var links = getSymbolLinks(symbol);
44714 return links.typeOnlyDeclaration || undefined;
44715 }
44716 function markExportAsReferenced(node) {
44717 var symbol = getSymbolOfNode(node);
44718 var target = resolveAlias(symbol);
44719 if (target) {
44720 var markAlias = target === unknownSymbol ||
44721 ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
44722 if (markAlias) {
44723 markAliasSymbolAsReferenced(symbol);
44724 }
44725 }
44726 }
44727 // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
44728 // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
44729 // the alias as an expression (which recursively takes us back here if the target references another alias).
44730 function markAliasSymbolAsReferenced(symbol) {
44731 var links = getSymbolLinks(symbol);
44732 if (!links.referenced) {
44733 links.referenced = true;
44734 var node = getDeclarationOfAliasSymbol(symbol);
44735 if (!node)
44736 return ts.Debug.fail();
44737 // We defer checking of the reference of an `import =` until the import itself is referenced,
44738 // This way a chain of imports can be elided if ultimately the final input is only used in a type
44739 // position.
44740 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
44741 var target = resolveSymbol(symbol);
44742 if (target === unknownSymbol || target.flags & 111551 /* Value */) {
44743 // import foo = <symbol>
44744 checkExpressionCached(node.moduleReference);
44745 }
44746 }
44747 }
44748 }
44749 // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
44750 // but their usage in value positions must be tracked to determine if the import can be type-only.
44751 function markConstEnumAliasAsReferenced(symbol) {
44752 var links = getSymbolLinks(symbol);
44753 if (!links.constEnumReferenced) {
44754 links.constEnumReferenced = true;
44755 }
44756 }
44757 // This function is only for imports with entity names
44758 function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
44759 // There are three things we might try to look for. In the following examples,
44760 // the search term is enclosed in |...|:
44761 //
44762 // import a = |b|; // Namespace
44763 // import a = |b.c|; // Value, type, namespace
44764 // import a = |b.c|.d; // Namespace
44765 if (entityName.kind === 78 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
44766 entityName = entityName.parent;
44767 }
44768 // Check for case 1 and 3 in the above example
44769 if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 156 /* QualifiedName */) {
44770 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
44771 }
44772 else {
44773 // Case 2 in above example
44774 // entityName.kind could be a QualifiedName or a Missing identifier
44775 ts.Debug.assert(entityName.parent.kind === 257 /* ImportEqualsDeclaration */);
44776 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
44777 }
44778 }
44779 function getFullyQualifiedName(symbol, containingLocation) {
44780 return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
44781 }
44782 /**
44783 * Resolves a qualified name and any involved aliases.
44784 */
44785 function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
44786 if (ts.nodeIsMissing(name)) {
44787 return undefined;
44788 }
44789 var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
44790 var symbol;
44791 if (name.kind === 78 /* Identifier */) {
44792 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
44793 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
44794 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
44795 if (!symbol) {
44796 return getMergedSymbol(symbolFromJSPrototype);
44797 }
44798 }
44799 else if (name.kind === 156 /* QualifiedName */ || name.kind === 198 /* PropertyAccessExpression */) {
44800 var left = name.kind === 156 /* QualifiedName */ ? name.left : name.expression;
44801 var right = name.kind === 156 /* QualifiedName */ ? name.right : name.name;
44802 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
44803 if (!namespace || ts.nodeIsMissing(right)) {
44804 return undefined;
44805 }
44806 else if (namespace === unknownSymbol) {
44807 return namespace;
44808 }
44809 if (ts.isInJSFile(name)) {
44810 if (namespace.valueDeclaration &&
44811 ts.isVariableDeclaration(namespace.valueDeclaration) &&
44812 namespace.valueDeclaration.initializer &&
44813 isCommonJsRequire(namespace.valueDeclaration.initializer)) {
44814 var moduleName = namespace.valueDeclaration.initializer.arguments[0];
44815 var moduleSym = resolveExternalModuleName(moduleName, moduleName);
44816 if (moduleSym) {
44817 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44818 if (resolvedModuleSymbol) {
44819 namespace = resolvedModuleSymbol;
44820 }
44821 }
44822 }
44823 }
44824 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
44825 if (!symbol) {
44826 if (!ignoreErrors) {
44827 error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
44828 }
44829 return undefined;
44830 }
44831 }
44832 else {
44833 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
44834 }
44835 ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
44836 if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 263 /* ExportAssignment */)) {
44837 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
44838 }
44839 return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
44840 }
44841 /**
44842 * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
44843 * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
44844 * name resolution won't work either.
44845 * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
44846 */
44847 function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
44848 if (isJSDocTypeReference(name.parent)) {
44849 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
44850 if (secondaryLocation) {
44851 return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
44852 }
44853 }
44854 }
44855 function getAssignmentDeclarationLocation(node) {
44856 var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
44857 if (typeAlias) {
44858 return;
44859 }
44860 var host = ts.getJSDocHost(node);
44861 if (ts.isExpressionStatement(host) &&
44862 ts.isBinaryExpression(host.expression) &&
44863 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
44864 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
44865 var symbol = getSymbolOfNode(host.expression.left);
44866 if (symbol) {
44867 return getDeclarationOfJSPrototypeContainer(symbol);
44868 }
44869 }
44870 if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
44871 ts.isBinaryExpression(host.parent.parent) &&
44872 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
44873 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
44874 var symbol = getSymbolOfNode(host.parent.parent.left);
44875 if (symbol) {
44876 return getDeclarationOfJSPrototypeContainer(symbol);
44877 }
44878 }
44879 var sig = ts.getEffectiveJSDocHost(node);
44880 if (sig && ts.isFunctionLike(sig)) {
44881 var symbol = getSymbolOfNode(sig);
44882 return symbol && symbol.valueDeclaration;
44883 }
44884 }
44885 function getDeclarationOfJSPrototypeContainer(symbol) {
44886 var decl = symbol.parent.valueDeclaration;
44887 if (!decl) {
44888 return undefined;
44889 }
44890 var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
44891 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
44892 undefined;
44893 return initializer || decl;
44894 }
44895 /**
44896 * Get the real symbol of a declaration with an expando initializer.
44897 *
44898 * Normally, declarations have an associated symbol, but when a declaration has an expando
44899 * initializer, the expando's symbol is the one that has all the members merged into it.
44900 */
44901 function getExpandoSymbol(symbol) {
44902 var decl = symbol.valueDeclaration;
44903 if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
44904 return undefined;
44905 }
44906 var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
44907 if (init) {
44908 var initSymbol = getSymbolOfNode(init);
44909 if (initSymbol) {
44910 return mergeJSSymbols(initSymbol, symbol);
44911 }
44912 }
44913 }
44914 function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
44915 var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
44916 var errorMessage = isClassic ?
44917 ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
44918 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
44919 return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage);
44920 }
44921 function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
44922 if (isForAugmentation === void 0) { isForAugmentation = false; }
44923 return ts.isStringLiteralLike(moduleReferenceExpression)
44924 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
44925 : undefined;
44926 }
44927 function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
44928 if (isForAugmentation === void 0) { isForAugmentation = false; }
44929 if (ts.startsWith(moduleReference, "@types/")) {
44930 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
44931 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
44932 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
44933 }
44934 var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
44935 if (ambientModule) {
44936 return ambientModule;
44937 }
44938 var currentSourceFile = ts.getSourceFileOfNode(location);
44939 var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
44940 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
44941 var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
44942 if (sourceFile) {
44943 if (sourceFile.symbol) {
44944 if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
44945 errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
44946 }
44947 // merged symbol is module declaration symbol combined with all augmentations
44948 return getMergedSymbol(sourceFile.symbol);
44949 }
44950 if (moduleNotFoundError) {
44951 // report errors only if it was requested
44952 error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
44953 }
44954 return undefined;
44955 }
44956 if (patternAmbientModules) {
44957 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
44958 if (pattern) {
44959 // If the module reference matched a pattern ambient module ('*.foo') but there's also a
44960 // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
44961 // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
44962 // from a.foo.
44963 var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
44964 if (augmentation) {
44965 return getMergedSymbol(augmentation);
44966 }
44967 return getMergedSymbol(pattern.symbol);
44968 }
44969 }
44970 // May be an untyped module. If so, ignore resolutionDiagnostic.
44971 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) {
44972 if (isForAugmentation) {
44973 var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
44974 error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
44975 }
44976 else {
44977 errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
44978 }
44979 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
44980 return undefined;
44981 }
44982 if (moduleNotFoundError) {
44983 // See if this was possibly a projectReference redirect
44984 if (resolvedModule) {
44985 var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
44986 if (redirect) {
44987 error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
44988 return undefined;
44989 }
44990 }
44991 if (resolutionDiagnostic) {
44992 error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
44993 }
44994 else {
44995 var tsExtension = ts.tryExtractTSExtension(moduleReference);
44996 if (tsExtension) {
44997 var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
44998 error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
44999 }
45000 else if (!compilerOptions.resolveJsonModule &&
45001 ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
45002 ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
45003 ts.hasJsonModuleEmitEnabled(compilerOptions)) {
45004 error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
45005 }
45006 else {
45007 error(errorNode, moduleNotFoundError, moduleReference);
45008 }
45009 }
45010 }
45011 return undefined;
45012 }
45013 function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
45014 var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
45015 var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
45016 ? typesPackageExists(packageId.name)
45017 ? ts.chainDiagnosticMessages(
45018 /*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))
45019 : ts.chainDiagnosticMessages(
45020 /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
45021 : undefined;
45022 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));
45023 }
45024 function typesPackageExists(packageName) {
45025 return getPackagesSet().has(ts.getTypesPackageName(packageName));
45026 }
45027 function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
45028 if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
45029 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
45030 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
45031 return getMergedSymbol(exported) || moduleSymbol;
45032 }
45033 return undefined;
45034 }
45035 function getCommonJsExportEquals(exported, moduleSymbol) {
45036 if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
45037 return exported;
45038 }
45039 var links = getSymbolLinks(exported);
45040 if (links.cjsExportMerged) {
45041 return links.cjsExportMerged;
45042 }
45043 var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
45044 merged.flags = merged.flags | 512 /* ValueModule */;
45045 if (merged.exports === undefined) {
45046 merged.exports = ts.createSymbolTable();
45047 }
45048 moduleSymbol.exports.forEach(function (s, name) {
45049 if (name === "export=" /* ExportEquals */)
45050 return;
45051 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
45052 });
45053 getSymbolLinks(merged).cjsExportMerged = merged;
45054 return links.cjsExportMerged = merged;
45055 }
45056 // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
45057 // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
45058 // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
45059 function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
45060 var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
45061 if (!dontResolveAlias && symbol) {
45062 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 294 /* SourceFile */)) {
45063 var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
45064 ? "allowSyntheticDefaultImports"
45065 : "esModuleInterop";
45066 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);
45067 return symbol;
45068 }
45069 if (compilerOptions.esModuleInterop) {
45070 var referenceParent = referencingLocation.parent;
45071 if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
45072 ts.isImportCall(referenceParent)) {
45073 var type = getTypeOfSymbol(symbol);
45074 var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
45075 if (!sigs || !sigs.length) {
45076 sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
45077 }
45078 if (sigs && sigs.length) {
45079 var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
45080 // Create a new symbol which has the module's type less the call and construct signatures
45081 var result = createSymbol(symbol.flags, symbol.escapedName);
45082 result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
45083 result.parent = symbol.parent;
45084 result.target = symbol;
45085 result.originatingImport = referenceParent;
45086 if (symbol.valueDeclaration)
45087 result.valueDeclaration = symbol.valueDeclaration;
45088 if (symbol.constEnumOnlyModule)
45089 result.constEnumOnlyModule = true;
45090 if (symbol.members)
45091 result.members = new ts.Map(symbol.members);
45092 if (symbol.exports)
45093 result.exports = new ts.Map(symbol.exports);
45094 var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
45095 result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
45096 return result;
45097 }
45098 }
45099 }
45100 }
45101 return symbol;
45102 }
45103 function hasExportAssignmentSymbol(moduleSymbol) {
45104 return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
45105 }
45106 function getExportsOfModuleAsArray(moduleSymbol) {
45107 return symbolsToArray(getExportsOfModule(moduleSymbol));
45108 }
45109 function getExportsAndPropertiesOfModule(moduleSymbol) {
45110 var exports = getExportsOfModuleAsArray(moduleSymbol);
45111 var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
45112 if (exportEquals !== moduleSymbol) {
45113 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
45114 }
45115 return exports;
45116 }
45117 function tryGetMemberInModuleExports(memberName, moduleSymbol) {
45118 var symbolTable = getExportsOfModule(moduleSymbol);
45119 if (symbolTable) {
45120 return symbolTable.get(memberName);
45121 }
45122 }
45123 function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
45124 var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
45125 if (symbol) {
45126 return symbol;
45127 }
45128 var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
45129 if (exportEquals === moduleSymbol) {
45130 return undefined;
45131 }
45132 var type = getTypeOfSymbol(exportEquals);
45133 return type.flags & 131068 /* Primitive */ ||
45134 ts.getObjectFlags(type) & 1 /* Class */ ||
45135 isArrayOrTupleLikeType(type)
45136 ? undefined
45137 : getPropertyOfType(type, memberName);
45138 }
45139 function getExportsOfSymbol(symbol) {
45140 return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
45141 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
45142 symbol.exports || emptySymbols;
45143 }
45144 function getExportsOfModule(moduleSymbol) {
45145 var links = getSymbolLinks(moduleSymbol);
45146 return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
45147 }
45148 /**
45149 * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
45150 * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
45151 */
45152 function extendExportSymbols(target, source, lookupTable, exportNode) {
45153 if (!source)
45154 return;
45155 source.forEach(function (sourceSymbol, id) {
45156 if (id === "default" /* Default */)
45157 return;
45158 var targetSymbol = target.get(id);
45159 if (!targetSymbol) {
45160 target.set(id, sourceSymbol);
45161 if (lookupTable && exportNode) {
45162 lookupTable.set(id, {
45163 specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
45164 });
45165 }
45166 }
45167 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
45168 var collisionTracker = lookupTable.get(id);
45169 if (!collisionTracker.exportsWithDuplicate) {
45170 collisionTracker.exportsWithDuplicate = [exportNode];
45171 }
45172 else {
45173 collisionTracker.exportsWithDuplicate.push(exportNode);
45174 }
45175 }
45176 });
45177 }
45178 function getExportsOfModuleWorker(moduleSymbol) {
45179 var visitedSymbols = [];
45180 // A module defined by an 'export=' consists of one export that needs to be resolved
45181 moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
45182 return visit(moduleSymbol) || emptySymbols;
45183 // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
45184 // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
45185 function visit(symbol) {
45186 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
45187 return;
45188 }
45189 var symbols = new ts.Map(symbol.exports);
45190 // All export * declarations are collected in an __export symbol by the binder
45191 var exportStars = symbol.exports.get("__export" /* ExportStar */);
45192 if (exportStars) {
45193 var nestedSymbols = ts.createSymbolTable();
45194 var lookupTable_1 = new ts.Map();
45195 for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
45196 var node = _a[_i];
45197 var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
45198 var exportedSymbols = visit(resolvedModule);
45199 extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
45200 }
45201 lookupTable_1.forEach(function (_a, id) {
45202 var exportsWithDuplicate = _a.exportsWithDuplicate;
45203 // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
45204 if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
45205 return;
45206 }
45207 for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
45208 var node = exportsWithDuplicate_1[_i];
45209 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)));
45210 }
45211 });
45212 extendExportSymbols(symbols, nestedSymbols);
45213 }
45214 return symbols;
45215 }
45216 }
45217 function getMergedSymbol(symbol) {
45218 var merged;
45219 return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
45220 }
45221 function getSymbolOfNode(node) {
45222 return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
45223 }
45224 function getParentOfSymbol(symbol) {
45225 return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
45226 }
45227 function getAlternativeContainingModules(symbol, enclosingDeclaration) {
45228 var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
45229 var id = getNodeId(containingFile);
45230 var links = getSymbolLinks(symbol);
45231 var results;
45232 if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
45233 return results;
45234 }
45235 if (containingFile && containingFile.imports) {
45236 // Try to make an import using an import already in the enclosing file, if possible
45237 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
45238 var importRef = _a[_i];
45239 if (ts.nodeIsSynthesized(importRef))
45240 continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
45241 var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
45242 if (!resolvedModule)
45243 continue;
45244 var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
45245 if (!ref)
45246 continue;
45247 results = ts.append(results, resolvedModule);
45248 }
45249 if (ts.length(results)) {
45250 (links.extendedContainersByFile || (links.extendedContainersByFile = new ts.Map())).set(id, results);
45251 return results;
45252 }
45253 }
45254 if (links.extendedContainers) {
45255 return links.extendedContainers;
45256 }
45257 // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
45258 var otherFiles = host.getSourceFiles();
45259 for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
45260 var file = otherFiles_1[_b];
45261 if (!ts.isExternalModule(file))
45262 continue;
45263 var sym = getSymbolOfNode(file);
45264 var ref = getAliasForSymbolInContainer(sym, symbol);
45265 if (!ref)
45266 continue;
45267 results = ts.append(results, sym);
45268 }
45269 return links.extendedContainers = results || ts.emptyArray;
45270 }
45271 /**
45272 * Attempts to find the symbol corresponding to the container a symbol is in - usually this
45273 * is just its' `.parent`, but for locals, this value is `undefined`
45274 */
45275 function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
45276 var container = getParentOfSymbol(symbol);
45277 // Type parameters end up in the `members` lists but are not externally visible
45278 if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
45279 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
45280 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
45281 var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning);
45282 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
45283 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
45284 }
45285 var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer);
45286 return ts.concatenate(res, reexportContainers);
45287 }
45288 var candidates = ts.mapDefined(symbol.declarations, function (d) {
45289 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
45290 return getSymbolOfNode(d.parent);
45291 }
45292 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)) {
45293 if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
45294 return getSymbolOfNode(ts.getSourceFileOfNode(d));
45295 }
45296 checkExpressionCached(d.parent.left.expression);
45297 return getNodeLinks(d.parent.left.expression).resolvedSymbol;
45298 }
45299 });
45300 if (!ts.length(candidates)) {
45301 return undefined;
45302 }
45303 return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
45304 function fileSymbolIfFileSymbolExportEqualsContainer(d) {
45305 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
45306 }
45307 }
45308 function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
45309 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
45310 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
45311 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
45312 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
45313 if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent)) {
45314 if (ts.isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || ts.isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
45315 return getSymbolOfNode(firstDecl.parent);
45316 }
45317 }
45318 }
45319 function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
45320 var fileSymbol = getExternalModuleContainer(d);
45321 var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
45322 return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
45323 }
45324 function getAliasForSymbolInContainer(container, symbol) {
45325 if (container === getParentOfSymbol(symbol)) {
45326 // fast path, `symbol` is either already the alias or isn't aliased
45327 return symbol;
45328 }
45329 // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
45330 // the container itself as the alias for the symbol
45331 var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
45332 if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
45333 return container;
45334 }
45335 var exports = getExportsOfSymbol(container);
45336 var quick = exports.get(symbol.escapedName);
45337 if (quick && getSymbolIfSameReference(quick, symbol)) {
45338 return quick;
45339 }
45340 return ts.forEachEntry(exports, function (exported) {
45341 if (getSymbolIfSameReference(exported, symbol)) {
45342 return exported;
45343 }
45344 });
45345 }
45346 /**
45347 * Checks if two symbols, through aliasing and/or merging, refer to the same thing
45348 */
45349 function getSymbolIfSameReference(s1, s2) {
45350 if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
45351 return s1;
45352 }
45353 }
45354 function getExportSymbolOfValueSymbolIfExported(symbol) {
45355 return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
45356 }
45357 function symbolIsValue(symbol) {
45358 return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
45359 }
45360 function findConstructorDeclaration(node) {
45361 var members = node.members;
45362 for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
45363 var member = members_3[_i];
45364 if (member.kind === 165 /* Constructor */ && ts.nodeIsPresent(member.body)) {
45365 return member;
45366 }
45367 }
45368 }
45369 function createType(flags) {
45370 var result = new Type(checker, flags);
45371 typeCount++;
45372 result.id = typeCount;
45373 return result;
45374 }
45375 function createIntrinsicType(kind, intrinsicName, objectFlags) {
45376 if (objectFlags === void 0) { objectFlags = 0; }
45377 var type = createType(kind);
45378 type.intrinsicName = intrinsicName;
45379 type.objectFlags = objectFlags;
45380 return type;
45381 }
45382 function createBooleanType(trueFalseTypes) {
45383 var type = getUnionType(trueFalseTypes);
45384 type.flags |= 16 /* Boolean */;
45385 type.intrinsicName = "boolean";
45386 return type;
45387 }
45388 function createObjectType(objectFlags, symbol) {
45389 var type = createType(524288 /* Object */);
45390 type.objectFlags = objectFlags;
45391 type.symbol = symbol;
45392 type.members = undefined;
45393 type.properties = undefined;
45394 type.callSignatures = undefined;
45395 type.constructSignatures = undefined;
45396 type.stringIndexInfo = undefined;
45397 type.numberIndexInfo = undefined;
45398 return type;
45399 }
45400 function createTypeofType() {
45401 return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
45402 }
45403 function createTypeParameter(symbol) {
45404 var type = createType(262144 /* TypeParameter */);
45405 if (symbol)
45406 type.symbol = symbol;
45407 return type;
45408 }
45409 // A reserved member name starts with two underscores, but the third character cannot be an underscore,
45410 // @, or #. A third underscore indicates an escaped form of an identifier that started
45411 // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
45412 // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
45413 function isReservedMemberName(name) {
45414 return name.charCodeAt(0) === 95 /* _ */ &&
45415 name.charCodeAt(1) === 95 /* _ */ &&
45416 name.charCodeAt(2) !== 95 /* _ */ &&
45417 name.charCodeAt(2) !== 64 /* at */ &&
45418 name.charCodeAt(2) !== 35 /* hash */;
45419 }
45420 function getNamedMembers(members) {
45421 var result;
45422 members.forEach(function (symbol, id) {
45423 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
45424 (result || (result = [])).push(symbol);
45425 }
45426 });
45427 return result || ts.emptyArray;
45428 }
45429 function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
45430 type.members = members;
45431 type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
45432 type.callSignatures = callSignatures;
45433 type.constructSignatures = constructSignatures;
45434 type.stringIndexInfo = stringIndexInfo;
45435 type.numberIndexInfo = numberIndexInfo;
45436 return type;
45437 }
45438 function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
45439 return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
45440 }
45441 function forEachSymbolTableInScope(enclosingDeclaration, callback) {
45442 var result;
45443 var _loop_8 = function (location) {
45444 // Locals of a source file are not in scope (because they get merged into the global symbol table)
45445 if (location.locals && !isGlobalSourceFile(location)) {
45446 if (result = callback(location.locals)) {
45447 return { value: result };
45448 }
45449 }
45450 switch (location.kind) {
45451 case 294 /* SourceFile */:
45452 if (!ts.isExternalOrCommonJsModule(location)) {
45453 break;
45454 }
45455 // falls through
45456 case 253 /* ModuleDeclaration */:
45457 var sym = getSymbolOfNode(location);
45458 // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
45459 // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
45460 // to one another anyway)
45461 if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
45462 return { value: result };
45463 }
45464 break;
45465 case 249 /* ClassDeclaration */:
45466 case 218 /* ClassExpression */:
45467 case 250 /* InterfaceDeclaration */:
45468 // Type parameters are bound into `members` lists so they can merge across declarations
45469 // This is troublesome, since in all other respects, they behave like locals :cries:
45470 // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
45471 // lookup logic in terms of `resolveName` would be nice
45472 // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
45473 // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
45474 // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
45475 var table_1;
45476 // TODO: Should this filtered table be cached in some way?
45477 (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
45478 if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
45479 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
45480 }
45481 });
45482 if (table_1 && (result = callback(table_1))) {
45483 return { value: result };
45484 }
45485 break;
45486 }
45487 };
45488 for (var location = enclosingDeclaration; location; location = location.parent) {
45489 var state_2 = _loop_8(location);
45490 if (typeof state_2 === "object")
45491 return state_2.value;
45492 }
45493 return callback(globals);
45494 }
45495 function getQualifiedLeftMeaning(rightMeaning) {
45496 // If we are looking in value space, the parent meaning is value, other wise it is namespace
45497 return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
45498 }
45499 function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
45500 if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = new ts.Map(); }
45501 if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
45502 return undefined;
45503 }
45504 var id = getSymbolId(symbol);
45505 var visitedSymbolTables = visitedSymbolTablesMap.get(id);
45506 if (!visitedSymbolTables) {
45507 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
45508 }
45509 return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
45510 /**
45511 * @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)
45512 */
45513 function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
45514 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
45515 return undefined;
45516 }
45517 var result = trySymbolTable(symbols, ignoreQualification);
45518 visitedSymbolTables.pop();
45519 return result;
45520 }
45521 function canQualifySymbol(symbolFromSymbolTable, meaning) {
45522 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
45523 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
45524 // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
45525 !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
45526 }
45527 function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
45528 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
45529 // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
45530 // and if symbolFromSymbolTable or alias resolution matches the symbol,
45531 // check the symbol can be qualified, it is only then this symbol is accessible
45532 !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
45533 (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
45534 }
45535 function trySymbolTable(symbols, ignoreQualification) {
45536 // If symbol is directly available by its name in the symbol table
45537 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
45538 return [symbol];
45539 }
45540 // Check if symbol is any of the aliases in scope
45541 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
45542 if (symbolFromSymbolTable.flags & 2097152 /* Alias */
45543 && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
45544 && symbolFromSymbolTable.escapedName !== "default" /* Default */
45545 && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
45546 // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
45547 && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
45548 // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
45549 // See similar comment in `resolveName` for details
45550 && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 267 /* ExportSpecifier */))) {
45551 var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
45552 var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
45553 if (candidate) {
45554 return candidate;
45555 }
45556 }
45557 if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
45558 if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
45559 return [symbol];
45560 }
45561 }
45562 });
45563 // 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
45564 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
45565 }
45566 function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
45567 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
45568 return [symbolFromSymbolTable];
45569 }
45570 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
45571 // but only if the symbolFromSymbolTable can be qualified
45572 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
45573 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
45574 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
45575 return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
45576 }
45577 }
45578 }
45579 function needsQualification(symbol, enclosingDeclaration, meaning) {
45580 var qualify = false;
45581 forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
45582 // If symbol of this name is not available in the symbol table we are ok
45583 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
45584 if (!symbolFromSymbolTable) {
45585 // Continue to the next symbol table
45586 return false;
45587 }
45588 // If the symbol with this name is present it should refer to the symbol
45589 if (symbolFromSymbolTable === symbol) {
45590 // No need to qualify
45591 return true;
45592 }
45593 // Qualify if the symbol from symbol table has same meaning as expected
45594 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 267 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
45595 if (symbolFromSymbolTable.flags & meaning) {
45596 qualify = true;
45597 return true;
45598 }
45599 // Continue to the next symbol table
45600 return false;
45601 });
45602 return qualify;
45603 }
45604 function isPropertyOrMethodDeclarationSymbol(symbol) {
45605 if (symbol.declarations && symbol.declarations.length) {
45606 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
45607 var declaration = _a[_i];
45608 switch (declaration.kind) {
45609 case 162 /* PropertyDeclaration */:
45610 case 164 /* MethodDeclaration */:
45611 case 166 /* GetAccessor */:
45612 case 167 /* SetAccessor */:
45613 continue;
45614 default:
45615 return false;
45616 }
45617 }
45618 return true;
45619 }
45620 return false;
45621 }
45622 function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
45623 var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
45624 return access.accessibility === 0 /* Accessible */;
45625 }
45626 function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
45627 var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
45628 return access.accessibility === 0 /* Accessible */;
45629 }
45630 function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
45631 var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ false);
45632 return access.accessibility === 0 /* Accessible */;
45633 }
45634 function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
45635 if (!ts.length(symbols))
45636 return;
45637 var hadAccessibleChain;
45638 var earlyModuleBail = false;
45639 for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
45640 var symbol = _a[_i];
45641 // Symbol is accessible if it by itself is accessible
45642 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
45643 if (accessibleSymbolChain) {
45644 hadAccessibleChain = symbol;
45645 var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
45646 if (hasAccessibleDeclarations) {
45647 return hasAccessibleDeclarations;
45648 }
45649 }
45650 else if (allowModules) {
45651 if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
45652 if (shouldComputeAliasesToMakeVisible) {
45653 earlyModuleBail = true;
45654 // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
45655 // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
45656 // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
45657 // all other visibility options (in order to capture the possible aliases used to reference the module)
45658 continue;
45659 }
45660 // Any meaning of a module symbol is always accessible via an `import` type
45661 return {
45662 accessibility: 0 /* Accessible */
45663 };
45664 }
45665 }
45666 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
45667 // It could be a qualified symbol and hence verify the path
45668 // e.g.:
45669 // module m {
45670 // export class c {
45671 // }
45672 // }
45673 // const x: typeof m.c
45674 // In the above example when we start with checking if typeof m.c symbol is accessible,
45675 // we are going to see if c can be accessed in scope directly.
45676 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
45677 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
45678 var containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
45679 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
45680 if (parentResult) {
45681 return parentResult;
45682 }
45683 }
45684 if (earlyModuleBail) {
45685 return {
45686 accessibility: 0 /* Accessible */
45687 };
45688 }
45689 if (hadAccessibleChain) {
45690 return {
45691 accessibility: 1 /* NotAccessible */,
45692 errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
45693 errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
45694 };
45695 }
45696 }
45697 /**
45698 * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
45699 *
45700 * @param symbol a Symbol to check if accessible
45701 * @param enclosingDeclaration a Node containing reference to the symbol
45702 * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
45703 * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
45704 */
45705 function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
45706 return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ true);
45707 }
45708 function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
45709 if (symbol && enclosingDeclaration) {
45710 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
45711 if (result) {
45712 return result;
45713 }
45714 // This could be a symbol that is not exported in the external module
45715 // or it could be a symbol from different external module that is not aliased and hence cannot be named
45716 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
45717 if (symbolExternalModule) {
45718 var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
45719 if (symbolExternalModule !== enclosingExternalModule) {
45720 // name from different external module that is not visible
45721 return {
45722 accessibility: 2 /* CannotBeNamed */,
45723 errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
45724 errorModuleName: symbolToString(symbolExternalModule)
45725 };
45726 }
45727 }
45728 // Just a local name that is not accessible
45729 return {
45730 accessibility: 1 /* NotAccessible */,
45731 errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
45732 };
45733 }
45734 return { accessibility: 0 /* Accessible */ };
45735 }
45736 function getExternalModuleContainer(declaration) {
45737 var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
45738 return node && getSymbolOfNode(node);
45739 }
45740 function hasExternalModuleSymbol(declaration) {
45741 return ts.isAmbientModule(declaration) || (declaration.kind === 294 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
45742 }
45743 function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
45744 return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 294 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
45745 }
45746 function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
45747 var aliasesToMakeVisible;
45748 if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 78 /* Identifier */; }), getIsDeclarationVisible)) {
45749 return undefined;
45750 }
45751 return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
45752 function getIsDeclarationVisible(declaration) {
45753 if (!isDeclarationVisible(declaration)) {
45754 // Mark the unexported alias as visible if its parent is visible
45755 // because these kind of aliases can be used to name types in declaration file
45756 var anyImportSyntax = getAnyImportSyntax(declaration);
45757 if (anyImportSyntax &&
45758 !ts.hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
45759 isDeclarationVisible(anyImportSyntax.parent)) {
45760 return addVisibleAlias(declaration, anyImportSyntax);
45761 }
45762 else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
45763 !ts.hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
45764 isDeclarationVisible(declaration.parent.parent.parent)) {
45765 return addVisibleAlias(declaration, declaration.parent.parent);
45766 }
45767 else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
45768 && !ts.hasSyntacticModifier(declaration, 1 /* Export */)
45769 && isDeclarationVisible(declaration.parent)) {
45770 return addVisibleAlias(declaration, declaration);
45771 }
45772 // Declaration is not visible
45773 return false;
45774 }
45775 return true;
45776 }
45777 function addVisibleAlias(declaration, aliasingStatement) {
45778 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
45779 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
45780 // since we will do the emitting later in trackSymbol.
45781 if (shouldComputeAliasToMakeVisible) {
45782 getNodeLinks(declaration).isVisible = true;
45783 aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
45784 }
45785 return true;
45786 }
45787 }
45788 function isEntityNameVisible(entityName, enclosingDeclaration) {
45789 // get symbol of the first identifier of the entityName
45790 var meaning;
45791 if (entityName.parent.kind === 175 /* TypeQuery */ ||
45792 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
45793 entityName.parent.kind === 157 /* ComputedPropertyName */) {
45794 // Typeof value
45795 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
45796 }
45797 else if (entityName.kind === 156 /* QualifiedName */ || entityName.kind === 198 /* PropertyAccessExpression */ ||
45798 entityName.parent.kind === 257 /* ImportEqualsDeclaration */) {
45799 // Left identifier from type reference or TypeAlias
45800 // Entity name of the import declaration
45801 meaning = 1920 /* Namespace */;
45802 }
45803 else {
45804 // Type Reference or TypeAlias entity = Identifier
45805 meaning = 788968 /* Type */;
45806 }
45807 var firstIdentifier = ts.getFirstIdentifier(entityName);
45808 var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
45809 if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
45810 return { accessibility: 0 /* Accessible */ };
45811 }
45812 // Verify if the symbol is accessible
45813 return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
45814 accessibility: 1 /* NotAccessible */,
45815 errorSymbolName: ts.getTextOfNode(firstIdentifier),
45816 errorNode: firstIdentifier
45817 };
45818 }
45819 function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
45820 if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
45821 var nodeFlags = 70221824 /* IgnoreErrors */;
45822 if (flags & 2 /* UseOnlyExternalAliasing */) {
45823 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
45824 }
45825 if (flags & 1 /* WriteTypeParametersOrArguments */) {
45826 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
45827 }
45828 if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
45829 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
45830 }
45831 if (flags & 16 /* DoNotIncludeSymbolChain */) {
45832 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
45833 }
45834 var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
45835 return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
45836 function symbolToStringWorker(writer) {
45837 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
45838 // add neverAsciiEscape for GH#39027
45839 var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 294 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true });
45840 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
45841 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
45842 return writer;
45843 }
45844 }
45845 function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
45846 if (flags === void 0) { flags = 0 /* None */; }
45847 return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
45848 function signatureToStringWorker(writer) {
45849 var sigOutput;
45850 if (flags & 262144 /* WriteArrowStyleSignature */) {
45851 sigOutput = kind === 1 /* Construct */ ? 174 /* ConstructorType */ : 173 /* FunctionType */;
45852 }
45853 else {
45854 sigOutput = kind === 1 /* Construct */ ? 169 /* ConstructSignature */ : 168 /* CallSignature */;
45855 }
45856 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
45857 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
45858 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
45859 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
45860 return writer;
45861 }
45862 }
45863 function typeToString(type, enclosingDeclaration, flags, writer) {
45864 if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
45865 if (writer === void 0) { writer = ts.createTextWriter(""); }
45866 var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
45867 var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
45868 if (typeNode === undefined)
45869 return ts.Debug.fail("should always get typenode");
45870 var options = { removeComments: true };
45871 var printer = ts.createPrinter(options);
45872 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
45873 printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
45874 var result = writer.getText();
45875 var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
45876 if (maxLength && result && result.length >= maxLength) {
45877 return result.substr(0, maxLength - "...".length) + "...";
45878 }
45879 return result;
45880 }
45881 function getTypeNamesForErrorDisplay(left, right) {
45882 var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
45883 var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
45884 if (leftStr === rightStr) {
45885 leftStr = getTypeNameForErrorDisplay(left);
45886 rightStr = getTypeNameForErrorDisplay(right);
45887 }
45888 return [leftStr, rightStr];
45889 }
45890 function getTypeNameForErrorDisplay(type) {
45891 return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
45892 }
45893 function symbolValueDeclarationIsContextSensitive(symbol) {
45894 return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
45895 }
45896 function toNodeBuilderFlags(flags) {
45897 if (flags === void 0) { flags = 0 /* None */; }
45898 return flags & 814775659 /* NodeBuilderFlagsMask */;
45899 }
45900 function createNodeBuilder() {
45901 return {
45902 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
45903 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
45904 },
45905 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
45906 return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, /*typeNode*/ undefined); });
45907 },
45908 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
45909 return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
45910 },
45911 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
45912 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
45913 },
45914 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
45915 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
45916 },
45917 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
45918 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
45919 },
45920 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
45921 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
45922 },
45923 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
45924 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
45925 },
45926 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
45927 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
45928 },
45929 };
45930 function withContext(enclosingDeclaration, flags, tracker, cb) {
45931 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
45932 var context = {
45933 enclosingDeclaration: enclosingDeclaration,
45934 flags: flags || 0 /* None */,
45935 // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
45936 tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
45937 getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
45938 getSourceFiles: function () { return host.getSourceFiles(); },
45939 getCurrentDirectory: function () { return host.getCurrentDirectory(); },
45940 getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache),
45941 useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
45942 redirectTargetsMap: host.redirectTargetsMap,
45943 getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
45944 isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
45945 fileExists: function (fileName) { return host.fileExists(fileName); },
45946 } : undefined },
45947 encounteredError: false,
45948 visitedTypes: undefined,
45949 symbolDepth: undefined,
45950 inferTypeParameters: undefined,
45951 approximateLength: 0
45952 };
45953 var resultingNode = cb(context);
45954 return context.encounteredError ? undefined : resultingNode;
45955 }
45956 function checkTruncationLength(context) {
45957 if (context.truncating)
45958 return context.truncating;
45959 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
45960 }
45961 function typeToTypeNodeHelper(type, context) {
45962 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
45963 cancellationToken.throwIfCancellationRequested();
45964 }
45965 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
45966 context.flags &= ~8388608 /* InTypeAlias */;
45967 if (!type) {
45968 if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
45969 context.encounteredError = true;
45970 return undefined; // TODO: GH#18217
45971 }
45972 context.approximateLength += 3;
45973 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
45974 }
45975 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
45976 type = getReducedType(type);
45977 }
45978 if (type.flags & 1 /* Any */) {
45979 context.approximateLength += 3;
45980 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
45981 }
45982 if (type.flags & 2 /* Unknown */) {
45983 return ts.factory.createKeywordTypeNode(151 /* UnknownKeyword */);
45984 }
45985 if (type.flags & 4 /* String */) {
45986 context.approximateLength += 6;
45987 return ts.factory.createKeywordTypeNode(146 /* StringKeyword */);
45988 }
45989 if (type.flags & 8 /* Number */) {
45990 context.approximateLength += 6;
45991 return ts.factory.createKeywordTypeNode(143 /* NumberKeyword */);
45992 }
45993 if (type.flags & 64 /* BigInt */) {
45994 context.approximateLength += 6;
45995 return ts.factory.createKeywordTypeNode(154 /* BigIntKeyword */);
45996 }
45997 if (type.flags & 16 /* Boolean */) {
45998 context.approximateLength += 7;
45999 return ts.factory.createKeywordTypeNode(131 /* BooleanKeyword */);
46000 }
46001 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
46002 var parentSymbol = getParentOfSymbol(type.symbol);
46003 var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
46004 var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
46005 ? parentName
46006 : appendReferenceToType(parentName, ts.factory.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
46007 return enumLiteralName;
46008 }
46009 if (type.flags & 1056 /* EnumLike */) {
46010 return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
46011 }
46012 if (type.flags & 128 /* StringLiteral */) {
46013 context.approximateLength += (type.value.length + 2);
46014 return ts.factory.createLiteralTypeNode(ts.setEmitFlags(ts.factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
46015 }
46016 if (type.flags & 256 /* NumberLiteral */) {
46017 var value = type.value;
46018 context.approximateLength += ("" + value).length;
46019 return ts.factory.createLiteralTypeNode(value < 0 ? ts.factory.createPrefixUnaryExpression(40 /* MinusToken */, ts.factory.createNumericLiteral(-value)) : ts.factory.createNumericLiteral(value));
46020 }
46021 if (type.flags & 2048 /* BigIntLiteral */) {
46022 context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
46023 return ts.factory.createLiteralTypeNode((ts.factory.createBigIntLiteral(type.value)));
46024 }
46025 if (type.flags & 512 /* BooleanLiteral */) {
46026 context.approximateLength += type.intrinsicName.length;
46027 return ts.factory.createLiteralTypeNode(type.intrinsicName === "true" ? ts.factory.createTrue() : ts.factory.createFalse());
46028 }
46029 if (type.flags & 8192 /* UniqueESSymbol */) {
46030 if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
46031 if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
46032 context.approximateLength += 6;
46033 return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
46034 }
46035 if (context.tracker.reportInaccessibleUniqueSymbolError) {
46036 context.tracker.reportInaccessibleUniqueSymbolError();
46037 }
46038 }
46039 context.approximateLength += 13;
46040 return ts.factory.createTypeOperatorNode(150 /* UniqueKeyword */, ts.factory.createKeywordTypeNode(147 /* SymbolKeyword */));
46041 }
46042 if (type.flags & 16384 /* Void */) {
46043 context.approximateLength += 4;
46044 return ts.factory.createKeywordTypeNode(113 /* VoidKeyword */);
46045 }
46046 if (type.flags & 32768 /* Undefined */) {
46047 context.approximateLength += 9;
46048 return ts.factory.createKeywordTypeNode(149 /* UndefinedKeyword */);
46049 }
46050 if (type.flags & 65536 /* Null */) {
46051 context.approximateLength += 4;
46052 return ts.factory.createLiteralTypeNode(ts.factory.createNull());
46053 }
46054 if (type.flags & 131072 /* Never */) {
46055 context.approximateLength += 5;
46056 return ts.factory.createKeywordTypeNode(140 /* NeverKeyword */);
46057 }
46058 if (type.flags & 4096 /* ESSymbol */) {
46059 context.approximateLength += 6;
46060 return ts.factory.createKeywordTypeNode(147 /* SymbolKeyword */);
46061 }
46062 if (type.flags & 67108864 /* NonPrimitive */) {
46063 context.approximateLength += 6;
46064 return ts.factory.createKeywordTypeNode(144 /* ObjectKeyword */);
46065 }
46066 if (isThisTypeParameter(type)) {
46067 if (context.flags & 4194304 /* InObjectTypeLiteral */) {
46068 if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
46069 context.encounteredError = true;
46070 }
46071 if (context.tracker.reportInaccessibleThisError) {
46072 context.tracker.reportInaccessibleThisError();
46073 }
46074 }
46075 context.approximateLength += 4;
46076 return ts.factory.createThisTypeNode();
46077 }
46078 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
46079 var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
46080 if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
46081 return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes);
46082 return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
46083 }
46084 var objectFlags = ts.getObjectFlags(type);
46085 if (objectFlags & 4 /* Reference */) {
46086 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
46087 return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
46088 }
46089 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
46090 if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
46091 context.approximateLength += (ts.symbolName(type.symbol).length + 6);
46092 return ts.factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
46093 }
46094 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
46095 type.flags & 262144 /* TypeParameter */ &&
46096 !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
46097 var name = typeParameterToName(type, context);
46098 context.approximateLength += ts.idText(name).length;
46099 return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
46100 }
46101 // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
46102 return type.symbol
46103 ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
46104 : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
46105 }
46106 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
46107 var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
46108 if (ts.length(types) === 1) {
46109 return typeToTypeNodeHelper(types[0], context);
46110 }
46111 var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
46112 if (typeNodes && typeNodes.length > 0) {
46113 var unionOrIntersectionTypeNode = type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
46114 return unionOrIntersectionTypeNode;
46115 }
46116 else {
46117 if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
46118 context.encounteredError = true;
46119 }
46120 return undefined; // TODO: GH#18217
46121 }
46122 }
46123 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
46124 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
46125 // The type is an object literal type.
46126 return createAnonymousTypeNode(type);
46127 }
46128 if (type.flags & 4194304 /* Index */) {
46129 var indexedType = type.type;
46130 context.approximateLength += 6;
46131 var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
46132 return ts.factory.createTypeOperatorNode(137 /* KeyOfKeyword */, indexTypeNode);
46133 }
46134 if (type.flags & 8388608 /* IndexedAccess */) {
46135 var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
46136 var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
46137 context.approximateLength += 2;
46138 return ts.factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
46139 }
46140 if (type.flags & 16777216 /* Conditional */) {
46141 var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
46142 var saveInferTypeParameters = context.inferTypeParameters;
46143 context.inferTypeParameters = type.root.inferTypeParameters;
46144 var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
46145 context.inferTypeParameters = saveInferTypeParameters;
46146 var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
46147 var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
46148 context.approximateLength += 15;
46149 return ts.factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
46150 }
46151 if (type.flags & 33554432 /* Substitution */) {
46152 return typeToTypeNodeHelper(type.baseType, context);
46153 }
46154 return ts.Debug.fail("Should be unreachable.");
46155 function typeToTypeNodeOrCircularityElision(type) {
46156 var _a, _b, _c;
46157 if (type.flags & 1048576 /* Union */) {
46158 if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(getTypeId(type))) {
46159 if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
46160 context.encounteredError = true;
46161 (_c = (_b = context.tracker) === null || _b === void 0 ? void 0 : _b.reportCyclicStructureError) === null || _c === void 0 ? void 0 : _c.call(_b);
46162 }
46163 return createElidedInformationPlaceholder(context);
46164 }
46165 return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
46166 }
46167 return typeToTypeNodeHelper(type, context);
46168 }
46169 function createMappedTypeNodeFromType(type) {
46170 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
46171 var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined;
46172 var questionToken = type.declaration.questionToken ? ts.factory.createToken(type.declaration.questionToken.kind) : undefined;
46173 var appropriateConstraintTypeNode;
46174 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
46175 // We have a { [P in keyof T]: X }
46176 // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
46177 appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(137 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
46178 }
46179 else {
46180 appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
46181 }
46182 var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
46183 var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
46184 var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
46185 context.approximateLength += 10;
46186 return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
46187 }
46188 function createAnonymousTypeNode(type) {
46189 var _a;
46190 var typeId = type.id;
46191 var symbol = type.symbol;
46192 if (symbol) {
46193 if (isJSConstructor(symbol.valueDeclaration)) {
46194 // Instance and static types share the same symbol; only add 'typeof' for the static side.
46195 var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
46196 return symbolToTypeNode(symbol, context, isInstanceType);
46197 }
46198 // Always use 'typeof T' for type of class, enum, and module objects
46199 else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 218 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
46200 symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
46201 shouldWriteTypeOfFunctionSymbol()) {
46202 return symbolToTypeNode(symbol, context, 111551 /* Value */);
46203 }
46204 else if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId)) {
46205 // If type is an anonymous type literal in a type alias declaration, use type alias name
46206 var typeAlias = getTypeAliasForTypeLiteral(type);
46207 if (typeAlias) {
46208 // The specified symbol flags need to be reinterpreted as type flags
46209 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
46210 }
46211 else {
46212 return createElidedInformationPlaceholder(context);
46213 }
46214 }
46215 else {
46216 return visitAndTransformType(type, createTypeNodeFromObjectType);
46217 }
46218 }
46219 else {
46220 // Anonymous types without a symbol are never circular.
46221 return createTypeNodeFromObjectType(type);
46222 }
46223 function shouldWriteTypeOfFunctionSymbol() {
46224 var _a;
46225 var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
46226 ts.some(symbol.declarations, function (declaration) { return ts.hasSyntacticModifier(declaration, 32 /* Static */); });
46227 var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
46228 (symbol.parent || // is exported function symbol
46229 ts.forEach(symbol.declarations, function (declaration) {
46230 return declaration.parent.kind === 294 /* SourceFile */ || declaration.parent.kind === 254 /* ModuleBlock */;
46231 }));
46232 if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
46233 // typeof is allowed only for static/non local functions
46234 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
46235 (!(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
46236 }
46237 }
46238 }
46239 function visitAndTransformType(type, transform) {
46240 var typeId = type.id;
46241 var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
46242 var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
46243 type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
46244 undefined;
46245 // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
46246 // of types allows us to catch circular references to instantiations of the same anonymous type
46247 if (!context.visitedTypes) {
46248 context.visitedTypes = new ts.Set();
46249 }
46250 if (id && !context.symbolDepth) {
46251 context.symbolDepth = new ts.Map();
46252 }
46253 var depth;
46254 if (id) {
46255 depth = context.symbolDepth.get(id) || 0;
46256 if (depth > 10) {
46257 return createElidedInformationPlaceholder(context);
46258 }
46259 context.symbolDepth.set(id, depth + 1);
46260 }
46261 context.visitedTypes.add(typeId);
46262 var result = transform(type);
46263 context.visitedTypes.delete(typeId);
46264 if (id) {
46265 context.symbolDepth.set(id, depth);
46266 }
46267 return result;
46268 }
46269 function createTypeNodeFromObjectType(type) {
46270 if (isGenericMappedType(type) || type.containsError) {
46271 return createMappedTypeNodeFromType(type);
46272 }
46273 var resolved = resolveStructuredTypeMembers(type);
46274 if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
46275 if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
46276 context.approximateLength += 2;
46277 return ts.setEmitFlags(ts.factory.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
46278 }
46279 if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
46280 var signature = resolved.callSignatures[0];
46281 var signatureNode = signatureToSignatureDeclarationHelper(signature, 173 /* FunctionType */, context);
46282 return signatureNode;
46283 }
46284 if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
46285 var signature = resolved.constructSignatures[0];
46286 var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* ConstructorType */, context);
46287 return signatureNode;
46288 }
46289 }
46290 var savedFlags = context.flags;
46291 context.flags |= 4194304 /* InObjectTypeLiteral */;
46292 var members = createTypeNodesFromResolvedType(resolved);
46293 context.flags = savedFlags;
46294 var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
46295 context.approximateLength += 2;
46296 return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
46297 }
46298 function typeReferenceToTypeNode(type) {
46299 var typeArguments = getTypeArguments(type);
46300 if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
46301 if (context.flags & 2 /* WriteArrayAsGenericType */) {
46302 var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
46303 return ts.factory.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
46304 }
46305 var elementType = typeToTypeNodeHelper(typeArguments[0], context);
46306 var arrayType = ts.factory.createArrayTypeNode(elementType);
46307 return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(141 /* ReadonlyKeyword */, arrayType);
46308 }
46309 else if (type.target.objectFlags & 8 /* Tuple */) {
46310 if (typeArguments.length > 0) {
46311 var arity = getTypeReferenceArity(type);
46312 var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
46313 if (tupleConstituentNodes) {
46314 if (type.target.labeledElementDeclarations) {
46315 for (var i = 0; i < tupleConstituentNodes.length; i++) {
46316 var flags = type.target.elementFlags[i];
46317 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]) :
46318 tupleConstituentNodes[i]);
46319 }
46320 }
46321 else {
46322 for (var i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++) {
46323 var flags = type.target.elementFlags[i];
46324 tupleConstituentNodes[i] =
46325 flags & 12 /* Variable */ ? ts.factory.createRestTypeNode(flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) :
46326 flags & 2 /* Optional */ ? ts.factory.createOptionalTypeNode(tupleConstituentNodes[i]) :
46327 tupleConstituentNodes[i];
46328 }
46329 }
46330 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
46331 return type.target.readonly ? ts.factory.createTypeOperatorNode(141 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
46332 }
46333 }
46334 if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
46335 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* SingleLine */);
46336 return type.target.readonly ? ts.factory.createTypeOperatorNode(141 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
46337 }
46338 context.encounteredError = true;
46339 return undefined; // TODO: GH#18217
46340 }
46341 else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
46342 type.symbol.valueDeclaration &&
46343 ts.isClassLike(type.symbol.valueDeclaration) &&
46344 !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
46345 return createAnonymousTypeNode(type);
46346 }
46347 else {
46348 var outerTypeParameters = type.target.outerTypeParameters;
46349 var i = 0;
46350 var resultType = void 0;
46351 if (outerTypeParameters) {
46352 var length_2 = outerTypeParameters.length;
46353 while (i < length_2) {
46354 // Find group of type arguments for type parameters with the same declaring container.
46355 var start = i;
46356 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
46357 do {
46358 i++;
46359 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
46360 // When type parameters are their own type arguments for the whole group (i.e. we have
46361 // the default outer type arguments), we don't show the group.
46362 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
46363 var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
46364 var flags_2 = context.flags;
46365 context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
46366 var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
46367 context.flags = flags_2;
46368 resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
46369 }
46370 }
46371 }
46372 var typeArgumentNodes = void 0;
46373 if (typeArguments.length > 0) {
46374 var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
46375 typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
46376 }
46377 var flags = context.flags;
46378 context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
46379 var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
46380 context.flags = flags;
46381 return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
46382 }
46383 }
46384 function appendReferenceToType(root, ref) {
46385 if (ts.isImportTypeNode(root)) {
46386 // first shift type arguments
46387 var typeArguments = root.typeArguments;
46388 var qualifier = root.qualifier;
46389 if (qualifier) {
46390 if (ts.isIdentifier(qualifier)) {
46391 qualifier = ts.factory.updateIdentifier(qualifier, typeArguments);
46392 }
46393 else {
46394 qualifier = ts.factory.updateQualifiedName(qualifier, qualifier.left, ts.factory.updateIdentifier(qualifier.right, typeArguments));
46395 }
46396 }
46397 typeArguments = ref.typeArguments;
46398 // then move qualifiers
46399 var ids = getAccessStack(ref);
46400 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
46401 var id = ids_1[_i];
46402 qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id;
46403 }
46404 return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf);
46405 }
46406 else {
46407 // first shift type arguments
46408 var typeArguments = root.typeArguments;
46409 var typeName = root.typeName;
46410 if (ts.isIdentifier(typeName)) {
46411 typeName = ts.factory.updateIdentifier(typeName, typeArguments);
46412 }
46413 else {
46414 typeName = ts.factory.updateQualifiedName(typeName, typeName.left, ts.factory.updateIdentifier(typeName.right, typeArguments));
46415 }
46416 typeArguments = ref.typeArguments;
46417 // then move qualifiers
46418 var ids = getAccessStack(ref);
46419 for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
46420 var id = ids_2[_a];
46421 typeName = ts.factory.createQualifiedName(typeName, id);
46422 }
46423 return ts.factory.updateTypeReferenceNode(root, typeName, typeArguments);
46424 }
46425 }
46426 function getAccessStack(ref) {
46427 var state = ref.typeName;
46428 var ids = [];
46429 while (!ts.isIdentifier(state)) {
46430 ids.unshift(state.right);
46431 state = state.left;
46432 }
46433 ids.unshift(state);
46434 return ids;
46435 }
46436 function createTypeNodesFromResolvedType(resolvedType) {
46437 if (checkTruncationLength(context)) {
46438 return [ts.factory.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined)];
46439 }
46440 var typeElements = [];
46441 for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
46442 var signature = _a[_i];
46443 typeElements.push(signatureToSignatureDeclarationHelper(signature, 168 /* CallSignature */, context));
46444 }
46445 for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
46446 var signature = _c[_b];
46447 typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* ConstructSignature */, context));
46448 }
46449 if (resolvedType.stringIndexInfo) {
46450 var indexSignature = void 0;
46451 if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
46452 indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context));
46453 }
46454 else {
46455 indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context, /*typeNode*/ undefined);
46456 }
46457 typeElements.push(indexSignature);
46458 }
46459 if (resolvedType.numberIndexInfo) {
46460 typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context, /*typeNode*/ undefined));
46461 }
46462 var properties = resolvedType.properties;
46463 if (!properties) {
46464 return typeElements;
46465 }
46466 var i = 0;
46467 for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
46468 var propertySymbol = properties_1[_d];
46469 i++;
46470 if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
46471 if (propertySymbol.flags & 4194304 /* Prototype */) {
46472 continue;
46473 }
46474 if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
46475 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
46476 }
46477 }
46478 if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
46479 typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined));
46480 addPropertyToElementList(properties[properties.length - 1], context, typeElements);
46481 break;
46482 }
46483 addPropertyToElementList(propertySymbol, context, typeElements);
46484 }
46485 return typeElements.length ? typeElements : undefined;
46486 }
46487 }
46488 function createElidedInformationPlaceholder(context) {
46489 context.approximateLength += 3;
46490 if (!(context.flags & 1 /* NoTruncation */)) {
46491 return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined);
46492 }
46493 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
46494 }
46495 function addPropertyToElementList(propertySymbol, context, typeElements) {
46496 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
46497 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
46498 anyType : getTypeOfSymbol(propertySymbol);
46499 var saveEnclosingDeclaration = context.enclosingDeclaration;
46500 context.enclosingDeclaration = undefined;
46501 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
46502 var decl = ts.first(propertySymbol.declarations);
46503 if (hasLateBindableName(decl)) {
46504 if (ts.isBinaryExpression(decl)) {
46505 var name = ts.getNameOfDeclaration(decl);
46506 if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
46507 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
46508 }
46509 }
46510 else {
46511 trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
46512 }
46513 }
46514 }
46515 context.enclosingDeclaration = saveEnclosingDeclaration;
46516 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
46517 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
46518 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
46519 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
46520 var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
46521 for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
46522 var signature = signatures_1[_i];
46523 var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 163 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
46524 typeElements.push(preserveCommentsOn(methodDeclaration));
46525 }
46526 }
46527 else {
46528 var savedFlags = context.flags;
46529 context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
46530 var propertyTypeNode = void 0;
46531 if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
46532 propertyTypeNode = createElidedInformationPlaceholder(context);
46533 }
46534 else {
46535 propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
46536 }
46537 context.flags = savedFlags;
46538 var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(141 /* ReadonlyKeyword */)] : undefined;
46539 if (modifiers) {
46540 context.approximateLength += 9;
46541 }
46542 var propertySignature = ts.factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode);
46543 typeElements.push(preserveCommentsOn(propertySignature));
46544 }
46545 function preserveCommentsOn(node) {
46546 if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 328 /* JSDocPropertyTag */; })) {
46547 var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 328 /* JSDocPropertyTag */; });
46548 var commentText = d.comment;
46549 if (commentText) {
46550 ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
46551 }
46552 }
46553 else if (propertySymbol.valueDeclaration) {
46554 // Copy comments to node for declaration emit
46555 ts.setCommentRange(node, propertySymbol.valueDeclaration);
46556 }
46557 return node;
46558 }
46559 }
46560 function mapToTypeNodes(types, context, isBareList) {
46561 if (ts.some(types)) {
46562 if (checkTruncationLength(context)) {
46563 if (!isBareList) {
46564 return [ts.factory.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
46565 }
46566 else if (types.length > 2) {
46567 return [
46568 typeToTypeNodeHelper(types[0], context),
46569 ts.factory.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
46570 typeToTypeNodeHelper(types[types.length - 1], context)
46571 ];
46572 }
46573 }
46574 var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
46575 /** Map from type reference identifier text to [type, index in `result` where the type node is] */
46576 var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
46577 var result_4 = [];
46578 var i = 0;
46579 for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
46580 var type = types_1[_i];
46581 i++;
46582 if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
46583 result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
46584 var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
46585 if (typeNode_1) {
46586 result_4.push(typeNode_1);
46587 }
46588 break;
46589 }
46590 context.approximateLength += 2; // Account for whitespace + separator
46591 var typeNode = typeToTypeNodeHelper(type, context);
46592 if (typeNode) {
46593 result_4.push(typeNode);
46594 if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
46595 seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]);
46596 }
46597 }
46598 }
46599 if (seenNames) {
46600 // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
46601 // occurrences of the same name actually come from different
46602 // namespaces, go through the single-identifier type reference nodes
46603 // we just generated, and see if any names were generated more than
46604 // once while referring to different types. If so, regenerate the
46605 // type node for each entry by that name with the
46606 // `UseFullyQualifiedType` flag enabled.
46607 var saveContextFlags = context.flags;
46608 context.flags |= 64 /* UseFullyQualifiedType */;
46609 seenNames.forEach(function (types) {
46610 if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
46611 var a = _a[0];
46612 var b = _b[0];
46613 return typesAreSameReference(a, b);
46614 })) {
46615 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
46616 var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
46617 result_4[resultIndex] = typeToTypeNodeHelper(type, context);
46618 }
46619 }
46620 });
46621 context.flags = saveContextFlags;
46622 }
46623 return result_4;
46624 }
46625 }
46626 function typesAreSameReference(a, b) {
46627 return a === b
46628 || !!a.symbol && a.symbol === b.symbol
46629 || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
46630 }
46631 function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, typeNode) {
46632 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
46633 var indexerTypeNode = ts.factory.createKeywordTypeNode(kind === 0 /* String */ ? 146 /* StringKeyword */ : 143 /* NumberKeyword */);
46634 var indexingParameter = ts.factory.createParameterDeclaration(
46635 /*decorators*/ undefined,
46636 /*modifiers*/ undefined,
46637 /*dotDotDotToken*/ undefined, name,
46638 /*questionToken*/ undefined, indexerTypeNode,
46639 /*initializer*/ undefined);
46640 if (!typeNode) {
46641 typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
46642 }
46643 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
46644 context.encounteredError = true;
46645 }
46646 context.approximateLength += (name.length + 4);
46647 return ts.factory.createIndexSignature(
46648 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(141 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
46649 }
46650 function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
46651 var _a, _b, _c, _d;
46652 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
46653 if (suppressAny)
46654 context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
46655 var typeParameters;
46656 var typeArguments;
46657 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
46658 typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
46659 }
46660 else {
46661 typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
46662 }
46663 var parameters = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0].map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 165 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); });
46664 if (signature.thisParameter) {
46665 var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
46666 parameters.unshift(thisParameter);
46667 }
46668 var returnTypeNode;
46669 var typePredicate = getTypePredicateOfSignature(signature);
46670 if (typePredicate) {
46671 var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
46672 ts.factory.createToken(127 /* AssertsKeyword */) :
46673 undefined;
46674 var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
46675 ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
46676 ts.factory.createThisTypeNode();
46677 var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
46678 returnTypeNode = ts.factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
46679 }
46680 else {
46681 var returnType = getReturnTypeOfSignature(signature);
46682 if (returnType && !(suppressAny && isTypeAny(returnType))) {
46683 returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports);
46684 }
46685 else if (!suppressAny) {
46686 returnTypeNode = ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
46687 }
46688 }
46689 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
46690 var node = kind === 168 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
46691 kind === 169 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
46692 kind === 163 /* 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) :
46693 kind === 164 /* 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) :
46694 kind === 165 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, /*body*/ undefined) :
46695 kind === 166 /* 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) :
46696 kind === 167 /* 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) :
46697 kind === 170 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, returnTypeNode) :
46698 kind === 304 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
46699 kind === 173 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
46700 kind === 174 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
46701 kind === 248 /* 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) :
46702 kind === 205 /* 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([])) :
46703 kind === 206 /* ArrowFunction */ ? ts.factory.createArrowFunction(options === null || options === void 0 ? void 0 : options.modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
46704 ts.Debug.assertNever(kind);
46705 if (typeArguments) {
46706 node.typeArguments = ts.factory.createNodeArray(typeArguments);
46707 }
46708 return node;
46709 }
46710 function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
46711 var savedContextFlags = context.flags;
46712 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
46713 var name = typeParameterToName(type, context);
46714 var defaultParameter = getDefaultFromTypeParameter(type);
46715 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
46716 context.flags = savedContextFlags;
46717 return ts.factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
46718 }
46719 function typeParameterToDeclaration(type, context, constraint) {
46720 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
46721 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
46722 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
46723 }
46724 function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
46725 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 159 /* Parameter */);
46726 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
46727 parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 322 /* JSDocParameterTag */);
46728 }
46729 var parameterType = getTypeOfSymbol(parameterSymbol);
46730 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
46731 parameterType = getOptionalType(parameterType);
46732 }
46733 if ((context.flags & 1073741824 /* NoUndefinedOptionalParameterType */) && parameterDeclaration && !ts.isJSDocParameterTag(parameterDeclaration) && isOptionalUninitializedParameter(parameterDeclaration)) {
46734 parameterType = getTypeWithFacts(parameterType, 524288 /* NEUndefined */);
46735 }
46736 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
46737 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined;
46738 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
46739 var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined;
46740 var name = parameterDeclaration ? parameterDeclaration.name ?
46741 parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
46742 parameterDeclaration.name.kind === 156 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
46743 cloneBindingName(parameterDeclaration.name) :
46744 ts.symbolName(parameterSymbol) :
46745 ts.symbolName(parameterSymbol);
46746 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
46747 var questionToken = isOptional ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
46748 var parameterNode = ts.factory.createParameterDeclaration(
46749 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode,
46750 /*initializer*/ undefined);
46751 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
46752 return parameterNode;
46753 function cloneBindingName(node) {
46754 return elideInitializerAndSetEmitFlags(node);
46755 function elideInitializerAndSetEmitFlags(node) {
46756 if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
46757 trackComputedName(node.expression, context.enclosingDeclaration, context);
46758 }
46759 var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
46760 if (ts.isBindingElement(visited)) {
46761 visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
46762 /*initializer*/ undefined);
46763 }
46764 if (!ts.nodeIsSynthesized(visited)) {
46765 visited = ts.factory.cloneNode(visited);
46766 }
46767 return ts.setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
46768 }
46769 }
46770 }
46771 function trackComputedName(accessExpression, enclosingDeclaration, context) {
46772 if (!context.tracker.trackSymbol)
46773 return;
46774 // get symbol of the first identifier of the entityName
46775 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
46776 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
46777 if (name) {
46778 context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
46779 }
46780 }
46781 function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
46782 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
46783 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
46784 }
46785 function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
46786 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
46787 var chain;
46788 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
46789 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
46790 chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
46791 ts.Debug.assert(chain && chain.length > 0);
46792 }
46793 else {
46794 chain = [symbol];
46795 }
46796 return chain;
46797 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
46798 function getSymbolChain(symbol, meaning, endOfChain) {
46799 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
46800 var parentSpecifiers;
46801 if (!accessibleSymbolChain ||
46802 needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
46803 // Go up and add our parent.
46804 var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning);
46805 if (ts.length(parents_1)) {
46806 parentSpecifiers = parents_1.map(function (symbol) {
46807 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
46808 ? getSpecifierForModuleSymbol(symbol, context)
46809 : undefined;
46810 });
46811 var indices = parents_1.map(function (_, i) { return i; });
46812 indices.sort(sortByBestName);
46813 var sortedParents = indices.map(function (i) { return parents_1[i]; });
46814 for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
46815 var parent = sortedParents_1[_i];
46816 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
46817 if (parentChain) {
46818 if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
46819 getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
46820 // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
46821 // No need to lookup an alias for the symbol in itself
46822 accessibleSymbolChain = parentChain;
46823 break;
46824 }
46825 accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
46826 break;
46827 }
46828 }
46829 }
46830 }
46831 if (accessibleSymbolChain) {
46832 return accessibleSymbolChain;
46833 }
46834 if (
46835 // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
46836 endOfChain ||
46837 // If a parent symbol is an anonymous type, don't write it.
46838 !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
46839 // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
46840 if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
46841 return;
46842 }
46843 return [symbol];
46844 }
46845 function sortByBestName(a, b) {
46846 var specifierA = parentSpecifiers[a];
46847 var specifierB = parentSpecifiers[b];
46848 if (specifierA && specifierB) {
46849 var isBRelative = ts.pathIsRelative(specifierB);
46850 if (ts.pathIsRelative(specifierA) === isBRelative) {
46851 // Both relative or both non-relative, sort by number of parts
46852 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
46853 }
46854 if (isBRelative) {
46855 // A is non-relative, B is relative: prefer A
46856 return -1;
46857 }
46858 // A is relative, B is non-relative: prefer B
46859 return 1;
46860 }
46861 return 0;
46862 }
46863 }
46864 }
46865 function typeParametersToTypeParameterDeclarations(symbol, context) {
46866 var typeParameterNodes;
46867 var targetSymbol = getTargetSymbol(symbol);
46868 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
46869 typeParameterNodes = ts.factory.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
46870 }
46871 return typeParameterNodes;
46872 }
46873 function lookupTypeParameterNodes(chain, index, context) {
46874 var _a;
46875 ts.Debug.assert(chain && 0 <= index && index < chain.length);
46876 var symbol = chain[index];
46877 var symbolId = getSymbolId(symbol);
46878 if ((_a = context.typeParameterSymbolList) === null || _a === void 0 ? void 0 : _a.has(symbolId)) {
46879 return undefined;
46880 }
46881 (context.typeParameterSymbolList || (context.typeParameterSymbolList = new ts.Set())).add(symbolId);
46882 var typeParameterNodes;
46883 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
46884 var parentSymbol = symbol;
46885 var nextSymbol_1 = chain[index + 1];
46886 if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
46887 var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
46888 typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
46889 }
46890 else {
46891 typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
46892 }
46893 }
46894 return typeParameterNodes;
46895 }
46896 /**
46897 * Given A[B][C][D], finds A[B]
46898 */
46899 function getTopmostIndexedAccessType(top) {
46900 if (ts.isIndexedAccessTypeNode(top.objectType)) {
46901 return getTopmostIndexedAccessType(top.objectType);
46902 }
46903 return top;
46904 }
46905 function getSpecifierForModuleSymbol(symbol, context) {
46906 var _a;
46907 var file = ts.getDeclarationOfKind(symbol, 294 /* SourceFile */);
46908 if (!file) {
46909 var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
46910 if (equivalentFileSymbol) {
46911 file = ts.getDeclarationOfKind(equivalentFileSymbol, 294 /* SourceFile */);
46912 }
46913 }
46914 if (file && file.moduleName !== undefined) {
46915 // Use the amd name if it is available
46916 return file.moduleName;
46917 }
46918 if (!file) {
46919 if (context.tracker.trackReferencedAmbientModule) {
46920 var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
46921 if (ts.length(ambientDecls)) {
46922 for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
46923 var decl = ambientDecls_1[_i];
46924 context.tracker.trackReferencedAmbientModule(decl, symbol);
46925 }
46926 }
46927 }
46928 if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
46929 return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
46930 }
46931 }
46932 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
46933 // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
46934 if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
46935 return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
46936 }
46937 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
46938 }
46939 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
46940 var links = getSymbolLinks(symbol);
46941 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
46942 if (!specifier) {
46943 var isBundle_1 = !!ts.outFile(compilerOptions);
46944 // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
46945 // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
46946 // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
46947 // specifier preference
46948 var moduleResolverHost = context.tracker.moduleResolverHost;
46949 var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
46950 specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
46951 (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
46952 links.specifierCache.set(contextFile.path, specifier);
46953 }
46954 return specifier;
46955 }
46956 function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
46957 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
46958 var isTypeOf = meaning === 111551 /* Value */;
46959 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
46960 // module is root, must use `ImportTypeNode`
46961 var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
46962 var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
46963 var specifier = getSpecifierForModuleSymbol(chain[0], context);
46964 if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
46965 // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
46966 // since declaration files with these kinds of references are liable to fail when published :(
46967 context.encounteredError = true;
46968 if (context.tracker.reportLikelyUnsafeImportRequiredError) {
46969 context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
46970 }
46971 }
46972 var lit = ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier));
46973 if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
46974 context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
46975 context.approximateLength += specifier.length + 10; // specifier + import("")
46976 if (!nonRootParts || ts.isEntityName(nonRootParts)) {
46977 if (nonRootParts) {
46978 var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
46979 lastId.typeArguments = undefined;
46980 }
46981 return ts.factory.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
46982 }
46983 else {
46984 var splitNode = getTopmostIndexedAccessType(nonRootParts);
46985 var qualifier = splitNode.objectType.typeName;
46986 return ts.factory.createIndexedAccessTypeNode(ts.factory.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
46987 }
46988 }
46989 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
46990 if (ts.isIndexedAccessTypeNode(entityName)) {
46991 return entityName; // Indexed accesses can never be `typeof`
46992 }
46993 if (isTypeOf) {
46994 return ts.factory.createTypeQueryNode(entityName);
46995 }
46996 else {
46997 var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
46998 var lastTypeArgs = lastId.typeArguments;
46999 lastId.typeArguments = undefined;
47000 return ts.factory.createTypeReferenceNode(entityName, lastTypeArgs);
47001 }
47002 function createAccessFromSymbolChain(chain, index, stopper) {
47003 var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
47004 var symbol = chain[index];
47005 var parent = chain[index - 1];
47006 var symbolName;
47007 if (index === 0) {
47008 context.flags |= 16777216 /* InInitialEntityName */;
47009 symbolName = getNameOfSymbolAsWritten(symbol, context);
47010 context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
47011 context.flags ^= 16777216 /* InInitialEntityName */;
47012 }
47013 else {
47014 if (parent && getExportsOfSymbol(parent)) {
47015 var exports_1 = getExportsOfSymbol(parent);
47016 ts.forEachEntry(exports_1, function (ex, name) {
47017 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
47018 symbolName = ts.unescapeLeadingUnderscores(name);
47019 return true;
47020 }
47021 });
47022 }
47023 }
47024 if (!symbolName) {
47025 symbolName = getNameOfSymbolAsWritten(symbol, context);
47026 }
47027 context.approximateLength += symbolName.length + 1;
47028 if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
47029 getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
47030 getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
47031 // Should use an indexed access
47032 var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
47033 if (ts.isIndexedAccessTypeNode(LHS)) {
47034 return ts.factory.createIndexedAccessTypeNode(LHS, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
47035 }
47036 else {
47037 return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(LHS, typeParameterNodes), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
47038 }
47039 }
47040 var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
47041 identifier.symbol = symbol;
47042 if (index > stopper) {
47043 var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
47044 if (!ts.isEntityName(LHS)) {
47045 return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
47046 }
47047 return ts.factory.createQualifiedName(LHS, identifier);
47048 }
47049 return identifier;
47050 }
47051 }
47052 function typeParameterShadowsNameInScope(escapedName, context, type) {
47053 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
47054 if (result) {
47055 if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
47056 return false;
47057 }
47058 return true;
47059 }
47060 return false;
47061 }
47062 function typeParameterToName(type, context) {
47063 var _a;
47064 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
47065 var cached = context.typeParameterNames.get(getTypeId(type));
47066 if (cached) {
47067 return cached;
47068 }
47069 }
47070 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
47071 if (!(result.kind & 78 /* Identifier */)) {
47072 return ts.factory.createIdentifier("(Missing type parameter)");
47073 }
47074 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
47075 var rawtext = result.escapedText;
47076 var i = 0;
47077 var text = rawtext;
47078 while (((_a = context.typeParameterNamesByText) === null || _a === void 0 ? void 0 : _a.has(text)) || typeParameterShadowsNameInScope(text, context, type)) {
47079 i++;
47080 text = rawtext + "_" + i;
47081 }
47082 if (text !== rawtext) {
47083 result = ts.factory.createIdentifier(text, result.typeArguments);
47084 }
47085 (context.typeParameterNames || (context.typeParameterNames = new ts.Map())).set(getTypeId(type), result);
47086 (context.typeParameterNamesByText || (context.typeParameterNamesByText = new ts.Set())).add(result.escapedText);
47087 }
47088 return result;
47089 }
47090 function symbolToName(symbol, context, meaning, expectsIdentifier) {
47091 var chain = lookupSymbolChain(symbol, context, meaning);
47092 if (expectsIdentifier && chain.length !== 1
47093 && !context.encounteredError
47094 && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
47095 context.encounteredError = true;
47096 }
47097 return createEntityNameFromSymbolChain(chain, chain.length - 1);
47098 function createEntityNameFromSymbolChain(chain, index) {
47099 var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
47100 var symbol = chain[index];
47101 if (index === 0) {
47102 context.flags |= 16777216 /* InInitialEntityName */;
47103 }
47104 var symbolName = getNameOfSymbolAsWritten(symbol, context);
47105 if (index === 0) {
47106 context.flags ^= 16777216 /* InInitialEntityName */;
47107 }
47108 var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
47109 identifier.symbol = symbol;
47110 return index > 0 ? ts.factory.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
47111 }
47112 }
47113 function symbolToExpression(symbol, context, meaning) {
47114 var chain = lookupSymbolChain(symbol, context, meaning);
47115 return createExpressionFromSymbolChain(chain, chain.length - 1);
47116 function createExpressionFromSymbolChain(chain, index) {
47117 var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
47118 var symbol = chain[index];
47119 if (index === 0) {
47120 context.flags |= 16777216 /* InInitialEntityName */;
47121 }
47122 var symbolName = getNameOfSymbolAsWritten(symbol, context);
47123 if (index === 0) {
47124 context.flags ^= 16777216 /* InInitialEntityName */;
47125 }
47126 var firstChar = symbolName.charCodeAt(0);
47127 if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
47128 return ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context));
47129 }
47130 var canUsePropertyAccess = firstChar === 35 /* hash */ ?
47131 symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
47132 ts.isIdentifierStart(firstChar, languageVersion);
47133 if (index === 0 || canUsePropertyAccess) {
47134 var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
47135 identifier.symbol = symbol;
47136 return index > 0 ? ts.factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
47137 }
47138 else {
47139 if (firstChar === 91 /* openBracket */) {
47140 symbolName = symbolName.substring(1, symbolName.length - 1);
47141 firstChar = symbolName.charCodeAt(0);
47142 }
47143 var expression = void 0;
47144 if (ts.isSingleOrDoubleQuote(firstChar)) {
47145 expression = ts.factory.createStringLiteral(symbolName
47146 .substring(1, symbolName.length - 1)
47147 .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */);
47148 }
47149 else if (("" + +symbolName) === symbolName) {
47150 expression = ts.factory.createNumericLiteral(+symbolName);
47151 }
47152 if (!expression) {
47153 expression = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
47154 expression.symbol = symbol;
47155 }
47156 return ts.factory.createElementAccessExpression(createExpressionFromSymbolChain(chain, index - 1), expression);
47157 }
47158 }
47159 }
47160 function isStringNamed(d) {
47161 var name = ts.getNameOfDeclaration(d);
47162 return !!name && ts.isStringLiteral(name);
47163 }
47164 function isSingleQuotedStringNamed(d) {
47165 var name = ts.getNameOfDeclaration(d);
47166 return !!(name && ts.isStringLiteral(name) && (name.singleQuote || !ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")));
47167 }
47168 function getPropertyNameNodeForSymbol(symbol, context) {
47169 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
47170 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
47171 if (fromNameType) {
47172 return fromNameType;
47173 }
47174 if (ts.isKnownSymbol(symbol)) {
47175 return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
47176 }
47177 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
47178 var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed);
47179 return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote);
47180 }
47181 // See getNameForSymbolFromNameType for a stringy equivalent
47182 function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
47183 var nameType = getSymbolLinks(symbol).nameType;
47184 if (nameType) {
47185 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
47186 var name = "" + nameType.value;
47187 if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
47188 return ts.factory.createStringLiteral(name, !!singleQuote);
47189 }
47190 if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
47191 return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name));
47192 }
47193 return createPropertyNameNodeForIdentifierOrLiteral(name);
47194 }
47195 if (nameType.flags & 8192 /* UniqueESSymbol */) {
47196 return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
47197 }
47198 }
47199 }
47200 function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) {
47201 return ts.isIdentifierText(name, compilerOptions.target) ? ts.factory.createIdentifier(name) :
47202 !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) :
47203 ts.factory.createStringLiteral(name, !!singleQuote);
47204 }
47205 function cloneNodeBuilderContext(context) {
47206 var initial = __assign({}, context);
47207 // Make type parameters created within this context not consume the name outside this context
47208 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
47209 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
47210 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
47211 // were multiple generic overloads with similar generated type parameter names
47212 // The effect:
47213 // When we write out
47214 // export const x: <T>(x: T) => T
47215 // export const y: <T>(x: T) => T
47216 // we write it out like that, rather than as
47217 // export const x: <T>(x: T) => T
47218 // export const y: <T_1>(x: T_1) => T_1
47219 if (initial.typeParameterNames) {
47220 initial.typeParameterNames = new ts.Map(initial.typeParameterNames);
47221 }
47222 if (initial.typeParameterNamesByText) {
47223 initial.typeParameterNamesByText = new ts.Set(initial.typeParameterNamesByText);
47224 }
47225 if (initial.typeParameterSymbolList) {
47226 initial.typeParameterSymbolList = new ts.Set(initial.typeParameterSymbolList);
47227 }
47228 return initial;
47229 }
47230 function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
47231 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
47232 }
47233 function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
47234 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
47235 }
47236 /**
47237 * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
47238 * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
47239 */
47240 function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
47241 if (type !== errorType && enclosingDeclaration) {
47242 var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
47243 if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
47244 // try to reuse the existing annotation
47245 var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
47246 if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
47247 var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
47248 if (result_5) {
47249 return result_5;
47250 }
47251 }
47252 }
47253 }
47254 var oldFlags = context.flags;
47255 if (type.flags & 8192 /* UniqueESSymbol */ &&
47256 type.symbol === symbol) {
47257 context.flags |= 1048576 /* AllowUniqueESSymbolType */;
47258 }
47259 var result = typeToTypeNodeHelper(type, context);
47260 context.flags = oldFlags;
47261 return result;
47262 }
47263 function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
47264 if (type !== errorType && context.enclosingDeclaration) {
47265 var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
47266 if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
47267 var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
47268 if (result) {
47269 return result;
47270 }
47271 }
47272 }
47273 return typeToTypeNodeHelper(type, context);
47274 }
47275 function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
47276 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
47277 cancellationToken.throwIfCancellationRequested();
47278 }
47279 var hadError = false;
47280 var file = ts.getSourceFileOfNode(existing);
47281 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
47282 if (hadError) {
47283 return undefined;
47284 }
47285 return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
47286 function visitExistingNodeTreeSymbols(node) {
47287 var _a, _b;
47288 // We don't _actually_ support jsdoc namepath types, emit `any` instead
47289 if (ts.isJSDocAllType(node) || node.kind === 306 /* JSDocNamepathType */) {
47290 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47291 }
47292 if (ts.isJSDocUnknownType(node)) {
47293 return ts.factory.createKeywordTypeNode(151 /* UnknownKeyword */);
47294 }
47295 if (ts.isJSDocNullableType(node)) {
47296 return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]);
47297 }
47298 if (ts.isJSDocOptionalType(node)) {
47299 return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(149 /* UndefinedKeyword */)]);
47300 }
47301 if (ts.isJSDocNonNullableType(node)) {
47302 return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
47303 }
47304 if (ts.isJSDocVariadicType(node)) {
47305 return ts.factory.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
47306 }
47307 if (ts.isJSDocTypeLiteral(node)) {
47308 return ts.factory.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
47309 var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
47310 var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
47311 var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
47312 return ts.factory.createPropertySignature(
47313 /*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 */));
47314 }));
47315 }
47316 if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
47317 return ts.setOriginalNode(ts.factory.createKeywordTypeNode(128 /* AnyKeyword */), node);
47318 }
47319 if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
47320 return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(
47321 /*decorators*/ undefined,
47322 /*modifiers*/ undefined, [ts.factory.createParameterDeclaration(
47323 /*decorators*/ undefined,
47324 /*modifiers*/ undefined,
47325 /*dotdotdotToken*/ undefined, "x",
47326 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
47327 }
47328 if (ts.isJSDocFunctionType(node)) {
47329 if (ts.isJSDocConstructSignature(node)) {
47330 var newTypeNode_1;
47331 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(
47332 /*decorators*/ undefined,
47333 /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols),
47334 /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
47335 }
47336 else {
47337 return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(
47338 /*decorators*/ undefined,
47339 /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols),
47340 /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
47341 }
47342 }
47343 if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
47344 return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
47345 }
47346 if (ts.isLiteralImportTypeNode(node)) {
47347 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);
47348 }
47349 if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
47350 var leftmost = ts.getFirstIdentifier(node);
47351 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)))) {
47352 hadError = true;
47353 return node;
47354 }
47355 var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
47356 if (sym) {
47357 if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
47358 hadError = true;
47359 }
47360 else {
47361 (_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 */);
47362 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
47363 }
47364 if (ts.isIdentifier(node)) {
47365 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
47366 name.symbol = sym; // for quickinfo, which uses identifier symbol information
47367 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
47368 }
47369 }
47370 }
47371 if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
47372 ts.setEmitFlags(node, 1 /* SingleLine */);
47373 }
47374 return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
47375 function getEffectiveDotDotDotForParameter(p) {
47376 return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined);
47377 }
47378 /** Note that `new:T` parameters are not handled, but should be before calling this function. */
47379 function getNameForJSDocFunctionParameter(p, index) {
47380 return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this"
47381 : getEffectiveDotDotDotForParameter(p) ? "args"
47382 : "arg" + index;
47383 }
47384 function rewriteModuleSpecifier(parent, lit) {
47385 if (bundled) {
47386 if (context.tracker && context.tracker.moduleResolverHost) {
47387 var targetFile = getExternalModuleFileFromDeclaration(parent);
47388 if (targetFile) {
47389 var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
47390 var resolverHost = {
47391 getCanonicalFileName: getCanonicalFileName,
47392 getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
47393 getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
47394 };
47395 var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
47396 return ts.factory.createStringLiteral(newName);
47397 }
47398 }
47399 }
47400 else {
47401 if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
47402 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
47403 if (moduleSym) {
47404 context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
47405 }
47406 }
47407 }
47408 return lit;
47409 }
47410 }
47411 }
47412 function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
47413 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 164 /* MethodDeclaration */, /*useAcessors*/ true);
47414 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 163 /* MethodSignature */, /*useAcessors*/ false);
47415 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
47416 // declaration mapping
47417 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
47418 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
47419 // we're trying to emit from later on)
47420 var enclosingDeclaration = context.enclosingDeclaration;
47421 var results = [];
47422 var visitedSymbols = new ts.Set();
47423 var deferredPrivatesStack = [];
47424 var oldcontext = context;
47425 context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
47426 var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
47427 if (accessibleResult.accessibility === 0 /* Accessible */) {
47428 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
47429 var chain = lookupSymbolChainWorker(sym, context, meaning);
47430 if (!(sym.flags & 4 /* Property */)) {
47431 includePrivateSymbol(chain[0]);
47432 }
47433 }
47434 else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
47435 oldcontext.tracker.trackSymbol(sym, decl, meaning);
47436 }
47437 } }) });
47438 ts.forEachEntry(symbolTable, function (symbol, name) {
47439 var baseName = ts.unescapeLeadingUnderscores(name);
47440 void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
47441 });
47442 var addingDeclare = !bundled;
47443 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
47444 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
47445 symbolTable = ts.createSymbolTable();
47446 // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
47447 symbolTable.set("export=" /* ExportEquals */, exportEquals);
47448 }
47449 visitSymbolTable(symbolTable);
47450 return mergeRedundantStatements(results);
47451 function isIdentifierAndNotUndefined(node) {
47452 return !!node && node.kind === 78 /* Identifier */;
47453 }
47454 function getNamesOfDeclaration(statement) {
47455 if (ts.isVariableStatement(statement)) {
47456 return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
47457 }
47458 return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
47459 }
47460 function flattenExportAssignedNamespace(statements) {
47461 var exportAssignment = ts.find(statements, ts.isExportAssignment);
47462 var nsIndex = ts.findIndex(statements, ts.isModuleDeclaration);
47463 var ns = nsIndex !== -1 ? statements[nsIndex] : undefined;
47464 if (ns && exportAssignment && exportAssignment.isExportEquals &&
47465 ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
47466 ns.body && ts.isModuleBlock(ns.body)) {
47467 // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
47468 // 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
47469 var excessExports = ts.filter(statements, function (s) { return !!(ts.getEffectiveModifierFlags(s) & 1 /* Export */); });
47470 var name_2 = ns.name;
47471 var body = ns.body;
47472 if (ts.length(excessExports)) {
47473 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(
47474 /*decorators*/ undefined,
47475 /*modifiers*/ undefined,
47476 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*alias*/ undefined, id); })),
47477 /*moduleSpecifier*/ undefined)]))));
47478 statements = __spreadArrays(statements.slice(0, nsIndex), [ns], statements.slice(nsIndex + 1));
47479 }
47480 // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
47481 if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
47482 results = [];
47483 // If the namespace contains no export assignments or declarations, and no declarations flagged with `export`, then _everything_ is exported -
47484 // to respect this as the top level, we need to add an `export` modifier to everything
47485 var mixinExportFlag_1 = !ts.some(body.statements, function (s) { return ts.hasSyntacticModifier(s, 1 /* Export */) || ts.isExportAssignment(s) || ts.isExportDeclaration(s); });
47486 ts.forEach(body.statements, function (s) {
47487 addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
47488 });
47489 statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
47490 }
47491 }
47492 return statements;
47493 }
47494 function mergeExportDeclarations(statements) {
47495 // Pass 2: Combine all `export {}` declarations
47496 var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
47497 if (ts.length(exports) > 1) {
47498 var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
47499 statements = __spreadArrays(nonExports, [ts.factory.createExportDeclaration(
47500 /*decorators*/ undefined,
47501 /*modifiers*/ undefined,
47502 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })),
47503 /*moduleSpecifier*/ undefined)]);
47504 }
47505 // Pass 2b: Also combine all `export {} from "..."` declarations as needed
47506 var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
47507 if (ts.length(reexports) > 1) {
47508 var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
47509 if (groups.length !== reexports.length) {
47510 var _loop_9 = function (group_1) {
47511 if (group_1.length > 1) {
47512 // remove group members from statements and then merge group members and add back to statements
47513 statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
47514 ts.factory.createExportDeclaration(
47515 /*decorators*/ undefined,
47516 /*modifiers*/ undefined,
47517 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
47518 ]);
47519 }
47520 };
47521 for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
47522 var group_1 = groups_1[_i];
47523 _loop_9(group_1);
47524 }
47525 }
47526 }
47527 return statements;
47528 }
47529 function inlineExportModifiers(statements) {
47530 // Pass 3: Move all `export {}`'s to `export` modifiers where possible
47531 var index = ts.findIndex(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
47532 if (index >= 0) {
47533 var exportDecl = statements[index];
47534 var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
47535 if (!e.propertyName) {
47536 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
47537 var indices = ts.indicesOf(statements);
47538 var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); });
47539 if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) {
47540 for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) {
47541 var index_1 = associatedIndices_1[_i];
47542 statements[index_1] = addExportModifier(statements[index_1]);
47543 }
47544 return undefined;
47545 }
47546 }
47547 return e;
47548 });
47549 if (!ts.length(replacements)) {
47550 // all clauses removed, remove the export declaration
47551 ts.orderedRemoveItemAt(statements, index);
47552 }
47553 else {
47554 // some items filtered, others not - update the export declaration
47555 statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier);
47556 }
47557 }
47558 return statements;
47559 }
47560 function mergeRedundantStatements(statements) {
47561 statements = flattenExportAssignedNamespace(statements);
47562 statements = mergeExportDeclarations(statements);
47563 statements = inlineExportModifiers(statements);
47564 // 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
47565 // declaration privacy is respected.
47566 if (enclosingDeclaration &&
47567 ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
47568 (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
47569 statements.push(ts.createEmptyExports(ts.factory));
47570 }
47571 return statements;
47572 }
47573 function canHaveExportModifier(node) {
47574 return ts.isEnumDeclaration(node) ||
47575 ts.isVariableStatement(node) ||
47576 ts.isFunctionDeclaration(node) ||
47577 ts.isClassDeclaration(node) ||
47578 (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
47579 ts.isInterfaceDeclaration(node) ||
47580 isTypeDeclaration(node);
47581 }
47582 function addExportModifier(node) {
47583 var flags = (ts.getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */;
47584 return ts.factory.updateModifiers(node, flags);
47585 }
47586 function removeExportModifier(node) {
47587 var flags = ts.getEffectiveModifierFlags(node) & ~1 /* Export */;
47588 return ts.factory.updateModifiers(node, flags);
47589 }
47590 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
47591 if (!suppressNewPrivateContext) {
47592 deferredPrivatesStack.push(new ts.Map());
47593 }
47594 symbolTable.forEach(function (symbol) {
47595 serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
47596 });
47597 if (!suppressNewPrivateContext) {
47598 // deferredPrivates will be filled up by visiting the symbol table
47599 // And will continue to iterate as elements are added while visited `deferredPrivates`
47600 // (As that's how a map iterator is defined to work)
47601 deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(function (symbol) {
47602 serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
47603 });
47604 deferredPrivatesStack.pop();
47605 }
47606 }
47607 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
47608 // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
47609 // still skip reserializing it if we encounter the merged product later on
47610 var visitedSym = getMergedSymbol(symbol);
47611 if (visitedSymbols.has(getSymbolId(visitedSym))) {
47612 return; // Already printed
47613 }
47614 visitedSymbols.add(getSymbolId(visitedSym));
47615 // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
47616 var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
47617 if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
47618 var oldContext = context;
47619 context = cloneNodeBuilderContext(context);
47620 var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
47621 context = oldContext;
47622 return result;
47623 }
47624 }
47625 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
47626 // or a merge of some number of those.
47627 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
47628 // each symbol in only one of the representations
47629 // Also, synthesizing a default export of some kind
47630 // If it's an alias: emit `export default ref`
47631 // If it's a property: emit `export default _default` with a `_default` prop
47632 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
47633 // These forms can merge, eg (`export default 12; export default interface A {}`)
47634 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
47635 var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
47636 var isDefault = symbol.escapedName === "default" /* Default */;
47637 if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
47638 // 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` :(
47639 context.encounteredError = true;
47640 // TODO: Issue error via symbol tracker?
47641 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
47642 }
47643 var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
47644 || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
47645 var needsExportDeclaration = !needsPostExportDefault && !isPrivate && ts.isStringANonContextualKeyword(symbolName) && !isDefault;
47646 // `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
47647 if (needsPostExportDefault || needsExportDeclaration) {
47648 isPrivate = true;
47649 }
47650 var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
47651 var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
47652 symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
47653 symbol.escapedName !== "export=" /* ExportEquals */;
47654 var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
47655 if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
47656 serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
47657 }
47658 if (symbol.flags & 524288 /* TypeAlias */) {
47659 serializeTypeAlias(symbol, symbolName, modifierFlags);
47660 }
47661 // Need to skip over export= symbols below - json source files get a single `Property` flagged
47662 // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
47663 if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
47664 && symbol.escapedName !== "export=" /* ExportEquals */
47665 && !(symbol.flags & 4194304 /* Prototype */)
47666 && !(symbol.flags & 32 /* Class */)
47667 && !isConstMergedWithNSPrintableAsSignatureMerge) {
47668 if (propertyAsAlias) {
47669 var createdExport = serializeMaybeAliasAssignment(symbol);
47670 if (createdExport) {
47671 needsExportDeclaration = false;
47672 needsPostExportDefault = false;
47673 }
47674 }
47675 else {
47676 var type = getTypeOfSymbol(symbol);
47677 var localName = getInternalSymbolName(symbol, symbolName);
47678 if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
47679 // 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
47680 serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
47681 }
47682 else {
47683 // 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!_
47684 // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
47685 var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
47686 : isConstVariable(symbol) ? 2 /* Const */
47687 : 1 /* Let */;
47688 var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
47689 var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
47690 if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
47691 textRange = textRange.parent.parent;
47692 }
47693 var statement = ts.setTextRange(ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
47694 ts.factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
47695 ], flags)), textRange);
47696 addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
47697 if (name !== localName && !isPrivate) {
47698 // We rename the variable declaration we generate for Property symbols since they may have a name which
47699 // conflicts with a local declaration. For example, given input:
47700 // ```
47701 // function g() {}
47702 // module.exports.g = g
47703 // ```
47704 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
47705 // Naively, we would emit
47706 // ```
47707 // function g() {}
47708 // export const g: typeof g;
47709 // ```
47710 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
47711 // the export declaration shadows it.
47712 // To work around that, we instead write
47713 // ```
47714 // function g() {}
47715 // const g_1: typeof g;
47716 // export { g_1 as g };
47717 // ```
47718 // To create an export named `g` that does _not_ shadow the local `g`
47719 addResult(ts.factory.createExportDeclaration(
47720 /*decorators*/ undefined,
47721 /*modifiers*/ undefined,
47722 /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(name, localName)])), 0 /* None */);
47723 needsExportDeclaration = false;
47724 needsPostExportDefault = false;
47725 }
47726 }
47727 }
47728 }
47729 if (symbol.flags & 384 /* Enum */) {
47730 serializeEnum(symbol, symbolName, modifierFlags);
47731 }
47732 if (symbol.flags & 32 /* Class */) {
47733 if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
47734 // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
47735 // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
47736 // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
47737 serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
47738 }
47739 else {
47740 serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
47741 }
47742 }
47743 if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
47744 serializeModule(symbol, symbolName, modifierFlags);
47745 }
47746 if (symbol.flags & 64 /* Interface */) {
47747 serializeInterface(symbol, symbolName, modifierFlags);
47748 }
47749 if (symbol.flags & 2097152 /* Alias */) {
47750 serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
47751 }
47752 if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
47753 serializeMaybeAliasAssignment(symbol);
47754 }
47755 if (symbol.flags & 8388608 /* ExportStar */) {
47756 // synthesize export * from "moduleReference"
47757 // Straightforward - only one thing to do - make an export declaration
47758 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
47759 var node = _a[_i];
47760 var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
47761 if (!resolvedModule)
47762 continue;
47763 addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
47764 }
47765 }
47766 if (needsPostExportDefault) {
47767 addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
47768 }
47769 else if (needsExportDeclaration) {
47770 addResult(ts.factory.createExportDeclaration(
47771 /*decorators*/ undefined,
47772 /*modifiers*/ undefined,
47773 /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* None */);
47774 }
47775 }
47776 function includePrivateSymbol(symbol) {
47777 if (ts.some(symbol.declarations, ts.isParameterDeclaration))
47778 return;
47779 ts.Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
47780 getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
47781 // Blanket moving (import) aliases into the root private context should work, since imports are not valid within namespaces
47782 // (so they must have been in the root to begin with if they were real imports) cjs `require` aliases (an upcoming feature)
47783 // will throw a wrench in this, since those may have been nested, but we'll need to synthesize them in the outer scope
47784 // 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
47785 // for the moved import; which hopefully the above `getUnusedName` call should produce.
47786 var isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !ts.some(symbol.declarations, function (d) {
47787 return !!ts.findAncestor(d, ts.isExportDeclaration) ||
47788 ts.isNamespaceExport(d) ||
47789 (ts.isImportEqualsDeclaration(d) && !ts.isExternalModuleReference(d.moduleReference));
47790 });
47791 deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol);
47792 }
47793 function isExportingScope(enclosingDeclaration) {
47794 return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
47795 (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
47796 }
47797 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
47798 function addResult(node, additionalModifierFlags) {
47799 if (ts.canHaveModifiers(node)) {
47800 var newModifierFlags = 0 /* None */;
47801 if (additionalModifierFlags & 1 /* Export */ &&
47802 context.enclosingDeclaration &&
47803 (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) &&
47804 canHaveExportModifier(node)) {
47805 // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
47806 newModifierFlags |= 1 /* Export */;
47807 }
47808 if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
47809 (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
47810 (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
47811 // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
47812 newModifierFlags |= 2 /* Ambient */;
47813 }
47814 if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
47815 newModifierFlags |= 512 /* Default */;
47816 }
47817 if (newModifierFlags) {
47818 node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node));
47819 }
47820 }
47821 results.push(node);
47822 }
47823 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
47824 var aliasType = getDeclaredTypeOfTypeAlias(symbol);
47825 var typeParams = getSymbolLinks(symbol).typeParameters;
47826 var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
47827 var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
47828 var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
47829 var oldFlags = context.flags;
47830 context.flags |= 8388608 /* InTypeAlias */;
47831 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);
47832 context.flags = oldFlags;
47833 }
47834 function serializeInterface(symbol, symbolName, modifierFlags) {
47835 var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
47836 var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
47837 var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
47838 var baseTypes = getBaseTypes(interfaceType);
47839 var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
47840 var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
47841 var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 168 /* CallSignature */);
47842 var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 169 /* ConstructSignature */);
47843 var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
47844 var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
47845 addResult(ts.factory.createInterfaceDeclaration(
47846 /*decorators*/ undefined,
47847 /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
47848 }
47849 function getNamespaceMembersForSerialization(symbol) {
47850 return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
47851 }
47852 function isTypeOnlyNamespace(symbol) {
47853 return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
47854 }
47855 function serializeModule(symbol, symbolName, modifierFlags) {
47856 var members = getNamespaceMembersForSerialization(symbol);
47857 // 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)
47858 var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
47859 var realMembers = locationMap.get("real") || ts.emptyArray;
47860 var mergedMembers = locationMap.get("merged") || ts.emptyArray;
47861 // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
47862 // 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,
47863 // so we don't even have placeholders to fill in.
47864 if (ts.length(realMembers)) {
47865 var localName = getInternalSymbolName(symbol, symbolName);
47866 serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
47867 }
47868 if (ts.length(mergedMembers)) {
47869 var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
47870 var localName = getInternalSymbolName(symbol, symbolName);
47871 var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(
47872 /*decorators*/ undefined,
47873 /*modifiers*/ undefined,
47874 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
47875 var _a, _b;
47876 var name = ts.unescapeLeadingUnderscores(s.escapedName);
47877 var localName = getInternalSymbolName(s, name);
47878 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
47879 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
47880 (_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);
47881 return undefined;
47882 }
47883 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
47884 includePrivateSymbol(target || s);
47885 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
47886 return ts.factory.createExportSpecifier(name === targetName ? undefined : targetName, name);
47887 })))]);
47888 addResult(ts.factory.createModuleDeclaration(
47889 /*decorators*/ undefined,
47890 /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
47891 }
47892 }
47893 function serializeEnum(symbol, symbolName, modifierFlags) {
47894 addResult(ts.factory.createEnumDeclaration(
47895 /*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) {
47896 // TODO: Handle computed names
47897 // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
47898 // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
47899 // _on the declaration_, not on the declaration's symbol...
47900 var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined;
47901 return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined :
47902 typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) :
47903 ts.factory.createNumericLiteral(initializedValue));
47904 })), modifierFlags);
47905 }
47906 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
47907 var signatures = getSignaturesOfType(type, 0 /* Call */);
47908 for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
47909 var sig = signatures_2[_i];
47910 // Each overload becomes a separate function declaration, in order
47911 var decl = signatureToSignatureDeclarationHelper(sig, 248 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled });
47912 // for expressions assigned to `var`s, use the `var` as the text range
47913 addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
47914 }
47915 // Module symbol emit will take care of module-y members, provided it has exports
47916 if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
47917 var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
47918 serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
47919 }
47920 }
47921 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
47922 if (ts.length(props)) {
47923 var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
47924 return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
47925 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
47926 }) ? "local" : "remote";
47927 });
47928 var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
47929 // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
47930 // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
47931 // Example:
47932 // import Foo_1 = require("./exporter");
47933 // export namespace ns {
47934 // import Foo = Foo_1.Foo;
47935 // export { Foo };
47936 // export const c: number;
47937 // }
47938 // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
47939 // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
47940 // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
47941 // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
47942 // emit akin to the above would be needed.
47943 // Add a namespace
47944 // Create namespace as non-synthetic so it is usable as an enclosing declaration
47945 var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* Namespace */);
47946 ts.setParent(fakespace, enclosingDeclaration);
47947 fakespace.locals = ts.createSymbolTable(props);
47948 fakespace.symbol = props[0].parent;
47949 var oldResults = results;
47950 results = [];
47951 var oldAddingDeclare = addingDeclare;
47952 addingDeclare = false;
47953 var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
47954 var oldContext = context;
47955 context = subcontext;
47956 // 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
47957 visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
47958 context = oldContext;
47959 addingDeclare = oldAddingDeclare;
47960 var declarations = results;
47961 results = oldResults;
47962 // replace namespace with synthetic version
47963 var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(
47964 /*decorators*/ undefined,
47965 /*modifiers*/ undefined,
47966 /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(d.expression, ts.factory.createIdentifier("default" /* Default */))])) : d; });
47967 var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced;
47968 fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped));
47969 addResult(fakespace, modifierFlags); // namespaces can never be default exported
47970 }
47971 }
47972 function isNamespaceMember(p) {
47973 return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
47974 !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
47975 }
47976 function serializeAsClass(symbol, localName, modifierFlags) {
47977 var _a;
47978 var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
47979 var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
47980 var classType = getDeclaredTypeOfClassOrInterface(symbol);
47981 var baseTypes = getBaseTypes(classType);
47982 var implementsExpressions = ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
47983 var staticType = getTypeOfSymbol(symbol);
47984 var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
47985 var staticBaseType = isClass
47986 ? getBaseConstructorTypeOfClass(staticType)
47987 : anyType;
47988 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)]);
47989 var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
47990 var publicSymbolProps = ts.filter(symbolProps, function (s) {
47991 // `valueDeclaration` could be undefined if inherited from
47992 // a union/intersection base type, but inherited properties
47993 // don't matter here.
47994 var valueDecl = s.valueDeclaration;
47995 return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
47996 });
47997 var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
47998 // `valueDeclaration` could be undefined if inherited from
47999 // a union/intersection base type, but inherited properties
48000 // don't matter here.
48001 var valueDecl = s.valueDeclaration;
48002 return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
48003 });
48004 // Boil down all private properties into a single one.
48005 var privateProperties = hasPrivateIdentifier ?
48006 [ts.factory.createPropertyDeclaration(
48007 /*decorators*/ undefined,
48008 /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"),
48009 /*questionOrExclamationToken*/ undefined,
48010 /*type*/ undefined,
48011 /*initializer*/ undefined)] :
48012 ts.emptyArray;
48013 var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
48014 // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
48015 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); });
48016 // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether
48017 // the value is ever initialized with a class or function-like value. For cases where `X` could never be
48018 // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable.
48019 var isNonConstructableClassLikeInJsFile = !isClass &&
48020 !!symbol.valueDeclaration &&
48021 ts.isInJSFile(symbol.valueDeclaration) &&
48022 !ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
48023 var constructors = isNonConstructableClassLikeInJsFile ?
48024 [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
48025 serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 165 /* Constructor */);
48026 var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
48027 addResult(ts.setTextRange(ts.factory.createClassDeclaration(
48028 /*decorators*/ undefined,
48029 /*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);
48030 }
48031 function serializeAsAlias(symbol, localName, modifierFlags) {
48032 // synthesize an alias, eg `export { symbolName as Name }`
48033 // need to mark the alias `symbol` points at
48034 // as something we need to serialize as a private declaration as well
48035 var node = getDeclarationOfAliasSymbol(symbol);
48036 if (!node)
48037 return ts.Debug.fail();
48038 var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
48039 if (!target) {
48040 return;
48041 }
48042 var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
48043 if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
48044 // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
48045 verbatimTargetName = "default" /* Default */;
48046 }
48047 var targetName = getInternalSymbolName(target, verbatimTargetName);
48048 includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
48049 switch (node.kind) {
48050 case 257 /* ImportEqualsDeclaration */:
48051 // Could be a local `import localName = ns.member` or
48052 // an external `import localName = require("whatever")`
48053 var isLocalImport = !(target.flags & 512 /* ValueModule */);
48054 addResult(ts.factory.createImportEqualsDeclaration(
48055 /*decorators*/ undefined,
48056 /*modifiers*/ undefined, ts.factory.createIdentifier(localName), isLocalImport
48057 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
48058 : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
48059 break;
48060 case 256 /* NamespaceExportDeclaration */:
48061 // export as namespace foo
48062 // TODO: Not part of a file's local or export symbol tables
48063 // Is bound into file.symbol.globalExports instead, which we don't currently traverse
48064 addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
48065 break;
48066 case 259 /* ImportClause */:
48067 addResult(ts.factory.createImportDeclaration(
48068 /*decorators*/ undefined,
48069 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined),
48070 // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
48071 // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
48072 // In such cases, the `target` refers to the module itself already
48073 ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
48074 break;
48075 case 260 /* NamespaceImport */:
48076 addResult(ts.factory.createImportDeclaration(
48077 /*decorators*/ undefined,
48078 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
48079 break;
48080 case 266 /* NamespaceExport */:
48081 addResult(ts.factory.createExportDeclaration(
48082 /*decorators*/ undefined,
48083 /*modifiers*/ undefined,
48084 /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
48085 break;
48086 case 262 /* ImportSpecifier */:
48087 addResult(ts.factory.createImportDeclaration(
48088 /*decorators*/ undefined,
48089 /*modifiers*/ undefined, ts.factory.createImportClause(
48090 /*isTypeOnly*/ false,
48091 /*importClause*/ undefined, ts.factory.createNamedImports([
48092 ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName))
48093 ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
48094 break;
48095 case 267 /* ExportSpecifier */:
48096 // does not use localName because the symbol name in this case refers to the name in the exports table,
48097 // which we must exactly preserve
48098 var specifier = node.parent.parent.moduleSpecifier;
48099 // targetName is only used when the target is local, as otherwise the target is an alias that points at
48100 // another file
48101 serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined);
48102 break;
48103 case 263 /* ExportAssignment */:
48104 serializeMaybeAliasAssignment(symbol);
48105 break;
48106 case 213 /* BinaryExpression */:
48107 case 198 /* PropertyAccessExpression */:
48108 // Could be best encoded as though an export specifier or as though an export assignment
48109 // If name is default or export=, do an export assignment
48110 // Otherwise do an export specifier
48111 if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
48112 serializeMaybeAliasAssignment(symbol);
48113 }
48114 else {
48115 serializeExportSpecifier(localName, targetName);
48116 }
48117 break;
48118 default:
48119 return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
48120 }
48121 }
48122 function serializeExportSpecifier(localName, targetName, specifier) {
48123 addResult(ts.factory.createExportDeclaration(
48124 /*decorators*/ undefined,
48125 /*modifiers*/ undefined,
48126 /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
48127 }
48128 /**
48129 * Returns `true` if an export assignment or declaration was produced for the symbol
48130 */
48131 function serializeMaybeAliasAssignment(symbol) {
48132 if (symbol.flags & 4194304 /* Prototype */) {
48133 return false;
48134 }
48135 var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
48136 var isExportEquals = name === "export=" /* ExportEquals */;
48137 var isDefault = name === "default" /* Default */;
48138 var isExportAssignment = isExportEquals || isDefault;
48139 // synthesize export = ref
48140 // ref should refer to either be a locally scoped symbol which we need to emit, or
48141 // a reference to another namespace/module which we may need to emit an `import` statement for
48142 var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
48143 // serialize what the alias points to, preserve the declaration's initializer
48144 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
48145 // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
48146 if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
48147 // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
48148 // eg, `namespace A { export class B {} }; exports = A.B;`
48149 // Technically, this is all that's required in the case where the assignment is an entity name expression
48150 var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
48151 var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
48152 var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
48153 if (referenced || target) {
48154 includePrivateSymbol(referenced || target);
48155 }
48156 // We disable the context's symbol tracker for the duration of this name serialization
48157 // as, by virtue of being here, the name is required to print something, and we don't want to
48158 // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
48159 // a visibility error here (as they're not visible within any scope), but we want to hoist them
48160 // into the containing scope anyway, so we want to skip the visibility checks.
48161 var oldTrack = context.tracker.trackSymbol;
48162 context.tracker.trackSymbol = ts.noop;
48163 if (isExportAssignment) {
48164 results.push(ts.factory.createExportAssignment(
48165 /*decorators*/ undefined,
48166 /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
48167 }
48168 else {
48169 if (first_1 === expr) {
48170 // serialize as `export {target as name}`
48171 serializeExportSpecifier(name, ts.idText(first_1));
48172 }
48173 else if (ts.isClassExpression(expr)) {
48174 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
48175 }
48176 else {
48177 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
48178 var varName = getUnusedName(name, symbol);
48179 addResult(ts.factory.createImportEqualsDeclaration(
48180 /*decorators*/ undefined,
48181 /*modifiers*/ undefined, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
48182 serializeExportSpecifier(name, varName);
48183 }
48184 }
48185 context.tracker.trackSymbol = oldTrack;
48186 return true;
48187 }
48188 else {
48189 // serialize as an anonymous property declaration
48190 var varName = getUnusedName(name, symbol);
48191 // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
48192 // (Unwidened types can only exist in expression contexts and should never be serialized)
48193 var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
48194 if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
48195 // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
48196 serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
48197 }
48198 else {
48199 var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
48200 ts.factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
48201 ], 2 /* Const */));
48202 addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
48203 }
48204 if (isExportAssignment) {
48205 results.push(ts.factory.createExportAssignment(
48206 /*decorators*/ undefined,
48207 /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName)));
48208 return true;
48209 }
48210 else if (name !== varName) {
48211 serializeExportSpecifier(name, varName);
48212 return true;
48213 }
48214 return false;
48215 }
48216 }
48217 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
48218 // Only object types which are not constructable, or indexable, whose members all come from the
48219 // context source file, and whose property names are all valid identifiers and not late-bound, _and_
48220 // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
48221 var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
48222 return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
48223 !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
48224 !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
48225 !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
48226 !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
48227 !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
48228 !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
48229 !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
48230 !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
48231 ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion); });
48232 }
48233 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
48234 return function serializePropertySymbol(p, isStatic, baseType) {
48235 var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
48236 var isPrivate = !!(modifierFlags & 8 /* Private */);
48237 if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
48238 // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
48239 // need to be merged namespace members
48240 return [];
48241 }
48242 if (p.flags & 4194304 /* Prototype */ ||
48243 (baseType && getPropertyOfType(baseType, p.escapedName)
48244 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
48245 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
48246 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
48247 return [];
48248 }
48249 var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
48250 var name = getPropertyNameNodeForSymbol(p, context);
48251 var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
48252 if (p.flags & 98304 /* Accessor */ && useAccessors) {
48253 var result = [];
48254 if (p.flags & 65536 /* SetAccessor */) {
48255 result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(
48256 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(
48257 /*decorators*/ undefined,
48258 /*modifiers*/ undefined,
48259 /*dotDotDotToken*/ undefined, "arg",
48260 /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))],
48261 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
48262 }
48263 if (p.flags & 32768 /* GetAccessor */) {
48264 var isPrivate_1 = modifierFlags & 8 /* Private */;
48265 result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(
48266 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled),
48267 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
48268 }
48269 return result;
48270 }
48271 // This is an else/if as accessors and properties can't merge in TS, but might in JS
48272 // If this happens, we assume the accessor takes priority, as it imposes more constraints
48273 else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
48274 return ts.setTextRange(createProperty(
48275 /*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),
48276 // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
48277 // interface members can't have initializers, however class members _can_
48278 /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
48279 }
48280 if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
48281 var type = getTypeOfSymbol(p);
48282 var signatures = getSignaturesOfType(type, 0 /* Call */);
48283 if (flag & 8 /* Private */) {
48284 return ts.setTextRange(createProperty(
48285 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
48286 /*type*/ undefined,
48287 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
48288 }
48289 var results_1 = [];
48290 for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
48291 var sig = signatures_3[_i];
48292 // Each overload becomes a separate method declaration, in order
48293 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, {
48294 name: name,
48295 questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
48296 modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined
48297 });
48298 results_1.push(ts.setTextRange(decl, sig.declaration));
48299 }
48300 return results_1;
48301 }
48302 // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
48303 return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
48304 };
48305 }
48306 function serializePropertySymbolForInterface(p, baseType) {
48307 return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
48308 }
48309 function serializeSignatures(kind, input, baseType, outputKind) {
48310 var signatures = getSignaturesOfType(input, kind);
48311 if (kind === 1 /* Construct */) {
48312 if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
48313 return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
48314 }
48315 if (baseType) {
48316 // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
48317 var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
48318 if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
48319 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
48320 }
48321 if (baseSigs.length === signatures.length) {
48322 var failed = false;
48323 for (var i = 0; i < baseSigs.length; i++) {
48324 if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
48325 failed = true;
48326 break;
48327 }
48328 }
48329 if (!failed) {
48330 return []; // Every signature was identical - elide constructor list as it is inherited
48331 }
48332 }
48333 }
48334 var privateProtected = 0;
48335 for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
48336 var s = signatures_4[_i];
48337 if (s.declaration) {
48338 privateProtected |= ts.getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
48339 }
48340 }
48341 if (privateProtected) {
48342 return [ts.setTextRange(ts.factory.createConstructorDeclaration(
48343 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected),
48344 /*parameters*/ [],
48345 /*body*/ undefined), signatures[0].declaration)];
48346 }
48347 }
48348 var results = [];
48349 for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
48350 var sig = signatures_5[_a];
48351 // Each overload becomes a separate constructor declaration, in order
48352 var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
48353 results.push(ts.setTextRange(decl, sig.declaration));
48354 }
48355 return results;
48356 }
48357 function serializeIndexSignatures(input, baseType) {
48358 var results = [];
48359 for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
48360 var type = _a[_i];
48361 var info = getIndexInfoOfType(input, type);
48362 if (info) {
48363 if (baseType) {
48364 var baseInfo = getIndexInfoOfType(baseType, type);
48365 if (baseInfo) {
48366 if (isTypeIdenticalTo(info.type, baseInfo.type)) {
48367 continue; // elide identical index signatures
48368 }
48369 }
48370 }
48371 results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context, /*typeNode*/ undefined));
48372 }
48373 }
48374 return results;
48375 }
48376 function serializeBaseType(t, staticType, rootName) {
48377 var ref = trySerializeAsTypeReference(t, 111551 /* Value */);
48378 if (ref) {
48379 return ref;
48380 }
48381 var tempName = getUnusedName(rootName + "_base");
48382 var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
48383 ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context))
48384 ], 2 /* Const */));
48385 addResult(statement, 0 /* None */);
48386 return ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier(tempName), /*typeArgs*/ undefined);
48387 }
48388 function trySerializeAsTypeReference(t, flags) {
48389 var typeArgs;
48390 var reference;
48391 // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
48392 // which we can't write out in a syntactically valid way as an expression
48393 if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
48394 typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
48395 reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
48396 }
48397 else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
48398 reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
48399 }
48400 if (reference) {
48401 return ts.factory.createExpressionWithTypeArguments(reference, typeArgs);
48402 }
48403 }
48404 function serializeImplementedType(t) {
48405 var ref = trySerializeAsTypeReference(t, 788968 /* Type */);
48406 if (ref) {
48407 return ref;
48408 }
48409 if (t.symbol) {
48410 return ts.factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArgs*/ undefined);
48411 }
48412 }
48413 function getUnusedName(input, symbol) {
48414 var _a, _b;
48415 var id = symbol ? getSymbolId(symbol) : undefined;
48416 if (id) {
48417 if (context.remappedSymbolNames.has(id)) {
48418 return context.remappedSymbolNames.get(id);
48419 }
48420 }
48421 if (symbol) {
48422 input = getNameCandidateWorker(symbol, input);
48423 }
48424 var i = 0;
48425 var original = input;
48426 while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) {
48427 i++;
48428 input = original + "_" + i;
48429 }
48430 (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input);
48431 if (id) {
48432 context.remappedSymbolNames.set(id, input);
48433 }
48434 return input;
48435 }
48436 function getNameCandidateWorker(symbol, localName) {
48437 if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
48438 var flags = context.flags;
48439 context.flags |= 16777216 /* InInitialEntityName */;
48440 var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
48441 context.flags = flags;
48442 localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
48443 }
48444 if (localName === "default" /* Default */) {
48445 localName = "_default";
48446 }
48447 else if (localName === "export=" /* ExportEquals */) {
48448 localName = "_exports";
48449 }
48450 localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
48451 return localName;
48452 }
48453 function getInternalSymbolName(symbol, localName) {
48454 var id = getSymbolId(symbol);
48455 if (context.remappedSymbolNames.has(id)) {
48456 return context.remappedSymbolNames.get(id);
48457 }
48458 localName = getNameCandidateWorker(symbol, localName);
48459 // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
48460 context.remappedSymbolNames.set(id, localName);
48461 return localName;
48462 }
48463 }
48464 }
48465 function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
48466 if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
48467 return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
48468 function typePredicateToStringWorker(writer) {
48469 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
48470 );
48471 var printer = ts.createPrinter({ removeComments: true });
48472 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
48473 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
48474 return writer;
48475 }
48476 }
48477 function formatUnionTypes(types) {
48478 var result = [];
48479 var flags = 0;
48480 for (var i = 0; i < types.length; i++) {
48481 var t = types[i];
48482 flags |= t.flags;
48483 if (!(t.flags & 98304 /* Nullable */)) {
48484 if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
48485 var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
48486 if (baseType.flags & 1048576 /* Union */) {
48487 var count = baseType.types.length;
48488 if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
48489 result.push(baseType);
48490 i += count - 1;
48491 continue;
48492 }
48493 }
48494 }
48495 result.push(t);
48496 }
48497 }
48498 if (flags & 65536 /* Null */)
48499 result.push(nullType);
48500 if (flags & 32768 /* Undefined */)
48501 result.push(undefinedType);
48502 return result || types;
48503 }
48504 function visibilityToString(flags) {
48505 if (flags === 8 /* Private */) {
48506 return "private";
48507 }
48508 if (flags === 16 /* Protected */) {
48509 return "protected";
48510 }
48511 return "public";
48512 }
48513 function getTypeAliasForTypeLiteral(type) {
48514 if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
48515 var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
48516 if (node.kind === 251 /* TypeAliasDeclaration */) {
48517 return getSymbolOfNode(node);
48518 }
48519 }
48520 return undefined;
48521 }
48522 function isTopLevelInExternalModuleAugmentation(node) {
48523 return node && node.parent &&
48524 node.parent.kind === 254 /* ModuleBlock */ &&
48525 ts.isExternalModuleAugmentation(node.parent.parent);
48526 }
48527 function isDefaultBindingContext(location) {
48528 return location.kind === 294 /* SourceFile */ || ts.isAmbientModule(location);
48529 }
48530 function getNameOfSymbolFromNameType(symbol, context) {
48531 var nameType = getSymbolLinks(symbol).nameType;
48532 if (nameType) {
48533 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
48534 var name = "" + nameType.value;
48535 if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
48536 return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
48537 }
48538 if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
48539 return "[" + name + "]";
48540 }
48541 return name;
48542 }
48543 if (nameType.flags & 8192 /* UniqueESSymbol */) {
48544 return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
48545 }
48546 }
48547 }
48548 /**
48549 * Gets a human-readable name for a symbol.
48550 * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
48551 *
48552 * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
48553 * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
48554 */
48555 function getNameOfSymbolAsWritten(symbol, context) {
48556 if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
48557 // If it's not the first part of an entity name, it must print as `default`
48558 (!(context.flags & 16777216 /* InInitialEntityName */) ||
48559 // if the symbol is synthesized, it will only be referenced externally it must print as `default`
48560 !symbol.declarations ||
48561 // if not in the same binding context (source file, module declaration), it must print as `default`
48562 (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
48563 return "default";
48564 }
48565 if (symbol.declarations && symbol.declarations.length) {
48566 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
48567 var name_3 = declaration && ts.getNameOfDeclaration(declaration);
48568 if (declaration && name_3) {
48569 if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
48570 return ts.symbolName(symbol);
48571 }
48572 if (ts.isComputedPropertyName(name_3) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
48573 var nameType = getSymbolLinks(symbol).nameType;
48574 if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
48575 // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
48576 var result = getNameOfSymbolFromNameType(symbol, context);
48577 if (result !== undefined) {
48578 return result;
48579 }
48580 }
48581 }
48582 return ts.declarationNameToString(name_3);
48583 }
48584 if (!declaration) {
48585 declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
48586 }
48587 if (declaration.parent && declaration.parent.kind === 246 /* VariableDeclaration */) {
48588 return ts.declarationNameToString(declaration.parent.name);
48589 }
48590 switch (declaration.kind) {
48591 case 218 /* ClassExpression */:
48592 case 205 /* FunctionExpression */:
48593 case 206 /* ArrowFunction */:
48594 if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
48595 context.encounteredError = true;
48596 }
48597 return declaration.kind === 218 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
48598 }
48599 }
48600 var name = getNameOfSymbolFromNameType(symbol, context);
48601 return name !== undefined ? name : ts.symbolName(symbol);
48602 }
48603 function isDeclarationVisible(node) {
48604 if (node) {
48605 var links = getNodeLinks(node);
48606 if (links.isVisible === undefined) {
48607 links.isVisible = !!determineIfDeclarationIsVisible();
48608 }
48609 return links.isVisible;
48610 }
48611 return false;
48612 function determineIfDeclarationIsVisible() {
48613 switch (node.kind) {
48614 case 320 /* JSDocCallbackTag */:
48615 case 327 /* JSDocTypedefTag */:
48616 case 321 /* JSDocEnumTag */:
48617 // Top-level jsdoc type aliases are considered exported
48618 // 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
48619 return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
48620 case 195 /* BindingElement */:
48621 return isDeclarationVisible(node.parent.parent);
48622 case 246 /* VariableDeclaration */:
48623 if (ts.isBindingPattern(node.name) &&
48624 !node.name.elements.length) {
48625 // If the binding pattern is empty, this variable declaration is not visible
48626 return false;
48627 }
48628 // falls through
48629 case 253 /* ModuleDeclaration */:
48630 case 249 /* ClassDeclaration */:
48631 case 250 /* InterfaceDeclaration */:
48632 case 251 /* TypeAliasDeclaration */:
48633 case 248 /* FunctionDeclaration */:
48634 case 252 /* EnumDeclaration */:
48635 case 257 /* ImportEqualsDeclaration */:
48636 // external module augmentation is always visible
48637 if (ts.isExternalModuleAugmentation(node)) {
48638 return true;
48639 }
48640 var parent = getDeclarationContainer(node);
48641 // If the node is not exported or it is not ambient module element (except import declaration)
48642 if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
48643 !(node.kind !== 257 /* ImportEqualsDeclaration */ && parent.kind !== 294 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
48644 return isGlobalSourceFile(parent);
48645 }
48646 // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
48647 return isDeclarationVisible(parent);
48648 case 162 /* PropertyDeclaration */:
48649 case 161 /* PropertySignature */:
48650 case 166 /* GetAccessor */:
48651 case 167 /* SetAccessor */:
48652 case 164 /* MethodDeclaration */:
48653 case 163 /* MethodSignature */:
48654 if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) {
48655 // Private/protected properties/methods are not visible
48656 return false;
48657 }
48658 // Public properties/methods are visible if its parents are visible, so:
48659 // falls through
48660 case 165 /* Constructor */:
48661 case 169 /* ConstructSignature */:
48662 case 168 /* CallSignature */:
48663 case 170 /* IndexSignature */:
48664 case 159 /* Parameter */:
48665 case 254 /* ModuleBlock */:
48666 case 173 /* FunctionType */:
48667 case 174 /* ConstructorType */:
48668 case 176 /* TypeLiteral */:
48669 case 172 /* TypeReference */:
48670 case 177 /* ArrayType */:
48671 case 178 /* TupleType */:
48672 case 181 /* UnionType */:
48673 case 182 /* IntersectionType */:
48674 case 185 /* ParenthesizedType */:
48675 case 191 /* NamedTupleMember */:
48676 return isDeclarationVisible(node.parent);
48677 // Default binding, import specifier and namespace import is visible
48678 // only on demand so by default it is not visible
48679 case 259 /* ImportClause */:
48680 case 260 /* NamespaceImport */:
48681 case 262 /* ImportSpecifier */:
48682 return false;
48683 // Type parameters are always visible
48684 case 158 /* TypeParameter */:
48685 // Source file and namespace export are always visible
48686 // falls through
48687 case 294 /* SourceFile */:
48688 case 256 /* NamespaceExportDeclaration */:
48689 return true;
48690 // Export assignments do not create name bindings outside the module
48691 case 263 /* ExportAssignment */:
48692 return false;
48693 default:
48694 return false;
48695 }
48696 }
48697 }
48698 function collectLinkedAliases(node, setVisibility) {
48699 var exportSymbol;
48700 if (node.parent && node.parent.kind === 263 /* ExportAssignment */) {
48701 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
48702 }
48703 else if (node.parent.kind === 267 /* ExportSpecifier */) {
48704 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
48705 }
48706 var result;
48707 var visited;
48708 if (exportSymbol) {
48709 visited = new ts.Set();
48710 visited.add(getSymbolId(exportSymbol));
48711 buildVisibleNodeList(exportSymbol.declarations);
48712 }
48713 return result;
48714 function buildVisibleNodeList(declarations) {
48715 ts.forEach(declarations, function (declaration) {
48716 var resultNode = getAnyImportSyntax(declaration) || declaration;
48717 if (setVisibility) {
48718 getNodeLinks(declaration).isVisible = true;
48719 }
48720 else {
48721 result = result || [];
48722 ts.pushIfUnique(result, resultNode);
48723 }
48724 if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
48725 // Add the referenced top container visible
48726 var internalModuleReference = declaration.moduleReference;
48727 var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
48728 var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
48729 if (importSymbol && visited) {
48730 if (ts.tryAddToSet(visited, getSymbolId(importSymbol))) {
48731 buildVisibleNodeList(importSymbol.declarations);
48732 }
48733 }
48734 }
48735 });
48736 }
48737 }
48738 /**
48739 * Push an entry on the type resolution stack. If an entry with the given target and the given property name
48740 * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
48741 * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
48742 * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
48743 * In order to see if the same query has already been done before, the target object and the propertyName both
48744 * must match the one passed in.
48745 *
48746 * @param target The symbol, type, or signature whose type is being queried
48747 * @param propertyName The property name that should be used to query the target for its type
48748 */
48749 function pushTypeResolution(target, propertyName) {
48750 var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
48751 if (resolutionCycleStartIndex >= 0) {
48752 // A cycle was found
48753 var length_3 = resolutionTargets.length;
48754 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
48755 resolutionResults[i] = false;
48756 }
48757 return false;
48758 }
48759 resolutionTargets.push(target);
48760 resolutionResults.push(/*items*/ true);
48761 resolutionPropertyNames.push(propertyName);
48762 return true;
48763 }
48764 function findResolutionCycleStartIndex(target, propertyName) {
48765 for (var i = resolutionTargets.length - 1; i >= 0; i--) {
48766 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
48767 return -1;
48768 }
48769 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
48770 return i;
48771 }
48772 }
48773 return -1;
48774 }
48775 function hasType(target, propertyName) {
48776 switch (propertyName) {
48777 case 0 /* Type */:
48778 return !!getSymbolLinks(target).type;
48779 case 5 /* EnumTagType */:
48780 return !!(getNodeLinks(target).resolvedEnumType);
48781 case 2 /* DeclaredType */:
48782 return !!getSymbolLinks(target).declaredType;
48783 case 1 /* ResolvedBaseConstructorType */:
48784 return !!target.resolvedBaseConstructorType;
48785 case 3 /* ResolvedReturnType */:
48786 return !!target.resolvedReturnType;
48787 case 4 /* ImmediateBaseConstraint */:
48788 return !!target.immediateBaseConstraint;
48789 case 6 /* ResolvedTypeArguments */:
48790 return !!target.resolvedTypeArguments;
48791 case 7 /* ResolvedBaseTypes */:
48792 return !!target.baseTypesResolved;
48793 }
48794 return ts.Debug.assertNever(propertyName);
48795 }
48796 /**
48797 * Pop an entry from the type resolution stack and return its associated result value. The result value will
48798 * be true if no circularities were detected, or false if a circularity was found.
48799 */
48800 function popTypeResolution() {
48801 resolutionTargets.pop();
48802 resolutionPropertyNames.pop();
48803 return resolutionResults.pop();
48804 }
48805 function getDeclarationContainer(node) {
48806 return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
48807 switch (node.kind) {
48808 case 246 /* VariableDeclaration */:
48809 case 247 /* VariableDeclarationList */:
48810 case 262 /* ImportSpecifier */:
48811 case 261 /* NamedImports */:
48812 case 260 /* NamespaceImport */:
48813 case 259 /* ImportClause */:
48814 return false;
48815 default:
48816 return true;
48817 }
48818 }).parent;
48819 }
48820 function getTypeOfPrototypeProperty(prototype) {
48821 // TypeScript 1.0 spec (April 2014): 8.4
48822 // Every class automatically contains a static property member named 'prototype',
48823 // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
48824 // It is an error to explicitly declare a static property member with the name 'prototype'.
48825 var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
48826 return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
48827 }
48828 // Return the type of the given property in the given type, or undefined if no such property exists
48829 function getTypeOfPropertyOfType(type, name) {
48830 var prop = getPropertyOfType(type, name);
48831 return prop ? getTypeOfSymbol(prop) : undefined;
48832 }
48833 function getTypeOfPropertyOrIndexSignature(type, name) {
48834 return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
48835 }
48836 function isTypeAny(type) {
48837 return type && (type.flags & 1 /* Any */) !== 0;
48838 }
48839 // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
48840 // assigned by contextual typing.
48841 function getTypeForBindingElementParent(node) {
48842 var symbol = getSymbolOfNode(node);
48843 return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
48844 }
48845 function getRestType(source, properties, symbol) {
48846 source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
48847 if (source.flags & 131072 /* Never */) {
48848 return emptyObjectType;
48849 }
48850 if (source.flags & 1048576 /* Union */) {
48851 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
48852 }
48853 var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
48854 if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
48855 if (omitKeyType.flags & 131072 /* Never */) {
48856 return source;
48857 }
48858 var omitTypeAlias = getGlobalOmitSymbol();
48859 if (!omitTypeAlias) {
48860 return errorType;
48861 }
48862 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
48863 }
48864 var members = ts.createSymbolTable();
48865 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
48866 var prop = _a[_i];
48867 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
48868 && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
48869 && isSpreadableProperty(prop)) {
48870 members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
48871 }
48872 }
48873 var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
48874 var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
48875 var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
48876 result.objectFlags |= 131072 /* ObjectRestType */;
48877 return result;
48878 }
48879 // Determine the control flow type associated with a destructuring declaration or assignment. The following
48880 // forms of destructuring are possible:
48881 // let { x } = obj; // BindingElement
48882 // let [ x ] = obj; // BindingElement
48883 // { x } = obj; // ShorthandPropertyAssignment
48884 // { x: v } = obj; // PropertyAssignment
48885 // [ x ] = obj; // Expression
48886 // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
48887 // flow analyzer doesn't have to handle all the different syntactic forms.
48888 function getFlowTypeOfDestructuring(node, declaredType) {
48889 var reference = getSyntheticElementAccess(node);
48890 return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
48891 }
48892 function getSyntheticElementAccess(node) {
48893 var parentAccess = getParentElementAccess(node);
48894 if (parentAccess && parentAccess.flowNode) {
48895 var propName = getDestructuringPropertyName(node);
48896 if (propName) {
48897 var literal = ts.setTextRange(ts.parseNodeFactory.createStringLiteral(propName), node);
48898 var result = ts.setTextRange(ts.parseNodeFactory.createElementAccessExpression(parentAccess, literal), node);
48899 ts.setParent(literal, result);
48900 ts.setParent(result, node);
48901 result.flowNode = parentAccess.flowNode;
48902 return result;
48903 }
48904 }
48905 }
48906 function getParentElementAccess(node) {
48907 var ancestor = node.parent.parent;
48908 switch (ancestor.kind) {
48909 case 195 /* BindingElement */:
48910 case 285 /* PropertyAssignment */:
48911 return getSyntheticElementAccess(ancestor);
48912 case 196 /* ArrayLiteralExpression */:
48913 return getSyntheticElementAccess(node.parent);
48914 case 246 /* VariableDeclaration */:
48915 return ancestor.initializer;
48916 case 213 /* BinaryExpression */:
48917 return ancestor.right;
48918 }
48919 }
48920 function getDestructuringPropertyName(node) {
48921 var parent = node.parent;
48922 if (node.kind === 195 /* BindingElement */ && parent.kind === 193 /* ObjectBindingPattern */) {
48923 return getLiteralPropertyNameText(node.propertyName || node.name);
48924 }
48925 if (node.kind === 285 /* PropertyAssignment */ || node.kind === 286 /* ShorthandPropertyAssignment */) {
48926 return getLiteralPropertyNameText(node.name);
48927 }
48928 return "" + parent.elements.indexOf(node);
48929 }
48930 function getLiteralPropertyNameText(name) {
48931 var type = getLiteralTypeFromPropertyName(name);
48932 return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
48933 }
48934 /** Return the inferred type for a binding element */
48935 function getTypeForBindingElement(declaration) {
48936 var pattern = declaration.parent;
48937 var parentType = getTypeForBindingElementParent(pattern.parent);
48938 // If no type or an any type was inferred for parent, infer that for the binding element
48939 if (!parentType || isTypeAny(parentType)) {
48940 return parentType;
48941 }
48942 // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
48943 if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
48944 parentType = getNonNullableType(parentType);
48945 }
48946 // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
48947 else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
48948 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
48949 }
48950 var type;
48951 if (pattern.kind === 193 /* ObjectBindingPattern */) {
48952 if (declaration.dotDotDotToken) {
48953 parentType = getReducedType(parentType);
48954 if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
48955 error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
48956 return errorType;
48957 }
48958 var literalMembers = [];
48959 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
48960 var element = _a[_i];
48961 if (!element.dotDotDotToken) {
48962 literalMembers.push(element.propertyName || element.name);
48963 }
48964 }
48965 type = getRestType(parentType, literalMembers, declaration.symbol);
48966 }
48967 else {
48968 // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
48969 var name = declaration.propertyName || declaration.name;
48970 var indexType = getLiteralTypeFromPropertyName(name);
48971 var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
48972 type = getFlowTypeOfDestructuring(declaration, declaredType);
48973 }
48974 }
48975 else {
48976 // This elementType will be used if the specific property corresponding to this index is not
48977 // present (aka the tuple element property). This call also checks that the parentType is in
48978 // fact an iterable or array (depending on target language).
48979 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
48980 var index_2 = pattern.elements.indexOf(declaration);
48981 if (declaration.dotDotDotToken) {
48982 // If the parent is a tuple type, the rest element has a tuple type of the
48983 // remaining tuple element types. Otherwise, the rest element has an array type with same
48984 // element type as the parent type.
48985 type = everyType(parentType, isTupleType) ?
48986 mapType(parentType, function (t) { return sliceTupleType(t, index_2); }) :
48987 createArrayType(elementType);
48988 }
48989 else if (isArrayLikeType(parentType)) {
48990 var indexType = getLiteralType(index_2);
48991 var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
48992 var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
48993 type = getFlowTypeOfDestructuring(declaration, declaredType);
48994 }
48995 else {
48996 type = elementType;
48997 }
48998 }
48999 if (!declaration.initializer) {
49000 return type;
49001 }
49002 if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
49003 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
49004 // undefined from the final type.
49005 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
49006 getTypeWithFacts(type, 524288 /* NEUndefined */) :
49007 type;
49008 }
49009 return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
49010 }
49011 function getTypeForDeclarationFromJSDocComment(declaration) {
49012 var jsdocType = ts.getJSDocType(declaration);
49013 if (jsdocType) {
49014 return getTypeFromTypeNode(jsdocType);
49015 }
49016 return undefined;
49017 }
49018 function isNullOrUndefined(node) {
49019 var expr = ts.skipParentheses(node);
49020 return expr.kind === 103 /* NullKeyword */ || expr.kind === 78 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
49021 }
49022 function isEmptyArrayLiteral(node) {
49023 var expr = ts.skipParentheses(node);
49024 return expr.kind === 196 /* ArrayLiteralExpression */ && expr.elements.length === 0;
49025 }
49026 function addOptionality(type, optional) {
49027 if (optional === void 0) { optional = true; }
49028 return strictNullChecks && optional ? getOptionalType(type) : type;
49029 }
49030 // Return the inferred type for a variable, parameter, or property declaration
49031 function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
49032 // A variable declared in a for..in statement is of type string, or of type keyof T when the
49033 // right hand expression is of a type parameter type.
49034 if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 235 /* ForInStatement */) {
49035 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
49036 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
49037 }
49038 if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 236 /* ForOfStatement */) {
49039 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
49040 // missing properties/signatures required to get its iteratedType (like
49041 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
49042 // or it may have led to an error inside getElementTypeOfIterable.
49043 var forOfStatement = declaration.parent.parent;
49044 return checkRightHandSideOfForOf(forOfStatement) || anyType;
49045 }
49046 if (ts.isBindingPattern(declaration.parent)) {
49047 return getTypeForBindingElement(declaration);
49048 }
49049 var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
49050 || isOptionalJSDocPropertyLikeTag(declaration)
49051 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
49052 // Use type from type annotation if one is present
49053 var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
49054 if (declaredType) {
49055 return addOptionality(declaredType, isOptional);
49056 }
49057 if ((noImplicitAny || ts.isInJSFile(declaration)) &&
49058 ts.isVariableDeclaration(declaration) && !ts.isBindingPattern(declaration.name) &&
49059 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
49060 // If --noImplicitAny is on or the declaration is in a Javascript file,
49061 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
49062 // initializer or a 'null' or 'undefined' initializer.
49063 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
49064 return autoType;
49065 }
49066 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
49067 // literal initializer.
49068 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
49069 return autoArrayType;
49070 }
49071 }
49072 if (ts.isParameter(declaration)) {
49073 var func = declaration.parent;
49074 // For a parameter of a set accessor, use the type of the get accessor if one is present
49075 if (func.kind === 167 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
49076 var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 166 /* GetAccessor */);
49077 if (getter) {
49078 var getterSignature = getSignatureFromDeclaration(getter);
49079 var thisParameter = getAccessorThisParameter(func);
49080 if (thisParameter && declaration === thisParameter) {
49081 // Use the type from the *getter*
49082 ts.Debug.assert(!thisParameter.type);
49083 return getTypeOfSymbol(getterSignature.thisParameter);
49084 }
49085 return getReturnTypeOfSignature(getterSignature);
49086 }
49087 }
49088 if (ts.isInJSFile(declaration)) {
49089 var typeTag = ts.getJSDocType(func);
49090 if (typeTag && ts.isFunctionTypeNode(typeTag)) {
49091 var signature = getSignatureFromDeclaration(typeTag);
49092 var pos = func.parameters.indexOf(declaration);
49093 return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
49094 }
49095 }
49096 // Use contextual parameter type if one is available
49097 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
49098 if (type) {
49099 return addOptionality(type, isOptional);
49100 }
49101 }
49102 // Use the type of the initializer expression if one is present and the declaration is
49103 // not a parameter of a contextually typed function
49104 if (ts.hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
49105 if (ts.isInJSFile(declaration) && !ts.isParameter(declaration)) {
49106 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
49107 if (containerObjectType) {
49108 return containerObjectType;
49109 }
49110 }
49111 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
49112 return addOptionality(type, isOptional);
49113 }
49114 if (ts.isPropertyDeclaration(declaration) && !ts.hasStaticModifier(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) {
49115 // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file.
49116 // Use control flow analysis of this.xxx assignments in the constructor to determine the type of the property.
49117 var constructor = findConstructorDeclaration(declaration.parent);
49118 var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
49119 ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
49120 undefined;
49121 return type && addOptionality(type, isOptional);
49122 }
49123 if (ts.isJsxAttribute(declaration)) {
49124 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
49125 // I.e <Elem attr /> is sugar for <Elem attr={true} />
49126 return trueType;
49127 }
49128 // If the declaration specifies a binding pattern and is not a parameter of a contextually
49129 // typed function, use the type implied by the binding pattern
49130 if (ts.isBindingPattern(declaration.name)) {
49131 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
49132 }
49133 // No type specified and nothing can be inferred
49134 return undefined;
49135 }
49136 function isConstructorDeclaredProperty(symbol) {
49137 // A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
49138 // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
49139 // a class constructor.
49140 if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) {
49141 var links = getSymbolLinks(symbol);
49142 if (links.isConstructorDeclaredProperty === undefined) {
49143 links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) {
49144 return ts.isBinaryExpression(declaration) &&
49145 ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ &&
49146 (declaration.left.kind !== 199 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) &&
49147 !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration);
49148 });
49149 }
49150 return links.isConstructorDeclaredProperty;
49151 }
49152 return false;
49153 }
49154 function isAutoTypedProperty(symbol) {
49155 // A property is auto-typed when its declaration has no type annotation or initializer and we're in
49156 // noImplicitAny mode or a .js file.
49157 var declaration = symbol.valueDeclaration;
49158 return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) &&
49159 !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration));
49160 }
49161 function getDeclaringConstructor(symbol) {
49162 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
49163 var declaration = _a[_i];
49164 var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false);
49165 if (container && (container.kind === 165 /* Constructor */ || isJSConstructor(container))) {
49166 return container;
49167 }
49168 }
49169 }
49170 function getFlowTypeInConstructor(symbol, constructor) {
49171 var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName));
49172 ts.setParent(reference.expression, reference);
49173 ts.setParent(reference, constructor);
49174 reference.flowNode = constructor.returnFlowNode;
49175 var flowType = getFlowTypeOfProperty(reference, symbol);
49176 if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
49177 error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
49178 }
49179 // We don't infer a type if assignments are only null or undefined.
49180 return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType);
49181 }
49182 function getFlowTypeOfProperty(reference, prop) {
49183 var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
49184 return getFlowTypeOfReference(reference, autoType, initialType);
49185 }
49186 function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
49187 // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
49188 var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
49189 if (container) {
49190 var tag = ts.getJSDocTypeTag(container);
49191 if (tag && tag.typeExpression) {
49192 return getTypeFromTypeNode(tag.typeExpression);
49193 }
49194 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
49195 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
49196 }
49197 var type;
49198 var definedInConstructor = false;
49199 var definedInMethod = false;
49200 // We use control flow analysis to determine the type of the property if the property qualifies as a constructor
49201 // declared property and the resulting control flow type isn't just undefined or null.
49202 if (isConstructorDeclaredProperty(symbol)) {
49203 type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
49204 }
49205 if (!type) {
49206 var jsdocType = void 0;
49207 var types = void 0;
49208 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
49209 var declaration = _a[_i];
49210 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
49211 ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
49212 undefined;
49213 if (!expression) {
49214 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
49215 }
49216 var kind = ts.isAccessExpression(expression)
49217 ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
49218 : ts.getAssignmentDeclarationKind(expression);
49219 if (kind === 4 /* ThisProperty */) {
49220 if (isDeclarationInConstructor(expression)) {
49221 definedInConstructor = true;
49222 }
49223 else {
49224 definedInMethod = true;
49225 }
49226 }
49227 if (!ts.isCallExpression(expression)) {
49228 jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
49229 }
49230 if (!jsdocType) {
49231 (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
49232 }
49233 }
49234 type = jsdocType;
49235 if (!type) {
49236 if (!ts.length(types)) {
49237 return errorType; // No types from any declarations :(
49238 }
49239 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
49240 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
49241 if (definedInMethod) {
49242 var propType = getTypeOfPropertyInBaseClass(symbol);
49243 if (propType) {
49244 (constructorTypes || (constructorTypes = [])).push(propType);
49245 definedInConstructor = true;
49246 }
49247 }
49248 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
49249 type = getUnionType(sourceTypes, 2 /* Subtype */);
49250 }
49251 }
49252 var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
49253 if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
49254 reportImplicitAny(symbol.valueDeclaration, anyType);
49255 return anyType;
49256 }
49257 return widened;
49258 }
49259 function getJSContainerObjectType(decl, symbol, init) {
49260 var _a, _b;
49261 if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
49262 return undefined;
49263 }
49264 var exports = ts.createSymbolTable();
49265 while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
49266 var s_2 = getSymbolOfNode(decl);
49267 if ((_a = s_2 === null || s_2 === void 0 ? void 0 : s_2.exports) === null || _a === void 0 ? void 0 : _a.size) {
49268 mergeSymbolTable(exports, s_2.exports);
49269 }
49270 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
49271 }
49272 var s = getSymbolOfNode(decl);
49273 if ((_b = s === null || s === void 0 ? void 0 : s.exports) === null || _b === void 0 ? void 0 : _b.size) {
49274 mergeSymbolTable(exports, s.exports);
49275 }
49276 var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
49277 type.objectFlags |= 16384 /* JSLiteral */;
49278 return type;
49279 }
49280 function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
49281 var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
49282 if (typeNode) {
49283 var type = getWidenedType(getTypeFromTypeNode(typeNode));
49284 if (!declaredType) {
49285 return type;
49286 }
49287 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
49288 errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
49289 }
49290 }
49291 if (symbol.parent) {
49292 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
49293 if (typeNode_2) {
49294 return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
49295 }
49296 }
49297 return declaredType;
49298 }
49299 /** If we don't have an explicit JSDoc type, get the type from the initializer. */
49300 function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
49301 if (ts.isCallExpression(expression)) {
49302 if (resolvedSymbol) {
49303 return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
49304 }
49305 var objectLitType = checkExpressionCached(expression.arguments[2]);
49306 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
49307 if (valueType) {
49308 return valueType;
49309 }
49310 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
49311 if (getFunc) {
49312 var getSig = getSingleCallSignature(getFunc);
49313 if (getSig) {
49314 return getReturnTypeOfSignature(getSig);
49315 }
49316 }
49317 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
49318 if (setFunc) {
49319 var setSig = getSingleCallSignature(setFunc);
49320 if (setSig) {
49321 return getTypeOfFirstParameterOfSignature(setSig);
49322 }
49323 }
49324 return anyType;
49325 }
49326 if (containsSameNamedThisProperty(expression.left, expression.right)) {
49327 return anyType;
49328 }
49329 var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
49330 if (type.flags & 524288 /* Object */ &&
49331 kind === 2 /* ModuleExports */ &&
49332 symbol.escapedName === "export=" /* ExportEquals */) {
49333 var exportedType = resolveStructuredTypeMembers(type);
49334 var members_4 = ts.createSymbolTable();
49335 ts.copyEntries(exportedType.members, members_4);
49336 if (resolvedSymbol && !resolvedSymbol.exports) {
49337 resolvedSymbol.exports = ts.createSymbolTable();
49338 }
49339 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
49340 var _a;
49341 var exportedMember = members_4.get(name);
49342 if (exportedMember && exportedMember !== s) {
49343 if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
49344 // If the member has an additional value-like declaration, union the types from the two declarations,
49345 // but issue an error if they occurred in two different files. The purpose is to support a JS file with
49346 // a pattern like:
49347 //
49348 // module.exports = { a: true };
49349 // module.exports.a = 3;
49350 //
49351 // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
49352 // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
49353 // it's unclear what that's supposed to mean, so it's probably a mistake.
49354 if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
49355 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
49356 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
49357 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
49358 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
49359 }
49360 var union = createSymbol(s.flags | exportedMember.flags, name);
49361 union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
49362 union.valueDeclaration = exportedMember.valueDeclaration;
49363 union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
49364 members_4.set(name, union);
49365 }
49366 else {
49367 members_4.set(name, mergeSymbol(s, exportedMember));
49368 }
49369 }
49370 else {
49371 members_4.set(name, s);
49372 }
49373 });
49374 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
49375 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
49376 return result;
49377 }
49378 if (isEmptyArrayLiteralType(type)) {
49379 reportImplicitAny(expression, anyArrayType);
49380 return anyArrayType;
49381 }
49382 return type;
49383 }
49384 function containsSameNamedThisProperty(thisProperty, expression) {
49385 return ts.isPropertyAccessExpression(thisProperty)
49386 && thisProperty.expression.kind === 107 /* ThisKeyword */
49387 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
49388 }
49389 function isDeclarationInConstructor(expression) {
49390 var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
49391 // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
49392 // Function expressions that are assigned to the prototype count as methods.
49393 return thisContainer.kind === 165 /* Constructor */ ||
49394 thisContainer.kind === 248 /* FunctionDeclaration */ ||
49395 (thisContainer.kind === 205 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
49396 }
49397 function getConstructorDefinedThisAssignmentTypes(types, declarations) {
49398 ts.Debug.assert(types.length === declarations.length);
49399 return types.filter(function (_, i) {
49400 var declaration = declarations[i];
49401 var expression = ts.isBinaryExpression(declaration) ? declaration :
49402 ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
49403 return expression && isDeclarationInConstructor(expression);
49404 });
49405 }
49406 // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
49407 // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
49408 // pattern. Otherwise, it is the type any.
49409 function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
49410 if (element.initializer) {
49411 // The type implied by a binding pattern is independent of context, so we check the initializer with no
49412 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
49413 // pattern.
49414 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
49415 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
49416 }
49417 if (ts.isBindingPattern(element.name)) {
49418 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
49419 }
49420 if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
49421 reportImplicitAny(element, anyType);
49422 }
49423 // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
49424 // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
49425 // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
49426 // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
49427 return includePatternInType ? nonInferrableAnyType : anyType;
49428 }
49429 // Return the type implied by an object binding pattern
49430 function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
49431 var members = ts.createSymbolTable();
49432 var stringIndexInfo;
49433 var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
49434 ts.forEach(pattern.elements, function (e) {
49435 var name = e.propertyName || e.name;
49436 if (e.dotDotDotToken) {
49437 stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
49438 return;
49439 }
49440 var exprType = getLiteralTypeFromPropertyName(name);
49441 if (!isTypeUsableAsPropertyName(exprType)) {
49442 // do not include computed properties in the implied type
49443 objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
49444 return;
49445 }
49446 var text = getPropertyNameFromType(exprType);
49447 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
49448 var symbol = createSymbol(flags, text);
49449 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
49450 symbol.bindingElement = e;
49451 members.set(symbol.escapedName, symbol);
49452 });
49453 var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
49454 result.objectFlags |= objectFlags;
49455 if (includePatternInType) {
49456 result.pattern = pattern;
49457 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
49458 }
49459 return result;
49460 }
49461 // Return the type implied by an array binding pattern
49462 function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
49463 var elements = pattern.elements;
49464 var lastElement = ts.lastOrUndefined(elements);
49465 var restElement = lastElement && lastElement.kind === 195 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined;
49466 if (elements.length === 0 || elements.length === 1 && restElement) {
49467 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
49468 }
49469 var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
49470 var minLength = ts.findLastIndex(elements, function (e) { return !(e === restElement || ts.isOmittedExpression(e) || hasDefaultValue(e)); }, elements.length - 1) + 1;
49471 var elementFlags = ts.map(elements, function (e, i) { return e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */; });
49472 var result = createTupleType(elementTypes, elementFlags);
49473 if (includePatternInType) {
49474 result = cloneTypeReference(result);
49475 result.pattern = pattern;
49476 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
49477 }
49478 return result;
49479 }
49480 // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
49481 // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
49482 // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
49483 // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
49484 // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
49485 // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
49486 // the parameter.
49487 function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
49488 if (includePatternInType === void 0) { includePatternInType = false; }
49489 if (reportErrors === void 0) { reportErrors = false; }
49490 return pattern.kind === 193 /* ObjectBindingPattern */
49491 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
49492 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
49493 }
49494 // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
49495 // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
49496 // is a bit more involved. For example:
49497 //
49498 // var [x, s = ""] = [1, "one"];
49499 //
49500 // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
49501 // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
49502 // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
49503 function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
49504 return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
49505 }
49506 function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
49507 if (type) {
49508 if (reportErrors) {
49509 reportErrorsFromWidening(declaration, type);
49510 }
49511 // always widen a 'unique symbol' type if the type was created for a different declaration.
49512 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
49513 type = esSymbolType;
49514 }
49515 return getWidenedType(type);
49516 }
49517 // Rest parameters default to type any[], other parameters default to type any
49518 type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
49519 // Report implicit any errors unless this is a private property within an ambient declaration
49520 if (reportErrors) {
49521 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
49522 reportImplicitAny(declaration, type);
49523 }
49524 }
49525 return type;
49526 }
49527 function declarationBelongsToPrivateAmbientMember(declaration) {
49528 var root = ts.getRootDeclaration(declaration);
49529 var memberDeclaration = root.kind === 159 /* Parameter */ ? root.parent : root;
49530 return isPrivateWithinAmbient(memberDeclaration);
49531 }
49532 function tryGetTypeFromEffectiveTypeNode(declaration) {
49533 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
49534 if (typeNode) {
49535 return getTypeFromTypeNode(typeNode);
49536 }
49537 }
49538 function getTypeOfVariableOrParameterOrProperty(symbol) {
49539 var links = getSymbolLinks(symbol);
49540 if (!links.type) {
49541 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
49542 // For a contextually typed parameter it is possible that a type has already
49543 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
49544 // to preserve this type.
49545 if (!links.type) {
49546 links.type = type;
49547 }
49548 }
49549 return links.type;
49550 }
49551 function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
49552 // Handle prototype property
49553 if (symbol.flags & 4194304 /* Prototype */) {
49554 return getTypeOfPrototypeProperty(symbol);
49555 }
49556 // CommonsJS require and module both have type any.
49557 if (symbol === requireSymbol) {
49558 return anyType;
49559 }
49560 if (symbol.flags & 134217728 /* ModuleExports */) {
49561 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
49562 var members = ts.createSymbolTable();
49563 members.set("exports", fileSymbol);
49564 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
49565 }
49566 // Handle catch clause variables
49567 var declaration = symbol.valueDeclaration;
49568 if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
49569 var decl = declaration;
49570 if (!decl.type)
49571 return anyType;
49572 var type_1 = getTypeOfNode(decl.type);
49573 // an errorType will make `checkTryStatement` issue an error
49574 return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
49575 }
49576 // Handle export default expressions
49577 if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
49578 if (!declaration.statements.length) {
49579 return emptyObjectType;
49580 }
49581 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
49582 }
49583 // Handle variable, parameter or property
49584 if (!pushTypeResolution(symbol, 0 /* Type */)) {
49585 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
49586 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
49587 return getTypeOfFuncClassEnumModule(symbol);
49588 }
49589 return reportCircularityError(symbol);
49590 }
49591 var type;
49592 if (declaration.kind === 263 /* ExportAssignment */) {
49593 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
49594 }
49595 else if (ts.isBinaryExpression(declaration) ||
49596 (ts.isInJSFile(declaration) &&
49597 (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
49598 type = getWidenedTypeForAssignmentDeclaration(symbol);
49599 }
49600 else if (ts.isPropertyAccessExpression(declaration)
49601 || ts.isElementAccessExpression(declaration)
49602 || ts.isIdentifier(declaration)
49603 || ts.isStringLiteralLike(declaration)
49604 || ts.isNumericLiteral(declaration)
49605 || ts.isClassDeclaration(declaration)
49606 || ts.isFunctionDeclaration(declaration)
49607 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
49608 || ts.isMethodSignature(declaration)
49609 || ts.isSourceFile(declaration)) {
49610 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
49611 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
49612 return getTypeOfFuncClassEnumModule(symbol);
49613 }
49614 type = ts.isBinaryExpression(declaration.parent) ?
49615 getWidenedTypeForAssignmentDeclaration(symbol) :
49616 tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
49617 }
49618 else if (ts.isPropertyAssignment(declaration)) {
49619 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
49620 }
49621 else if (ts.isJsxAttribute(declaration)) {
49622 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
49623 }
49624 else if (ts.isShorthandPropertyAssignment(declaration)) {
49625 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
49626 }
49627 else if (ts.isObjectLiteralMethod(declaration)) {
49628 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
49629 }
49630 else if (ts.isParameter(declaration)
49631 || ts.isPropertyDeclaration(declaration)
49632 || ts.isPropertySignature(declaration)
49633 || ts.isVariableDeclaration(declaration)
49634 || ts.isBindingElement(declaration)
49635 || ts.isJSDocPropertyLikeTag(declaration)) {
49636 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
49637 }
49638 // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
49639 // Re-dispatch based on valueDeclaration.kind instead.
49640 else if (ts.isEnumDeclaration(declaration)) {
49641 type = getTypeOfFuncClassEnumModule(symbol);
49642 }
49643 else if (ts.isEnumMember(declaration)) {
49644 type = getTypeOfEnumMember(symbol);
49645 }
49646 else if (ts.isAccessor(declaration)) {
49647 type = resolveTypeOfAccessors(symbol);
49648 }
49649 else {
49650 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
49651 }
49652 if (!popTypeResolution()) {
49653 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
49654 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
49655 return getTypeOfFuncClassEnumModule(symbol);
49656 }
49657 return reportCircularityError(symbol);
49658 }
49659 return type;
49660 }
49661 function getAnnotatedAccessorTypeNode(accessor) {
49662 if (accessor) {
49663 if (accessor.kind === 166 /* GetAccessor */) {
49664 var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
49665 return getterTypeAnnotation;
49666 }
49667 else {
49668 var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
49669 return setterTypeAnnotation;
49670 }
49671 }
49672 return undefined;
49673 }
49674 function getAnnotatedAccessorType(accessor) {
49675 var node = getAnnotatedAccessorTypeNode(accessor);
49676 return node && getTypeFromTypeNode(node);
49677 }
49678 function getAnnotatedAccessorThisParameter(accessor) {
49679 var parameter = getAccessorThisParameter(accessor);
49680 return parameter && parameter.symbol;
49681 }
49682 function getThisTypeOfDeclaration(declaration) {
49683 return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
49684 }
49685 function getTypeOfAccessors(symbol) {
49686 var links = getSymbolLinks(symbol);
49687 return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
49688 }
49689 function getTypeOfAccessorsWorker(symbol) {
49690 if (!pushTypeResolution(symbol, 0 /* Type */)) {
49691 return errorType;
49692 }
49693 var type = resolveTypeOfAccessors(symbol);
49694 if (!popTypeResolution()) {
49695 type = anyType;
49696 if (noImplicitAny) {
49697 var getter = ts.getDeclarationOfKind(symbol, 166 /* GetAccessor */);
49698 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));
49699 }
49700 }
49701 return type;
49702 }
49703 function resolveTypeOfAccessors(symbol) {
49704 var getter = ts.getDeclarationOfKind(symbol, 166 /* GetAccessor */);
49705 var setter = ts.getDeclarationOfKind(symbol, 167 /* SetAccessor */);
49706 if (getter && ts.isInJSFile(getter)) {
49707 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
49708 if (jsDocType) {
49709 return jsDocType;
49710 }
49711 }
49712 // First try to see if the user specified a return type on the get-accessor.
49713 var getterReturnType = getAnnotatedAccessorType(getter);
49714 if (getterReturnType) {
49715 return getterReturnType;
49716 }
49717 else {
49718 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
49719 var setterParameterType = getAnnotatedAccessorType(setter);
49720 if (setterParameterType) {
49721 return setterParameterType;
49722 }
49723 else {
49724 // If there are no specified types, try to infer it from the body of the get accessor if it exists.
49725 if (getter && getter.body) {
49726 return getReturnTypeFromBody(getter);
49727 }
49728 // Otherwise, fall back to 'any'.
49729 else {
49730 if (setter) {
49731 if (!isPrivateWithinAmbient(setter)) {
49732 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
49733 }
49734 }
49735 else {
49736 ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
49737 if (!isPrivateWithinAmbient(getter)) {
49738 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
49739 }
49740 }
49741 return anyType;
49742 }
49743 }
49744 }
49745 }
49746 function getBaseTypeVariableOfClass(symbol) {
49747 var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
49748 return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
49749 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
49750 undefined;
49751 }
49752 function getTypeOfFuncClassEnumModule(symbol) {
49753 var links = getSymbolLinks(symbol);
49754 var originalLinks = links;
49755 if (!links.type) {
49756 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
49757 if (jsDeclaration) {
49758 var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
49759 if (merged) {
49760 // note:we overwrite links because we just cloned the symbol
49761 symbol = links = merged;
49762 }
49763 }
49764 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
49765 }
49766 return links.type;
49767 }
49768 function getTypeOfFuncClassEnumModuleWorker(symbol) {
49769 var declaration = symbol.valueDeclaration;
49770 if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
49771 return anyType;
49772 }
49773 else if (declaration && (declaration.kind === 213 /* BinaryExpression */ ||
49774 ts.isAccessExpression(declaration) &&
49775 declaration.parent.kind === 213 /* BinaryExpression */)) {
49776 return getWidenedTypeForAssignmentDeclaration(symbol);
49777 }
49778 else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
49779 var resolvedModule = resolveExternalModuleSymbol(symbol);
49780 if (resolvedModule !== symbol) {
49781 if (!pushTypeResolution(symbol, 0 /* Type */)) {
49782 return errorType;
49783 }
49784 var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
49785 var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
49786 if (!popTypeResolution()) {
49787 return reportCircularityError(symbol);
49788 }
49789 return type_2;
49790 }
49791 }
49792 var type = createObjectType(16 /* Anonymous */, symbol);
49793 if (symbol.flags & 32 /* Class */) {
49794 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
49795 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
49796 }
49797 else {
49798 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
49799 }
49800 }
49801 function getTypeOfEnumMember(symbol) {
49802 var links = getSymbolLinks(symbol);
49803 return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
49804 }
49805 function getTypeOfAlias(symbol) {
49806 var links = getSymbolLinks(symbol);
49807 if (!links.type) {
49808 var targetSymbol = resolveAlias(symbol);
49809 // It only makes sense to get the type of a value symbol. If the result of resolving
49810 // the alias is not a value, then it has no type. To get the type associated with a
49811 // type symbol, call getDeclaredTypeOfSymbol.
49812 // This check is important because without it, a call to getTypeOfSymbol could end
49813 // up recursively calling getTypeOfAlias, causing a stack overflow.
49814 links.type = targetSymbol.flags & 111551 /* Value */
49815 ? getTypeOfSymbol(targetSymbol)
49816 : errorType;
49817 }
49818 return links.type;
49819 }
49820 function getTypeOfInstantiatedSymbol(symbol) {
49821 var links = getSymbolLinks(symbol);
49822 if (!links.type) {
49823 if (!pushTypeResolution(symbol, 0 /* Type */)) {
49824 return links.type = errorType;
49825 }
49826 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
49827 if (!popTypeResolution()) {
49828 type = reportCircularityError(symbol);
49829 }
49830 links.type = type;
49831 }
49832 return links.type;
49833 }
49834 function reportCircularityError(symbol) {
49835 var declaration = symbol.valueDeclaration;
49836 // Check if variable has type annotation that circularly references the variable itself
49837 if (ts.getEffectiveTypeAnnotationNode(declaration)) {
49838 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
49839 return errorType;
49840 }
49841 // Check if variable has initializer that circularly references the variable itself
49842 if (noImplicitAny && (declaration.kind !== 159 /* Parameter */ || declaration.initializer)) {
49843 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));
49844 }
49845 // Circularities could also result from parameters in function expressions that end up
49846 // having themselves as contextual types following type argument inference. In those cases
49847 // we have already reported an implicit any error so we don't report anything here.
49848 return anyType;
49849 }
49850 function getTypeOfSymbolWithDeferredType(symbol) {
49851 var links = getSymbolLinks(symbol);
49852 if (!links.type) {
49853 ts.Debug.assertIsDefined(links.deferralParent);
49854 ts.Debug.assertIsDefined(links.deferralConstituents);
49855 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
49856 }
49857 return links.type;
49858 }
49859 function getTypeOfSymbol(symbol) {
49860 var checkFlags = ts.getCheckFlags(symbol);
49861 if (checkFlags & 65536 /* DeferredType */) {
49862 return getTypeOfSymbolWithDeferredType(symbol);
49863 }
49864 if (checkFlags & 1 /* Instantiated */) {
49865 return getTypeOfInstantiatedSymbol(symbol);
49866 }
49867 if (checkFlags & 262144 /* Mapped */) {
49868 return getTypeOfMappedSymbol(symbol);
49869 }
49870 if (checkFlags & 8192 /* ReverseMapped */) {
49871 return getTypeOfReverseMappedSymbol(symbol);
49872 }
49873 if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
49874 return getTypeOfVariableOrParameterOrProperty(symbol);
49875 }
49876 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
49877 return getTypeOfFuncClassEnumModule(symbol);
49878 }
49879 if (symbol.flags & 8 /* EnumMember */) {
49880 return getTypeOfEnumMember(symbol);
49881 }
49882 if (symbol.flags & 98304 /* Accessor */) {
49883 return getTypeOfAccessors(symbol);
49884 }
49885 if (symbol.flags & 2097152 /* Alias */) {
49886 return getTypeOfAlias(symbol);
49887 }
49888 return errorType;
49889 }
49890 function isReferenceToType(type, target) {
49891 return type !== undefined
49892 && target !== undefined
49893 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
49894 && type.target === target;
49895 }
49896 function getTargetType(type) {
49897 return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
49898 }
49899 // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
49900 function hasBaseType(type, checkBase) {
49901 return check(type);
49902 function check(type) {
49903 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
49904 var target = getTargetType(type);
49905 return target === checkBase || ts.some(getBaseTypes(target), check);
49906 }
49907 else if (type.flags & 2097152 /* Intersection */) {
49908 return ts.some(type.types, check);
49909 }
49910 return false;
49911 }
49912 }
49913 // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
49914 // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
49915 // in-place and returns the same array.
49916 function appendTypeParameters(typeParameters, declarations) {
49917 for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
49918 var declaration = declarations_2[_i];
49919 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
49920 }
49921 return typeParameters;
49922 }
49923 // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
49924 function getOuterTypeParameters(node, includeThisTypes) {
49925 while (true) {
49926 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
49927 if (node && ts.isBinaryExpression(node)) {
49928 // prototype assignments get the outer type parameters of their constructor function
49929 var assignmentKind = ts.getAssignmentDeclarationKind(node);
49930 if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
49931 var symbol = getSymbolOfNode(node.left);
49932 if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
49933 node = symbol.parent.valueDeclaration;
49934 }
49935 }
49936 }
49937 if (!node) {
49938 return undefined;
49939 }
49940 switch (node.kind) {
49941 case 229 /* VariableStatement */:
49942 case 249 /* ClassDeclaration */:
49943 case 218 /* ClassExpression */:
49944 case 250 /* InterfaceDeclaration */:
49945 case 168 /* CallSignature */:
49946 case 169 /* ConstructSignature */:
49947 case 163 /* MethodSignature */:
49948 case 173 /* FunctionType */:
49949 case 174 /* ConstructorType */:
49950 case 304 /* JSDocFunctionType */:
49951 case 248 /* FunctionDeclaration */:
49952 case 164 /* MethodDeclaration */:
49953 case 205 /* FunctionExpression */:
49954 case 206 /* ArrowFunction */:
49955 case 251 /* TypeAliasDeclaration */:
49956 case 326 /* JSDocTemplateTag */:
49957 case 327 /* JSDocTypedefTag */:
49958 case 321 /* JSDocEnumTag */:
49959 case 320 /* JSDocCallbackTag */:
49960 case 189 /* MappedType */:
49961 case 183 /* ConditionalType */:
49962 var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
49963 if (node.kind === 189 /* MappedType */) {
49964 return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
49965 }
49966 else if (node.kind === 183 /* ConditionalType */) {
49967 return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
49968 }
49969 else if (node.kind === 229 /* VariableStatement */ && !ts.isInJSFile(node)) {
49970 break;
49971 }
49972 var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
49973 var thisType = includeThisTypes &&
49974 (node.kind === 249 /* ClassDeclaration */ || node.kind === 218 /* ClassExpression */ || node.kind === 250 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
49975 getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
49976 return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
49977 case 322 /* JSDocParameterTag */:
49978 var paramSymbol = ts.getParameterSymbolFromJSDoc(node);
49979 if (paramSymbol) {
49980 node = paramSymbol.valueDeclaration;
49981 }
49982 break;
49983 }
49984 }
49985 }
49986 // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
49987 function getOuterTypeParametersOfClassOrInterface(symbol) {
49988 var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 250 /* InterfaceDeclaration */);
49989 ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
49990 return getOuterTypeParameters(declaration);
49991 }
49992 // The local type parameters are the combined set of type parameters from all declarations of the class,
49993 // interface, or type alias.
49994 function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
49995 var result;
49996 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
49997 var node = _a[_i];
49998 if (node.kind === 250 /* InterfaceDeclaration */ ||
49999 node.kind === 249 /* ClassDeclaration */ ||
50000 node.kind === 218 /* ClassExpression */ ||
50001 isJSConstructor(node) ||
50002 ts.isTypeAlias(node)) {
50003 var declaration = node;
50004 result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
50005 }
50006 }
50007 return result;
50008 }
50009 // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
50010 // its locally declared type parameters.
50011 function getTypeParametersOfClassOrInterface(symbol) {
50012 return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
50013 }
50014 // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
50015 // rest parameter of type any[].
50016 function isMixinConstructorType(type) {
50017 var signatures = getSignaturesOfType(type, 1 /* Construct */);
50018 if (signatures.length === 1) {
50019 var s = signatures[0];
50020 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
50021 }
50022 return false;
50023 }
50024 function isConstructorType(type) {
50025 if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
50026 return true;
50027 }
50028 if (type.flags & 8650752 /* TypeVariable */) {
50029 var constraint = getBaseConstraintOfType(type);
50030 return !!constraint && isMixinConstructorType(constraint);
50031 }
50032 return false;
50033 }
50034 function getBaseTypeNodeOfClass(type) {
50035 return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
50036 }
50037 function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
50038 var typeArgCount = ts.length(typeArgumentNodes);
50039 var isJavascript = ts.isInJSFile(location);
50040 return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
50041 }
50042 function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
50043 var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
50044 var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
50045 return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
50046 }
50047 /**
50048 * The base constructor of a class can resolve to
50049 * * undefinedType if the class has no extends clause,
50050 * * unknownType if an error occurred during resolution of the extends expression,
50051 * * nullType if the extends expression is the null value,
50052 * * anyType if the extends expression has type any, or
50053 * * an object type with at least one construct signature.
50054 */
50055 function getBaseConstructorTypeOfClass(type) {
50056 if (!type.resolvedBaseConstructorType) {
50057 var decl = type.symbol.valueDeclaration;
50058 var extended = ts.getEffectiveBaseTypeNode(decl);
50059 var baseTypeNode = getBaseTypeNodeOfClass(type);
50060 if (!baseTypeNode) {
50061 return type.resolvedBaseConstructorType = undefinedType;
50062 }
50063 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
50064 return errorType;
50065 }
50066 var baseConstructorType = checkExpression(baseTypeNode.expression);
50067 if (extended && baseTypeNode !== extended) {
50068 ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
50069 checkExpression(extended.expression);
50070 }
50071 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
50072 // Resolving the members of a class requires us to resolve the base class of that class.
50073 // We force resolution here such that we catch circularities now.
50074 resolveStructuredTypeMembers(baseConstructorType);
50075 }
50076 if (!popTypeResolution()) {
50077 error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
50078 return type.resolvedBaseConstructorType = errorType;
50079 }
50080 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
50081 var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
50082 if (baseConstructorType.flags & 262144 /* TypeParameter */) {
50083 var constraint = getConstraintFromTypeParameter(baseConstructorType);
50084 var ctorReturn = unknownType;
50085 if (constraint) {
50086 var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
50087 if (ctorSig[0]) {
50088 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
50089 }
50090 }
50091 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)));
50092 }
50093 return type.resolvedBaseConstructorType = errorType;
50094 }
50095 type.resolvedBaseConstructorType = baseConstructorType;
50096 }
50097 return type.resolvedBaseConstructorType;
50098 }
50099 function getImplementsTypes(type) {
50100 var resolvedImplementsTypes = ts.emptyArray;
50101 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
50102 var declaration = _a[_i];
50103 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
50104 if (!implementsTypeNodes)
50105 continue;
50106 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
50107 var node = implementsTypeNodes_1[_b];
50108 var implementsType = getTypeFromTypeNode(node);
50109 if (implementsType !== errorType) {
50110 if (resolvedImplementsTypes === ts.emptyArray) {
50111 resolvedImplementsTypes = [implementsType];
50112 }
50113 else {
50114 resolvedImplementsTypes.push(implementsType);
50115 }
50116 }
50117 }
50118 }
50119 return resolvedImplementsTypes;
50120 }
50121 function reportCircularBaseType(node, type) {
50122 error(node, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
50123 }
50124 function getBaseTypes(type) {
50125 if (!type.baseTypesResolved) {
50126 if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) {
50127 if (type.objectFlags & 8 /* Tuple */) {
50128 type.resolvedBaseTypes = [getTupleBaseType(type)];
50129 }
50130 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
50131 if (type.symbol.flags & 32 /* Class */) {
50132 resolveBaseTypesOfClass(type);
50133 }
50134 if (type.symbol.flags & 64 /* Interface */) {
50135 resolveBaseTypesOfInterface(type);
50136 }
50137 }
50138 else {
50139 ts.Debug.fail("type must be class or interface");
50140 }
50141 if (!popTypeResolution()) {
50142 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
50143 var declaration = _a[_i];
50144 if (declaration.kind === 249 /* ClassDeclaration */ || declaration.kind === 250 /* InterfaceDeclaration */) {
50145 reportCircularBaseType(declaration, type);
50146 }
50147 }
50148 }
50149 }
50150 type.baseTypesResolved = true;
50151 }
50152 return type.resolvedBaseTypes;
50153 }
50154 function getTupleBaseType(type) {
50155 var elementTypes = ts.sameMap(type.typeParameters, function (t, i) { return type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; });
50156 return createArrayType(getUnionType(elementTypes || ts.emptyArray), type.readonly);
50157 }
50158 function resolveBaseTypesOfClass(type) {
50159 type.resolvedBaseTypes = ts.resolvingEmptyArray;
50160 var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
50161 if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
50162 return type.resolvedBaseTypes = ts.emptyArray;
50163 }
50164 var baseTypeNode = getBaseTypeNodeOfClass(type);
50165 var baseType;
50166 var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
50167 if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
50168 areAllOuterTypeParametersApplied(originalBaseType)) {
50169 // 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
50170 // class and all return the instance type of the class. There is no need for further checks and we can apply the
50171 // type arguments in the same manner as a type reference to get the same error reporting experience.
50172 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
50173 }
50174 else if (baseConstructorType.flags & 1 /* Any */) {
50175 baseType = baseConstructorType;
50176 }
50177 else {
50178 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
50179 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
50180 // we check that all instantiated signatures return the same type.
50181 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
50182 if (!constructors.length) {
50183 error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
50184 return type.resolvedBaseTypes = ts.emptyArray;
50185 }
50186 baseType = getReturnTypeOfSignature(constructors[0]);
50187 }
50188 if (baseType === errorType) {
50189 return type.resolvedBaseTypes = ts.emptyArray;
50190 }
50191 var reducedBaseType = getReducedType(baseType);
50192 if (!isValidBaseType(reducedBaseType)) {
50193 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
50194 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));
50195 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
50196 return type.resolvedBaseTypes = ts.emptyArray;
50197 }
50198 if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
50199 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
50200 return type.resolvedBaseTypes = ts.emptyArray;
50201 }
50202 if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
50203 // Circular reference, likely through instantiation of default parameters
50204 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
50205 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
50206 // partial instantiation of the members without the base types fully resolved
50207 type.members = undefined;
50208 }
50209 return type.resolvedBaseTypes = [reducedBaseType];
50210 }
50211 function areAllOuterTypeParametersApplied(type) {
50212 // An unapplied type parameter has its symbol still the same as the matching argument symbol.
50213 // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
50214 var outerTypeParameters = type.outerTypeParameters;
50215 if (outerTypeParameters) {
50216 var last_1 = outerTypeParameters.length - 1;
50217 var typeArguments = getTypeArguments(type);
50218 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
50219 }
50220 return true;
50221 }
50222 // A valid base type is `any`, an object type or intersection of object types.
50223 function isValidBaseType(type) {
50224 if (type.flags & 262144 /* TypeParameter */) {
50225 var constraint = getBaseConstraintOfType(type);
50226 if (constraint) {
50227 return isValidBaseType(constraint);
50228 }
50229 }
50230 // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
50231 // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
50232 return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
50233 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
50234 }
50235 function resolveBaseTypesOfInterface(type) {
50236 type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
50237 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
50238 var declaration = _a[_i];
50239 if (declaration.kind === 250 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
50240 for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
50241 var node = _c[_b];
50242 var baseType = getReducedType(getTypeFromTypeNode(node));
50243 if (baseType !== errorType) {
50244 if (isValidBaseType(baseType)) {
50245 if (type !== baseType && !hasBaseType(baseType, type)) {
50246 if (type.resolvedBaseTypes === ts.emptyArray) {
50247 type.resolvedBaseTypes = [baseType];
50248 }
50249 else {
50250 type.resolvedBaseTypes.push(baseType);
50251 }
50252 }
50253 else {
50254 reportCircularBaseType(declaration, type);
50255 }
50256 }
50257 else {
50258 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
50259 }
50260 }
50261 }
50262 }
50263 }
50264 }
50265 /**
50266 * Returns true if the interface given by the symbol is free of "this" references.
50267 *
50268 * Specifically, the result is true if the interface itself contains no references
50269 * to "this" in its body, if all base types are interfaces,
50270 * and if none of the base interfaces have a "this" type.
50271 */
50272 function isThislessInterface(symbol) {
50273 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50274 var declaration = _a[_i];
50275 if (declaration.kind === 250 /* InterfaceDeclaration */) {
50276 if (declaration.flags & 128 /* ContainsThis */) {
50277 return false;
50278 }
50279 var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
50280 if (baseTypeNodes) {
50281 for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
50282 var node = baseTypeNodes_1[_b];
50283 if (ts.isEntityNameExpression(node.expression)) {
50284 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
50285 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
50286 return false;
50287 }
50288 }
50289 }
50290 }
50291 }
50292 }
50293 return true;
50294 }
50295 function getDeclaredTypeOfClassOrInterface(symbol) {
50296 var links = getSymbolLinks(symbol);
50297 var originalLinks = links;
50298 if (!links.declaredType) {
50299 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
50300 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
50301 if (merged) {
50302 // note:we overwrite links because we just cloned the symbol
50303 symbol = links = merged;
50304 }
50305 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
50306 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
50307 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
50308 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
50309 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
50310 // property types inferred from initializers and method return types inferred from return statements are very hard
50311 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
50312 // "this" references.
50313 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
50314 type.objectFlags |= 4 /* Reference */;
50315 type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
50316 type.outerTypeParameters = outerTypeParameters;
50317 type.localTypeParameters = localTypeParameters;
50318 type.instantiations = new ts.Map();
50319 type.instantiations.set(getTypeListId(type.typeParameters), type);
50320 type.target = type;
50321 type.resolvedTypeArguments = type.typeParameters;
50322 type.thisType = createTypeParameter(symbol);
50323 type.thisType.isThisType = true;
50324 type.thisType.constraint = type;
50325 }
50326 }
50327 return links.declaredType;
50328 }
50329 function getDeclaredTypeOfTypeAlias(symbol) {
50330 var links = getSymbolLinks(symbol);
50331 if (!links.declaredType) {
50332 // Note that we use the links object as the target here because the symbol object is used as the unique
50333 // identity for resolution of the 'type' property in SymbolLinks.
50334 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
50335 return errorType;
50336 }
50337 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
50338 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
50339 // If typeNode is missing, we will error in checkJSDocTypedefTag.
50340 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
50341 if (popTypeResolution()) {
50342 var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
50343 if (typeParameters) {
50344 // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
50345 // an instantiation of the type alias with the type parameters supplied as type arguments.
50346 links.typeParameters = typeParameters;
50347 links.instantiations = new ts.Map();
50348 links.instantiations.set(getTypeListId(typeParameters), type);
50349 }
50350 }
50351 else {
50352 type = errorType;
50353 error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
50354 }
50355 links.declaredType = type;
50356 }
50357 return links.declaredType;
50358 }
50359 function isStringConcatExpression(expr) {
50360 if (ts.isStringLiteralLike(expr)) {
50361 return true;
50362 }
50363 else if (expr.kind === 213 /* BinaryExpression */) {
50364 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
50365 }
50366 return false;
50367 }
50368 function isLiteralEnumMember(member) {
50369 var expr = member.initializer;
50370 if (!expr) {
50371 return !(member.flags & 8388608 /* Ambient */);
50372 }
50373 switch (expr.kind) {
50374 case 10 /* StringLiteral */:
50375 case 8 /* NumericLiteral */:
50376 case 14 /* NoSubstitutionTemplateLiteral */:
50377 return true;
50378 case 211 /* PrefixUnaryExpression */:
50379 return expr.operator === 40 /* MinusToken */ &&
50380 expr.operand.kind === 8 /* NumericLiteral */;
50381 case 78 /* Identifier */:
50382 return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
50383 case 213 /* BinaryExpression */:
50384 return isStringConcatExpression(expr);
50385 default:
50386 return false;
50387 }
50388 }
50389 function getEnumKind(symbol) {
50390 var links = getSymbolLinks(symbol);
50391 if (links.enumKind !== undefined) {
50392 return links.enumKind;
50393 }
50394 var hasNonLiteralMember = false;
50395 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50396 var declaration = _a[_i];
50397 if (declaration.kind === 252 /* EnumDeclaration */) {
50398 for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
50399 var member = _c[_b];
50400 if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
50401 return links.enumKind = 1 /* Literal */;
50402 }
50403 if (!isLiteralEnumMember(member)) {
50404 hasNonLiteralMember = true;
50405 }
50406 }
50407 }
50408 }
50409 return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
50410 }
50411 function getBaseTypeOfEnumLiteralType(type) {
50412 return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
50413 }
50414 function getDeclaredTypeOfEnum(symbol) {
50415 var links = getSymbolLinks(symbol);
50416 if (links.declaredType) {
50417 return links.declaredType;
50418 }
50419 if (getEnumKind(symbol) === 1 /* Literal */) {
50420 enumCount++;
50421 var memberTypeList = [];
50422 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50423 var declaration = _a[_i];
50424 if (declaration.kind === 252 /* EnumDeclaration */) {
50425 for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
50426 var member = _c[_b];
50427 var value = getEnumMemberValue(member);
50428 var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
50429 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
50430 memberTypeList.push(getRegularTypeOfLiteralType(memberType));
50431 }
50432 }
50433 }
50434 if (memberTypeList.length) {
50435 var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
50436 if (enumType_1.flags & 1048576 /* Union */) {
50437 enumType_1.flags |= 1024 /* EnumLiteral */;
50438 enumType_1.symbol = symbol;
50439 }
50440 return links.declaredType = enumType_1;
50441 }
50442 }
50443 var enumType = createType(32 /* Enum */);
50444 enumType.symbol = symbol;
50445 return links.declaredType = enumType;
50446 }
50447 function getDeclaredTypeOfEnumMember(symbol) {
50448 var links = getSymbolLinks(symbol);
50449 if (!links.declaredType) {
50450 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
50451 if (!links.declaredType) {
50452 links.declaredType = enumType;
50453 }
50454 }
50455 return links.declaredType;
50456 }
50457 function getDeclaredTypeOfTypeParameter(symbol) {
50458 var links = getSymbolLinks(symbol);
50459 return links.declaredType || (links.declaredType = createTypeParameter(symbol));
50460 }
50461 function getDeclaredTypeOfAlias(symbol) {
50462 var links = getSymbolLinks(symbol);
50463 return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
50464 }
50465 function getDeclaredTypeOfSymbol(symbol) {
50466 return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
50467 }
50468 function tryGetDeclaredTypeOfSymbol(symbol) {
50469 if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
50470 return getDeclaredTypeOfClassOrInterface(symbol);
50471 }
50472 if (symbol.flags & 524288 /* TypeAlias */) {
50473 return getDeclaredTypeOfTypeAlias(symbol);
50474 }
50475 if (symbol.flags & 262144 /* TypeParameter */) {
50476 return getDeclaredTypeOfTypeParameter(symbol);
50477 }
50478 if (symbol.flags & 384 /* Enum */) {
50479 return getDeclaredTypeOfEnum(symbol);
50480 }
50481 if (symbol.flags & 8 /* EnumMember */) {
50482 return getDeclaredTypeOfEnumMember(symbol);
50483 }
50484 if (symbol.flags & 2097152 /* Alias */) {
50485 return getDeclaredTypeOfAlias(symbol);
50486 }
50487 return undefined;
50488 }
50489 /**
50490 * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
50491 * literal type, an array with an element type that is free of this references, or a type reference that is
50492 * free of this references.
50493 */
50494 function isThislessType(node) {
50495 switch (node.kind) {
50496 case 128 /* AnyKeyword */:
50497 case 151 /* UnknownKeyword */:
50498 case 146 /* StringKeyword */:
50499 case 143 /* NumberKeyword */:
50500 case 154 /* BigIntKeyword */:
50501 case 131 /* BooleanKeyword */:
50502 case 147 /* SymbolKeyword */:
50503 case 144 /* ObjectKeyword */:
50504 case 113 /* VoidKeyword */:
50505 case 149 /* UndefinedKeyword */:
50506 case 140 /* NeverKeyword */:
50507 case 190 /* LiteralType */:
50508 return true;
50509 case 177 /* ArrayType */:
50510 return isThislessType(node.elementType);
50511 case 172 /* TypeReference */:
50512 return !node.typeArguments || node.typeArguments.every(isThislessType);
50513 }
50514 return false;
50515 }
50516 /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
50517 function isThislessTypeParameter(node) {
50518 var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
50519 return !constraint || isThislessType(constraint);
50520 }
50521 /**
50522 * A variable-like declaration is free of this references if it has a type annotation
50523 * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
50524 */
50525 function isThislessVariableLikeDeclaration(node) {
50526 var typeNode = ts.getEffectiveTypeAnnotationNode(node);
50527 return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
50528 }
50529 /**
50530 * A function-like declaration is considered free of `this` references if it has a return type
50531 * annotation that is free of this references and if each parameter is thisless and if
50532 * each type parameter (if present) is thisless.
50533 */
50534 function isThislessFunctionLikeDeclaration(node) {
50535 var returnType = ts.getEffectiveReturnTypeNode(node);
50536 var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
50537 return (node.kind === 165 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
50538 node.parameters.every(isThislessVariableLikeDeclaration) &&
50539 typeParameters.every(isThislessTypeParameter);
50540 }
50541 /**
50542 * Returns true if the class or interface member given by the symbol is free of "this" references. The
50543 * function may return false for symbols that are actually free of "this" references because it is not
50544 * feasible to perform a complete analysis in all cases. In particular, property members with types
50545 * inferred from their initializers and function members with inferred return types are conservatively
50546 * assumed not to be free of "this" references.
50547 */
50548 function isThisless(symbol) {
50549 if (symbol.declarations && symbol.declarations.length === 1) {
50550 var declaration = symbol.declarations[0];
50551 if (declaration) {
50552 switch (declaration.kind) {
50553 case 162 /* PropertyDeclaration */:
50554 case 161 /* PropertySignature */:
50555 return isThislessVariableLikeDeclaration(declaration);
50556 case 164 /* MethodDeclaration */:
50557 case 163 /* MethodSignature */:
50558 case 165 /* Constructor */:
50559 case 166 /* GetAccessor */:
50560 case 167 /* SetAccessor */:
50561 return isThislessFunctionLikeDeclaration(declaration);
50562 }
50563 }
50564 }
50565 return false;
50566 }
50567 // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
50568 // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
50569 function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
50570 var result = ts.createSymbolTable();
50571 for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
50572 var symbol = symbols_2[_i];
50573 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
50574 }
50575 return result;
50576 }
50577 function addInheritedMembers(symbols, baseSymbols) {
50578 for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
50579 var s = baseSymbols_1[_i];
50580 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
50581 symbols.set(s.escapedName, s);
50582 }
50583 }
50584 }
50585 function isStaticPrivateIdentifierProperty(s) {
50586 return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */);
50587 }
50588 function resolveDeclaredMembers(type) {
50589 if (!type.declaredProperties) {
50590 var symbol = type.symbol;
50591 var members = getMembersOfSymbol(symbol);
50592 type.declaredProperties = getNamedMembers(members);
50593 // Start with signatures at empty array in case of recursive types
50594 type.declaredCallSignatures = ts.emptyArray;
50595 type.declaredConstructSignatures = ts.emptyArray;
50596 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
50597 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
50598 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
50599 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
50600 }
50601 return type;
50602 }
50603 /**
50604 * Indicates whether a type can be used as a property name.
50605 */
50606 function isTypeUsableAsPropertyName(type) {
50607 return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
50608 }
50609 /**
50610 * Indicates whether a declaration name is definitely late-bindable.
50611 * A declaration name is only late-bindable if:
50612 * - It is a `ComputedPropertyName`.
50613 * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
50614 * `ElementAccessExpression` consisting only of these same three types of nodes.
50615 * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
50616 */
50617 function isLateBindableName(node) {
50618 if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
50619 return false;
50620 }
50621 var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
50622 return ts.isEntityNameExpression(expr)
50623 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
50624 }
50625 function isLateBoundName(name) {
50626 return name.charCodeAt(0) === 95 /* _ */ &&
50627 name.charCodeAt(1) === 95 /* _ */ &&
50628 name.charCodeAt(2) === 64 /* at */;
50629 }
50630 /**
50631 * Indicates whether a declaration has a late-bindable dynamic name.
50632 */
50633 function hasLateBindableName(node) {
50634 var name = ts.getNameOfDeclaration(node);
50635 return !!name && isLateBindableName(name);
50636 }
50637 /**
50638 * Indicates whether a declaration has a dynamic name that cannot be late-bound.
50639 */
50640 function hasNonBindableDynamicName(node) {
50641 return ts.hasDynamicName(node) && !hasLateBindableName(node);
50642 }
50643 /**
50644 * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
50645 */
50646 function isNonBindableDynamicName(node) {
50647 return ts.isDynamicName(node) && !isLateBindableName(node);
50648 }
50649 /**
50650 * Gets the symbolic name for a member from its type.
50651 */
50652 function getPropertyNameFromType(type) {
50653 if (type.flags & 8192 /* UniqueESSymbol */) {
50654 return type.escapedName;
50655 }
50656 if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
50657 return ts.escapeLeadingUnderscores("" + type.value);
50658 }
50659 return ts.Debug.fail();
50660 }
50661 /**
50662 * Adds a declaration to a late-bound dynamic member. This performs the same function for
50663 * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
50664 * members.
50665 */
50666 function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
50667 ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
50668 symbol.flags |= symbolFlags;
50669 getSymbolLinks(member.symbol).lateSymbol = symbol;
50670 if (!symbol.declarations) {
50671 symbol.declarations = [member];
50672 }
50673 else {
50674 symbol.declarations.push(member);
50675 }
50676 if (symbolFlags & 111551 /* Value */) {
50677 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
50678 symbol.valueDeclaration = member;
50679 }
50680 }
50681 }
50682 /**
50683 * Performs late-binding of a dynamic member. This performs the same function for
50684 * late-bound members that `declareSymbol` in binder.ts performs for early-bound
50685 * members.
50686 *
50687 * If a symbol is a dynamic name from a computed property, we perform an additional "late"
50688 * binding phase to attempt to resolve the name for the symbol from the type of the computed
50689 * property's expression. If the type of the expression is a string-literal, numeric-literal,
50690 * or unique symbol type, we can use that type as the name of the symbol.
50691 *
50692 * For example, given:
50693 *
50694 * const x = Symbol();
50695 *
50696 * interface I {
50697 * [x]: number;
50698 * }
50699 *
50700 * The binder gives the property `[x]: number` a special symbol with the name "__computed".
50701 * In the late-binding phase we can type-check the expression `x` and see that it has a
50702 * unique symbol type which we can then use as the name of the member. This allows users
50703 * to define custom symbols that can be used in the members of an object type.
50704 *
50705 * @param parent The containing symbol for the member.
50706 * @param earlySymbols The early-bound symbols of the parent.
50707 * @param lateSymbols The late-bound symbols of the parent.
50708 * @param decl The member to bind.
50709 */
50710 function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
50711 ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
50712 var links = getNodeLinks(decl);
50713 if (!links.resolvedSymbol) {
50714 // In the event we attempt to resolve the late-bound name of this member recursively,
50715 // fall back to the early-bound name of this member.
50716 links.resolvedSymbol = decl.symbol;
50717 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
50718 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
50719 if (isTypeUsableAsPropertyName(type)) {
50720 var memberName = getPropertyNameFromType(type);
50721 var symbolFlags = decl.symbol.flags;
50722 // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
50723 var lateSymbol = lateSymbols.get(memberName);
50724 if (!lateSymbol)
50725 lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
50726 // Report an error if a late-bound member has the same name as an early-bound member,
50727 // or if we have another early-bound symbol declaration with the same name and
50728 // conflicting flags.
50729 var earlySymbol = earlySymbols && earlySymbols.get(memberName);
50730 if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
50731 // If we have an existing early-bound member, combine its declarations so that we can
50732 // report an error at each declaration.
50733 var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
50734 var name_4 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
50735 ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_4); });
50736 error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_4);
50737 lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
50738 }
50739 lateSymbol.nameType = type;
50740 addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
50741 if (lateSymbol.parent) {
50742 ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
50743 }
50744 else {
50745 lateSymbol.parent = parent;
50746 }
50747 return links.resolvedSymbol = lateSymbol;
50748 }
50749 }
50750 return links.resolvedSymbol;
50751 }
50752 function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
50753 var links = getSymbolLinks(symbol);
50754 if (!links[resolutionKind]) {
50755 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
50756 var earlySymbols = !isStatic ? symbol.members :
50757 symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
50758 symbol.exports;
50759 // In the event we recursively resolve the members/exports of the symbol, we
50760 // set the initial value of resolvedMembers/resolvedExports to the early-bound
50761 // members/exports of the symbol.
50762 links[resolutionKind] = earlySymbols || emptySymbols;
50763 // fill in any as-yet-unresolved late-bound members.
50764 var lateSymbols = ts.createSymbolTable();
50765 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50766 var decl = _a[_i];
50767 var members = ts.getMembersOfDeclaration(decl);
50768 if (members) {
50769 for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
50770 var member = members_5[_b];
50771 if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
50772 lateBindMember(symbol, earlySymbols, lateSymbols, member);
50773 }
50774 }
50775 }
50776 }
50777 var assignments = symbol.assignmentDeclarationMembers;
50778 if (assignments) {
50779 var decls = ts.arrayFrom(assignments.values());
50780 for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
50781 var member = decls_1[_c];
50782 var assignmentKind = ts.getAssignmentDeclarationKind(member);
50783 var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
50784 || assignmentKind === 4 /* ThisProperty */
50785 || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
50786 || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
50787 if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
50788 lateBindMember(symbol, earlySymbols, lateSymbols, member);
50789 }
50790 }
50791 }
50792 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
50793 }
50794 return links[resolutionKind];
50795 }
50796 /**
50797 * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
50798 *
50799 * For a description of late-binding, see `lateBindMember`.
50800 */
50801 function getMembersOfSymbol(symbol) {
50802 return symbol.flags & 6256 /* LateBindingContainer */
50803 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
50804 : symbol.members || emptySymbols;
50805 }
50806 /**
50807 * If a symbol is the dynamic name of the member of an object type, get the late-bound
50808 * symbol of the member.
50809 *
50810 * For a description of late-binding, see `lateBindMember`.
50811 */
50812 function getLateBoundSymbol(symbol) {
50813 if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
50814 var links = getSymbolLinks(symbol);
50815 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
50816 // force late binding of members/exports. This will set the late-bound symbol
50817 var parent = getMergedSymbol(symbol.parent);
50818 if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
50819 getExportsOfSymbol(parent);
50820 }
50821 else {
50822 getMembersOfSymbol(parent);
50823 }
50824 }
50825 return links.lateSymbol || (links.lateSymbol = symbol);
50826 }
50827 return symbol;
50828 }
50829 function getTypeWithThisArgument(type, thisArgument, needApparentType) {
50830 if (ts.getObjectFlags(type) & 4 /* Reference */) {
50831 var target = type.target;
50832 var typeArguments = getTypeArguments(type);
50833 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
50834 var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
50835 return needApparentType ? getApparentType(ref) : ref;
50836 }
50837 }
50838 else if (type.flags & 2097152 /* Intersection */) {
50839 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
50840 }
50841 return needApparentType ? getApparentType(type) : type;
50842 }
50843 function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
50844 var mapper;
50845 var members;
50846 var callSignatures;
50847 var constructSignatures;
50848 var stringIndexInfo;
50849 var numberIndexInfo;
50850 if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
50851 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
50852 callSignatures = source.declaredCallSignatures;
50853 constructSignatures = source.declaredConstructSignatures;
50854 stringIndexInfo = source.declaredStringIndexInfo;
50855 numberIndexInfo = source.declaredNumberIndexInfo;
50856 }
50857 else {
50858 mapper = createTypeMapper(typeParameters, typeArguments);
50859 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
50860 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
50861 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
50862 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
50863 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
50864 }
50865 var baseTypes = getBaseTypes(source);
50866 if (baseTypes.length) {
50867 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
50868 members = ts.createSymbolTable(source.declaredProperties);
50869 }
50870 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
50871 var thisArgument = ts.lastOrUndefined(typeArguments);
50872 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
50873 var baseType = baseTypes_1[_i];
50874 var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
50875 addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
50876 callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
50877 constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
50878 if (!stringIndexInfo) {
50879 stringIndexInfo = instantiatedBaseType === anyType ?
50880 createIndexInfo(anyType, /*isReadonly*/ false) :
50881 getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
50882 }
50883 numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
50884 }
50885 }
50886 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
50887 }
50888 function resolveClassOrInterfaceMembers(type) {
50889 resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
50890 }
50891 function resolveTypeReferenceMembers(type) {
50892 var source = resolveDeclaredMembers(type.target);
50893 var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
50894 var typeArguments = getTypeArguments(type);
50895 var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
50896 resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
50897 }
50898 function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
50899 var sig = new Signature(checker, flags);
50900 sig.declaration = declaration;
50901 sig.typeParameters = typeParameters;
50902 sig.parameters = parameters;
50903 sig.thisParameter = thisParameter;
50904 sig.resolvedReturnType = resolvedReturnType;
50905 sig.resolvedTypePredicate = resolvedTypePredicate;
50906 sig.minArgumentCount = minArgumentCount;
50907 sig.target = undefined;
50908 sig.mapper = undefined;
50909 sig.unionSignatures = undefined;
50910 return sig;
50911 }
50912 function cloneSignature(sig) {
50913 var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
50914 /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */);
50915 result.target = sig.target;
50916 result.mapper = sig.mapper;
50917 result.unionSignatures = sig.unionSignatures;
50918 return result;
50919 }
50920 function createUnionSignature(signature, unionSignatures) {
50921 var result = cloneSignature(signature);
50922 result.unionSignatures = unionSignatures;
50923 result.target = undefined;
50924 result.mapper = undefined;
50925 return result;
50926 }
50927 function getOptionalCallSignature(signature, callChainFlags) {
50928 if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
50929 return signature;
50930 }
50931 if (!signature.optionalCallSignatureCache) {
50932 signature.optionalCallSignatureCache = {};
50933 }
50934 var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
50935 return signature.optionalCallSignatureCache[key]
50936 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
50937 }
50938 function createOptionalCallSignature(signature, callChainFlags) {
50939 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.");
50940 var result = cloneSignature(signature);
50941 result.flags |= callChainFlags;
50942 return result;
50943 }
50944 function getExpandedParameters(sig, skipUnionExpanding) {
50945 if (signatureHasRestParameter(sig)) {
50946 var restIndex_1 = sig.parameters.length - 1;
50947 var restType = getTypeOfSymbol(sig.parameters[restIndex_1]);
50948 if (isTupleType(restType)) {
50949 return [expandSignatureParametersWithTupleMembers(restType, restIndex_1)];
50950 }
50951 else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && ts.every(restType.types, isTupleType)) {
50952 return ts.map(restType.types, function (t) { return expandSignatureParametersWithTupleMembers(t, restIndex_1); });
50953 }
50954 }
50955 return [sig.parameters];
50956 function expandSignatureParametersWithTupleMembers(restType, restIndex) {
50957 var elementTypes = getTypeArguments(restType);
50958 var associatedNames = restType.target.labeledElementDeclarations;
50959 var restParams = ts.map(elementTypes, function (t, i) {
50960 // Lookup the label from the individual tuple passed in before falling back to the signature `rest` parameter name
50961 var tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]);
50962 var name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType);
50963 var flags = restType.target.elementFlags[i];
50964 var checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ :
50965 flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
50966 var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
50967 symbol.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
50968 return symbol;
50969 });
50970 return ts.concatenate(sig.parameters.slice(0, restIndex), restParams);
50971 }
50972 }
50973 function getDefaultConstructSignatures(classType) {
50974 var baseConstructorType = getBaseConstructorTypeOfClass(classType);
50975 var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
50976 if (baseSignatures.length === 0) {
50977 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
50978 }
50979 var baseTypeNode = getBaseTypeNodeOfClass(classType);
50980 var isJavaScript = ts.isInJSFile(baseTypeNode);
50981 var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
50982 var typeArgCount = ts.length(typeArguments);
50983 var result = [];
50984 for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
50985 var baseSig = baseSignatures_1[_i];
50986 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
50987 var typeParamCount = ts.length(baseSig.typeParameters);
50988 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
50989 var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
50990 sig.typeParameters = classType.localTypeParameters;
50991 sig.resolvedReturnType = classType;
50992 result.push(sig);
50993 }
50994 }
50995 return result;
50996 }
50997 function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
50998 for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
50999 var s = signatureList_1[_i];
51000 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
51001 return s;
51002 }
51003 }
51004 }
51005 function findMatchingSignatures(signatureLists, signature, listIndex) {
51006 if (signature.typeParameters) {
51007 // We require an exact match for generic signatures, so we only return signatures from the first
51008 // signature list and only if they have exact matches in the other signature lists.
51009 if (listIndex > 0) {
51010 return undefined;
51011 }
51012 for (var i = 1; i < signatureLists.length; i++) {
51013 if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
51014 return undefined;
51015 }
51016 }
51017 return [signature];
51018 }
51019 var result;
51020 for (var i = 0; i < signatureLists.length; i++) {
51021 // Allow matching non-generic signatures to have excess parameters and different return types.
51022 // Prefer matching this types if possible.
51023 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
51024 if (!match) {
51025 return undefined;
51026 }
51027 result = ts.appendIfUnique(result, match);
51028 }
51029 return result;
51030 }
51031 // The signatures of a union type are those signatures that are present in each of the constituent types.
51032 // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
51033 // parameters and may differ in return types. When signatures differ in return types, the resulting return
51034 // type is the union of the constituent return types.
51035 function getUnionSignatures(signatureLists) {
51036 var result;
51037 var indexWithLengthOverOne;
51038 for (var i = 0; i < signatureLists.length; i++) {
51039 if (signatureLists[i].length === 0)
51040 return ts.emptyArray;
51041 if (signatureLists[i].length > 1) {
51042 indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
51043 }
51044 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
51045 var signature = _a[_i];
51046 // Only process signatures with parameter lists that aren't already in the result list
51047 if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
51048 var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
51049 if (unionSignatures) {
51050 var s = signature;
51051 // Union the result types when more than one signature matches
51052 if (unionSignatures.length > 1) {
51053 var thisParameter = signature.thisParameter;
51054 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
51055 if (firstThisParameterOfUnionSignatures) {
51056 var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
51057 thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
51058 }
51059 s = createUnionSignature(signature, unionSignatures);
51060 s.thisParameter = thisParameter;
51061 }
51062 (result || (result = [])).push(s);
51063 }
51064 }
51065 }
51066 }
51067 if (!ts.length(result) && indexWithLengthOverOne !== -1) {
51068 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
51069 // signature that handles all over them. We only do this when there are overloads in only one constituent.
51070 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
51071 // signatures from the type, whose ordering would be non-obvious)
51072 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
51073 var results = masterList.slice();
51074 var _loop_10 = function (signatures) {
51075 if (signatures !== masterList) {
51076 var signature_1 = signatures[0];
51077 ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
51078 results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
51079 if (!results) {
51080 return "break";
51081 }
51082 }
51083 };
51084 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
51085 var signatures = signatureLists_1[_b];
51086 var state_3 = _loop_10(signatures);
51087 if (state_3 === "break")
51088 break;
51089 }
51090 result = results;
51091 }
51092 return result || ts.emptyArray;
51093 }
51094 function combineUnionThisParam(left, right) {
51095 if (!left || !right) {
51096 return left || right;
51097 }
51098 // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
51099 // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
51100 // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
51101 var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
51102 return createSymbolWithType(left, thisType);
51103 }
51104 function combineUnionParameters(left, right) {
51105 var leftCount = getParameterCount(left);
51106 var rightCount = getParameterCount(right);
51107 var longest = leftCount >= rightCount ? left : right;
51108 var shorter = longest === left ? right : left;
51109 var longestCount = longest === left ? leftCount : rightCount;
51110 var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
51111 var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
51112 var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
51113 for (var i = 0; i < longestCount; i++) {
51114 var longestParamType = tryGetTypeAtPosition(longest, i);
51115 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
51116 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
51117 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
51118 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
51119 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
51120 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
51121 var paramName = leftName === rightName ? leftName :
51122 !leftName ? rightName :
51123 !rightName ? leftName :
51124 undefined;
51125 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
51126 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
51127 params[i] = paramSymbol;
51128 }
51129 if (needsExtraRestElement) {
51130 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
51131 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
51132 params[longestCount] = restParamSymbol;
51133 }
51134 return params;
51135 }
51136 function combineSignaturesOfUnionMembers(left, right) {
51137 var declaration = left.declaration;
51138 var params = combineUnionParameters(left, right);
51139 var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
51140 var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
51141 var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params,
51142 /*resolvedReturnType*/ undefined,
51143 /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 19 /* PropagatingFlags */);
51144 result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
51145 return result;
51146 }
51147 function getUnionIndexInfo(types, kind) {
51148 var indexTypes = [];
51149 var isAnyReadonly = false;
51150 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
51151 var type = types_3[_i];
51152 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
51153 if (!indexInfo) {
51154 return undefined;
51155 }
51156 indexTypes.push(indexInfo.type);
51157 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
51158 }
51159 return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
51160 }
51161 function resolveUnionTypeMembers(type) {
51162 // The members and properties collections are empty for union types. To get all properties of a union
51163 // type use getPropertiesOfType (only the language service uses this).
51164 var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
51165 var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
51166 var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
51167 var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
51168 setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
51169 }
51170 function intersectTypes(type1, type2) {
51171 return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
51172 }
51173 function intersectIndexInfos(info1, info2) {
51174 return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
51175 }
51176 function unionSpreadIndexInfos(info1, info2) {
51177 return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
51178 }
51179 function findMixins(types) {
51180 var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
51181 var mixinFlags = ts.map(types, isMixinConstructorType);
51182 if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
51183 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
51184 mixinFlags[firstMixinIndex] = false;
51185 }
51186 return mixinFlags;
51187 }
51188 function includeMixinType(type, types, mixinFlags, index) {
51189 var mixedTypes = [];
51190 for (var i = 0; i < types.length; i++) {
51191 if (i === index) {
51192 mixedTypes.push(type);
51193 }
51194 else if (mixinFlags[i]) {
51195 mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
51196 }
51197 }
51198 return getIntersectionType(mixedTypes);
51199 }
51200 function resolveIntersectionTypeMembers(type) {
51201 // The members and properties collections are empty for intersection types. To get all properties of an
51202 // intersection type use getPropertiesOfType (only the language service uses this).
51203 var callSignatures;
51204 var constructSignatures;
51205 var stringIndexInfo;
51206 var numberIndexInfo;
51207 var types = type.types;
51208 var mixinFlags = findMixins(types);
51209 var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
51210 var _loop_11 = function (i) {
51211 var t = type.types[i];
51212 // When an intersection type contains mixin constructor types, the construct signatures from
51213 // those types are discarded and their return types are mixed into the return types of all
51214 // other construct signatures in the intersection type. For example, the intersection type
51215 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
51216 // 'new(s: string) => A & B'.
51217 if (!mixinFlags[i]) {
51218 var signatures = getSignaturesOfType(t, 1 /* Construct */);
51219 if (signatures.length && mixinCount > 0) {
51220 signatures = ts.map(signatures, function (s) {
51221 var clone = cloneSignature(s);
51222 clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
51223 return clone;
51224 });
51225 }
51226 constructSignatures = appendSignatures(constructSignatures, signatures);
51227 }
51228 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
51229 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
51230 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
51231 };
51232 for (var i = 0; i < types.length; i++) {
51233 _loop_11(i);
51234 }
51235 setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
51236 }
51237 function appendSignatures(signatures, newSignatures) {
51238 var _loop_12 = function (sig) {
51239 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
51240 signatures = ts.append(signatures, sig);
51241 }
51242 };
51243 for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
51244 var sig = newSignatures_1[_i];
51245 _loop_12(sig);
51246 }
51247 return signatures;
51248 }
51249 /**
51250 * Converts an AnonymousType to a ResolvedType.
51251 */
51252 function resolveAnonymousTypeMembers(type) {
51253 var symbol = getMergedSymbol(type.symbol);
51254 if (type.target) {
51255 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
51256 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
51257 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
51258 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
51259 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
51260 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
51261 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
51262 }
51263 else if (symbol.flags & 2048 /* TypeLiteral */) {
51264 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
51265 var members = getMembersOfSymbol(symbol);
51266 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
51267 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
51268 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
51269 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
51270 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
51271 }
51272 else {
51273 // Combinations of function, class, enum and module
51274 var members = emptySymbols;
51275 var stringIndexInfo = void 0;
51276 if (symbol.exports) {
51277 members = getExportsOfSymbol(symbol);
51278 if (symbol === globalThisSymbol) {
51279 var varsOnly_1 = new ts.Map();
51280 members.forEach(function (p) {
51281 if (!(p.flags & 418 /* BlockScoped */)) {
51282 varsOnly_1.set(p.escapedName, p);
51283 }
51284 });
51285 members = varsOnly_1;
51286 }
51287 }
51288 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
51289 if (symbol.flags & 32 /* Class */) {
51290 var classType = getDeclaredTypeOfClassOrInterface(symbol);
51291 var baseConstructorType = getBaseConstructorTypeOfClass(classType);
51292 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
51293 members = ts.createSymbolTable(getNamedMembers(members));
51294 addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
51295 }
51296 else if (baseConstructorType === anyType) {
51297 stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
51298 }
51299 }
51300 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
51301 ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
51302 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
51303 // We resolve the members before computing the signatures because a signature may use
51304 // typeof with a qualified name expression that circularly references the type we are
51305 // in the process of resolving (see issue #6072). The temporarily empty signature list
51306 // will never be observed because a qualified name can't reference signatures.
51307 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
51308 type.callSignatures = getSignaturesOfSymbol(symbol);
51309 }
51310 // And likewise for construct signatures for classes
51311 if (symbol.flags & 32 /* Class */) {
51312 var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
51313 var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
51314 if (symbol.flags & 16 /* Function */) {
51315 constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
51316 createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */) :
51317 undefined; }));
51318 }
51319 if (!constructSignatures.length) {
51320 constructSignatures = getDefaultConstructSignatures(classType_1);
51321 }
51322 type.constructSignatures = constructSignatures;
51323 }
51324 }
51325 }
51326 function resolveReverseMappedTypeMembers(type) {
51327 var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
51328 var modifiers = getMappedTypeModifiers(type.mappedType);
51329 var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
51330 var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
51331 var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
51332 var members = ts.createSymbolTable();
51333 for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
51334 var prop = _a[_i];
51335 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
51336 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
51337 inferredProp.declarations = prop.declarations;
51338 inferredProp.nameType = getSymbolLinks(prop).nameType;
51339 inferredProp.propertyType = getTypeOfSymbol(prop);
51340 inferredProp.mappedType = type.mappedType;
51341 inferredProp.constraintType = type.constraintType;
51342 members.set(prop.escapedName, inferredProp);
51343 }
51344 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
51345 }
51346 // Return the lower bound of the key type in a mapped type. Intuitively, the lower
51347 // bound includes those keys that are known to always be present, for example because
51348 // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
51349 function getLowerBoundOfKeyType(type) {
51350 if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
51351 return type;
51352 }
51353 if (type.flags & 4194304 /* Index */) {
51354 var t = getApparentType(type.type);
51355 return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
51356 }
51357 if (type.flags & 16777216 /* Conditional */) {
51358 if (type.root.isDistributive) {
51359 var checkType = type.checkType;
51360 var constraint = getLowerBoundOfKeyType(checkType);
51361 if (constraint !== checkType) {
51362 return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
51363 }
51364 }
51365 return type;
51366 }
51367 if (type.flags & 1048576 /* Union */) {
51368 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
51369 }
51370 if (type.flags & 2097152 /* Intersection */) {
51371 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
51372 }
51373 return neverType;
51374 }
51375 /** Resolve the members of a mapped type { [P in K]: T } */
51376 function resolveMappedTypeMembers(type) {
51377 var members = ts.createSymbolTable();
51378 var stringIndexInfo;
51379 var numberIndexInfo;
51380 // Resolve upfront such that recursive references see an empty object type.
51381 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
51382 // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
51383 // and T as the template type.
51384 var typeParameter = getTypeParameterFromMappedType(type);
51385 var constraintType = getConstraintTypeFromMappedType(type);
51386 var templateType = getTemplateTypeFromMappedType(type.target || type);
51387 var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
51388 var templateModifiers = getMappedTypeModifiers(type);
51389 var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
51390 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
51391 // We have a { [P in keyof T]: X }
51392 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
51393 var prop = _a[_i];
51394 addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
51395 }
51396 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
51397 addMemberForKeyType(stringType);
51398 }
51399 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
51400 addMemberForKeyType(numberType);
51401 }
51402 }
51403 else {
51404 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
51405 }
51406 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
51407 function addMemberForKeyType(t) {
51408 // Create a mapper from T to the current iteration type constituent. Then, if the
51409 // mapped type is itself an instantiated type, combine the iteration mapper with the
51410 // instantiation mapper.
51411 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
51412 // If the current iteration type constituent is a string literal type, create a property.
51413 // Otherwise, for type string create a string index signature.
51414 if (isTypeUsableAsPropertyName(t)) {
51415 var propName = getPropertyNameFromType(t);
51416 // String enum members from separate enums with identical values
51417 // are distinct types with the same property name. Make the resulting
51418 // property symbol's name type be the union of those enum member types.
51419 var existingProp = members.get(propName);
51420 if (existingProp) {
51421 existingProp.nameType = getUnionType([existingProp.nameType, t]);
51422 existingProp.mapper = appendTypeMapping(type.mapper, typeParameter, existingProp.nameType);
51423 }
51424 else {
51425 var modifiersProp = getPropertyOfType(modifiersType, propName);
51426 var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
51427 !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
51428 var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
51429 !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
51430 var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
51431 var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
51432 prop.mappedType = type;
51433 if (modifiersProp) {
51434 prop.syntheticOrigin = modifiersProp;
51435 prop.declarations = modifiersProp.declarations;
51436 }
51437 prop.nameType = t;
51438 prop.mapper = templateMapper;
51439 members.set(propName, prop);
51440 }
51441 }
51442 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
51443 var propType = instantiateType(templateType, templateMapper);
51444 if (t.flags & (1 /* Any */ | 4 /* String */)) {
51445 stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
51446 }
51447 else {
51448 numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
51449 }
51450 }
51451 }
51452 }
51453 function getTypeOfMappedSymbol(symbol) {
51454 if (!symbol.type) {
51455 if (!pushTypeResolution(symbol, 0 /* Type */)) {
51456 symbol.mappedType.containsError = true;
51457 return errorType;
51458 }
51459 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
51460 var propType = instantiateType(templateType, symbol.mapper);
51461 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
51462 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
51463 // mode, if the underlying property is optional we remove 'undefined' from the type.
51464 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
51465 symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
51466 propType;
51467 if (!popTypeResolution()) {
51468 error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
51469 type = errorType;
51470 }
51471 symbol.type = type;
51472 symbol.mapper = undefined;
51473 }
51474 return symbol.type;
51475 }
51476 function getTypeParameterFromMappedType(type) {
51477 return type.typeParameter ||
51478 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
51479 }
51480 function getConstraintTypeFromMappedType(type) {
51481 return type.constraintType ||
51482 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
51483 }
51484 function getTemplateTypeFromMappedType(type) {
51485 return type.templateType ||
51486 (type.templateType = type.declaration.type ?
51487 instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
51488 errorType);
51489 }
51490 function getConstraintDeclarationForMappedType(type) {
51491 return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
51492 }
51493 function isMappedTypeWithKeyofConstraintDeclaration(type) {
51494 var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
51495 return constraintDeclaration.kind === 187 /* TypeOperator */ &&
51496 constraintDeclaration.operator === 137 /* KeyOfKeyword */;
51497 }
51498 function getModifiersTypeFromMappedType(type) {
51499 if (!type.modifiersType) {
51500 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
51501 // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
51502 // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
51503 // 'keyof T' to a literal union type and we can't recover T from that type.
51504 type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
51505 }
51506 else {
51507 // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
51508 // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
51509 // the modifiers type is T. Otherwise, the modifiers type is unknown.
51510 var declaredType = getTypeFromMappedTypeNode(type.declaration);
51511 var constraint = getConstraintTypeFromMappedType(declaredType);
51512 var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
51513 type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
51514 }
51515 }
51516 return type.modifiersType;
51517 }
51518 function getMappedTypeModifiers(type) {
51519 var declaration = type.declaration;
51520 return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
51521 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
51522 }
51523 function getMappedTypeOptionality(type) {
51524 var modifiers = getMappedTypeModifiers(type);
51525 return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
51526 }
51527 function getCombinedMappedTypeOptionality(type) {
51528 var optionality = getMappedTypeOptionality(type);
51529 var modifiersType = getModifiersTypeFromMappedType(type);
51530 return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
51531 }
51532 function isPartialMappedType(type) {
51533 return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
51534 }
51535 function isGenericMappedType(type) {
51536 return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
51537 }
51538 function resolveStructuredTypeMembers(type) {
51539 if (!type.members) {
51540 if (type.flags & 524288 /* Object */) {
51541 if (type.objectFlags & 4 /* Reference */) {
51542 resolveTypeReferenceMembers(type);
51543 }
51544 else if (type.objectFlags & 3 /* ClassOrInterface */) {
51545 resolveClassOrInterfaceMembers(type);
51546 }
51547 else if (type.objectFlags & 2048 /* ReverseMapped */) {
51548 resolveReverseMappedTypeMembers(type);
51549 }
51550 else if (type.objectFlags & 16 /* Anonymous */) {
51551 resolveAnonymousTypeMembers(type);
51552 }
51553 else if (type.objectFlags & 32 /* Mapped */) {
51554 resolveMappedTypeMembers(type);
51555 }
51556 }
51557 else if (type.flags & 1048576 /* Union */) {
51558 resolveUnionTypeMembers(type);
51559 }
51560 else if (type.flags & 2097152 /* Intersection */) {
51561 resolveIntersectionTypeMembers(type);
51562 }
51563 }
51564 return type;
51565 }
51566 /** Return properties of an object type or an empty array for other types */
51567 function getPropertiesOfObjectType(type) {
51568 if (type.flags & 524288 /* Object */) {
51569 return resolveStructuredTypeMembers(type).properties;
51570 }
51571 return ts.emptyArray;
51572 }
51573 /** If the given type is an object type and that type has a property by the given name,
51574 * return the symbol for that property. Otherwise return undefined.
51575 */
51576 function getPropertyOfObjectType(type, name) {
51577 if (type.flags & 524288 /* Object */) {
51578 var resolved = resolveStructuredTypeMembers(type);
51579 var symbol = resolved.members.get(name);
51580 if (symbol && symbolIsValue(symbol)) {
51581 return symbol;
51582 }
51583 }
51584 }
51585 function getPropertiesOfUnionOrIntersectionType(type) {
51586 if (!type.resolvedProperties) {
51587 var members = ts.createSymbolTable();
51588 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51589 var current = _a[_i];
51590 for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
51591 var prop = _c[_b];
51592 if (!members.has(prop.escapedName)) {
51593 var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
51594 if (combinedProp) {
51595 members.set(prop.escapedName, combinedProp);
51596 }
51597 }
51598 }
51599 // The properties of a union type are those that are present in all constituent types, so
51600 // we only need to check the properties of the first type without index signature
51601 if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
51602 break;
51603 }
51604 }
51605 type.resolvedProperties = getNamedMembers(members);
51606 }
51607 return type.resolvedProperties;
51608 }
51609 function getPropertiesOfType(type) {
51610 type = getReducedApparentType(type);
51611 return type.flags & 3145728 /* UnionOrIntersection */ ?
51612 getPropertiesOfUnionOrIntersectionType(type) :
51613 getPropertiesOfObjectType(type);
51614 }
51615 function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
51616 var list = obj.properties;
51617 return list.some(function (property) {
51618 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
51619 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
51620 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
51621 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
51622 });
51623 }
51624 function getAllPossiblePropertiesOfTypes(types) {
51625 var unionType = getUnionType(types);
51626 if (!(unionType.flags & 1048576 /* Union */)) {
51627 return getAugmentedPropertiesOfType(unionType);
51628 }
51629 var props = ts.createSymbolTable();
51630 for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
51631 var memberType = types_4[_i];
51632 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
51633 var escapedName = _b[_a].escapedName;
51634 if (!props.has(escapedName)) {
51635 var prop = createUnionOrIntersectionProperty(unionType, escapedName);
51636 // May be undefined if the property is private
51637 if (prop)
51638 props.set(escapedName, prop);
51639 }
51640 }
51641 }
51642 return ts.arrayFrom(props.values());
51643 }
51644 function getConstraintOfType(type) {
51645 return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
51646 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
51647 type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
51648 getBaseConstraintOfType(type);
51649 }
51650 function getConstraintOfTypeParameter(typeParameter) {
51651 return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
51652 }
51653 function getConstraintOfIndexedAccess(type) {
51654 return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
51655 }
51656 function getSimplifiedTypeOrConstraint(type) {
51657 var simplified = getSimplifiedType(type, /*writing*/ false);
51658 return simplified !== type ? simplified : getConstraintOfType(type);
51659 }
51660 function getConstraintFromIndexedAccess(type) {
51661 var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
51662 if (indexConstraint && indexConstraint !== type.indexType) {
51663 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
51664 if (indexedAccess) {
51665 return indexedAccess;
51666 }
51667 }
51668 var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
51669 if (objectConstraint && objectConstraint !== type.objectType) {
51670 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
51671 }
51672 return undefined;
51673 }
51674 function getDefaultConstraintOfConditionalType(type) {
51675 if (!type.resolvedDefaultConstraint) {
51676 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
51677 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
51678 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
51679 // in effect treating `any` like `never` rather than `unknown` in this location.
51680 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
51681 var falseConstraint = getFalseTypeFromConditionalType(type);
51682 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
51683 }
51684 return type.resolvedDefaultConstraint;
51685 }
51686 function getConstraintOfDistributiveConditionalType(type) {
51687 // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
51688 // type parameter. If so, create an instantiation of the conditional type where T is replaced
51689 // with its constraint. We do this because if the constraint is a union type it will be distributed
51690 // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
51691 // removes 'undefined' from T.
51692 // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
51693 // as the constraint for all type params (check type included) have been replace with `unknown`, which
51694 // is going to produce even more false positive/negative results than the distribute constraint already does.
51695 // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
51696 // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
51697 // likely doesn't need to exist.
51698 if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
51699 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
51700 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
51701 if (constraint && constraint !== type.checkType) {
51702 var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
51703 if (!(instantiated.flags & 131072 /* Never */)) {
51704 return instantiated;
51705 }
51706 }
51707 }
51708 return undefined;
51709 }
51710 function getConstraintFromConditionalType(type) {
51711 return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
51712 }
51713 function getConstraintOfConditionalType(type) {
51714 return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
51715 }
51716 function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
51717 var constraints;
51718 var hasDisjointDomainType = false;
51719 for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
51720 var t = types_5[_i];
51721 if (t.flags & 63176704 /* Instantiable */) {
51722 // We keep following constraints as long as we have an instantiable type that is known
51723 // not to be circular or infinite (hence we stop on index access types).
51724 var constraint = getConstraintOfType(t);
51725 while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
51726 constraint = getConstraintOfType(constraint);
51727 }
51728 if (constraint) {
51729 constraints = ts.append(constraints, constraint);
51730 if (targetIsUnion) {
51731 constraints = ts.append(constraints, t);
51732 }
51733 }
51734 }
51735 else if (t.flags & 67238908 /* DisjointDomains */) {
51736 hasDisjointDomainType = true;
51737 }
51738 }
51739 // If the target is a union type or if we are intersecting with types belonging to one of the
51740 // disjoint domains, we may end up producing a constraint that hasn't been examined before.
51741 if (constraints && (targetIsUnion || hasDisjointDomainType)) {
51742 if (hasDisjointDomainType) {
51743 // We add any types belong to one of the disjoint domains because they might cause the final
51744 // intersection operation to reduce the union constraints.
51745 for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
51746 var t = types_6[_a];
51747 if (t.flags & 67238908 /* DisjointDomains */) {
51748 constraints = ts.append(constraints, t);
51749 }
51750 }
51751 }
51752 return getIntersectionType(constraints);
51753 }
51754 return undefined;
51755 }
51756 function getBaseConstraintOfType(type) {
51757 if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
51758 var constraint = getResolvedBaseConstraint(type);
51759 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
51760 }
51761 return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
51762 }
51763 /**
51764 * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
51765 * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
51766 */
51767 function getBaseConstraintOrType(type) {
51768 return getBaseConstraintOfType(type) || type;
51769 }
51770 function hasNonCircularBaseConstraint(type) {
51771 return getResolvedBaseConstraint(type) !== circularConstraintType;
51772 }
51773 /**
51774 * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
51775 * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
51776 * circularly references the type variable.
51777 */
51778 function getResolvedBaseConstraint(type) {
51779 var nonTerminating = false;
51780 return type.resolvedBaseConstraint ||
51781 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
51782 function getImmediateBaseConstraint(t) {
51783 if (!t.immediateBaseConstraint) {
51784 if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
51785 return circularConstraintType;
51786 }
51787 if (constraintDepth >= 50) {
51788 // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
51789 // very high likelihood we're dealing with an infinite generic type that perpetually generates
51790 // new type identities as we descend into it. We stop the recursion here and mark this type
51791 // and the outer types as having circular constraints.
51792 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
51793 nonTerminating = true;
51794 return t.immediateBaseConstraint = noConstraintType;
51795 }
51796 constraintDepth++;
51797 var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
51798 constraintDepth--;
51799 if (!popTypeResolution()) {
51800 if (t.flags & 262144 /* TypeParameter */) {
51801 var errorNode = getConstraintDeclaration(t);
51802 if (errorNode) {
51803 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
51804 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
51805 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
51806 }
51807 }
51808 }
51809 result = circularConstraintType;
51810 }
51811 if (nonTerminating) {
51812 result = circularConstraintType;
51813 }
51814 t.immediateBaseConstraint = result || noConstraintType;
51815 }
51816 return t.immediateBaseConstraint;
51817 }
51818 function getBaseConstraint(t) {
51819 var c = getImmediateBaseConstraint(t);
51820 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
51821 }
51822 function computeBaseConstraint(t) {
51823 if (t.flags & 262144 /* TypeParameter */) {
51824 var constraint = getConstraintFromTypeParameter(t);
51825 return t.isThisType || !constraint ?
51826 constraint :
51827 getBaseConstraint(constraint);
51828 }
51829 if (t.flags & 3145728 /* UnionOrIntersection */) {
51830 var types = t.types;
51831 var baseTypes = [];
51832 for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
51833 var type_3 = types_7[_i];
51834 var baseType = getBaseConstraint(type_3);
51835 if (baseType) {
51836 baseTypes.push(baseType);
51837 }
51838 }
51839 return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
51840 t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
51841 undefined;
51842 }
51843 if (t.flags & 4194304 /* Index */) {
51844 return keyofConstraintType;
51845 }
51846 if (t.flags & 8388608 /* IndexedAccess */) {
51847 var baseObjectType = getBaseConstraint(t.objectType);
51848 var baseIndexType = getBaseConstraint(t.indexType);
51849 var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
51850 return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
51851 }
51852 if (t.flags & 16777216 /* Conditional */) {
51853 var constraint = getConstraintFromConditionalType(t);
51854 constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
51855 var result = constraint && getBaseConstraint(constraint);
51856 constraintDepth--;
51857 return result;
51858 }
51859 if (t.flags & 33554432 /* Substitution */) {
51860 return getBaseConstraint(t.substitute);
51861 }
51862 return t;
51863 }
51864 }
51865 function getApparentTypeOfIntersectionType(type) {
51866 return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
51867 }
51868 function getResolvedTypeParameterDefault(typeParameter) {
51869 if (!typeParameter.default) {
51870 if (typeParameter.target) {
51871 var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
51872 typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
51873 }
51874 else {
51875 // To block recursion, set the initial value to the resolvingDefaultType.
51876 typeParameter.default = resolvingDefaultType;
51877 var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
51878 var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
51879 if (typeParameter.default === resolvingDefaultType) {
51880 // If we have not been called recursively, set the correct default type.
51881 typeParameter.default = defaultType;
51882 }
51883 }
51884 }
51885 else if (typeParameter.default === resolvingDefaultType) {
51886 // If we are called recursively for this type parameter, mark the default as circular.
51887 typeParameter.default = circularConstraintType;
51888 }
51889 return typeParameter.default;
51890 }
51891 /**
51892 * Gets the default type for a type parameter.
51893 *
51894 * If the type parameter is the result of an instantiation, this gets the instantiated
51895 * default type of its target. If the type parameter has no default type or the default is
51896 * circular, `undefined` is returned.
51897 */
51898 function getDefaultFromTypeParameter(typeParameter) {
51899 var defaultType = getResolvedTypeParameterDefault(typeParameter);
51900 return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
51901 }
51902 function hasNonCircularTypeParameterDefault(typeParameter) {
51903 return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
51904 }
51905 /**
51906 * Indicates whether the declaration of a typeParameter has a default type.
51907 */
51908 function hasTypeParameterDefault(typeParameter) {
51909 return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
51910 }
51911 function getApparentTypeOfMappedType(type) {
51912 return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
51913 }
51914 function getResolvedApparentTypeOfMappedType(type) {
51915 var typeVariable = getHomomorphicTypeVariable(type);
51916 if (typeVariable) {
51917 var constraint = getConstraintOfTypeParameter(typeVariable);
51918 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
51919 return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
51920 }
51921 }
51922 return type;
51923 }
51924 /**
51925 * For a type parameter, return the base constraint of the type parameter. For the string, number,
51926 * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
51927 * type itself.
51928 */
51929 function getApparentType(type) {
51930 var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
51931 return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
51932 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
51933 t.flags & 132 /* StringLike */ ? globalStringType :
51934 t.flags & 296 /* NumberLike */ ? globalNumberType :
51935 t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
51936 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
51937 t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
51938 t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
51939 t.flags & 4194304 /* Index */ ? keyofConstraintType :
51940 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
51941 t;
51942 }
51943 function getReducedApparentType(type) {
51944 // Since getApparentType may return a non-reduced union or intersection type, we need to perform
51945 // type reduction both before and after obtaining the apparent type. For example, given a type parameter
51946 // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
51947 // that type may need further reduction to remove empty intersections.
51948 return getReducedType(getApparentType(getReducedType(type)));
51949 }
51950 function createUnionOrIntersectionProperty(containingType, name) {
51951 var singleProp;
51952 var propSet;
51953 var indexTypes;
51954 var isUnion = containingType.flags & 1048576 /* Union */;
51955 // Flags we want to propagate to the result if they exist in all source symbols
51956 var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
51957 var syntheticFlag = 4 /* SyntheticMethod */;
51958 var checkFlags = 0;
51959 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
51960 var current = _a[_i];
51961 var type = getApparentType(current);
51962 if (!(type === errorType || type.flags & 131072 /* Never */)) {
51963 var prop = getPropertyOfType(type, name);
51964 var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
51965 if (prop) {
51966 if (isUnion) {
51967 optionalFlag |= (prop.flags & 16777216 /* Optional */);
51968 }
51969 else {
51970 optionalFlag &= prop.flags;
51971 }
51972 if (!singleProp) {
51973 singleProp = prop;
51974 }
51975 else if (prop !== singleProp) {
51976 if (!propSet) {
51977 propSet = new ts.Map();
51978 propSet.set(getSymbolId(singleProp), singleProp);
51979 }
51980 var id = getSymbolId(prop);
51981 if (!propSet.has(id)) {
51982 propSet.set(id, prop);
51983 }
51984 }
51985 checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
51986 (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
51987 (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
51988 (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
51989 (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
51990 if (!isPrototypeProperty(prop)) {
51991 syntheticFlag = 2 /* SyntheticProperty */;
51992 }
51993 }
51994 else if (isUnion) {
51995 var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
51996 if (indexInfo) {
51997 checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
51998 indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
51999 }
52000 else if (isObjectLiteralType(type)) {
52001 checkFlags |= 32 /* WritePartial */;
52002 indexTypes = ts.append(indexTypes, undefinedType);
52003 }
52004 else {
52005 checkFlags |= 16 /* ReadPartial */;
52006 }
52007 }
52008 }
52009 }
52010 if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
52011 // No property was found, or, in a union, a property has a private or protected declaration in one
52012 // constituent, but is missing or has a different declaration in another constituent.
52013 return undefined;
52014 }
52015 if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
52016 return singleProp;
52017 }
52018 var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
52019 var declarations;
52020 var firstType;
52021 var nameType;
52022 var propTypes = [];
52023 var firstValueDeclaration;
52024 var hasNonUniformValueDeclaration = false;
52025 for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
52026 var prop = props_1[_b];
52027 if (!firstValueDeclaration) {
52028 firstValueDeclaration = prop.valueDeclaration;
52029 }
52030 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
52031 hasNonUniformValueDeclaration = true;
52032 }
52033 declarations = ts.addRange(declarations, prop.declarations);
52034 var type = getTypeOfSymbol(prop);
52035 if (!firstType) {
52036 firstType = type;
52037 nameType = getSymbolLinks(prop).nameType;
52038 }
52039 else if (type !== firstType) {
52040 checkFlags |= 64 /* HasNonUniformType */;
52041 }
52042 if (isLiteralType(type)) {
52043 checkFlags |= 128 /* HasLiteralType */;
52044 }
52045 if (type.flags & 131072 /* Never */) {
52046 checkFlags |= 131072 /* HasNeverType */;
52047 }
52048 propTypes.push(type);
52049 }
52050 ts.addRange(propTypes, indexTypes);
52051 var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
52052 result.containingType = containingType;
52053 if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
52054 result.valueDeclaration = firstValueDeclaration;
52055 // Inherit information about parent type.
52056 if (firstValueDeclaration.symbol.parent) {
52057 result.parent = firstValueDeclaration.symbol.parent;
52058 }
52059 }
52060 result.declarations = declarations;
52061 result.nameType = nameType;
52062 if (propTypes.length > 2) {
52063 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
52064 result.checkFlags |= 65536 /* DeferredType */;
52065 result.deferralParent = containingType;
52066 result.deferralConstituents = propTypes;
52067 }
52068 else {
52069 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
52070 }
52071 return result;
52072 }
52073 // Return the symbol for a given property in a union or intersection type, or undefined if the property
52074 // does not exist in any constituent type. Note that the returned property may only be present in some
52075 // constituents, in which case the isPartial flag is set when the containing type is union type. We need
52076 // these partial properties when identifying discriminant properties, but otherwise they are filtered out
52077 // and do not appear to be present in the union type.
52078 function getUnionOrIntersectionProperty(type, name) {
52079 var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
52080 var property = properties.get(name);
52081 if (!property) {
52082 property = createUnionOrIntersectionProperty(type, name);
52083 if (property) {
52084 properties.set(name, property);
52085 }
52086 }
52087 return property;
52088 }
52089 function getPropertyOfUnionOrIntersectionType(type, name) {
52090 var property = getUnionOrIntersectionProperty(type, name);
52091 // We need to filter out partial properties in union types
52092 return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
52093 }
52094 /**
52095 * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
52096 * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
52097 * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
52098 * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
52099 */
52100 function getReducedType(type) {
52101 if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
52102 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
52103 }
52104 else if (type.flags & 2097152 /* Intersection */) {
52105 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
52106 type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
52107 (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
52108 }
52109 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
52110 }
52111 return type;
52112 }
52113 function getReducedUnionType(unionType) {
52114 var reducedTypes = ts.sameMap(unionType.types, getReducedType);
52115 if (reducedTypes === unionType.types) {
52116 return unionType;
52117 }
52118 var reduced = getUnionType(reducedTypes);
52119 if (reduced.flags & 1048576 /* Union */) {
52120 reduced.resolvedReducedType = reduced;
52121 }
52122 return reduced;
52123 }
52124 function isNeverReducedProperty(prop) {
52125 return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
52126 }
52127 function isDiscriminantWithNeverType(prop) {
52128 // Return true for a synthetic non-optional property with non-uniform types, where at least one is
52129 // a literal type and none is never, that reduces to never.
52130 return !(prop.flags & 16777216 /* Optional */) &&
52131 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
52132 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
52133 }
52134 function isConflictingPrivateProperty(prop) {
52135 // Return true for a synthetic property with multiple declarations, at least one of which is private.
52136 return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
52137 }
52138 function elaborateNeverIntersection(errorInfo, type) {
52139 if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
52140 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
52141 if (neverProp) {
52142 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));
52143 }
52144 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
52145 if (privateProp) {
52146 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));
52147 }
52148 }
52149 return errorInfo;
52150 }
52151 /**
52152 * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
52153 * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
52154 * Object and Function as appropriate.
52155 *
52156 * @param type a type to look up property from
52157 * @param name a name of property to look up in a given type
52158 */
52159 function getPropertyOfType(type, name) {
52160 type = getReducedApparentType(type);
52161 if (type.flags & 524288 /* Object */) {
52162 var resolved = resolveStructuredTypeMembers(type);
52163 var symbol = resolved.members.get(name);
52164 if (symbol && symbolIsValue(symbol)) {
52165 return symbol;
52166 }
52167 var functionType = resolved === anyFunctionType ? globalFunctionType :
52168 resolved.callSignatures.length ? globalCallableFunctionType :
52169 resolved.constructSignatures.length ? globalNewableFunctionType :
52170 undefined;
52171 if (functionType) {
52172 var symbol_1 = getPropertyOfObjectType(functionType, name);
52173 if (symbol_1) {
52174 return symbol_1;
52175 }
52176 }
52177 return getPropertyOfObjectType(globalObjectType, name);
52178 }
52179 if (type.flags & 3145728 /* UnionOrIntersection */) {
52180 return getPropertyOfUnionOrIntersectionType(type, name);
52181 }
52182 return undefined;
52183 }
52184 function getSignaturesOfStructuredType(type, kind) {
52185 if (type.flags & 3670016 /* StructuredType */) {
52186 var resolved = resolveStructuredTypeMembers(type);
52187 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
52188 }
52189 return ts.emptyArray;
52190 }
52191 /**
52192 * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
52193 * maps primitive types and type parameters are to their apparent types.
52194 */
52195 function getSignaturesOfType(type, kind) {
52196 return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
52197 }
52198 function getIndexInfoOfStructuredType(type, kind) {
52199 if (type.flags & 3670016 /* StructuredType */) {
52200 var resolved = resolveStructuredTypeMembers(type);
52201 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
52202 }
52203 }
52204 function getIndexTypeOfStructuredType(type, kind) {
52205 var info = getIndexInfoOfStructuredType(type, kind);
52206 return info && info.type;
52207 }
52208 // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
52209 // maps primitive types and type parameters are to their apparent types.
52210 function getIndexInfoOfType(type, kind) {
52211 return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
52212 }
52213 // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
52214 // maps primitive types and type parameters are to their apparent types.
52215 function getIndexTypeOfType(type, kind) {
52216 return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
52217 }
52218 function getImplicitIndexTypeOfType(type, kind) {
52219 if (isObjectTypeWithInferableIndex(type)) {
52220 var propTypes = [];
52221 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
52222 var prop = _a[_i];
52223 if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
52224 propTypes.push(getTypeOfSymbol(prop));
52225 }
52226 }
52227 if (kind === 0 /* String */) {
52228 ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
52229 }
52230 if (propTypes.length) {
52231 return getUnionType(propTypes);
52232 }
52233 }
52234 return undefined;
52235 }
52236 // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
52237 // type checking functions).
52238 function getTypeParametersFromDeclaration(declaration) {
52239 var result;
52240 for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
52241 var node = _a[_i];
52242 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
52243 }
52244 return result;
52245 }
52246 function symbolsToArray(symbols) {
52247 var result = [];
52248 symbols.forEach(function (symbol, id) {
52249 if (!isReservedMemberName(id)) {
52250 result.push(symbol);
52251 }
52252 });
52253 return result;
52254 }
52255 function isJSDocOptionalParameter(node) {
52256 return ts.isInJSFile(node) && (
52257 // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
52258 node.type && node.type.kind === 303 /* JSDocOptionalType */
52259 || ts.getJSDocParameterTags(node).some(function (_a) {
52260 var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
52261 return isBracketed || !!typeExpression && typeExpression.type.kind === 303 /* JSDocOptionalType */;
52262 }));
52263 }
52264 function tryFindAmbientModule(moduleName, withAugmentations) {
52265 if (ts.isExternalModuleNameRelative(moduleName)) {
52266 return undefined;
52267 }
52268 var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
52269 // merged symbol is module declaration symbol combined with all augmentations
52270 return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
52271 }
52272 function isOptionalParameter(node) {
52273 if (ts.hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isJSDocOptionalParameter(node)) {
52274 return true;
52275 }
52276 if (node.initializer) {
52277 var signature = getSignatureFromDeclaration(node.parent);
52278 var parameterIndex = node.parent.parameters.indexOf(node);
52279 ts.Debug.assert(parameterIndex >= 0);
52280 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
52281 }
52282 var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
52283 if (iife) {
52284 return !node.type &&
52285 !node.dotDotDotToken &&
52286 node.parent.parameters.indexOf(node) >= iife.arguments.length;
52287 }
52288 return false;
52289 }
52290 function isOptionalJSDocPropertyLikeTag(node) {
52291 if (!ts.isJSDocPropertyLikeTag(node)) {
52292 return false;
52293 }
52294 var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
52295 return isBracketed || !!typeExpression && typeExpression.type.kind === 303 /* JSDocOptionalType */;
52296 }
52297 function createTypePredicate(kind, parameterName, parameterIndex, type) {
52298 return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
52299 }
52300 /**
52301 * Gets the minimum number of type arguments needed to satisfy all non-optional type
52302 * parameters.
52303 */
52304 function getMinTypeArgumentCount(typeParameters) {
52305 var minTypeArgumentCount = 0;
52306 if (typeParameters) {
52307 for (var i = 0; i < typeParameters.length; i++) {
52308 if (!hasTypeParameterDefault(typeParameters[i])) {
52309 minTypeArgumentCount = i + 1;
52310 }
52311 }
52312 }
52313 return minTypeArgumentCount;
52314 }
52315 function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
52316 var numTypeParameters = ts.length(typeParameters);
52317 if (!numTypeParameters) {
52318 return [];
52319 }
52320 var numTypeArguments = ts.length(typeArguments);
52321 if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
52322 var result = typeArguments ? typeArguments.slice() : [];
52323 // Map invalid forward references in default types to the error type
52324 for (var i = numTypeArguments; i < numTypeParameters; i++) {
52325 result[i] = errorType;
52326 }
52327 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
52328 for (var i = numTypeArguments; i < numTypeParameters; i++) {
52329 var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
52330 if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
52331 defaultType = anyType;
52332 }
52333 result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
52334 }
52335 result.length = typeParameters.length;
52336 return result;
52337 }
52338 return typeArguments && typeArguments.slice();
52339 }
52340 function getSignatureFromDeclaration(declaration) {
52341 var links = getNodeLinks(declaration);
52342 if (!links.resolvedSignature) {
52343 var parameters = [];
52344 var flags = 0 /* None */;
52345 var minArgumentCount = 0;
52346 var thisParameter = void 0;
52347 var hasThisParameter = false;
52348 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
52349 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
52350 var isUntypedSignatureInJSFile = !iife &&
52351 ts.isInJSFile(declaration) &&
52352 ts.isValueSignatureDeclaration(declaration) &&
52353 !ts.hasJSDocParameterTags(declaration) &&
52354 !ts.getJSDocType(declaration);
52355 if (isUntypedSignatureInJSFile) {
52356 flags |= 16 /* IsUntypedSignatureInJSFile */;
52357 }
52358 // If this is a JSDoc construct signature, then skip the first parameter in the
52359 // parameter list. The first parameter represents the return type of the construct
52360 // signature.
52361 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
52362 var param = declaration.parameters[i];
52363 var paramSymbol = param.symbol;
52364 var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
52365 // Include parameter symbol instead of property symbol in the signature
52366 if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
52367 var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
52368 paramSymbol = resolvedSymbol;
52369 }
52370 if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
52371 hasThisParameter = true;
52372 thisParameter = param.symbol;
52373 }
52374 else {
52375 parameters.push(paramSymbol);
52376 }
52377 if (type && type.kind === 190 /* LiteralType */) {
52378 flags |= 2 /* HasLiteralTypes */;
52379 }
52380 // Record a new minimum argument count if this is not an optional parameter
52381 var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) ||
52382 param.initializer || param.questionToken || param.dotDotDotToken ||
52383 iife && parameters.length > iife.arguments.length && !type ||
52384 isJSDocOptionalParameter(param);
52385 if (!isOptionalParameter_1) {
52386 minArgumentCount = parameters.length;
52387 }
52388 }
52389 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
52390 if ((declaration.kind === 166 /* GetAccessor */ || declaration.kind === 167 /* SetAccessor */) &&
52391 !hasNonBindableDynamicName(declaration) &&
52392 (!hasThisParameter || !thisParameter)) {
52393 var otherKind = declaration.kind === 166 /* GetAccessor */ ? 167 /* SetAccessor */ : 166 /* GetAccessor */;
52394 var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
52395 if (other) {
52396 thisParameter = getAnnotatedAccessorThisParameter(other);
52397 }
52398 }
52399 var classType = declaration.kind === 165 /* Constructor */ ?
52400 getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
52401 : undefined;
52402 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
52403 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
52404 flags |= 1 /* HasRestParameter */;
52405 }
52406 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters,
52407 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
52408 }
52409 return links.resolvedSignature;
52410 }
52411 /**
52412 * A JS function gets a synthetic rest parameter if it references `arguments` AND:
52413 * 1. It has no parameters but at least one `@param` with a type that starts with `...`
52414 * OR
52415 * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
52416 */
52417 function maybeAddJsSyntheticRestParameter(declaration, parameters) {
52418 if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
52419 return false;
52420 }
52421 var lastParam = ts.lastOrUndefined(declaration.parameters);
52422 var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
52423 var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
52424 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
52425 });
52426 var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
52427 syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
52428 if (lastParamVariadicType) {
52429 // Replace the last parameter with a rest parameter.
52430 parameters.pop();
52431 }
52432 parameters.push(syntheticArgsSymbol);
52433 return true;
52434 }
52435 function getSignatureOfTypeTag(node) {
52436 // should be attached to a function declaration or expression
52437 if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
52438 return undefined;
52439 var typeTag = ts.getJSDocTypeTag(node);
52440 var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
52441 return signature && getErasedSignature(signature);
52442 }
52443 function getReturnTypeOfTypeTag(node) {
52444 var signature = getSignatureOfTypeTag(node);
52445 return signature && getReturnTypeOfSignature(signature);
52446 }
52447 function containsArgumentsReference(declaration) {
52448 var links = getNodeLinks(declaration);
52449 if (links.containsArgumentsReference === undefined) {
52450 if (links.flags & 8192 /* CaptureArguments */) {
52451 links.containsArgumentsReference = true;
52452 }
52453 else {
52454 links.containsArgumentsReference = traverse(declaration.body);
52455 }
52456 }
52457 return links.containsArgumentsReference;
52458 function traverse(node) {
52459 if (!node)
52460 return false;
52461 switch (node.kind) {
52462 case 78 /* Identifier */:
52463 return node.escapedText === "arguments" && ts.isExpressionNode(node);
52464 case 162 /* PropertyDeclaration */:
52465 case 164 /* MethodDeclaration */:
52466 case 166 /* GetAccessor */:
52467 case 167 /* SetAccessor */:
52468 return node.name.kind === 157 /* ComputedPropertyName */
52469 && traverse(node.name);
52470 default:
52471 return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
52472 }
52473 }
52474 }
52475 function getSignaturesOfSymbol(symbol) {
52476 if (!symbol)
52477 return ts.emptyArray;
52478 var result = [];
52479 for (var i = 0; i < symbol.declarations.length; i++) {
52480 var decl = symbol.declarations[i];
52481 if (!ts.isFunctionLike(decl))
52482 continue;
52483 // Don't include signature if node is the implementation of an overloaded function. A node is considered
52484 // an implementation node if it has a body and the previous node is of the same kind and immediately
52485 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
52486 if (i > 0 && decl.body) {
52487 var previous = symbol.declarations[i - 1];
52488 if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
52489 continue;
52490 }
52491 }
52492 result.push(getSignatureFromDeclaration(decl));
52493 }
52494 return result;
52495 }
52496 function resolveExternalModuleTypeByLiteral(name) {
52497 var moduleSym = resolveExternalModuleName(name, name);
52498 if (moduleSym) {
52499 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
52500 if (resolvedModuleSymbol) {
52501 return getTypeOfSymbol(resolvedModuleSymbol);
52502 }
52503 }
52504 return anyType;
52505 }
52506 function getThisTypeOfSignature(signature) {
52507 if (signature.thisParameter) {
52508 return getTypeOfSymbol(signature.thisParameter);
52509 }
52510 }
52511 function getTypePredicateOfSignature(signature) {
52512 if (!signature.resolvedTypePredicate) {
52513 if (signature.target) {
52514 var targetTypePredicate = getTypePredicateOfSignature(signature.target);
52515 signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
52516 }
52517 else if (signature.unionSignatures) {
52518 signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
52519 }
52520 else {
52521 var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
52522 var jsdocPredicate = void 0;
52523 if (!type && ts.isInJSFile(signature.declaration)) {
52524 var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
52525 if (jsdocSignature && signature !== jsdocSignature) {
52526 jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
52527 }
52528 }
52529 signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
52530 createTypePredicateFromTypePredicateNode(type, signature) :
52531 jsdocPredicate || noTypePredicate;
52532 }
52533 ts.Debug.assert(!!signature.resolvedTypePredicate);
52534 }
52535 return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
52536 }
52537 function createTypePredicateFromTypePredicateNode(node, signature) {
52538 var parameterName = node.parameterName;
52539 var type = node.type && getTypeFromTypeNode(node.type);
52540 return parameterName.kind === 186 /* ThisType */ ?
52541 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
52542 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
52543 }
52544 function getReturnTypeOfSignature(signature) {
52545 if (!signature.resolvedReturnType) {
52546 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
52547 return errorType;
52548 }
52549 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
52550 signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
52551 getReturnTypeFromAnnotation(signature.declaration) ||
52552 (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
52553 if (signature.flags & 4 /* IsInnerCallChain */) {
52554 type = addOptionalTypeMarker(type);
52555 }
52556 else if (signature.flags & 8 /* IsOuterCallChain */) {
52557 type = getOptionalType(type);
52558 }
52559 if (!popTypeResolution()) {
52560 if (signature.declaration) {
52561 var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
52562 if (typeNode) {
52563 error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
52564 }
52565 else if (noImplicitAny) {
52566 var declaration = signature.declaration;
52567 var name = ts.getNameOfDeclaration(declaration);
52568 if (name) {
52569 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));
52570 }
52571 else {
52572 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);
52573 }
52574 }
52575 }
52576 type = anyType;
52577 }
52578 signature.resolvedReturnType = type;
52579 }
52580 return signature.resolvedReturnType;
52581 }
52582 function getReturnTypeFromAnnotation(declaration) {
52583 if (declaration.kind === 165 /* Constructor */) {
52584 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
52585 }
52586 if (ts.isJSDocConstructSignature(declaration)) {
52587 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
52588 }
52589 var typeNode = ts.getEffectiveReturnTypeNode(declaration);
52590 if (typeNode) {
52591 return getTypeFromTypeNode(typeNode);
52592 }
52593 if (declaration.kind === 166 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
52594 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
52595 if (jsDocType) {
52596 return jsDocType;
52597 }
52598 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 167 /* SetAccessor */);
52599 var setterType = getAnnotatedAccessorType(setter);
52600 if (setterType) {
52601 return setterType;
52602 }
52603 }
52604 return getReturnTypeOfTypeTag(declaration);
52605 }
52606 function isResolvingReturnTypeOfSignature(signature) {
52607 return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
52608 }
52609 function getRestTypeOfSignature(signature) {
52610 return tryGetRestTypeOfSignature(signature) || anyType;
52611 }
52612 function tryGetRestTypeOfSignature(signature) {
52613 if (signatureHasRestParameter(signature)) {
52614 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
52615 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
52616 return restType && getIndexTypeOfType(restType, 1 /* Number */);
52617 }
52618 return undefined;
52619 }
52620 function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
52621 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
52622 if (inferredTypeParameters) {
52623 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
52624 if (returnSignature) {
52625 var newReturnSignature = cloneSignature(returnSignature);
52626 newReturnSignature.typeParameters = inferredTypeParameters;
52627 var newInstantiatedSignature = cloneSignature(instantiatedSignature);
52628 newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
52629 return newInstantiatedSignature;
52630 }
52631 }
52632 return instantiatedSignature;
52633 }
52634 function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
52635 var instantiations = signature.instantiations || (signature.instantiations = new ts.Map());
52636 var id = getTypeListId(typeArguments);
52637 var instantiation = instantiations.get(id);
52638 if (!instantiation) {
52639 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
52640 }
52641 return instantiation;
52642 }
52643 function createSignatureInstantiation(signature, typeArguments) {
52644 return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
52645 }
52646 function createSignatureTypeMapper(signature, typeArguments) {
52647 return createTypeMapper(signature.typeParameters, typeArguments);
52648 }
52649 function getErasedSignature(signature) {
52650 return signature.typeParameters ?
52651 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
52652 signature;
52653 }
52654 function createErasedSignature(signature) {
52655 // Create an instantiation of the signature where all type arguments are the any type.
52656 return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
52657 }
52658 function getCanonicalSignature(signature) {
52659 return signature.typeParameters ?
52660 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
52661 signature;
52662 }
52663 function createCanonicalSignature(signature) {
52664 // Create an instantiation of the signature where each unconstrained type parameter is replaced with
52665 // its original. When a generic class or interface is instantiated, each generic method in the class or
52666 // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
52667 // where different generations of the same type parameter are in scope). This leads to a lot of new type
52668 // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
52669 // that uses the original type identities for all unconstrained type parameters.
52670 return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
52671 }
52672 function getBaseSignature(signature) {
52673 var typeParameters = signature.typeParameters;
52674 if (typeParameters) {
52675 var typeEraser_1 = createTypeEraser(typeParameters);
52676 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
52677 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
52678 }
52679 return signature;
52680 }
52681 function getOrCreateTypeFromSignature(signature) {
52682 // There are two ways to declare a construct signature, one is by declaring a class constructor
52683 // using the constructor keyword, and the other is declaring a bare construct signature in an
52684 // object type literal or interface (using the new keyword). Each way of declaring a constructor
52685 // will result in a different declaration kind.
52686 if (!signature.isolatedSignatureType) {
52687 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
52688 var isConstructor = kind === 165 /* Constructor */ || kind === 169 /* ConstructSignature */ || kind === 174 /* ConstructorType */;
52689 var type = createObjectType(16 /* Anonymous */);
52690 type.members = emptySymbols;
52691 type.properties = ts.emptyArray;
52692 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
52693 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
52694 signature.isolatedSignatureType = type;
52695 }
52696 return signature.isolatedSignatureType;
52697 }
52698 function getIndexSymbol(symbol) {
52699 return symbol.members.get("__index" /* Index */);
52700 }
52701 function getIndexDeclarationOfSymbol(symbol, kind) {
52702 var syntaxKind = kind === 1 /* Number */ ? 143 /* NumberKeyword */ : 146 /* StringKeyword */;
52703 var indexSymbol = getIndexSymbol(symbol);
52704 if (indexSymbol) {
52705 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
52706 var decl = _a[_i];
52707 var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
52708 if (node.parameters.length === 1) {
52709 var parameter = node.parameters[0];
52710 if (parameter.type && parameter.type.kind === syntaxKind) {
52711 return node;
52712 }
52713 }
52714 }
52715 }
52716 return undefined;
52717 }
52718 function createIndexInfo(type, isReadonly, declaration) {
52719 return { type: type, isReadonly: isReadonly, declaration: declaration };
52720 }
52721 function getIndexInfoOfSymbol(symbol, kind) {
52722 var declaration = getIndexDeclarationOfSymbol(symbol, kind);
52723 if (declaration) {
52724 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration);
52725 }
52726 return undefined;
52727 }
52728 function getConstraintDeclaration(type) {
52729 return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
52730 }
52731 function getInferredTypeParameterConstraint(typeParameter) {
52732 var inferences;
52733 if (typeParameter.symbol) {
52734 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
52735 var declaration = _a[_i];
52736 if (declaration.parent.kind === 184 /* InferType */) {
52737 // When an 'infer T' declaration is immediately contained in a type reference node
52738 // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
52739 // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
52740 // present, we form an intersection of the inferred constraint types.
52741 var grandParent = declaration.parent.parent;
52742 if (grandParent.kind === 172 /* TypeReference */) {
52743 var typeReference = grandParent;
52744 var typeParameters = getTypeParametersForTypeReference(typeReference);
52745 if (typeParameters) {
52746 var index = typeReference.typeArguments.indexOf(declaration.parent);
52747 if (index < typeParameters.length) {
52748 var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
52749 if (declaredConstraint) {
52750 // Type parameter constraints can reference other type parameters so
52751 // constraints need to be instantiated. If instantiation produces the
52752 // type parameter itself, we discard that inference. For example, in
52753 // type Foo<T extends string, U extends T> = [T, U];
52754 // type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
52755 // the instantiated constraint for U is X, so we discard that inference.
52756 var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
52757 var constraint = instantiateType(declaredConstraint, mapper);
52758 if (constraint !== typeParameter) {
52759 inferences = ts.append(inferences, constraint);
52760 }
52761 }
52762 }
52763 }
52764 }
52765 // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type
52766 // or a named rest tuple element, we infer an 'unknown[]' constraint.
52767 else if (grandParent.kind === 159 /* Parameter */ && grandParent.dotDotDotToken ||
52768 grandParent.kind === 180 /* RestType */ ||
52769 grandParent.kind === 191 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
52770 inferences = ts.append(inferences, createArrayType(unknownType));
52771 }
52772 }
52773 }
52774 }
52775 return inferences && getIntersectionType(inferences);
52776 }
52777 /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
52778 function getConstraintFromTypeParameter(typeParameter) {
52779 if (!typeParameter.constraint) {
52780 if (typeParameter.target) {
52781 var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
52782 typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
52783 }
52784 else {
52785 var constraintDeclaration = getConstraintDeclaration(typeParameter);
52786 if (!constraintDeclaration) {
52787 typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
52788 }
52789 else {
52790 var type = getTypeFromTypeNode(constraintDeclaration);
52791 if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
52792 // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
52793 // use unknown otherwise
52794 type = constraintDeclaration.parent.parent.kind === 189 /* MappedType */ ? keyofConstraintType : unknownType;
52795 }
52796 typeParameter.constraint = type;
52797 }
52798 }
52799 }
52800 return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
52801 }
52802 function getParentSymbolOfTypeParameter(typeParameter) {
52803 var tp = ts.getDeclarationOfKind(typeParameter.symbol, 158 /* TypeParameter */);
52804 var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
52805 return host && getSymbolOfNode(host);
52806 }
52807 function getTypeListId(types) {
52808 var result = "";
52809 if (types) {
52810 var length_4 = types.length;
52811 var i = 0;
52812 while (i < length_4) {
52813 var startId = types[i].id;
52814 var count = 1;
52815 while (i + count < length_4 && types[i + count].id === startId + count) {
52816 count++;
52817 }
52818 if (result.length) {
52819 result += ",";
52820 }
52821 result += startId;
52822 if (count > 1) {
52823 result += ":" + count;
52824 }
52825 i += count;
52826 }
52827 }
52828 return result;
52829 }
52830 // This function is used to propagate certain flags when creating new object type references and union types.
52831 // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
52832 // of an object literal or the anyFunctionType. This is because there are operations in the type checker
52833 // that care about the presence of such types at arbitrary depth in a containing type.
52834 function getPropagatingFlagsOfTypes(types, excludeKinds) {
52835 var result = 0;
52836 for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
52837 var type = types_8[_i];
52838 if (!(type.flags & excludeKinds)) {
52839 result |= ts.getObjectFlags(type);
52840 }
52841 }
52842 return result & 3670016 /* PropagatingFlags */;
52843 }
52844 function createTypeReference(target, typeArguments) {
52845 var id = getTypeListId(typeArguments);
52846 var type = target.instantiations.get(id);
52847 if (!type) {
52848 type = createObjectType(4 /* Reference */, target.symbol);
52849 target.instantiations.set(id, type);
52850 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
52851 type.target = target;
52852 type.resolvedTypeArguments = typeArguments;
52853 }
52854 return type;
52855 }
52856 function cloneTypeReference(source) {
52857 var type = createType(source.flags);
52858 type.symbol = source.symbol;
52859 type.objectFlags = source.objectFlags;
52860 type.target = source.target;
52861 type.resolvedTypeArguments = source.resolvedTypeArguments;
52862 return type;
52863 }
52864 function createDeferredTypeReference(target, node, mapper) {
52865 var aliasSymbol = getAliasSymbolForTypeNode(node);
52866 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
52867 var type = createObjectType(4 /* Reference */, target.symbol);
52868 type.target = target;
52869 type.node = node;
52870 type.mapper = mapper;
52871 type.aliasSymbol = aliasSymbol;
52872 type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
52873 return type;
52874 }
52875 function getTypeArguments(type) {
52876 var _a, _b;
52877 if (!type.resolvedTypeArguments) {
52878 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
52879 return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
52880 }
52881 var node = type.node;
52882 var typeArguments = !node ? ts.emptyArray :
52883 node.kind === 172 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
52884 node.kind === 177 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
52885 ts.map(node.elements, getTypeFromTypeNode);
52886 if (popTypeResolution()) {
52887 type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
52888 }
52889 else {
52890 type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
52891 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));
52892 }
52893 }
52894 return type.resolvedTypeArguments;
52895 }
52896 function getTypeReferenceArity(type) {
52897 return ts.length(type.target.typeParameters);
52898 }
52899 /**
52900 * Get type from type-reference that reference to class or interface
52901 */
52902 function getTypeFromClassOrInterfaceReference(node, symbol) {
52903 var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
52904 var typeParameters = type.localTypeParameters;
52905 if (typeParameters) {
52906 var numTypeArguments = ts.length(node.typeArguments);
52907 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
52908 var isJs = ts.isInJSFile(node);
52909 var isJsImplicitAny = !noImplicitAny && isJs;
52910 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
52911 var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
52912 var diag = minTypeArgumentCount === typeParameters.length ?
52913 missingAugmentsTag ?
52914 ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
52915 ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
52916 missingAugmentsTag ?
52917 ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
52918 ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
52919 var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
52920 error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
52921 if (!isJs) {
52922 // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
52923 return errorType;
52924 }
52925 }
52926 if (node.kind === 172 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
52927 return createDeferredTypeReference(type, node, /*mapper*/ undefined);
52928 }
52929 // In a type reference, the outer type parameters of the referenced class or interface are automatically
52930 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
52931 // of the class or interface.
52932 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
52933 return createTypeReference(type, typeArguments);
52934 }
52935 return checkNoTypeArguments(node, symbol) ? type : errorType;
52936 }
52937 function getTypeAliasInstantiation(symbol, typeArguments) {
52938 var type = getDeclaredTypeOfSymbol(symbol);
52939 var links = getSymbolLinks(symbol);
52940 var typeParameters = links.typeParameters;
52941 var id = getTypeListId(typeArguments);
52942 var instantiation = links.instantiations.get(id);
52943 if (!instantiation) {
52944 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
52945 }
52946 return instantiation;
52947 }
52948 /**
52949 * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
52950 * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
52951 * declared type. Instantiations are cached using the type identities of the type arguments as the key.
52952 */
52953 function getTypeFromTypeAliasReference(node, symbol) {
52954 var type = getDeclaredTypeOfSymbol(symbol);
52955 var typeParameters = getSymbolLinks(symbol).typeParameters;
52956 if (typeParameters) {
52957 var numTypeArguments = ts.length(node.typeArguments);
52958 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
52959 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
52960 error(node, minTypeArgumentCount === typeParameters.length ?
52961 ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
52962 ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
52963 return errorType;
52964 }
52965 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
52966 }
52967 return checkNoTypeArguments(node, symbol) ? type : errorType;
52968 }
52969 function getTypeReferenceName(node) {
52970 switch (node.kind) {
52971 case 172 /* TypeReference */:
52972 return node.typeName;
52973 case 220 /* ExpressionWithTypeArguments */:
52974 // We only support expressions that are simple qualified names. For other
52975 // expressions this produces undefined.
52976 var expr = node.expression;
52977 if (ts.isEntityNameExpression(expr)) {
52978 return expr;
52979 }
52980 // fall through;
52981 }
52982 return undefined;
52983 }
52984 function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
52985 if (!typeReferenceName) {
52986 return unknownSymbol;
52987 }
52988 return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
52989 }
52990 function getTypeReferenceType(node, symbol) {
52991 if (symbol === unknownSymbol) {
52992 return errorType;
52993 }
52994 symbol = getExpandoSymbol(symbol) || symbol;
52995 if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
52996 return getTypeFromClassOrInterfaceReference(node, symbol);
52997 }
52998 if (symbol.flags & 524288 /* TypeAlias */) {
52999 return getTypeFromTypeAliasReference(node, symbol);
53000 }
53001 // Get type from reference to named type that cannot be generic (enum or type parameter)
53002 var res = tryGetDeclaredTypeOfSymbol(symbol);
53003 if (res) {
53004 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
53005 }
53006 if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
53007 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
53008 if (jsdocType) {
53009 return jsdocType;
53010 }
53011 else {
53012 // Resolve the type reference as a Type for the purpose of reporting errors.
53013 resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
53014 return getTypeOfSymbol(symbol);
53015 }
53016 }
53017 return errorType;
53018 }
53019 /**
53020 * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
53021 * Note: If the value is imported from commonjs, it should really be an alias,
53022 * but this function's special-case code fakes alias resolution as well.
53023 */
53024 function getTypeFromJSDocValueReference(node, symbol) {
53025 var links = getNodeLinks(node);
53026 if (!links.resolvedJSDocType) {
53027 var valueType = getTypeOfSymbol(symbol);
53028 var typeType = valueType;
53029 if (symbol.valueDeclaration) {
53030 var decl = ts.getRootDeclaration(symbol.valueDeclaration);
53031 var isRequireAlias = false;
53032 if (ts.isVariableDeclaration(decl) && decl.initializer) {
53033 var expr = decl.initializer;
53034 // skip past entity names, eg `require("x").a.b.c`
53035 while (ts.isPropertyAccessExpression(expr)) {
53036 expr = expr.expression;
53037 }
53038 isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
53039 }
53040 var isImportTypeWithQualifier = node.kind === 192 /* ImportType */ && node.qualifier;
53041 // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
53042 if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
53043 typeType = getTypeReferenceType(node, valueType.symbol);
53044 }
53045 }
53046 links.resolvedJSDocType = typeType;
53047 }
53048 return links.resolvedJSDocType;
53049 }
53050 function getSubstitutionType(baseType, substitute) {
53051 if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
53052 return baseType;
53053 }
53054 var id = getTypeId(baseType) + ">" + getTypeId(substitute);
53055 var cached = substitutionTypes.get(id);
53056 if (cached) {
53057 return cached;
53058 }
53059 var result = createType(33554432 /* Substitution */);
53060 result.baseType = baseType;
53061 result.substitute = substitute;
53062 substitutionTypes.set(id, result);
53063 return result;
53064 }
53065 function isUnaryTupleTypeNode(node) {
53066 return node.kind === 178 /* TupleType */ && node.elements.length === 1;
53067 }
53068 function getImpliedConstraint(type, checkNode, extendsNode) {
53069 return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) :
53070 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
53071 undefined;
53072 }
53073 function getConditionalFlowTypeOfType(type, node) {
53074 var constraints;
53075 while (node && !ts.isStatement(node) && node.kind !== 307 /* JSDocComment */) {
53076 var parent = node.parent;
53077 if (parent.kind === 183 /* ConditionalType */ && node === parent.trueType) {
53078 var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
53079 if (constraint) {
53080 constraints = ts.append(constraints, constraint);
53081 }
53082 }
53083 node = parent;
53084 }
53085 return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
53086 }
53087 function isJSDocTypeReference(node) {
53088 return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 172 /* TypeReference */ || node.kind === 192 /* ImportType */);
53089 }
53090 function checkNoTypeArguments(node, symbol) {
53091 if (node.typeArguments) {
53092 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
53093 return false;
53094 }
53095 return true;
53096 }
53097 function getIntendedTypeFromJSDocTypeReference(node) {
53098 if (ts.isIdentifier(node.typeName)) {
53099 var typeArgs = node.typeArguments;
53100 switch (node.typeName.escapedText) {
53101 case "String":
53102 checkNoTypeArguments(node);
53103 return stringType;
53104 case "Number":
53105 checkNoTypeArguments(node);
53106 return numberType;
53107 case "Boolean":
53108 checkNoTypeArguments(node);
53109 return booleanType;
53110 case "Void":
53111 checkNoTypeArguments(node);
53112 return voidType;
53113 case "Undefined":
53114 checkNoTypeArguments(node);
53115 return undefinedType;
53116 case "Null":
53117 checkNoTypeArguments(node);
53118 return nullType;
53119 case "Function":
53120 case "function":
53121 checkNoTypeArguments(node);
53122 return globalFunctionType;
53123 case "array":
53124 return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
53125 case "promise":
53126 return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
53127 case "Object":
53128 if (typeArgs && typeArgs.length === 2) {
53129 if (ts.isJSDocIndexSignature(node)) {
53130 var indexed = getTypeFromTypeNode(typeArgs[0]);
53131 var target = getTypeFromTypeNode(typeArgs[1]);
53132 var index = createIndexInfo(target, /*isReadonly*/ false);
53133 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
53134 }
53135 return anyType;
53136 }
53137 checkNoTypeArguments(node);
53138 return !noImplicitAny ? anyType : undefined;
53139 }
53140 }
53141 }
53142 function getTypeFromJSDocNullableTypeNode(node) {
53143 var type = getTypeFromTypeNode(node.type);
53144 return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
53145 }
53146 function getTypeFromTypeReference(node) {
53147 var links = getNodeLinks(node);
53148 if (!links.resolvedType) {
53149 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
53150 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
53151 links.resolvedSymbol = unknownSymbol;
53152 return links.resolvedType = checkExpressionCached(node.parent.expression);
53153 }
53154 var symbol = void 0;
53155 var type = void 0;
53156 var meaning = 788968 /* Type */;
53157 if (isJSDocTypeReference(node)) {
53158 type = getIntendedTypeFromJSDocTypeReference(node);
53159 if (!type) {
53160 symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
53161 if (symbol === unknownSymbol) {
53162 symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
53163 }
53164 else {
53165 resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
53166 }
53167 type = getTypeReferenceType(node, symbol);
53168 }
53169 }
53170 if (!type) {
53171 symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
53172 type = getTypeReferenceType(node, symbol);
53173 }
53174 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
53175 // type reference in checkTypeReferenceNode.
53176 links.resolvedSymbol = symbol;
53177 links.resolvedType = type;
53178 }
53179 return links.resolvedType;
53180 }
53181 function typeArgumentsFromTypeReferenceNode(node) {
53182 return ts.map(node.typeArguments, getTypeFromTypeNode);
53183 }
53184 function getTypeFromTypeQueryNode(node) {
53185 var links = getNodeLinks(node);
53186 if (!links.resolvedType) {
53187 // TypeScript 1.0 spec (April 2014): 3.6.3
53188 // The expression is processed as an identifier expression (section 4.3)
53189 // or property access expression(section 4.10),
53190 // the widened type(section 3.9) of which becomes the result.
53191 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
53192 }
53193 return links.resolvedType;
53194 }
53195 function getTypeOfGlobalSymbol(symbol, arity) {
53196 function getTypeDeclaration(symbol) {
53197 var declarations = symbol.declarations;
53198 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
53199 var declaration = declarations_3[_i];
53200 switch (declaration.kind) {
53201 case 249 /* ClassDeclaration */:
53202 case 250 /* InterfaceDeclaration */:
53203 case 252 /* EnumDeclaration */:
53204 return declaration;
53205 }
53206 }
53207 }
53208 if (!symbol) {
53209 return arity ? emptyGenericType : emptyObjectType;
53210 }
53211 var type = getDeclaredTypeOfSymbol(symbol);
53212 if (!(type.flags & 524288 /* Object */)) {
53213 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
53214 return arity ? emptyGenericType : emptyObjectType;
53215 }
53216 if (ts.length(type.typeParameters) !== arity) {
53217 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
53218 return arity ? emptyGenericType : emptyObjectType;
53219 }
53220 return type;
53221 }
53222 function getGlobalValueSymbol(name, reportErrors) {
53223 return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
53224 }
53225 function getGlobalTypeSymbol(name, reportErrors) {
53226 return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
53227 }
53228 function getGlobalSymbol(name, meaning, diagnostic) {
53229 // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
53230 return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
53231 }
53232 function getGlobalType(name, arity, reportErrors) {
53233 var symbol = getGlobalTypeSymbol(name, reportErrors);
53234 return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
53235 }
53236 function getGlobalTypedPropertyDescriptorType() {
53237 return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
53238 }
53239 function getGlobalTemplateStringsArrayType() {
53240 return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
53241 }
53242 function getGlobalImportMetaType() {
53243 return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
53244 }
53245 function getGlobalESSymbolConstructorSymbol(reportErrors) {
53246 return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
53247 }
53248 function getGlobalESSymbolType(reportErrors) {
53249 return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
53250 }
53251 function getGlobalPromiseType(reportErrors) {
53252 return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
53253 }
53254 function getGlobalPromiseLikeType(reportErrors) {
53255 return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
53256 }
53257 function getGlobalPromiseConstructorSymbol(reportErrors) {
53258 return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
53259 }
53260 function getGlobalPromiseConstructorLikeType(reportErrors) {
53261 return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
53262 }
53263 function getGlobalAsyncIterableType(reportErrors) {
53264 return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
53265 }
53266 function getGlobalAsyncIteratorType(reportErrors) {
53267 return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
53268 }
53269 function getGlobalAsyncIterableIteratorType(reportErrors) {
53270 return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
53271 }
53272 function getGlobalAsyncGeneratorType(reportErrors) {
53273 return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
53274 }
53275 function getGlobalIterableType(reportErrors) {
53276 return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
53277 }
53278 function getGlobalIteratorType(reportErrors) {
53279 return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
53280 }
53281 function getGlobalIterableIteratorType(reportErrors) {
53282 return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
53283 }
53284 function getGlobalGeneratorType(reportErrors) {
53285 return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
53286 }
53287 function getGlobalIteratorYieldResultType(reportErrors) {
53288 return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
53289 }
53290 function getGlobalIteratorReturnResultType(reportErrors) {
53291 return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
53292 }
53293 function getGlobalTypeOrUndefined(name, arity) {
53294 if (arity === void 0) { arity = 0; }
53295 var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
53296 return symbol && getTypeOfGlobalSymbol(symbol, arity);
53297 }
53298 function getGlobalExtractSymbol() {
53299 return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
53300 }
53301 function getGlobalOmitSymbol() {
53302 return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
53303 }
53304 function getGlobalBigIntType(reportErrors) {
53305 return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
53306 }
53307 /**
53308 * Instantiates a global type that is generic with some element type, and returns that instantiation.
53309 */
53310 function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
53311 return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
53312 }
53313 function createTypedPropertyDescriptorType(propertyType) {
53314 return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
53315 }
53316 function createIterableType(iteratedType) {
53317 return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
53318 }
53319 function createArrayType(elementType, readonly) {
53320 return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
53321 }
53322 function getTupleElementFlags(node) {
53323 switch (node.kind) {
53324 case 179 /* OptionalType */:
53325 return 2 /* Optional */;
53326 case 180 /* RestType */:
53327 return getRestTypeElementFlags(node);
53328 case 191 /* NamedTupleMember */:
53329 return node.questionToken ? 2 /* Optional */ :
53330 node.dotDotDotToken ? getRestTypeElementFlags(node) :
53331 1 /* Required */;
53332 default:
53333 return 1 /* Required */;
53334 }
53335 }
53336 function getRestTypeElementFlags(node) {
53337 return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */;
53338 }
53339 function getArrayOrTupleTargetType(node) {
53340 var readonly = isReadonlyTypeOperator(node.parent);
53341 var elementType = getArrayElementTypeNode(node);
53342 if (elementType) {
53343 return readonly ? globalReadonlyArrayType : globalArrayType;
53344 }
53345 var elementFlags = ts.map(node.elements, getTupleElementFlags);
53346 var missingName = ts.some(node.elements, function (e) { return e.kind !== 191 /* NamedTupleMember */; });
53347 return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements);
53348 }
53349 // Return true if the given type reference node is directly aliased or if it needs to be deferred
53350 // because it is possibly contained in a circular chain of eagerly resolved types.
53351 function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
53352 return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 177 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
53353 node.kind === 178 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) :
53354 hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
53355 }
53356 // Return true when the given node is transitively contained in type constructs that eagerly
53357 // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
53358 // of type aliases are eagerly resolved.
53359 function isResolvedByTypeAlias(node) {
53360 var parent = node.parent;
53361 switch (parent.kind) {
53362 case 185 /* ParenthesizedType */:
53363 case 191 /* NamedTupleMember */:
53364 case 172 /* TypeReference */:
53365 case 181 /* UnionType */:
53366 case 182 /* IntersectionType */:
53367 case 188 /* IndexedAccessType */:
53368 case 183 /* ConditionalType */:
53369 case 187 /* TypeOperator */:
53370 case 177 /* ArrayType */:
53371 case 178 /* TupleType */:
53372 return isResolvedByTypeAlias(parent);
53373 case 251 /* TypeAliasDeclaration */:
53374 return true;
53375 }
53376 return false;
53377 }
53378 // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
53379 // of a type alias.
53380 function mayResolveTypeAlias(node) {
53381 switch (node.kind) {
53382 case 172 /* TypeReference */:
53383 return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
53384 case 175 /* TypeQuery */:
53385 return true;
53386 case 187 /* TypeOperator */:
53387 return node.operator !== 150 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
53388 case 185 /* ParenthesizedType */:
53389 case 179 /* OptionalType */:
53390 case 191 /* NamedTupleMember */:
53391 case 303 /* JSDocOptionalType */:
53392 case 301 /* JSDocNullableType */:
53393 case 302 /* JSDocNonNullableType */:
53394 case 298 /* JSDocTypeExpression */:
53395 return mayResolveTypeAlias(node.type);
53396 case 180 /* RestType */:
53397 return node.type.kind !== 177 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
53398 case 181 /* UnionType */:
53399 case 182 /* IntersectionType */:
53400 return ts.some(node.types, mayResolveTypeAlias);
53401 case 188 /* IndexedAccessType */:
53402 return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
53403 case 183 /* ConditionalType */:
53404 return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
53405 mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
53406 }
53407 return false;
53408 }
53409 function getTypeFromArrayOrTupleTypeNode(node) {
53410 var links = getNodeLinks(node);
53411 if (!links.resolvedType) {
53412 var target = getArrayOrTupleTargetType(node);
53413 if (target === emptyGenericType) {
53414 links.resolvedType = emptyObjectType;
53415 }
53416 else if (!(node.kind === 178 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) {
53417 links.resolvedType = node.kind === 178 /* TupleType */ && node.elements.length === 0 ? target :
53418 createDeferredTypeReference(target, node, /*mapper*/ undefined);
53419 }
53420 else {
53421 var elementTypes = node.kind === 177 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode);
53422 links.resolvedType = createNormalizedTypeReference(target, elementTypes);
53423 }
53424 }
53425 return links.resolvedType;
53426 }
53427 function isReadonlyTypeOperator(node) {
53428 return ts.isTypeOperatorNode(node) && node.operator === 141 /* ReadonlyKeyword */;
53429 }
53430 function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) {
53431 if (readonly === void 0) { readonly = false; }
53432 var tupleTarget = getTupleTargetType(elementFlags || ts.map(elementTypes, function (_) { return 1 /* Required */; }), readonly, namedMemberDeclarations);
53433 return tupleTarget === emptyGenericType ? emptyObjectType :
53434 elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) :
53435 tupleTarget;
53436 }
53437 function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
53438 if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
53439 // [...X[]] is equivalent to just X[]
53440 return readonly ? globalReadonlyArrayType : globalArrayType;
53441 }
53442 var key = ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*"; }).join() +
53443 (readonly ? "R" : "") +
53444 (namedMemberDeclarations && namedMemberDeclarations.length ? "," + ts.map(namedMemberDeclarations, getNodeId).join(",") : "");
53445 var type = tupleTypes.get(key);
53446 if (!type) {
53447 tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
53448 }
53449 return type;
53450 }
53451 // We represent tuple types as type references to synthesized generic interface types created by
53452 // this function. The types are of the form:
53453 //
53454 // interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
53455 //
53456 // Note that the generic type created by this function has no symbol associated with it. The same
53457 // is true for each of the synthesized type parameters.
53458 function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
53459 var arity = elementFlags.length;
53460 var minLength = ts.findLastIndex(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); }) + 1;
53461 var typeParameters;
53462 var properties = [];
53463 var combinedFlags = 0;
53464 if (arity) {
53465 typeParameters = new Array(arity);
53466 for (var i = 0; i < arity; i++) {
53467 var typeParameter = typeParameters[i] = createTypeParameter();
53468 var flags = elementFlags[i];
53469 combinedFlags |= flags;
53470 if (!(combinedFlags & 12 /* Variable */)) {
53471 var property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
53472 property.tupleLabelDeclaration = namedMemberDeclarations === null || namedMemberDeclarations === void 0 ? void 0 : namedMemberDeclarations[i];
53473 property.type = typeParameter;
53474 properties.push(property);
53475 }
53476 }
53477 }
53478 var fixedLength = properties.length;
53479 var lengthSymbol = createSymbol(4 /* Property */, "length");
53480 if (combinedFlags & 12 /* Variable */) {
53481 lengthSymbol.type = numberType;
53482 }
53483 else {
53484 var literalTypes_1 = [];
53485 for (var i = minLength; i <= arity; i++)
53486 literalTypes_1.push(getLiteralType(i));
53487 lengthSymbol.type = getUnionType(literalTypes_1);
53488 }
53489 properties.push(lengthSymbol);
53490 var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
53491 type.typeParameters = typeParameters;
53492 type.outerTypeParameters = undefined;
53493 type.localTypeParameters = typeParameters;
53494 type.instantiations = new ts.Map();
53495 type.instantiations.set(getTypeListId(type.typeParameters), type);
53496 type.target = type;
53497 type.resolvedTypeArguments = type.typeParameters;
53498 type.thisType = createTypeParameter();
53499 type.thisType.isThisType = true;
53500 type.thisType.constraint = type;
53501 type.declaredProperties = properties;
53502 type.declaredCallSignatures = ts.emptyArray;
53503 type.declaredConstructSignatures = ts.emptyArray;
53504 type.declaredStringIndexInfo = undefined;
53505 type.declaredNumberIndexInfo = undefined;
53506 type.elementFlags = elementFlags;
53507 type.minLength = minLength;
53508 type.fixedLength = fixedLength;
53509 type.hasRestElement = !!(combinedFlags & 12 /* Variable */);
53510 type.combinedFlags = combinedFlags;
53511 type.readonly = readonly;
53512 type.labeledElementDeclarations = namedMemberDeclarations;
53513 return type;
53514 }
53515 function createNormalizedTypeReference(target, typeArguments) {
53516 return target.objectFlags & 8 /* Tuple */ && target.combinedFlags & 8 /* Variadic */ ?
53517 createNormalizedTupleType(target, typeArguments) :
53518 createTypeReference(target, typeArguments);
53519 }
53520 function createNormalizedTupleType(target, elementTypes) {
53521 var _a, _b, _c;
53522 // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
53523 var unionIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
53524 if (unionIndex >= 0) {
53525 return mapType(elementTypes[unionIndex], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex, t)); });
53526 }
53527 // If there are no variadic elements with non-generic types, just create a type reference with the same target type.
53528 var spreadIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */) && !(t.flags & 58982400 /* InstantiableNonPrimitive */) && !isGenericMappedType(t); });
53529 if (spreadIndex < 0) {
53530 return createTypeReference(target, elementTypes);
53531 }
53532 // We have non-generic variadic elements that need normalization.
53533 var expandedTypes = [];
53534 var expandedFlags = [];
53535 var expandedDeclarations = [];
53536 var optionalIndex = -1;
53537 var restTypes;
53538 var _loop_13 = function (i) {
53539 var type = elementTypes[i];
53540 var flags = target.elementFlags[i];
53541 if (flags & 8 /* Variadic */) {
53542 if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
53543 // Generic variadic elements stay as they are (except following a rest element).
53544 addElementOrRest(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
53545 }
53546 else if (isTupleType(type)) {
53547 // Spread variadic elements with tuple types into the resulting tuple.
53548 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]); });
53549 }
53550 else {
53551 // Treat everything else as an array type and create a rest element.
53552 addElementOrRest(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
53553 }
53554 }
53555 else {
53556 // Copy other element kinds with no change.
53557 addElementOrRest(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
53558 }
53559 };
53560 for (var i = 0; i < elementTypes.length; i++) {
53561 _loop_13(i);
53562 }
53563 if (restTypes) {
53564 // Create a union of the collected rest element types.
53565 expandedTypes[expandedTypes.length - 1] = getUnionType(restTypes);
53566 }
53567 var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
53568 return tupleTarget === emptyGenericType ? emptyObjectType :
53569 expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
53570 tupleTarget;
53571 function addElementOrRest(type, flags, declaration) {
53572 if (restTypes) {
53573 // A rest element was previously added, so simply collect the type of this element.
53574 restTypes.push(flags & 8 /* Variadic */ ? getIndexedAccessType(type, numberType) : type);
53575 }
53576 else {
53577 if (flags & 1 /* Required */ && optionalIndex >= 0) {
53578 // Turn preceding optional elements into required elements
53579 for (var i = optionalIndex; i < expandedFlags.length; i++) {
53580 if (expandedFlags[i] & 2 /* Optional */)
53581 expandedFlags[i] = 1 /* Required */;
53582 }
53583 optionalIndex = -1;
53584 }
53585 else if (flags & 2 /* Optional */ && optionalIndex < 0) {
53586 optionalIndex = expandedFlags.length;
53587 }
53588 else if (flags & 4 /* Rest */) {
53589 // Start collecting element types when a rest element is added.
53590 restTypes = [type];
53591 }
53592 expandedTypes.push(type);
53593 expandedFlags.push(flags);
53594 if (expandedDeclarations && declaration) {
53595 expandedDeclarations.push(declaration);
53596 }
53597 else {
53598 expandedDeclarations = undefined;
53599 }
53600 }
53601 }
53602 }
53603 function sliceTupleType(type, index, endSkipCount) {
53604 if (endSkipCount === void 0) { endSkipCount = 0; }
53605 var target = type.target;
53606 var endIndex = getTypeReferenceArity(type) - endSkipCount;
53607 return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(ts.emptyArray) :
53608 createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex),
53609 /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
53610 }
53611 function getKnownKeysOfTupleType(type) {
53612 return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
53613 }
53614 function getTypeFromOptionalTypeNode(node) {
53615 var type = getTypeFromTypeNode(node.type);
53616 return strictNullChecks ? getOptionalType(type) : type;
53617 }
53618 function getTypeId(type) {
53619 return type.id;
53620 }
53621 function containsType(types, type) {
53622 return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
53623 }
53624 function insertType(types, type) {
53625 var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
53626 if (index < 0) {
53627 types.splice(~index, 0, type);
53628 return true;
53629 }
53630 return false;
53631 }
53632 function addTypeToUnion(typeSet, includes, type) {
53633 var flags = type.flags;
53634 if (flags & 1048576 /* Union */) {
53635 return addTypesToUnion(typeSet, includes, type.types);
53636 }
53637 // We ignore 'never' types in unions
53638 if (!(flags & 131072 /* Never */)) {
53639 includes |= flags & 71041023 /* IncludesMask */;
53640 if (flags & 66846720 /* StructuredOrInstantiable */)
53641 includes |= 262144 /* IncludesStructuredOrInstantiable */;
53642 if (type === wildcardType)
53643 includes |= 8388608 /* IncludesWildcard */;
53644 if (!strictNullChecks && flags & 98304 /* Nullable */) {
53645 if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
53646 includes |= 4194304 /* IncludesNonWideningType */;
53647 }
53648 else {
53649 var len = typeSet.length;
53650 var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
53651 if (index < 0) {
53652 typeSet.splice(~index, 0, type);
53653 }
53654 }
53655 }
53656 return includes;
53657 }
53658 // Add the given types to the given type set. Order is preserved, duplicates are removed,
53659 // and nested types of the given kind are flattened into the set.
53660 function addTypesToUnion(typeSet, includes, types) {
53661 for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
53662 var type = types_9[_i];
53663 includes = addTypeToUnion(typeSet, includes, type);
53664 }
53665 return includes;
53666 }
53667 function isSetOfLiteralsFromSameEnum(types) {
53668 var first = types[0];
53669 if (first.flags & 1024 /* EnumLiteral */) {
53670 var firstEnum = getParentOfSymbol(first.symbol);
53671 for (var i = 1; i < types.length; i++) {
53672 var other = types[i];
53673 if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
53674 return false;
53675 }
53676 }
53677 return true;
53678 }
53679 return false;
53680 }
53681 function removeSubtypes(types, primitivesOnly) {
53682 var len = types.length;
53683 if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
53684 return true;
53685 }
53686 var i = len;
53687 var count = 0;
53688 while (i > 0) {
53689 i--;
53690 var source = types[i];
53691 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
53692 var target = types_10[_i];
53693 if (source !== target) {
53694 if (count === 100000) {
53695 // After 100000 subtype checks we estimate the remaining amount of work by assuming the
53696 // same ratio of checks per element. If the estimated number of remaining type checks is
53697 // greater than an upper limit we deem the union type too complex to represent. The
53698 // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
53699 // caps union types at 5000 unique literal types and 1000 unique object types.
53700 var estimatedCount = (count / (len - i)) * len;
53701 if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
53702 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
53703 return false;
53704 }
53705 }
53706 count++;
53707 if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
53708 !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
53709 isTypeDerivedFrom(source, target))) {
53710 ts.orderedRemoveItemAt(types, i);
53711 break;
53712 }
53713 }
53714 }
53715 }
53716 return true;
53717 }
53718 function removeRedundantLiteralTypes(types, includes) {
53719 var i = types.length;
53720 while (i > 0) {
53721 i--;
53722 var t = types[i];
53723 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
53724 t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
53725 t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
53726 t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
53727 isFreshLiteralType(t) && containsType(types, t.regularType);
53728 if (remove) {
53729 ts.orderedRemoveItemAt(types, i);
53730 }
53731 }
53732 }
53733 // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
53734 // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
53735 // of other types. Subtype reduction is expensive for large union types and is possible only when union
53736 // types are known not to circularly reference themselves (as is the case with union types created by
53737 // expression constructs such as array literals and the || and ?: operators). Named types can
53738 // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
53739 // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
53740 function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
53741 if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
53742 if (types.length === 0) {
53743 return neverType;
53744 }
53745 if (types.length === 1) {
53746 return types[0];
53747 }
53748 var typeSet = [];
53749 var includes = addTypesToUnion(typeSet, 0, types);
53750 if (unionReduction !== 0 /* None */) {
53751 if (includes & 3 /* AnyOrUnknown */) {
53752 return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
53753 }
53754 switch (unionReduction) {
53755 case 1 /* Literal */:
53756 if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
53757 removeRedundantLiteralTypes(typeSet, includes);
53758 }
53759 break;
53760 case 2 /* Subtype */:
53761 if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
53762 return errorType;
53763 }
53764 break;
53765 }
53766 if (typeSet.length === 0) {
53767 return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
53768 includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
53769 neverType;
53770 }
53771 }
53772 var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
53773 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
53774 return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
53775 }
53776 function getUnionTypePredicate(signatures) {
53777 var first;
53778 var types = [];
53779 for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
53780 var sig = signatures_6[_i];
53781 var pred = getTypePredicateOfSignature(sig);
53782 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
53783 continue;
53784 }
53785 if (first) {
53786 if (!typePredicateKindsMatch(first, pred)) {
53787 // No common type predicate.
53788 return undefined;
53789 }
53790 }
53791 else {
53792 first = pred;
53793 }
53794 types.push(pred.type);
53795 }
53796 if (!first) {
53797 // No union signatures had a type predicate.
53798 return undefined;
53799 }
53800 var unionType = getUnionType(types);
53801 return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
53802 }
53803 function typePredicateKindsMatch(a, b) {
53804 return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
53805 }
53806 // This function assumes the constituent type list is sorted and deduplicated.
53807 function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
53808 if (types.length === 0) {
53809 return neverType;
53810 }
53811 if (types.length === 1) {
53812 return types[0];
53813 }
53814 var id = getTypeListId(types);
53815 var type = unionTypes.get(id);
53816 if (!type) {
53817 type = createType(1048576 /* Union */);
53818 unionTypes.set(id, type);
53819 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
53820 type.types = types;
53821 /*
53822 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
53823 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
53824 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
53825 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
53826 */
53827 type.aliasSymbol = aliasSymbol;
53828 type.aliasTypeArguments = aliasTypeArguments;
53829 }
53830 return type;
53831 }
53832 function getTypeFromUnionTypeNode(node) {
53833 var links = getNodeLinks(node);
53834 if (!links.resolvedType) {
53835 var aliasSymbol = getAliasSymbolForTypeNode(node);
53836 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
53837 }
53838 return links.resolvedType;
53839 }
53840 function addTypeToIntersection(typeSet, includes, type) {
53841 var flags = type.flags;
53842 if (flags & 2097152 /* Intersection */) {
53843 return addTypesToIntersection(typeSet, includes, type.types);
53844 }
53845 if (isEmptyAnonymousObjectType(type)) {
53846 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
53847 includes |= 16777216 /* IncludesEmptyObject */;
53848 typeSet.set(type.id.toString(), type);
53849 }
53850 }
53851 else {
53852 if (flags & 3 /* AnyOrUnknown */) {
53853 if (type === wildcardType)
53854 includes |= 8388608 /* IncludesWildcard */;
53855 }
53856 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
53857 if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
53858 // We have seen two distinct unit types which means we should reduce to an
53859 // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
53860 includes |= 67108864 /* NonPrimitive */;
53861 }
53862 typeSet.set(type.id.toString(), type);
53863 }
53864 includes |= flags & 71041023 /* IncludesMask */;
53865 }
53866 return includes;
53867 }
53868 // Add the given types to the given type set. Order is preserved, freshness is removed from literal
53869 // types, duplicates are removed, and nested types of the given kind are flattened into the set.
53870 function addTypesToIntersection(typeSet, includes, types) {
53871 for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
53872 var type = types_11[_i];
53873 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
53874 }
53875 return includes;
53876 }
53877 function removeRedundantPrimitiveTypes(types, includes) {
53878 var i = types.length;
53879 while (i > 0) {
53880 i--;
53881 var t = types[i];
53882 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
53883 t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
53884 t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
53885 t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
53886 if (remove) {
53887 ts.orderedRemoveItemAt(types, i);
53888 }
53889 }
53890 }
53891 // Check that the given type has a match in every union. A given type is matched by
53892 // an identical type, and a literal type is additionally matched by its corresponding
53893 // primitive type.
53894 function eachUnionContains(unionTypes, type) {
53895 for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
53896 var u = unionTypes_1[_i];
53897 if (!containsType(u.types, type)) {
53898 var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
53899 type.flags & 256 /* NumberLiteral */ ? numberType :
53900 type.flags & 2048 /* BigIntLiteral */ ? bigintType :
53901 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
53902 undefined;
53903 if (!primitive || !containsType(u.types, primitive)) {
53904 return false;
53905 }
53906 }
53907 }
53908 return true;
53909 }
53910 function extractIrreducible(types, flag) {
53911 if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
53912 for (var i = 0; i < types.length; i++) {
53913 types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
53914 }
53915 return true;
53916 }
53917 return false;
53918 }
53919 // If the given list of types contains more than one union of primitive types, replace the
53920 // first with a union containing an intersection of those primitive types, then remove the
53921 // other unions and return true. Otherwise, do nothing and return false.
53922 function intersectUnionsOfPrimitiveTypes(types) {
53923 var unionTypes;
53924 var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
53925 if (index < 0) {
53926 return false;
53927 }
53928 var i = index + 1;
53929 // Remove all but the first union of primitive types and collect them in
53930 // the unionTypes array.
53931 while (i < types.length) {
53932 var t = types[i];
53933 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
53934 (unionTypes || (unionTypes = [types[index]])).push(t);
53935 ts.orderedRemoveItemAt(types, i);
53936 }
53937 else {
53938 i++;
53939 }
53940 }
53941 // Return false if there was only one union of primitive types
53942 if (!unionTypes) {
53943 return false;
53944 }
53945 // We have more than one union of primitive types, now intersect them. For each
53946 // type in each union we check if the type is matched in every union and if so
53947 // we include it in the result.
53948 var checked = [];
53949 var result = [];
53950 for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
53951 var u = unionTypes_2[_i];
53952 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
53953 var t = _b[_a];
53954 if (insertType(checked, t)) {
53955 if (eachUnionContains(unionTypes, t)) {
53956 insertType(result, t);
53957 }
53958 }
53959 }
53960 }
53961 // Finally replace the first union with the result
53962 types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
53963 return true;
53964 }
53965 function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
53966 var result = createType(2097152 /* Intersection */);
53967 result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
53968 result.types = types;
53969 result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
53970 result.aliasTypeArguments = aliasTypeArguments;
53971 return result;
53972 }
53973 // We normalize combinations of intersection and union types based on the distributive property of the '&'
53974 // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
53975 // types with union type constituents into equivalent union types with intersection type constituents and
53976 // effectively ensure that union types are always at the top level in type representations.
53977 //
53978 // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
53979 // type operator and we can't reduce those because we want to support recursive intersection types. For example,
53980 // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
53981 // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
53982 // for intersections of types with signatures can be deterministic.
53983 function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
53984 var typeMembershipMap = new ts.Map();
53985 var includes = addTypesToIntersection(typeMembershipMap, 0, types);
53986 var typeSet = ts.arrayFrom(typeMembershipMap.values());
53987 // An intersection type is considered empty if it contains
53988 // the type never, or
53989 // more than one unit type or,
53990 // an object type and a nullable type (null or undefined), or
53991 // a string-like type and a type known to be non-string-like, or
53992 // a number-like type and a type known to be non-number-like, or
53993 // a symbol-like type and a type known to be non-symbol-like, or
53994 // a void-like type and a type known to be non-void-like, or
53995 // a non-primitive type and a type known to be primitive.
53996 if (includes & 131072 /* Never */ ||
53997 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
53998 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
53999 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
54000 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
54001 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
54002 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
54003 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
54004 return neverType;
54005 }
54006 if (includes & 1 /* Any */) {
54007 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
54008 }
54009 if (!strictNullChecks && includes & 98304 /* Nullable */) {
54010 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
54011 }
54012 if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
54013 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
54014 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
54015 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
54016 removeRedundantPrimitiveTypes(typeSet, includes);
54017 }
54018 if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
54019 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
54020 }
54021 if (typeSet.length === 0) {
54022 return unknownType;
54023 }
54024 if (typeSet.length === 1) {
54025 return typeSet[0];
54026 }
54027 var id = getTypeListId(typeSet);
54028 var result = intersectionTypes.get(id);
54029 if (!result) {
54030 if (includes & 1048576 /* Union */) {
54031 if (intersectUnionsOfPrimitiveTypes(typeSet)) {
54032 // When the intersection creates a reduced set (which might mean that *all* union types have
54033 // disappeared), we restart the operation to get a new set of combined flags. Once we have
54034 // reduced we'll never reduce again, so this occurs at most once.
54035 result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
54036 }
54037 else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
54038 result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
54039 }
54040 else if (extractIrreducible(typeSet, 65536 /* Null */)) {
54041 result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
54042 }
54043 else {
54044 // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
54045 // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
54046 // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
54047 var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
54048 if (size >= 100000) {
54049 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
54050 return errorType;
54051 }
54052 var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
54053 var unionType = typeSet[unionIndex_1];
54054 result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
54055 }
54056 }
54057 else {
54058 result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
54059 }
54060 intersectionTypes.set(id, result);
54061 }
54062 return result;
54063 }
54064 function getTypeFromIntersectionTypeNode(node) {
54065 var links = getNodeLinks(node);
54066 if (!links.resolvedType) {
54067 var aliasSymbol = getAliasSymbolForTypeNode(node);
54068 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
54069 }
54070 return links.resolvedType;
54071 }
54072 function createIndexType(type, stringsOnly) {
54073 var result = createType(4194304 /* Index */);
54074 result.type = type;
54075 result.stringsOnly = stringsOnly;
54076 return result;
54077 }
54078 function getIndexTypeForGenericType(type, stringsOnly) {
54079 return stringsOnly ?
54080 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
54081 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
54082 }
54083 function getLiteralTypeFromPropertyName(name) {
54084 if (ts.isPrivateIdentifier(name)) {
54085 return neverType;
54086 }
54087 return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
54088 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
54089 }
54090 function getBigIntLiteralType(node) {
54091 return getLiteralType({
54092 negative: false,
54093 base10Value: ts.parsePseudoBigInt(node.text)
54094 });
54095 }
54096 function getLiteralTypeFromProperty(prop, include) {
54097 if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
54098 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
54099 if (!type && !ts.isKnownSymbol(prop)) {
54100 if (prop.escapedName === "default" /* Default */) {
54101 type = getLiteralType("default");
54102 }
54103 else {
54104 var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
54105 type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
54106 }
54107 }
54108 if (type && type.flags & include) {
54109 return type;
54110 }
54111 }
54112 return neverType;
54113 }
54114 function getLiteralTypeFromProperties(type, include) {
54115 return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
54116 }
54117 function getNonEnumNumberIndexInfo(type) {
54118 var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
54119 return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
54120 }
54121 function getIndexType(type, stringsOnly, noIndexSignatures) {
54122 if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
54123 type = getReducedType(type);
54124 return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
54125 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
54126 type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) ? getIndexTypeForGenericType(type, stringsOnly) :
54127 ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
54128 type === wildcardType ? wildcardType :
54129 type.flags & 2 /* Unknown */ ? neverType :
54130 type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
54131 stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
54132 !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
54133 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
54134 getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
54135 }
54136 function getExtractStringType(type) {
54137 if (keyofStringsOnly) {
54138 return type;
54139 }
54140 var extractTypeAlias = getGlobalExtractSymbol();
54141 return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
54142 }
54143 function getIndexTypeOrString(type) {
54144 var indexType = getExtractStringType(getIndexType(type));
54145 return indexType.flags & 131072 /* Never */ ? stringType : indexType;
54146 }
54147 function getTypeFromTypeOperatorNode(node) {
54148 var links = getNodeLinks(node);
54149 if (!links.resolvedType) {
54150 switch (node.operator) {
54151 case 137 /* KeyOfKeyword */:
54152 links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
54153 break;
54154 case 150 /* UniqueKeyword */:
54155 links.resolvedType = node.type.kind === 147 /* SymbolKeyword */
54156 ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
54157 : errorType;
54158 break;
54159 case 141 /* ReadonlyKeyword */:
54160 links.resolvedType = getTypeFromTypeNode(node.type);
54161 break;
54162 default:
54163 throw ts.Debug.assertNever(node.operator);
54164 }
54165 }
54166 return links.resolvedType;
54167 }
54168 function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
54169 var type = createType(8388608 /* IndexedAccess */);
54170 type.objectType = objectType;
54171 type.indexType = indexType;
54172 type.aliasSymbol = aliasSymbol;
54173 type.aliasTypeArguments = aliasTypeArguments;
54174 return type;
54175 }
54176 /**
54177 * Returns if a type is or consists of a JSLiteral object type
54178 * In addition to objects which are directly literals,
54179 * * unions where every element is a jsliteral
54180 * * intersections where at least one element is a jsliteral
54181 * * and instantiable types constrained to a jsliteral
54182 * Should all count as literals and not print errors on access or assignment of possibly existing properties.
54183 * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
54184 */
54185 function isJSLiteralType(type) {
54186 if (noImplicitAny) {
54187 return false; // Flag is meaningless under `noImplicitAny` mode
54188 }
54189 if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
54190 return true;
54191 }
54192 if (type.flags & 1048576 /* Union */) {
54193 return ts.every(type.types, isJSLiteralType);
54194 }
54195 if (type.flags & 2097152 /* Intersection */) {
54196 return ts.some(type.types, isJSLiteralType);
54197 }
54198 if (type.flags & 63176704 /* Instantiable */) {
54199 return isJSLiteralType(getResolvedBaseConstraint(type));
54200 }
54201 return false;
54202 }
54203 function getPropertyNameFromIndex(indexType, accessNode) {
54204 var accessExpression = accessNode && accessNode.kind === 199 /* ElementAccessExpression */ ? accessNode : undefined;
54205 return isTypeUsableAsPropertyName(indexType) ?
54206 getPropertyNameFromType(indexType) :
54207 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
54208 ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
54209 accessNode && ts.isPropertyName(accessNode) ?
54210 // late bound names are handled in the first branch, so here we only need to handle normal names
54211 ts.getPropertyNameForPropertyNameNode(accessNode) :
54212 undefined;
54213 }
54214 function isUncalledFunctionReference(node, symbol) {
54215 return !(symbol.flags & (16 /* Function */ | 8192 /* Method */))
54216 || !ts.isCallLikeExpression(ts.findAncestor(node, function (n) { return !ts.isAccessExpression(n); }) || node.parent)
54217 && ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
54218 }
54219 function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, reportDeprecated) {
54220 var _a, _b;
54221 var accessExpression = accessNode && accessNode.kind === 199 /* ElementAccessExpression */ ? accessNode : undefined;
54222 var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
54223 if (propName !== undefined) {
54224 var prop = getPropertyOfType(objectType, propName);
54225 if (prop) {
54226 if (reportDeprecated && accessNode && ((_a = prop.valueDeclaration) === null || _a === void 0 ? void 0 : _a.flags) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
54227 var deprecatedNode = (_b = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _b !== void 0 ? _b : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
54228 errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName);
54229 }
54230 if (accessExpression) {
54231 markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */);
54232 if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
54233 error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
54234 return undefined;
54235 }
54236 if (accessFlags & 4 /* CacheSymbol */) {
54237 getNodeLinks(accessNode).resolvedSymbol = prop;
54238 }
54239 if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
54240 return autoType;
54241 }
54242 }
54243 var propType = getTypeOfSymbol(prop);
54244 return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
54245 getFlowTypeOfReference(accessExpression, propType) :
54246 propType;
54247 }
54248 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
54249 if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
54250 var indexNode = getIndexNodeForAccessExpression(accessNode);
54251 if (isTupleType(objectType)) {
54252 error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
54253 }
54254 else {
54255 error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
54256 }
54257 }
54258 errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
54259 return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
54260 }
54261 }
54262 if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
54263 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
54264 return objectType;
54265 }
54266 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
54267 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
54268 if (indexInfo) {
54269 if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
54270 if (accessExpression) {
54271 error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
54272 }
54273 return undefined;
54274 }
54275 if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
54276 var indexNode = getIndexNodeForAccessExpression(accessNode);
54277 error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
54278 return indexInfo.type;
54279 }
54280 errorIfWritingToReadonlyIndex(indexInfo);
54281 return indexInfo.type;
54282 }
54283 if (indexType.flags & 131072 /* Never */) {
54284 return neverType;
54285 }
54286 if (isJSLiteralType(objectType)) {
54287 return anyType;
54288 }
54289 if (accessExpression && !isConstEnumObjectType(objectType)) {
54290 if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
54291 error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
54292 }
54293 else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
54294 if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
54295 error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
54296 }
54297 else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
54298 error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
54299 }
54300 else {
54301 var suggestion = void 0;
54302 if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
54303 if (suggestion !== undefined) {
54304 error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
54305 }
54306 }
54307 else {
54308 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
54309 if (suggestion_1 !== undefined) {
54310 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);
54311 }
54312 else {
54313 var errorInfo = void 0;
54314 if (indexType.flags & 1024 /* EnumLiteral */) {
54315 errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
54316 }
54317 else if (indexType.flags & 8192 /* UniqueESSymbol */) {
54318 var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
54319 errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
54320 }
54321 else if (indexType.flags & 128 /* StringLiteral */) {
54322 errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
54323 }
54324 else if (indexType.flags & 256 /* NumberLiteral */) {
54325 errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
54326 }
54327 else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
54328 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));
54329 }
54330 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));
54331 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
54332 }
54333 }
54334 }
54335 }
54336 return undefined;
54337 }
54338 }
54339 if (isJSLiteralType(objectType)) {
54340 return anyType;
54341 }
54342 if (accessNode) {
54343 var indexNode = getIndexNodeForAccessExpression(accessNode);
54344 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
54345 error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
54346 }
54347 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
54348 error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
54349 }
54350 else {
54351 error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
54352 }
54353 }
54354 if (isTypeAny(indexType)) {
54355 return indexType;
54356 }
54357 return undefined;
54358 function errorIfWritingToReadonlyIndex(indexInfo) {
54359 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
54360 error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
54361 }
54362 }
54363 }
54364 function getIndexNodeForAccessExpression(accessNode) {
54365 return accessNode.kind === 199 /* ElementAccessExpression */ ? accessNode.argumentExpression :
54366 accessNode.kind === 188 /* IndexedAccessType */ ? accessNode.indexType :
54367 accessNode.kind === 157 /* ComputedPropertyName */ ? accessNode.expression :
54368 accessNode;
54369 }
54370 function isGenericObjectType(type) {
54371 if (type.flags & 3145728 /* UnionOrIntersection */) {
54372 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
54373 type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
54374 (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
54375 }
54376 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
54377 }
54378 return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type);
54379 }
54380 function isGenericIndexType(type) {
54381 if (type.flags & 3145728 /* UnionOrIntersection */) {
54382 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
54383 type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
54384 (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
54385 }
54386 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
54387 }
54388 return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
54389 }
54390 function isThisTypeParameter(type) {
54391 return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
54392 }
54393 function getSimplifiedType(type, writing) {
54394 return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
54395 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
54396 type;
54397 }
54398 function distributeIndexOverObjectType(objectType, indexType, writing) {
54399 // (T | U)[K] -> T[K] | U[K] (reading)
54400 // (T | U)[K] -> T[K] & U[K] (writing)
54401 // (T & U)[K] -> T[K] & U[K]
54402 if (objectType.flags & 3145728 /* UnionOrIntersection */) {
54403 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
54404 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
54405 }
54406 }
54407 function distributeObjectOverIndexType(objectType, indexType, writing) {
54408 // T[A | B] -> T[A] | T[B] (reading)
54409 // T[A | B] -> T[A] & T[B] (writing)
54410 if (indexType.flags & 1048576 /* Union */) {
54411 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
54412 return writing ? getIntersectionType(types) : getUnionType(types);
54413 }
54414 }
54415 function unwrapSubstitution(type) {
54416 if (type.flags & 33554432 /* Substitution */) {
54417 return type.substitute;
54418 }
54419 return type;
54420 }
54421 // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
54422 // the type itself if no transformation is possible. The writing flag indicates that the type is
54423 // the target of an assignment.
54424 function getSimplifiedIndexedAccessType(type, writing) {
54425 var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
54426 if (type[cache]) {
54427 return type[cache] === circularConstraintType ? type : type[cache];
54428 }
54429 type[cache] = circularConstraintType;
54430 // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
54431 // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
54432 var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
54433 var indexType = getSimplifiedType(type.indexType, writing);
54434 // T[A | B] -> T[A] | T[B] (reading)
54435 // T[A | B] -> T[A] & T[B] (writing)
54436 var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
54437 if (distributedOverIndex) {
54438 return type[cache] = distributedOverIndex;
54439 }
54440 // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
54441 if (!(indexType.flags & 63176704 /* Instantiable */)) {
54442 // (T | U)[K] -> T[K] | U[K] (reading)
54443 // (T | U)[K] -> T[K] & U[K] (writing)
54444 // (T & U)[K] -> T[K] & U[K]
54445 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
54446 if (distributedOverObject) {
54447 return type[cache] = distributedOverObject;
54448 }
54449 }
54450 // So ultimately (reading):
54451 // ((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]
54452 // A generic tuple type indexed by a number exists only when the index type doesn't select a
54453 // fixed element. We simplify to either the combined type of all elements (when the index type
54454 // the actual number type) or to the combined type of all non-fixed elements.
54455 if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
54456 var elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ 0, writing);
54457 if (elementType) {
54458 return type[cache] = elementType;
54459 }
54460 }
54461 // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
54462 // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
54463 // construct the type Box<T[X]>.
54464 if (isGenericMappedType(objectType)) {
54465 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
54466 }
54467 return type[cache] = type;
54468 }
54469 function getSimplifiedConditionalType(type, writing) {
54470 var checkType = type.checkType;
54471 var extendsType = type.extendsType;
54472 var trueType = getTrueTypeFromConditionalType(type);
54473 var falseType = getFalseTypeFromConditionalType(type);
54474 // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
54475 if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
54476 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
54477 return getSimplifiedType(trueType, writing);
54478 }
54479 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
54480 return neverType;
54481 }
54482 }
54483 else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
54484 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
54485 return neverType;
54486 }
54487 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
54488 return getSimplifiedType(falseType, writing);
54489 }
54490 }
54491 return type;
54492 }
54493 /**
54494 * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
54495 */
54496 function isIntersectionEmpty(type1, type2) {
54497 return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
54498 }
54499 function substituteIndexedMappedType(objectType, index) {
54500 var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
54501 var templateMapper = combineTypeMappers(objectType.mapper, mapper);
54502 return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
54503 }
54504 function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
54505 return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
54506 }
54507 function indexTypeLessThan(indexType, limit) {
54508 return everyType(indexType, function (t) {
54509 if (t.flags & 384 /* StringOrNumberLiteral */) {
54510 var propName = getPropertyNameFromType(t);
54511 if (isNumericLiteralName(propName)) {
54512 var index = +propName;
54513 return index >= 0 && index < limit;
54514 }
54515 }
54516 return false;
54517 });
54518 }
54519 function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
54520 if (accessFlags === void 0) { accessFlags = 0 /* None */; }
54521 if (objectType === wildcardType || indexType === wildcardType) {
54522 return wildcardType;
54523 }
54524 // If the object type has a string index signature and no other members we know that the result will
54525 // always be the type of that index signature and we can simplify accordingly.
54526 if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
54527 indexType = stringType;
54528 }
54529 // If the index type is generic, or if the object type is generic and doesn't originate in an expression and
54530 // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing
54531 // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that
54532 // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
54533 // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
54534 // eagerly using the constraint type of 'this' at the given location.
54535 if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 188 /* IndexedAccessType */ ?
54536 isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) :
54537 isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) {
54538 if (objectType.flags & 3 /* AnyOrUnknown */) {
54539 return objectType;
54540 }
54541 // Defer the operation by creating an indexed access type.
54542 var id = objectType.id + "," + indexType.id;
54543 var type = indexedAccessTypes.get(id);
54544 if (!type) {
54545 indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
54546 }
54547 return type;
54548 }
54549 // In the following we resolve T[K] to the type of the property in T selected by K.
54550 // We treat boolean as different from other unions to improve errors;
54551 // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
54552 var apparentObjectType = getReducedApparentType(objectType);
54553 if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
54554 var propTypes = [];
54555 var wasMissingProp = false;
54556 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
54557 var t = _a[_i];
54558 var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
54559 if (propType) {
54560 propTypes.push(propType);
54561 }
54562 else if (!accessNode) {
54563 // If there's no error node, we can immeditely stop, since error reporting is off
54564 return undefined;
54565 }
54566 else {
54567 // Otherwise we set a flag and return at the end of the loop so we still mark all errors
54568 wasMissingProp = true;
54569 }
54570 }
54571 if (wasMissingProp) {
54572 return undefined;
54573 }
54574 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
54575 }
54576 return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */, /* reportDeprecated */ true);
54577 }
54578 function getTypeFromIndexedAccessTypeNode(node) {
54579 var links = getNodeLinks(node);
54580 if (!links.resolvedType) {
54581 var objectType = getTypeFromTypeNode(node.objectType);
54582 var indexType = getTypeFromTypeNode(node.indexType);
54583 var potentialAlias = getAliasSymbolForTypeNode(node);
54584 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
54585 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
54586 resolved.objectType === objectType &&
54587 resolved.indexType === indexType ?
54588 getConditionalFlowTypeOfType(resolved, node) : resolved;
54589 }
54590 return links.resolvedType;
54591 }
54592 function getTypeFromMappedTypeNode(node) {
54593 var links = getNodeLinks(node);
54594 if (!links.resolvedType) {
54595 var type = createObjectType(32 /* Mapped */, node.symbol);
54596 type.declaration = node;
54597 type.aliasSymbol = getAliasSymbolForTypeNode(node);
54598 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
54599 links.resolvedType = type;
54600 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
54601 // references itself through one or more type aliases.
54602 getConstraintTypeFromMappedType(type);
54603 }
54604 return links.resolvedType;
54605 }
54606 function getActualTypeVariable(type) {
54607 if (type.flags & 33554432 /* Substitution */) {
54608 return type.baseType;
54609 }
54610 if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
54611 type.indexType.flags & 33554432 /* Substitution */)) {
54612 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
54613 }
54614 return type;
54615 }
54616 function getConditionalType(root, mapper) {
54617 var result;
54618 var extraTypes;
54619 var _loop_14 = function () {
54620 var checkType = instantiateType(root.checkType, mapper);
54621 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
54622 var extendsType = instantiateType(root.extendsType, mapper);
54623 if (checkType === wildcardType || extendsType === wildcardType) {
54624 return { value: wildcardType };
54625 }
54626 var combinedMapper = void 0;
54627 if (root.inferTypeParameters) {
54628 var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
54629 // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
54630 // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
54631 // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
54632 // so in those cases we refain from performing inference and retain the uninfered type parameter
54633 if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
54634 // We don't want inferences from constraints as they may cause us to eagerly resolve the
54635 // conditional type instead of deferring resolution. Also, we always want strict function
54636 // types rules (i.e. proper contravariance) for inferences.
54637 inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
54638 }
54639 combinedMapper = mergeTypeMappers(mapper, context.mapper);
54640 }
54641 // Instantiate the extends type including inferences for 'infer T' type parameters
54642 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
54643 // We attempt to resolve the conditional type only when the check and extends types are non-generic
54644 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
54645 // Return falseType for a definitely false extends check. We check an instantiations of the two
54646 // types with type parameters mapped to the wildcard type, the most permissive instantiations
54647 // possible (the wildcard type is assignable to and from all types). If those are not related,
54648 // then no instantiations will be and we can just return the false branch type.
54649 if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
54650 // Return union of trueType and falseType for 'any' since it matches anything
54651 if (checkType.flags & 1 /* Any */) {
54652 (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
54653 }
54654 // If falseType is an immediately nested conditional type that isn't distributive or has an
54655 // identical checkType, switch to that type and loop.
54656 var falseType_1 = root.falseType;
54657 if (falseType_1.flags & 16777216 /* Conditional */) {
54658 var newRoot = falseType_1.root;
54659 if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
54660 root = newRoot;
54661 return "continue";
54662 }
54663 }
54664 result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
54665 return "break";
54666 }
54667 // Return trueType for a definitely true extends check. We check instantiations of the two
54668 // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
54669 // that has no constraint. This ensures that, for example, the type
54670 // type Foo<T extends { x: any }> = T extends { x: string } ? string : number
54671 // doesn't immediately resolve to 'string' instead of being deferred.
54672 if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
54673 result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
54674 return "break";
54675 }
54676 }
54677 // Return a deferred type for a check that is neither definitely true nor definitely false
54678 var erasedCheckType = getActualTypeVariable(checkType);
54679 result = createType(16777216 /* Conditional */);
54680 result.root = root;
54681 result.checkType = erasedCheckType;
54682 result.extendsType = extendsType;
54683 result.mapper = mapper;
54684 result.combinedMapper = combinedMapper;
54685 result.aliasSymbol = root.aliasSymbol;
54686 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
54687 return "break";
54688 };
54689 // We loop here for an immediately nested conditional type in the false position, effectively treating
54690 // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
54691 // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
54692 while (true) {
54693 var state_4 = _loop_14();
54694 if (typeof state_4 === "object")
54695 return state_4.value;
54696 if (state_4 === "break")
54697 break;
54698 }
54699 return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
54700 }
54701 function getTrueTypeFromConditionalType(type) {
54702 return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
54703 }
54704 function getFalseTypeFromConditionalType(type) {
54705 return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
54706 }
54707 function getInferredTrueTypeFromConditionalType(type) {
54708 return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
54709 }
54710 function getInferTypeParameters(node) {
54711 var result;
54712 if (node.locals) {
54713 node.locals.forEach(function (symbol) {
54714 if (symbol.flags & 262144 /* TypeParameter */) {
54715 result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
54716 }
54717 });
54718 }
54719 return result;
54720 }
54721 function getTypeFromConditionalTypeNode(node) {
54722 var links = getNodeLinks(node);
54723 if (!links.resolvedType) {
54724 var checkType = getTypeFromTypeNode(node.checkType);
54725 var aliasSymbol = getAliasSymbolForTypeNode(node);
54726 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
54727 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
54728 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
54729 var root = {
54730 node: node,
54731 checkType: checkType,
54732 extendsType: getTypeFromTypeNode(node.extendsType),
54733 trueType: getTypeFromTypeNode(node.trueType),
54734 falseType: getTypeFromTypeNode(node.falseType),
54735 isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
54736 inferTypeParameters: getInferTypeParameters(node),
54737 outerTypeParameters: outerTypeParameters,
54738 instantiations: undefined,
54739 aliasSymbol: aliasSymbol,
54740 aliasTypeArguments: aliasTypeArguments
54741 };
54742 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
54743 if (outerTypeParameters) {
54744 root.instantiations = new ts.Map();
54745 root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
54746 }
54747 }
54748 return links.resolvedType;
54749 }
54750 function getTypeFromInferTypeNode(node) {
54751 var links = getNodeLinks(node);
54752 if (!links.resolvedType) {
54753 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
54754 }
54755 return links.resolvedType;
54756 }
54757 function getIdentifierChain(node) {
54758 if (ts.isIdentifier(node)) {
54759 return [node];
54760 }
54761 else {
54762 return ts.append(getIdentifierChain(node.left), node.right);
54763 }
54764 }
54765 function getTypeFromImportTypeNode(node) {
54766 var links = getNodeLinks(node);
54767 if (!links.resolvedType) {
54768 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
54769 error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
54770 links.resolvedSymbol = unknownSymbol;
54771 return links.resolvedType = errorType;
54772 }
54773 if (!ts.isLiteralImportTypeNode(node)) {
54774 error(node.argument, ts.Diagnostics.String_literal_expected);
54775 links.resolvedSymbol = unknownSymbol;
54776 return links.resolvedType = errorType;
54777 }
54778 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
54779 // TODO: Future work: support unions/generics/whatever via a deferred import-type
54780 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
54781 if (!innerModuleSymbol) {
54782 links.resolvedSymbol = unknownSymbol;
54783 return links.resolvedType = errorType;
54784 }
54785 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
54786 if (!ts.nodeIsMissing(node.qualifier)) {
54787 var nameStack = getIdentifierChain(node.qualifier);
54788 var currentNamespace = moduleSymbol;
54789 var current = void 0;
54790 while (current = nameStack.shift()) {
54791 var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
54792 var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
54793 if (!next) {
54794 error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
54795 return links.resolvedType = errorType;
54796 }
54797 getNodeLinks(current).resolvedSymbol = next;
54798 getNodeLinks(current.parent).resolvedSymbol = next;
54799 currentNamespace = next;
54800 }
54801 links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
54802 }
54803 else {
54804 if (moduleSymbol.flags & targetMeaning) {
54805 links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
54806 }
54807 else {
54808 var errorMessage = targetMeaning === 111551 /* Value */
54809 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
54810 : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
54811 error(node, errorMessage, node.argument.literal.text);
54812 links.resolvedSymbol = unknownSymbol;
54813 links.resolvedType = errorType;
54814 }
54815 }
54816 }
54817 return links.resolvedType;
54818 }
54819 function resolveImportSymbolType(node, links, symbol, meaning) {
54820 var resolvedSymbol = resolveSymbol(symbol);
54821 links.resolvedSymbol = resolvedSymbol;
54822 if (meaning === 111551 /* Value */) {
54823 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
54824 }
54825 else {
54826 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
54827 }
54828 }
54829 function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
54830 var links = getNodeLinks(node);
54831 if (!links.resolvedType) {
54832 // Deferred resolution of members is handled by resolveObjectTypeMembers
54833 var aliasSymbol = getAliasSymbolForTypeNode(node);
54834 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
54835 links.resolvedType = emptyTypeLiteralType;
54836 }
54837 else {
54838 var type = createObjectType(16 /* Anonymous */, node.symbol);
54839 type.aliasSymbol = aliasSymbol;
54840 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
54841 if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
54842 type = createArrayType(type);
54843 }
54844 links.resolvedType = type;
54845 }
54846 }
54847 return links.resolvedType;
54848 }
54849 function getAliasSymbolForTypeNode(node) {
54850 var host = node.parent;
54851 while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 141 /* ReadonlyKeyword */) {
54852 host = host.parent;
54853 }
54854 return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
54855 }
54856 function getTypeArgumentsForAliasSymbol(symbol) {
54857 return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
54858 }
54859 function isNonGenericObjectType(type) {
54860 return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
54861 }
54862 function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
54863 return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
54864 }
54865 function isSinglePropertyAnonymousObjectType(type) {
54866 return !!(type.flags & 524288 /* Object */) &&
54867 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
54868 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
54869 }
54870 function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
54871 if (type.types.length === 2) {
54872 var firstType = type.types[0];
54873 var secondType = type.types[1];
54874 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
54875 return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
54876 }
54877 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
54878 return getAnonymousPartialType(secondType);
54879 }
54880 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
54881 return getAnonymousPartialType(firstType);
54882 }
54883 }
54884 function getAnonymousPartialType(type) {
54885 // gets the type as if it had been spread, but where everything in the spread is made optional
54886 var members = ts.createSymbolTable();
54887 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
54888 var prop = _a[_i];
54889 if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
54890 // do nothing, skip privates
54891 }
54892 else if (isSpreadableProperty(prop)) {
54893 var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
54894 var flags = 4 /* Property */ | 16777216 /* Optional */;
54895 var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
54896 result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
54897 result.declarations = prop.declarations;
54898 result.nameType = getSymbolLinks(prop).nameType;
54899 result.syntheticOrigin = prop;
54900 members.set(prop.escapedName, result);
54901 }
54902 }
54903 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
54904 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
54905 return spread;
54906 }
54907 }
54908 /**
54909 * Since the source of spread types are object literals, which are not binary,
54910 * this function should be called in a left folding style, with left = previous result of getSpreadType
54911 * and right = the new element to be spread.
54912 */
54913 function getSpreadType(left, right, symbol, objectFlags, readonly) {
54914 if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
54915 return anyType;
54916 }
54917 if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
54918 return unknownType;
54919 }
54920 if (left.flags & 131072 /* Never */) {
54921 return right;
54922 }
54923 if (right.flags & 131072 /* Never */) {
54924 return left;
54925 }
54926 if (left.flags & 1048576 /* Union */) {
54927 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
54928 if (merged) {
54929 return getSpreadType(merged, right, symbol, objectFlags, readonly);
54930 }
54931 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
54932 }
54933 if (right.flags & 1048576 /* Union */) {
54934 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
54935 if (merged) {
54936 return getSpreadType(left, merged, symbol, objectFlags, readonly);
54937 }
54938 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
54939 }
54940 if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
54941 return left;
54942 }
54943 if (isGenericObjectType(left) || isGenericObjectType(right)) {
54944 if (isEmptyObjectType(left)) {
54945 return right;
54946 }
54947 // When the left type is an intersection, we may need to merge the last constituent of the
54948 // intersection with the right type. For example when the left type is 'T & { a: string }'
54949 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
54950 if (left.flags & 2097152 /* Intersection */) {
54951 var types = left.types;
54952 var lastLeft = types[types.length - 1];
54953 if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
54954 return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
54955 }
54956 }
54957 return getIntersectionType([left, right]);
54958 }
54959 var members = ts.createSymbolTable();
54960 var skippedPrivateMembers = new ts.Set();
54961 var stringIndexInfo;
54962 var numberIndexInfo;
54963 if (left === emptyObjectType) {
54964 // for the first spread element, left === emptyObjectType, so take the right's string indexer
54965 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
54966 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
54967 }
54968 else {
54969 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
54970 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
54971 }
54972 for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
54973 var rightProp = _a[_i];
54974 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
54975 skippedPrivateMembers.add(rightProp.escapedName);
54976 }
54977 else if (isSpreadableProperty(rightProp)) {
54978 members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
54979 }
54980 }
54981 for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
54982 var leftProp = _c[_b];
54983 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
54984 continue;
54985 }
54986 if (members.has(leftProp.escapedName)) {
54987 var rightProp = members.get(leftProp.escapedName);
54988 var rightType = getTypeOfSymbol(rightProp);
54989 if (rightProp.flags & 16777216 /* Optional */) {
54990 var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
54991 var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
54992 var result = createSymbol(flags, leftProp.escapedName);
54993 result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
54994 result.leftSpread = leftProp;
54995 result.rightSpread = rightProp;
54996 result.declarations = declarations;
54997 result.nameType = getSymbolLinks(leftProp).nameType;
54998 members.set(leftProp.escapedName, result);
54999 }
55000 }
55001 else {
55002 members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
55003 }
55004 }
55005 var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
55006 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
55007 return spread;
55008 }
55009 /** We approximate own properties as non-methods plus methods that are inside the object literal */
55010 function isSpreadableProperty(prop) {
55011 return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
55012 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
55013 !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
55014 }
55015 function getSpreadSymbol(prop, readonly) {
55016 var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
55017 if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
55018 return prop;
55019 }
55020 var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
55021 var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
55022 result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
55023 result.declarations = prop.declarations;
55024 result.nameType = getSymbolLinks(prop).nameType;
55025 result.syntheticOrigin = prop;
55026 return result;
55027 }
55028 function getIndexInfoWithReadonly(info, readonly) {
55029 return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
55030 }
55031 function createLiteralType(flags, value, symbol) {
55032 var type = createType(flags);
55033 type.symbol = symbol;
55034 type.value = value;
55035 return type;
55036 }
55037 function getFreshTypeOfLiteralType(type) {
55038 if (type.flags & 2944 /* Literal */) {
55039 if (!type.freshType) {
55040 var freshType = createLiteralType(type.flags, type.value, type.symbol);
55041 freshType.regularType = type;
55042 freshType.freshType = freshType;
55043 type.freshType = freshType;
55044 }
55045 return type.freshType;
55046 }
55047 return type;
55048 }
55049 function getRegularTypeOfLiteralType(type) {
55050 return type.flags & 2944 /* Literal */ ? type.regularType :
55051 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
55052 type;
55053 }
55054 function isFreshLiteralType(type) {
55055 return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
55056 }
55057 function getLiteralType(value, enumId, symbol) {
55058 // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
55059 // where NNN is the text representation of a numeric literal and SSS are the characters
55060 // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
55061 // EEE is a unique id for the containing enum type.
55062 var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
55063 var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
55064 var type = literalTypes.get(key);
55065 if (!type) {
55066 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
55067 typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
55068 (enumId ? 1024 /* EnumLiteral */ : 0);
55069 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
55070 type.regularType = type;
55071 }
55072 return type;
55073 }
55074 function getTypeFromLiteralTypeNode(node) {
55075 if (node.literal.kind === 103 /* NullKeyword */) {
55076 return nullType;
55077 }
55078 var links = getNodeLinks(node);
55079 if (!links.resolvedType) {
55080 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
55081 }
55082 return links.resolvedType;
55083 }
55084 function createUniqueESSymbolType(symbol) {
55085 var type = createType(8192 /* UniqueESSymbol */);
55086 type.symbol = symbol;
55087 type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
55088 return type;
55089 }
55090 function getESSymbolLikeTypeForNode(node) {
55091 if (ts.isValidESSymbolDeclaration(node)) {
55092 var symbol = getSymbolOfNode(node);
55093 var links = getSymbolLinks(symbol);
55094 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
55095 }
55096 return esSymbolType;
55097 }
55098 function getThisType(node) {
55099 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
55100 var parent = container && container.parent;
55101 if (parent && (ts.isClassLike(parent) || parent.kind === 250 /* InterfaceDeclaration */)) {
55102 if (!ts.hasSyntacticModifier(container, 32 /* Static */) &&
55103 (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
55104 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
55105 }
55106 }
55107 // inside x.prototype = { ... }
55108 if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
55109 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
55110 }
55111 // /** @return {this} */
55112 // x.prototype.m = function() { ... }
55113 var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
55114 if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
55115 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
55116 }
55117 // inside constructor function C() { ... }
55118 if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
55119 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
55120 }
55121 error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
55122 return errorType;
55123 }
55124 function getTypeFromThisTypeNode(node) {
55125 var links = getNodeLinks(node);
55126 if (!links.resolvedType) {
55127 links.resolvedType = getThisType(node);
55128 }
55129 return links.resolvedType;
55130 }
55131 function getTypeFromRestTypeNode(node) {
55132 return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
55133 }
55134 function getArrayElementTypeNode(node) {
55135 switch (node.kind) {
55136 case 185 /* ParenthesizedType */:
55137 return getArrayElementTypeNode(node.type);
55138 case 178 /* TupleType */:
55139 if (node.elements.length === 1) {
55140 node = node.elements[0];
55141 if (node.kind === 180 /* RestType */ || node.kind === 191 /* NamedTupleMember */ && node.dotDotDotToken) {
55142 return getArrayElementTypeNode(node.type);
55143 }
55144 }
55145 break;
55146 case 177 /* ArrayType */:
55147 return node.elementType;
55148 }
55149 return undefined;
55150 }
55151 function getTypeFromNamedTupleTypeNode(node) {
55152 var links = getNodeLinks(node);
55153 return links.resolvedType || (links.resolvedType =
55154 node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
55155 node.questionToken && strictNullChecks ? getOptionalType(getTypeFromTypeNode(node.type)) :
55156 getTypeFromTypeNode(node.type));
55157 }
55158 function getTypeFromTypeNode(node) {
55159 return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
55160 }
55161 function getTypeFromTypeNodeWorker(node) {
55162 switch (node.kind) {
55163 case 128 /* AnyKeyword */:
55164 case 299 /* JSDocAllType */:
55165 case 300 /* JSDocUnknownType */:
55166 return anyType;
55167 case 151 /* UnknownKeyword */:
55168 return unknownType;
55169 case 146 /* StringKeyword */:
55170 return stringType;
55171 case 143 /* NumberKeyword */:
55172 return numberType;
55173 case 154 /* BigIntKeyword */:
55174 return bigintType;
55175 case 131 /* BooleanKeyword */:
55176 return booleanType;
55177 case 147 /* SymbolKeyword */:
55178 return esSymbolType;
55179 case 113 /* VoidKeyword */:
55180 return voidType;
55181 case 149 /* UndefinedKeyword */:
55182 return undefinedType;
55183 case 103 /* NullKeyword */:
55184 // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service.
55185 return nullType;
55186 case 140 /* NeverKeyword */:
55187 return neverType;
55188 case 144 /* ObjectKeyword */:
55189 return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
55190 case 186 /* ThisType */:
55191 case 107 /* ThisKeyword */:
55192 // 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`.
55193 return getTypeFromThisTypeNode(node);
55194 case 190 /* LiteralType */:
55195 return getTypeFromLiteralTypeNode(node);
55196 case 172 /* TypeReference */:
55197 return getTypeFromTypeReference(node);
55198 case 171 /* TypePredicate */:
55199 return node.assertsModifier ? voidType : booleanType;
55200 case 220 /* ExpressionWithTypeArguments */:
55201 return getTypeFromTypeReference(node);
55202 case 175 /* TypeQuery */:
55203 return getTypeFromTypeQueryNode(node);
55204 case 177 /* ArrayType */:
55205 case 178 /* TupleType */:
55206 return getTypeFromArrayOrTupleTypeNode(node);
55207 case 179 /* OptionalType */:
55208 return getTypeFromOptionalTypeNode(node);
55209 case 181 /* UnionType */:
55210 return getTypeFromUnionTypeNode(node);
55211 case 182 /* IntersectionType */:
55212 return getTypeFromIntersectionTypeNode(node);
55213 case 301 /* JSDocNullableType */:
55214 return getTypeFromJSDocNullableTypeNode(node);
55215 case 303 /* JSDocOptionalType */:
55216 return addOptionality(getTypeFromTypeNode(node.type));
55217 case 191 /* NamedTupleMember */:
55218 return getTypeFromNamedTupleTypeNode(node);
55219 case 185 /* ParenthesizedType */:
55220 case 302 /* JSDocNonNullableType */:
55221 case 298 /* JSDocTypeExpression */:
55222 return getTypeFromTypeNode(node.type);
55223 case 180 /* RestType */:
55224 return getTypeFromRestTypeNode(node);
55225 case 305 /* JSDocVariadicType */:
55226 return getTypeFromJSDocVariadicType(node);
55227 case 173 /* FunctionType */:
55228 case 174 /* ConstructorType */:
55229 case 176 /* TypeLiteral */:
55230 case 308 /* JSDocTypeLiteral */:
55231 case 304 /* JSDocFunctionType */:
55232 case 309 /* JSDocSignature */:
55233 return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
55234 case 187 /* TypeOperator */:
55235 return getTypeFromTypeOperatorNode(node);
55236 case 188 /* IndexedAccessType */:
55237 return getTypeFromIndexedAccessTypeNode(node);
55238 case 189 /* MappedType */:
55239 return getTypeFromMappedTypeNode(node);
55240 case 183 /* ConditionalType */:
55241 return getTypeFromConditionalTypeNode(node);
55242 case 184 /* InferType */:
55243 return getTypeFromInferTypeNode(node);
55244 case 192 /* ImportType */:
55245 return getTypeFromImportTypeNode(node);
55246 // This function assumes that an identifier, qualified name, or property access expression is a type expression
55247 // Callers should first ensure this by calling `isPartOfTypeNode`
55248 // 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.
55249 case 78 /* Identifier */:
55250 case 156 /* QualifiedName */:
55251 case 198 /* PropertyAccessExpression */:
55252 var symbol = getSymbolAtLocation(node);
55253 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
55254 default:
55255 return errorType;
55256 }
55257 }
55258 function instantiateList(items, mapper, instantiator) {
55259 if (items && items.length) {
55260 for (var i = 0; i < items.length; i++) {
55261 var item = items[i];
55262 var mapped = instantiator(item, mapper);
55263 if (item !== mapped) {
55264 var result = i === 0 ? [] : items.slice(0, i);
55265 result.push(mapped);
55266 for (i++; i < items.length; i++) {
55267 result.push(instantiator(items[i], mapper));
55268 }
55269 return result;
55270 }
55271 }
55272 }
55273 return items;
55274 }
55275 function instantiateTypes(types, mapper) {
55276 return instantiateList(types, mapper, instantiateType);
55277 }
55278 function instantiateSignatures(signatures, mapper) {
55279 return instantiateList(signatures, mapper, instantiateSignature);
55280 }
55281 function createTypeMapper(sources, targets) {
55282 return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
55283 }
55284 function getMappedType(type, mapper) {
55285 switch (mapper.kind) {
55286 case 0 /* Simple */:
55287 return type === mapper.source ? mapper.target : type;
55288 case 1 /* Array */:
55289 var sources = mapper.sources;
55290 var targets = mapper.targets;
55291 for (var i = 0; i < sources.length; i++) {
55292 if (type === sources[i]) {
55293 return targets ? targets[i] : anyType;
55294 }
55295 }
55296 return type;
55297 case 2 /* Function */:
55298 return mapper.func(type);
55299 case 3 /* Composite */:
55300 case 4 /* Merged */:
55301 var t1 = getMappedType(type, mapper.mapper1);
55302 return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
55303 }
55304 }
55305 function makeUnaryTypeMapper(source, target) {
55306 return { kind: 0 /* Simple */, source: source, target: target };
55307 }
55308 function makeArrayTypeMapper(sources, targets) {
55309 return { kind: 1 /* Array */, sources: sources, targets: targets };
55310 }
55311 function makeFunctionTypeMapper(func) {
55312 return { kind: 2 /* Function */, func: func };
55313 }
55314 function makeCompositeTypeMapper(kind, mapper1, mapper2) {
55315 return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
55316 }
55317 function createTypeEraser(sources) {
55318 return createTypeMapper(sources, /*targets*/ undefined);
55319 }
55320 /**
55321 * Maps forward-references to later types parameters to the empty object type.
55322 * This is used during inference when instantiating type parameter defaults.
55323 */
55324 function createBackreferenceMapper(context, index) {
55325 return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
55326 }
55327 function combineTypeMappers(mapper1, mapper2) {
55328 return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
55329 }
55330 function mergeTypeMappers(mapper1, mapper2) {
55331 return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
55332 }
55333 function prependTypeMapping(source, target, mapper) {
55334 return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
55335 }
55336 function appendTypeMapping(mapper, source, target) {
55337 return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
55338 }
55339 function getRestrictiveTypeParameter(tp) {
55340 return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
55341 tp.restrictiveInstantiation.constraint = unknownType,
55342 tp.restrictiveInstantiation);
55343 }
55344 function cloneTypeParameter(typeParameter) {
55345 var result = createTypeParameter(typeParameter.symbol);
55346 result.target = typeParameter;
55347 return result;
55348 }
55349 function instantiateTypePredicate(predicate, mapper) {
55350 return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
55351 }
55352 function instantiateSignature(signature, mapper, eraseTypeParameters) {
55353 var freshTypeParameters;
55354 if (signature.typeParameters && !eraseTypeParameters) {
55355 // First create a fresh set of type parameters, then include a mapping from the old to the
55356 // new type parameters in the mapper function. Finally store this mapper in the new type
55357 // parameters such that we can use it when instantiating constraints.
55358 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
55359 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
55360 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
55361 var tp = freshTypeParameters_1[_i];
55362 tp.mapper = mapper;
55363 }
55364 }
55365 // Don't compute resolvedReturnType and resolvedTypePredicate now,
55366 // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
55367 // See GH#17600.
55368 var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol),
55369 /*resolvedReturnType*/ undefined,
55370 /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 19 /* PropagatingFlags */);
55371 result.target = signature;
55372 result.mapper = mapper;
55373 return result;
55374 }
55375 function instantiateSymbol(symbol, mapper) {
55376 var links = getSymbolLinks(symbol);
55377 if (links.type && !couldContainTypeVariables(links.type)) {
55378 // If the type of the symbol is already resolved, and if that type could not possibly
55379 // be affected by instantiation, simply return the symbol itself.
55380 return symbol;
55381 }
55382 if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
55383 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
55384 // type mappers. This ensures that original type identities are properly preserved and that aliases
55385 // always reference a non-aliases.
55386 symbol = links.target;
55387 mapper = combineTypeMappers(links.mapper, mapper);
55388 }
55389 // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
55390 // also transient so that we can just store data on it directly.
55391 var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
55392 result.declarations = symbol.declarations;
55393 result.parent = symbol.parent;
55394 result.target = symbol;
55395 result.mapper = mapper;
55396 if (symbol.valueDeclaration) {
55397 result.valueDeclaration = symbol.valueDeclaration;
55398 }
55399 if (links.nameType) {
55400 result.nameType = links.nameType;
55401 }
55402 return result;
55403 }
55404 function getObjectTypeInstantiation(type, mapper) {
55405 var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
55406 var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
55407 var links = getNodeLinks(declaration);
55408 var typeParameters = links.outerTypeParameters;
55409 if (!typeParameters) {
55410 // The first time an anonymous type is instantiated we compute and store a list of the type
55411 // parameters that are in scope (and therefore potentially referenced). For type literals that
55412 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
55413 // set of type parameters to those that are possibly referenced in the literal.
55414 var outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true);
55415 if (isJSConstructor(declaration)) {
55416 var templateTagParameters = getTypeParametersFromDeclaration(declaration);
55417 outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
55418 }
55419 typeParameters = outerTypeParameters || ts.emptyArray;
55420 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
55421 ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) :
55422 typeParameters;
55423 links.outerTypeParameters = typeParameters;
55424 if (typeParameters.length) {
55425 links.instantiations = new ts.Map();
55426 links.instantiations.set(getTypeListId(typeParameters), target);
55427 }
55428 }
55429 if (typeParameters.length) {
55430 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
55431 // mapper to the type parameters to produce the effective list of type arguments, and compute the
55432 // instantiation cache key from the type IDs of the type arguments.
55433 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
55434 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
55435 var id = getTypeListId(typeArguments);
55436 var result = links.instantiations.get(id);
55437 if (!result) {
55438 var newMapper = createTypeMapper(typeParameters, typeArguments);
55439 result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
55440 target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
55441 instantiateAnonymousType(target, newMapper);
55442 links.instantiations.set(id, result);
55443 }
55444 return result;
55445 }
55446 return type;
55447 }
55448 function maybeTypeParameterReference(node) {
55449 return !(node.kind === 156 /* QualifiedName */ ||
55450 node.parent.kind === 172 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
55451 node.parent.kind === 192 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
55452 }
55453 function isTypeParameterPossiblyReferenced(tp, node) {
55454 // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
55455 // between the node and the type parameter declaration, if the node contains actual references to the
55456 // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
55457 if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
55458 var container = tp.symbol.declarations[0].parent;
55459 for (var n = node; n !== container; n = n.parent) {
55460 if (!n || n.kind === 227 /* Block */ || n.kind === 183 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
55461 return true;
55462 }
55463 }
55464 return !!ts.forEachChild(node, containsReference);
55465 }
55466 return true;
55467 function containsReference(node) {
55468 switch (node.kind) {
55469 case 186 /* ThisType */:
55470 return !!tp.isThisType;
55471 case 78 /* Identifier */:
55472 return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
55473 getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
55474 case 175 /* TypeQuery */:
55475 return true;
55476 }
55477 return !!ts.forEachChild(node, containsReference);
55478 }
55479 }
55480 function getHomomorphicTypeVariable(type) {
55481 var constraintType = getConstraintTypeFromMappedType(type);
55482 if (constraintType.flags & 4194304 /* Index */) {
55483 var typeVariable = getActualTypeVariable(constraintType.type);
55484 if (typeVariable.flags & 262144 /* TypeParameter */) {
55485 return typeVariable;
55486 }
55487 }
55488 return undefined;
55489 }
55490 function instantiateMappedType(type, mapper) {
55491 // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
55492 // operation depends on T as follows:
55493 // * If T is a primitive type no mapping is performed and the result is simply T.
55494 // * If T is a union type we distribute the mapped type over the union.
55495 // * If T is an array we map to an array where the element type has been transformed.
55496 // * If T is a tuple we map to a tuple where the element types have been transformed.
55497 // * Otherwise we map to an object type where the type of each property has been transformed.
55498 // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
55499 // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
55500 // { [P in keyof A]: X } | undefined.
55501 var typeVariable = getHomomorphicTypeVariable(type);
55502 if (typeVariable) {
55503 var mappedTypeVariable = instantiateType(typeVariable, mapper);
55504 if (typeVariable !== mappedTypeVariable) {
55505 return mapType(getReducedType(mappedTypeVariable), function (t) {
55506 if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
55507 if (isGenericTupleType(t)) {
55508 return instantiateMappedGenericTupleType(t, type, typeVariable, mapper);
55509 }
55510 var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
55511 return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
55512 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
55513 instantiateAnonymousType(type, replacementMapper);
55514 }
55515 return t;
55516 });
55517 }
55518 }
55519 return instantiateAnonymousType(type, mapper);
55520 }
55521 function getModifiedReadonlyState(state, modifiers) {
55522 return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
55523 }
55524 function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) {
55525 // When a tuple type is generic (i.e. when it contains variadic elements), we want to eagerly map the
55526 // non-generic elements and defer mapping the generic elements. In order to facilitate this, we transform
55527 // M<[A, B?, ...T, ...C[]] into [...M<[A]>, ...M<[B?]>, ...M<T>, ...M<C[]>] and then rely on tuple type
55528 // normalization to resolve the non-generic parts of the resulting tuple.
55529 var elementFlags = tupleType.target.elementFlags;
55530 var elementTypes = ts.map(getTypeArguments(tupleType), function (t, i) {
55531 var singleton = elementFlags[i] & 8 /* Variadic */ ? t :
55532 elementFlags[i] & 4 /* Rest */ ? createArrayType(t) :
55533 createTupleType([t], [elementFlags[i]]);
55534 // The singleton is never a generic tuple type, so it is safe to recurse here.
55535 return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper));
55536 });
55537 var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
55538 return createTupleType(elementTypes, ts.map(elementTypes, function (_) { return 8 /* Variadic */; }), newReadonly);
55539 }
55540 function instantiateMappedArrayType(arrayType, mappedType, mapper) {
55541 var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
55542 return elementType === errorType ? errorType :
55543 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
55544 }
55545 function instantiateMappedTupleType(tupleType, mappedType, mapper) {
55546 var elementFlags = tupleType.target.elementFlags;
55547 var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
55548 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper);
55549 });
55550 var modifiers = getMappedTypeModifiers(mappedType);
55551 var newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? 2 /* Optional */ : f; }) :
55552 modifiers & 8 /* ExcludeOptional */ ? ts.map(elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
55553 elementFlags;
55554 var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
55555 return ts.contains(elementTypes, errorType) ? errorType :
55556 createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations);
55557 }
55558 function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
55559 var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
55560 var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
55561 var modifiers = getMappedTypeModifiers(type);
55562 return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
55563 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
55564 propType;
55565 }
55566 function instantiateAnonymousType(type, mapper) {
55567 var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
55568 if (type.objectFlags & 32 /* Mapped */) {
55569 result.declaration = type.declaration;
55570 // C.f. instantiateSignature
55571 var origTypeParameter = getTypeParameterFromMappedType(type);
55572 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
55573 result.typeParameter = freshTypeParameter;
55574 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
55575 freshTypeParameter.mapper = mapper;
55576 }
55577 result.target = type;
55578 result.mapper = mapper;
55579 result.aliasSymbol = type.aliasSymbol;
55580 result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
55581 return result;
55582 }
55583 function getConditionalTypeInstantiation(type, mapper) {
55584 var root = type.root;
55585 if (root.outerTypeParameters) {
55586 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
55587 // mapper to the type parameters to produce the effective list of type arguments, and compute the
55588 // instantiation cache key from the type IDs of the type arguments.
55589 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
55590 var id = getTypeListId(typeArguments);
55591 var result = root.instantiations.get(id);
55592 if (!result) {
55593 var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
55594 result = instantiateConditionalType(root, newMapper);
55595 root.instantiations.set(id, result);
55596 }
55597 return result;
55598 }
55599 return type;
55600 }
55601 function instantiateConditionalType(root, mapper) {
55602 // Check if we have a conditional type where the check type is a naked type parameter. If so,
55603 // the conditional type is distributive over union types and when T is instantiated to a union
55604 // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
55605 if (root.isDistributive) {
55606 var checkType_1 = root.checkType;
55607 var instantiatedType = getMappedType(checkType_1, mapper);
55608 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
55609 return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
55610 }
55611 }
55612 return getConditionalType(root, mapper);
55613 }
55614 function instantiateType(type, mapper) {
55615 if (!(type && mapper && couldContainTypeVariables(type))) {
55616 return type;
55617 }
55618 if (instantiationDepth === 50 || instantiationCount >= 5000000) {
55619 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
55620 // with a combination of infinite generic types that perpetually generate new type identities. We stop
55621 // the recursion here by yielding the error type.
55622 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
55623 return errorType;
55624 }
55625 totalInstantiationCount++;
55626 instantiationCount++;
55627 instantiationDepth++;
55628 var result = instantiateTypeWorker(type, mapper);
55629 instantiationDepth--;
55630 return result;
55631 }
55632 /**
55633 * This can be used to avoid the penalty on instantiation depth for types which result from immediate
55634 * simplification. It essentially removes the depth increase done in `instantiateType`.
55635 */
55636 function instantiateTypeWithoutDepthIncrease(type, mapper) {
55637 instantiationDepth--;
55638 var result = instantiateType(type, mapper);
55639 instantiationDepth++;
55640 return result;
55641 }
55642 function instantiateTypeWorker(type, mapper) {
55643 var flags = type.flags;
55644 if (flags & 262144 /* TypeParameter */) {
55645 return getMappedType(type, mapper);
55646 }
55647 if (flags & 524288 /* Object */) {
55648 var objectFlags = type.objectFlags;
55649 if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
55650 if (objectFlags & 4 /* Reference */ && !(type.node)) {
55651 var resolvedTypeArguments = type.resolvedTypeArguments;
55652 var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
55653 return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
55654 }
55655 return getObjectTypeInstantiation(type, mapper);
55656 }
55657 return type;
55658 }
55659 if (flags & 3145728 /* UnionOrIntersection */) {
55660 var types = type.types;
55661 var newTypes = instantiateTypes(types, mapper);
55662 return newTypes === types ? type :
55663 flags & 2097152 /* Intersection */ ?
55664 getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) :
55665 getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
55666 }
55667 if (flags & 4194304 /* Index */) {
55668 return getIndexType(instantiateType(type.type, mapper));
55669 }
55670 if (flags & 8388608 /* IndexedAccess */) {
55671 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
55672 }
55673 if (flags & 16777216 /* Conditional */) {
55674 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
55675 }
55676 if (flags & 33554432 /* Substitution */) {
55677 var maybeVariable = instantiateType(type.baseType, mapper);
55678 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
55679 return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
55680 }
55681 else {
55682 var sub = instantiateType(type.substitute, mapper);
55683 if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
55684 return maybeVariable;
55685 }
55686 return sub;
55687 }
55688 }
55689 return type;
55690 }
55691 function getPermissiveInstantiation(type) {
55692 return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
55693 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
55694 }
55695 function getRestrictiveInstantiation(type) {
55696 if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
55697 return type;
55698 }
55699 if (type.restrictiveInstantiation) {
55700 return type.restrictiveInstantiation;
55701 }
55702 type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
55703 // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
55704 // which is redundant - we'll produce new type identities, but all type params have already been mapped.
55705 // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
55706 // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
55707 // are constrained to `unknown` and produce tons of false positives/negatives!
55708 type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
55709 return type.restrictiveInstantiation;
55710 }
55711 function instantiateIndexInfo(info, mapper) {
55712 return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
55713 }
55714 // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
55715 // that is subject to contextual typing.
55716 function isContextSensitive(node) {
55717 ts.Debug.assert(node.kind !== 164 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55718 switch (node.kind) {
55719 case 205 /* FunctionExpression */:
55720 case 206 /* ArrowFunction */:
55721 case 164 /* MethodDeclaration */:
55722 case 248 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
55723 return isContextSensitiveFunctionLikeDeclaration(node);
55724 case 197 /* ObjectLiteralExpression */:
55725 return ts.some(node.properties, isContextSensitive);
55726 case 196 /* ArrayLiteralExpression */:
55727 return ts.some(node.elements, isContextSensitive);
55728 case 214 /* ConditionalExpression */:
55729 return isContextSensitive(node.whenTrue) ||
55730 isContextSensitive(node.whenFalse);
55731 case 213 /* BinaryExpression */:
55732 return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
55733 (isContextSensitive(node.left) || isContextSensitive(node.right));
55734 case 285 /* PropertyAssignment */:
55735 return isContextSensitive(node.initializer);
55736 case 204 /* ParenthesizedExpression */:
55737 return isContextSensitive(node.expression);
55738 case 278 /* JsxAttributes */:
55739 return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
55740 case 277 /* JsxAttribute */: {
55741 // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
55742 var initializer = node.initializer;
55743 return !!initializer && isContextSensitive(initializer);
55744 }
55745 case 280 /* JsxExpression */: {
55746 // It is possible to that node.expression is undefined (e.g <div x={} />)
55747 var expression = node.expression;
55748 return !!expression && isContextSensitive(expression);
55749 }
55750 }
55751 return false;
55752 }
55753 function isContextSensitiveFunctionLikeDeclaration(node) {
55754 return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
55755 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
55756 }
55757 function hasContextSensitiveParameters(node) {
55758 // Functions with type parameters are not context sensitive.
55759 if (!node.typeParameters) {
55760 // Functions with any parameters that lack type annotations are context sensitive.
55761 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
55762 return true;
55763 }
55764 if (node.kind !== 206 /* ArrowFunction */) {
55765 // If the first parameter is not an explicit 'this' parameter, then the function has
55766 // an implicit 'this' parameter which is subject to contextual typing.
55767 var parameter = ts.firstOrUndefined(node.parameters);
55768 if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
55769 return true;
55770 }
55771 }
55772 }
55773 return false;
55774 }
55775 function hasContextSensitiveReturnExpression(node) {
55776 // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
55777 return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 227 /* Block */ && isContextSensitive(node.body);
55778 }
55779 function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
55780 return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
55781 isContextSensitiveFunctionLikeDeclaration(func);
55782 }
55783 function getTypeWithoutSignatures(type) {
55784 if (type.flags & 524288 /* Object */) {
55785 var resolved = resolveStructuredTypeMembers(type);
55786 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
55787 var result = createObjectType(16 /* Anonymous */, type.symbol);
55788 result.members = resolved.members;
55789 result.properties = resolved.properties;
55790 result.callSignatures = ts.emptyArray;
55791 result.constructSignatures = ts.emptyArray;
55792 return result;
55793 }
55794 }
55795 else if (type.flags & 2097152 /* Intersection */) {
55796 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
55797 }
55798 return type;
55799 }
55800 // TYPE CHECKING
55801 function isTypeIdenticalTo(source, target) {
55802 return isTypeRelatedTo(source, target, identityRelation);
55803 }
55804 function compareTypesIdentical(source, target) {
55805 return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
55806 }
55807 function compareTypesAssignable(source, target) {
55808 return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
55809 }
55810 function compareTypesSubtypeOf(source, target) {
55811 return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
55812 }
55813 function isTypeSubtypeOf(source, target) {
55814 return isTypeRelatedTo(source, target, subtypeRelation);
55815 }
55816 function isTypeAssignableTo(source, target) {
55817 return isTypeRelatedTo(source, target, assignableRelation);
55818 }
55819 // An object type S is considered to be derived from an object type T if
55820 // S is a union type and every constituent of S is derived from T,
55821 // T is a union type and S is derived from at least one constituent of T, or
55822 // S is a type variable with a base constraint that is derived from T,
55823 // T is one of the global types Object and Function and S is a subtype of T, or
55824 // T occurs directly or indirectly in an 'extends' clause of S.
55825 // Note that this check ignores type parameters and only considers the
55826 // inheritance hierarchy.
55827 function isTypeDerivedFrom(source, target) {
55828 return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
55829 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
55830 source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
55831 target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
55832 target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
55833 hasBaseType(source, getTargetType(target));
55834 }
55835 /**
55836 * This is *not* a bi-directional relationship.
55837 * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
55838 *
55839 * 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.
55840 * It is used to check following cases:
55841 * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
55842 * - the types of `case` clause expressions and their respective `switch` expressions.
55843 * - the type of an expression in a type assertion with the type being asserted.
55844 */
55845 function isTypeComparableTo(source, target) {
55846 return isTypeRelatedTo(source, target, comparableRelation);
55847 }
55848 function areTypesComparable(type1, type2) {
55849 return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
55850 }
55851 function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
55852 return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
55853 }
55854 /**
55855 * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
55856 * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
55857 */
55858 function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
55859 return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
55860 }
55861 function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
55862 if (isTypeRelatedTo(source, target, relation))
55863 return true;
55864 if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
55865 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
55866 }
55867 return false;
55868 }
55869 function isOrHasGenericConditional(type) {
55870 return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
55871 }
55872 function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
55873 if (!node || isOrHasGenericConditional(target))
55874 return false;
55875 if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
55876 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
55877 return true;
55878 }
55879 switch (node.kind) {
55880 case 280 /* JsxExpression */:
55881 case 204 /* ParenthesizedExpression */:
55882 return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
55883 case 213 /* BinaryExpression */:
55884 switch (node.operatorToken.kind) {
55885 case 62 /* EqualsToken */:
55886 case 27 /* CommaToken */:
55887 return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
55888 }
55889 break;
55890 case 197 /* ObjectLiteralExpression */:
55891 return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
55892 case 196 /* ArrayLiteralExpression */:
55893 return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
55894 case 278 /* JsxAttributes */:
55895 return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
55896 case 206 /* ArrowFunction */:
55897 return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
55898 }
55899 return false;
55900 }
55901 function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
55902 var callSignatures = getSignaturesOfType(source, 0 /* Call */);
55903 var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
55904 for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
55905 var signatures = _a[_i];
55906 if (ts.some(signatures, function (s) {
55907 var returnType = getReturnTypeOfSignature(s);
55908 return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
55909 })) {
55910 var resultObj = errorOutputContainer || {};
55911 checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
55912 var diagnostic = resultObj.errors[resultObj.errors.length - 1];
55913 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));
55914 return true;
55915 }
55916 }
55917 return false;
55918 }
55919 function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
55920 // Don't elaborate blocks
55921 if (ts.isBlock(node.body)) {
55922 return false;
55923 }
55924 // Or functions with annotated parameter types
55925 if (ts.some(node.parameters, ts.hasType)) {
55926 return false;
55927 }
55928 var sourceSig = getSingleCallSignature(source);
55929 if (!sourceSig) {
55930 return false;
55931 }
55932 var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
55933 if (!ts.length(targetSignatures)) {
55934 return false;
55935 }
55936 var returnExpression = node.body;
55937 var sourceReturn = getReturnTypeOfSignature(sourceSig);
55938 var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
55939 if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
55940 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
55941 if (elaborated) {
55942 return elaborated;
55943 }
55944 var resultObj = errorOutputContainer || {};
55945 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
55946 if (resultObj.errors) {
55947 if (target.symbol && ts.length(target.symbol.declarations)) {
55948 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));
55949 }
55950 if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
55951 // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
55952 // an IPromise and a Promise that are slightly different
55953 && !getTypeOfPropertyOfType(sourceReturn, "then")
55954 && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
55955 ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
55956 }
55957 return true;
55958 }
55959 }
55960 return false;
55961 }
55962 function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
55963 var idx = getIndexedAccessTypeOrUndefined(target, nameType);
55964 if (idx) {
55965 return idx;
55966 }
55967 if (target.flags & 1048576 /* Union */) {
55968 var best = getBestMatchingType(source, target);
55969 if (best) {
55970 return getIndexedAccessTypeOrUndefined(best, nameType);
55971 }
55972 }
55973 }
55974 function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
55975 next.contextualType = sourcePropType;
55976 try {
55977 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
55978 }
55979 finally {
55980 next.contextualType = undefined;
55981 }
55982 }
55983 /**
55984 * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
55985 * 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`
55986 * Otherwise, we issue an error on _every_ element which fail the assignability check
55987 */
55988 function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
55989 // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
55990 var reportedError = false;
55991 for (var status = iterator.next(); !status.done; status = iterator.next()) {
55992 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
55993 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
55994 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
55995 continue; // Don't elaborate on indexes on generic variables
55996 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
55997 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
55998 var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
55999 if (elaborated) {
56000 reportedError = true;
56001 }
56002 else {
56003 // Issue error on the prop itself, since the prop couldn't elaborate the error
56004 var resultObj = errorOutputContainer || {};
56005 // Use the expression type, if available
56006 var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
56007 var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
56008 if (result && specificSource !== sourcePropType) {
56009 // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
56010 checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
56011 }
56012 if (resultObj.errors) {
56013 var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
56014 var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
56015 var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
56016 var issuedElaboration = false;
56017 if (!targetProp) {
56018 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
56019 getIndexInfoOfType(target, 0 /* String */) ||
56020 undefined;
56021 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
56022 issuedElaboration = true;
56023 ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
56024 }
56025 }
56026 if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
56027 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
56028 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
56029 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)));
56030 }
56031 }
56032 }
56033 reportedError = true;
56034 }
56035 }
56036 }
56037 return reportedError;
56038 }
56039 function generateJsxAttributes(node) {
56040 var _i, _a, prop;
56041 return __generator(this, function (_b) {
56042 switch (_b.label) {
56043 case 0:
56044 if (!ts.length(node.properties))
56045 return [2 /*return*/];
56046 _i = 0, _a = node.properties;
56047 _b.label = 1;
56048 case 1:
56049 if (!(_i < _a.length)) return [3 /*break*/, 4];
56050 prop = _a[_i];
56051 if (ts.isJsxSpreadAttribute(prop))
56052 return [3 /*break*/, 3];
56053 return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
56054 case 2:
56055 _b.sent();
56056 _b.label = 3;
56057 case 3:
56058 _i++;
56059 return [3 /*break*/, 1];
56060 case 4: return [2 /*return*/];
56061 }
56062 });
56063 }
56064 function generateJsxChildren(node, getInvalidTextDiagnostic) {
56065 var memberOffset, i, child, nameType, elem;
56066 return __generator(this, function (_a) {
56067 switch (_a.label) {
56068 case 0:
56069 if (!ts.length(node.children))
56070 return [2 /*return*/];
56071 memberOffset = 0;
56072 i = 0;
56073 _a.label = 1;
56074 case 1:
56075 if (!(i < node.children.length)) return [3 /*break*/, 5];
56076 child = node.children[i];
56077 nameType = getLiteralType(i - memberOffset);
56078 elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
56079 if (!elem) return [3 /*break*/, 3];
56080 return [4 /*yield*/, elem];
56081 case 2:
56082 _a.sent();
56083 return [3 /*break*/, 4];
56084 case 3:
56085 memberOffset++;
56086 _a.label = 4;
56087 case 4:
56088 i++;
56089 return [3 /*break*/, 1];
56090 case 5: return [2 /*return*/];
56091 }
56092 });
56093 }
56094 function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
56095 switch (child.kind) {
56096 case 280 /* JsxExpression */:
56097 // child is of the type of the expression
56098 return { errorNode: child, innerExpression: child.expression, nameType: nameType };
56099 case 11 /* JsxText */:
56100 if (child.containsOnlyTriviaWhiteSpaces) {
56101 break; // Whitespace only jsx text isn't real jsx text
56102 }
56103 // child is a string
56104 return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
56105 case 270 /* JsxElement */:
56106 case 271 /* JsxSelfClosingElement */:
56107 case 274 /* JsxFragment */:
56108 // child is of type JSX.Element
56109 return { errorNode: child, innerExpression: child, nameType: nameType };
56110 default:
56111 return ts.Debug.assertNever(child, "Found invalid jsx child");
56112 }
56113 }
56114 function getSemanticJsxChildren(children) {
56115 return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
56116 }
56117 function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
56118 var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
56119 var invalidTextDiagnostic;
56120 if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
56121 var containingElement = node.parent.parent;
56122 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
56123 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
56124 var childrenNameType = getLiteralType(childrenPropName);
56125 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
56126 var validChildren = getSemanticJsxChildren(containingElement.children);
56127 if (!ts.length(validChildren)) {
56128 return result;
56129 }
56130 var moreThanOneRealChildren = ts.length(validChildren) > 1;
56131 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
56132 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
56133 if (moreThanOneRealChildren) {
56134 if (arrayLikeTargetParts !== neverType) {
56135 var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
56136 var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
56137 result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
56138 }
56139 else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
56140 // arity mismatch
56141 result = true;
56142 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));
56143 if (errorOutputContainer && errorOutputContainer.skipLogging) {
56144 (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
56145 }
56146 }
56147 }
56148 else {
56149 if (nonArrayLikeTargetParts !== neverType) {
56150 var child = validChildren[0];
56151 var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
56152 if (elem_1) {
56153 result = elaborateElementwise((function () { return __generator(this, function (_a) {
56154 switch (_a.label) {
56155 case 0: return [4 /*yield*/, elem_1];
56156 case 1:
56157 _a.sent();
56158 return [2 /*return*/];
56159 }
56160 }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
56161 }
56162 }
56163 else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
56164 // arity mismatch
56165 result = true;
56166 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));
56167 if (errorOutputContainer && errorOutputContainer.skipLogging) {
56168 (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
56169 }
56170 }
56171 }
56172 }
56173 return result;
56174 function getInvalidTextualChildDiagnostic() {
56175 if (!invalidTextDiagnostic) {
56176 var tagNameText = ts.getTextOfNode(node.parent.tagName);
56177 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
56178 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
56179 var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
56180 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;
56181 invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
56182 }
56183 return invalidTextDiagnostic;
56184 }
56185 }
56186 function generateLimitedTupleElements(node, target) {
56187 var len, i, elem, nameType;
56188 return __generator(this, function (_a) {
56189 switch (_a.label) {
56190 case 0:
56191 len = ts.length(node.elements);
56192 if (!len)
56193 return [2 /*return*/];
56194 i = 0;
56195 _a.label = 1;
56196 case 1:
56197 if (!(i < len)) return [3 /*break*/, 4];
56198 // 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
56199 if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
56200 return [3 /*break*/, 3];
56201 elem = node.elements[i];
56202 if (ts.isOmittedExpression(elem))
56203 return [3 /*break*/, 3];
56204 nameType = getLiteralType(i);
56205 return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
56206 case 2:
56207 _a.sent();
56208 _a.label = 3;
56209 case 3:
56210 i++;
56211 return [3 /*break*/, 1];
56212 case 4: return [2 /*return*/];
56213 }
56214 });
56215 }
56216 function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
56217 if (target.flags & 131068 /* Primitive */)
56218 return false;
56219 if (isTupleLikeType(source)) {
56220 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
56221 }
56222 // recreate a tuple from the elements, if possible
56223 // Since we're re-doing the expression type, we need to reapply the contextual type
56224 var oldContext = node.contextualType;
56225 node.contextualType = target;
56226 try {
56227 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
56228 node.contextualType = oldContext;
56229 if (isTupleLikeType(tupleizedType)) {
56230 return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
56231 }
56232 return false;
56233 }
56234 finally {
56235 node.contextualType = oldContext;
56236 }
56237 }
56238 function generateObjectLiteralElements(node) {
56239 var _i, _a, prop, type, _b;
56240 return __generator(this, function (_c) {
56241 switch (_c.label) {
56242 case 0:
56243 if (!ts.length(node.properties))
56244 return [2 /*return*/];
56245 _i = 0, _a = node.properties;
56246 _c.label = 1;
56247 case 1:
56248 if (!(_i < _a.length)) return [3 /*break*/, 8];
56249 prop = _a[_i];
56250 if (ts.isSpreadAssignment(prop))
56251 return [3 /*break*/, 7];
56252 type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
56253 if (!type || (type.flags & 131072 /* Never */)) {
56254 return [3 /*break*/, 7];
56255 }
56256 _b = prop.kind;
56257 switch (_b) {
56258 case 167 /* SetAccessor */: return [3 /*break*/, 2];
56259 case 166 /* GetAccessor */: return [3 /*break*/, 2];
56260 case 164 /* MethodDeclaration */: return [3 /*break*/, 2];
56261 case 286 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
56262 case 285 /* PropertyAssignment */: return [3 /*break*/, 4];
56263 }
56264 return [3 /*break*/, 6];
56265 case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
56266 case 3:
56267 _c.sent();
56268 return [3 /*break*/, 7];
56269 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 }];
56270 case 5:
56271 _c.sent();
56272 return [3 /*break*/, 7];
56273 case 6:
56274 ts.Debug.assertNever(prop);
56275 _c.label = 7;
56276 case 7:
56277 _i++;
56278 return [3 /*break*/, 1];
56279 case 8: return [2 /*return*/];
56280 }
56281 });
56282 }
56283 function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
56284 if (target.flags & 131068 /* Primitive */)
56285 return false;
56286 return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
56287 }
56288 /**
56289 * This is *not* a bi-directional relationship.
56290 * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
56291 */
56292 function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
56293 return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
56294 }
56295 function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
56296 return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false,
56297 /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
56298 }
56299 /**
56300 * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
56301 */
56302 function isAnySignature(s) {
56303 return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
56304 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
56305 isTypeAny(getReturnTypeOfSignature(s));
56306 }
56307 /**
56308 * See signatureRelatedTo, compareSignaturesIdentical
56309 */
56310 function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
56311 // TODO (drosen): De-duplicate code between related functions.
56312 if (source === target) {
56313 return -1 /* True */;
56314 }
56315 if (isAnySignature(target)) {
56316 return -1 /* True */;
56317 }
56318 var targetCount = getParameterCount(target);
56319 var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
56320 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
56321 if (sourceHasMoreParameters) {
56322 return 0 /* False */;
56323 }
56324 if (source.typeParameters && source.typeParameters !== target.typeParameters) {
56325 target = getCanonicalSignature(target);
56326 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
56327 }
56328 var sourceCount = getParameterCount(source);
56329 var sourceRestType = getNonArrayRestType(source);
56330 var targetRestType = getNonArrayRestType(target);
56331 if (sourceRestType || targetRestType) {
56332 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
56333 }
56334 if (sourceRestType && targetRestType && sourceCount !== targetCount) {
56335 // We're not able to relate misaligned complex rest parameters
56336 return 0 /* False */;
56337 }
56338 var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
56339 var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 164 /* MethodDeclaration */ &&
56340 kind !== 163 /* MethodSignature */ && kind !== 165 /* Constructor */;
56341 var result = -1 /* True */;
56342 var sourceThisType = getThisTypeOfSignature(source);
56343 if (sourceThisType && sourceThisType !== voidType) {
56344 var targetThisType = getThisTypeOfSignature(target);
56345 if (targetThisType) {
56346 // void sources are assignable to anything.
56347 var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
56348 || compareTypes(targetThisType, sourceThisType, reportErrors);
56349 if (!related) {
56350 if (reportErrors) {
56351 errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
56352 }
56353 return 0 /* False */;
56354 }
56355 result &= related;
56356 }
56357 }
56358 var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
56359 var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
56360 for (var i = 0; i < paramCount; i++) {
56361 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
56362 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
56363 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
56364 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
56365 // they naturally relate only contra-variantly). However, if the source and target parameters both have
56366 // function types with a single call signature, we know we are relating two callback parameters. In
56367 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
56368 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
56369 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
56370 // with respect to T.
56371 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
56372 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
56373 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
56374 (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
56375 var related = callbacks ?
56376 compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
56377 !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
56378 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
56379 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
56380 related = 0 /* False */;
56381 }
56382 if (!related) {
56383 if (reportErrors) {
56384 errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
56385 }
56386 return 0 /* False */;
56387 }
56388 result &= related;
56389 }
56390 if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
56391 // If a signature resolution is already in-flight, skip issuing a circularity error
56392 // here and just use the `any` type directly
56393 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
56394 : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
56395 : getReturnTypeOfSignature(target);
56396 if (targetReturnType === voidType) {
56397 return result;
56398 }
56399 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
56400 : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
56401 : getReturnTypeOfSignature(source);
56402 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
56403 var targetTypePredicate = getTypePredicateOfSignature(target);
56404 if (targetTypePredicate) {
56405 var sourceTypePredicate = getTypePredicateOfSignature(source);
56406 if (sourceTypePredicate) {
56407 result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
56408 }
56409 else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
56410 if (reportErrors) {
56411 errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
56412 }
56413 return 0 /* False */;
56414 }
56415 }
56416 else {
56417 // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
56418 // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
56419 // wouldn't be co-variant for T without this rule.
56420 result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
56421 compareTypes(sourceReturnType, targetReturnType, reportErrors);
56422 if (!result && reportErrors && incompatibleErrorReporter) {
56423 incompatibleErrorReporter(sourceReturnType, targetReturnType);
56424 }
56425 }
56426 }
56427 return result;
56428 }
56429 function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
56430 if (source.kind !== target.kind) {
56431 if (reportErrors) {
56432 errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
56433 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
56434 }
56435 return 0 /* False */;
56436 }
56437 if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
56438 if (source.parameterIndex !== target.parameterIndex) {
56439 if (reportErrors) {
56440 errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
56441 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
56442 }
56443 return 0 /* False */;
56444 }
56445 }
56446 var related = source.type === target.type ? -1 /* True */ :
56447 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
56448 0 /* False */;
56449 if (related === 0 /* False */ && reportErrors) {
56450 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
56451 }
56452 return related;
56453 }
56454 function isImplementationCompatibleWithOverload(implementation, overload) {
56455 var erasedSource = getErasedSignature(implementation);
56456 var erasedTarget = getErasedSignature(overload);
56457 // First see if the return types are compatible in either direction.
56458 var sourceReturnType = getReturnTypeOfSignature(erasedSource);
56459 var targetReturnType = getReturnTypeOfSignature(erasedTarget);
56460 if (targetReturnType === voidType
56461 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
56462 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
56463 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
56464 }
56465 return false;
56466 }
56467 function isEmptyResolvedType(t) {
56468 return t !== anyFunctionType &&
56469 t.properties.length === 0 &&
56470 t.callSignatures.length === 0 &&
56471 t.constructSignatures.length === 0 &&
56472 !t.stringIndexInfo &&
56473 !t.numberIndexInfo;
56474 }
56475 function isEmptyObjectType(type) {
56476 return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
56477 type.flags & 67108864 /* NonPrimitive */ ? true :
56478 type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
56479 type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
56480 false;
56481 }
56482 function isEmptyAnonymousObjectType(type) {
56483 return !!(ts.getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) ||
56484 type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
56485 }
56486 function isStringIndexSignatureOnlyType(type) {
56487 return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
56488 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
56489 false;
56490 }
56491 function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
56492 if (sourceSymbol === targetSymbol) {
56493 return true;
56494 }
56495 var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
56496 var entry = enumRelation.get(id);
56497 if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
56498 return !!(entry & 1 /* Succeeded */);
56499 }
56500 if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
56501 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
56502 return false;
56503 }
56504 var targetEnumType = getTypeOfSymbol(targetSymbol);
56505 for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
56506 var property = _a[_i];
56507 if (property.flags & 8 /* EnumMember */) {
56508 var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
56509 if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
56510 if (errorReporter) {
56511 errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
56512 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
56513 }
56514 else {
56515 enumRelation.set(id, 2 /* Failed */);
56516 }
56517 return false;
56518 }
56519 }
56520 }
56521 enumRelation.set(id, 1 /* Succeeded */);
56522 return true;
56523 }
56524 function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
56525 var s = source.flags;
56526 var t = target.flags;
56527 if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
56528 return true;
56529 if (t & 131072 /* Never */)
56530 return false;
56531 if (s & 132 /* StringLike */ && t & 4 /* String */)
56532 return true;
56533 if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
56534 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
56535 source.value === target.value)
56536 return true;
56537 if (s & 296 /* NumberLike */ && t & 8 /* Number */)
56538 return true;
56539 if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
56540 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
56541 source.value === target.value)
56542 return true;
56543 if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
56544 return true;
56545 if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
56546 return true;
56547 if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
56548 return true;
56549 if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
56550 return true;
56551 if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
56552 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
56553 return true;
56554 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
56555 source.value === target.value &&
56556 isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
56557 return true;
56558 }
56559 if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
56560 return true;
56561 if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
56562 return true;
56563 if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
56564 return true;
56565 if (relation === assignableRelation || relation === comparableRelation) {
56566 if (s & 1 /* Any */)
56567 return true;
56568 // Type number or any numeric literal type is assignable to any numeric enum type or any
56569 // numeric enum literal type. This rule exists for backwards compatibility reasons because
56570 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
56571 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
56572 return true;
56573 }
56574 return false;
56575 }
56576 function isTypeRelatedTo(source, target, relation) {
56577 if (isFreshLiteralType(source)) {
56578 source = source.regularType;
56579 }
56580 if (isFreshLiteralType(target)) {
56581 target = target.regularType;
56582 }
56583 if (source === target) {
56584 return true;
56585 }
56586 if (relation !== identityRelation) {
56587 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
56588 return true;
56589 }
56590 }
56591 else {
56592 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
56593 source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
56594 return false;
56595 }
56596 if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
56597 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
56598 if (related !== undefined) {
56599 return !!(related & 1 /* Succeeded */);
56600 }
56601 }
56602 if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
56603 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
56604 }
56605 return false;
56606 }
56607 function isIgnoredJsxProperty(source, sourceProp) {
56608 return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
56609 }
56610 function getNormalizedType(type, writing) {
56611 while (true) {
56612 var t = isFreshLiteralType(type) ? type.regularType :
56613 ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
56614 type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
56615 type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
56616 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
56617 type;
56618 if (t === type)
56619 break;
56620 type = t;
56621 }
56622 return type;
56623 }
56624 /**
56625 * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
56626 * @param source The left-hand-side of the relation.
56627 * @param target The right-hand-side of the relation.
56628 * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
56629 * Used as both to determine which checks are performed and as a cache of previously computed results.
56630 * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
56631 * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
56632 * @param containingMessageChain A chain of errors to prepend any new errors found.
56633 * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
56634 */
56635 function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
56636 var errorInfo;
56637 var relatedInfo;
56638 var maybeKeys;
56639 var sourceStack;
56640 var targetStack;
56641 var maybeCount = 0;
56642 var depth = 0;
56643 var expandingFlags = 0 /* None */;
56644 var overflow = false;
56645 var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
56646 var lastSkippedInfo;
56647 var incompatibleStack = [];
56648 var inPropertyCheck = false;
56649 ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
56650 var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
56651 if (incompatibleStack.length) {
56652 reportIncompatibleStack();
56653 }
56654 if (overflow) {
56655 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
56656 if (errorOutputContainer) {
56657 (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
56658 }
56659 }
56660 else if (errorInfo) {
56661 if (containingMessageChain) {
56662 var chain = containingMessageChain();
56663 if (chain) {
56664 ts.concatenateDiagnosticMessageChains(chain, errorInfo);
56665 errorInfo = chain;
56666 }
56667 }
56668 var relatedInformation = void 0;
56669 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
56670 if (headMessage && errorNode && !result && source.symbol) {
56671 var links = getSymbolLinks(source.symbol);
56672 if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
56673 var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
56674 if (helpfulRetry) {
56675 // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
56676 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);
56677 relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
56678 }
56679 }
56680 }
56681 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
56682 if (relatedInfo) {
56683 ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
56684 }
56685 if (errorOutputContainer) {
56686 (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
56687 }
56688 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
56689 diagnostics.add(diag);
56690 }
56691 }
56692 if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
56693 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
56694 }
56695 return result !== 0 /* False */;
56696 function resetErrorInfo(saved) {
56697 errorInfo = saved.errorInfo;
56698 lastSkippedInfo = saved.lastSkippedInfo;
56699 incompatibleStack = saved.incompatibleStack;
56700 overrideNextErrorInfo = saved.overrideNextErrorInfo;
56701 relatedInfo = saved.relatedInfo;
56702 }
56703 function captureErrorCalculationState() {
56704 return {
56705 errorInfo: errorInfo,
56706 lastSkippedInfo: lastSkippedInfo,
56707 incompatibleStack: incompatibleStack.slice(),
56708 overrideNextErrorInfo: overrideNextErrorInfo,
56709 relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
56710 };
56711 }
56712 function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
56713 overrideNextErrorInfo++; // Suppress the next relation error
56714 lastSkippedInfo = undefined; // Reset skipped info cache
56715 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
56716 }
56717 function reportIncompatibleStack() {
56718 var stack = incompatibleStack;
56719 incompatibleStack = [];
56720 var info = lastSkippedInfo;
56721 lastSkippedInfo = undefined;
56722 if (stack.length === 1) {
56723 reportError.apply(void 0, stack[0]);
56724 if (info) {
56725 // Actually do the last relation error
56726 reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
56727 }
56728 return;
56729 }
56730 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
56731 // we can build from left to right
56732 var path = "";
56733 var secondaryRootErrors = [];
56734 while (stack.length) {
56735 var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
56736 switch (msg.code) {
56737 case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
56738 // Parenthesize a `new` if there is one
56739 if (path.indexOf("new ") === 0) {
56740 path = "(" + path + ")";
56741 }
56742 var str = "" + args[0];
56743 // If leading, just print back the arg (irrespective of if it's a valid identifier)
56744 if (path.length === 0) {
56745 path = "" + str;
56746 }
56747 // Otherwise write a dotted name if possible
56748 else if (ts.isIdentifierText(str, compilerOptions.target)) {
56749 path = path + "." + str;
56750 }
56751 // Failing that, check if the name is already a computed name
56752 else if (str[0] === "[" && str[str.length - 1] === "]") {
56753 path = "" + path + str;
56754 }
56755 // And finally write out a computed name as a last resort
56756 else {
56757 path = path + "[" + str + "]";
56758 }
56759 break;
56760 }
56761 case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
56762 case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
56763 case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
56764 case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
56765 if (path.length === 0) {
56766 // Don't flatten signature compatability errors at the start of a chain - instead prefer
56767 // to unify (the with no arguments bit is excessive for printback) and print them back
56768 var mappedMsg = msg;
56769 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
56770 mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
56771 }
56772 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
56773 mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
56774 }
56775 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
56776 }
56777 else {
56778 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
56779 msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
56780 ? "new "
56781 : "";
56782 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
56783 msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
56784 ? ""
56785 : "...";
56786 path = "" + prefix + path + "(" + params + ")";
56787 }
56788 break;
56789 }
56790 default:
56791 return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
56792 }
56793 }
56794 if (path) {
56795 reportError(path[path.length - 1] === ")"
56796 ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
56797 : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
56798 }
56799 else {
56800 // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
56801 secondaryRootErrors.shift();
56802 }
56803 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
56804 var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
56805 var originalValue = msg.elidedInCompatabilityPyramid;
56806 msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
56807 reportError.apply(void 0, __spreadArrays([msg], args));
56808 msg.elidedInCompatabilityPyramid = originalValue;
56809 }
56810 if (info) {
56811 // Actually do the last relation error
56812 reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
56813 }
56814 }
56815 function reportError(message, arg0, arg1, arg2, arg3) {
56816 ts.Debug.assert(!!errorNode);
56817 if (incompatibleStack.length)
56818 reportIncompatibleStack();
56819 if (message.elidedInCompatabilityPyramid)
56820 return;
56821 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
56822 }
56823 function associateRelatedInfo(info) {
56824 ts.Debug.assert(!!errorInfo);
56825 if (!relatedInfo) {
56826 relatedInfo = [info];
56827 }
56828 else {
56829 relatedInfo.push(info);
56830 }
56831 }
56832 function reportRelationError(message, source, target) {
56833 if (incompatibleStack.length)
56834 reportIncompatibleStack();
56835 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
56836 var generalizedSource = source;
56837 var generalizedSourceType = sourceType;
56838 if (isLiteralType(source) && !typeCouldHaveTopLevelSingletonTypes(target)) {
56839 generalizedSource = getBaseTypeOfLiteralType(source);
56840 ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable");
56841 generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
56842 }
56843 if (target.flags & 262144 /* TypeParameter */) {
56844 var constraint = getBaseConstraintOfType(target);
56845 var needsOriginalSource = void 0;
56846 if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) {
56847 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));
56848 }
56849 else {
56850 reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType);
56851 }
56852 }
56853 if (!message) {
56854 if (relation === comparableRelation) {
56855 message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
56856 }
56857 else if (sourceType === targetType) {
56858 message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
56859 }
56860 else {
56861 message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
56862 }
56863 }
56864 reportError(message, generalizedSourceType, targetType);
56865 }
56866 function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
56867 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
56868 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
56869 if ((globalStringType === source && stringType === target) ||
56870 (globalNumberType === source && numberType === target) ||
56871 (globalBooleanType === source && booleanType === target) ||
56872 (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
56873 reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
56874 }
56875 }
56876 /**
56877 * Try and elaborate array and tuple errors. Returns false
56878 * if we have found an elaboration, or we should ignore
56879 * any other elaborations when relating the `source` and
56880 * `target` types.
56881 */
56882 function tryElaborateArrayLikeErrors(source, target, reportErrors) {
56883 /**
56884 * The spec for elaboration is:
56885 * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
56886 * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
56887 * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
56888 * - If the source an array then skip property elaborations if the target is a tuple.
56889 */
56890 if (isTupleType(source)) {
56891 if (source.target.readonly && isMutableArrayOrTuple(target)) {
56892 if (reportErrors) {
56893 reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
56894 }
56895 return false;
56896 }
56897 return isTupleType(target) || isArrayType(target);
56898 }
56899 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
56900 if (reportErrors) {
56901 reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
56902 }
56903 return false;
56904 }
56905 if (isTupleType(target)) {
56906 return isArrayType(source);
56907 }
56908 return true;
56909 }
56910 /**
56911 * Compare two types and return
56912 * * Ternary.True if they are related with no assumptions,
56913 * * Ternary.Maybe if they are related with assumptions of other relationships, or
56914 * * Ternary.False if they are not related.
56915 */
56916 function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
56917 if (reportErrors === void 0) { reportErrors = false; }
56918 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
56919 // Before normalization: if `source` is type an object type, and `target` is primitive,
56920 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
56921 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
56922 if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
56923 return -1 /* True */;
56924 }
56925 reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
56926 return 0 /* False */;
56927 }
56928 // Normalize the source and target types: Turn fresh literal types into regular literal types,
56929 // turn deferred type references into regular type references, simplify indexed access and
56930 // conditional types, and resolve substitution types to either the substitution (on the source
56931 // side) or the type variable (on the target side).
56932 var source = getNormalizedType(originalSource, /*writing*/ false);
56933 var target = getNormalizedType(originalTarget, /*writing*/ true);
56934 if (source === target)
56935 return -1 /* True */;
56936 if (relation === identityRelation) {
56937 return isIdenticalTo(source, target);
56938 }
56939 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
56940 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
56941 // as we break down the _target_ union first, _then_ get the source constraint - so for every
56942 // member of the target, we attempt to find a match in the source. This avoids that in cases where
56943 // the target is exactly the constraint.
56944 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
56945 return -1 /* True */;
56946 }
56947 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
56948 // If so, reporting the `null` and `undefined` in the type is hardly useful.
56949 // First, see if we're even relating an object type to a union.
56950 // Then see if the target is stripped down to a single non-union type.
56951 // Note
56952 // * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
56953 // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
56954 // when dealing with generics.
56955 // * We also don't deal with primitive source types, since we already halt elaboration below.
56956 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
56957 target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
56958 var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
56959 if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
56960 if (source === nullStrippedTarget)
56961 return -1 /* True */;
56962 target = nullStrippedTarget;
56963 }
56964 }
56965 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
56966 isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
56967 return -1 /* True */;
56968 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
56969 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
56970 if (isPerformingExcessPropertyChecks) {
56971 if (hasExcessProperties(source, target, reportErrors)) {
56972 if (reportErrors) {
56973 reportRelationError(headMessage, source, target);
56974 }
56975 return 0 /* False */;
56976 }
56977 }
56978 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
56979 source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
56980 target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
56981 (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
56982 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
56983 if (reportErrors) {
56984 var calls = getSignaturesOfType(source, 0 /* Call */);
56985 var constructs = getSignaturesOfType(source, 1 /* Construct */);
56986 if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
56987 constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
56988 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));
56989 }
56990 else {
56991 reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
56992 }
56993 }
56994 return 0 /* False */;
56995 }
56996 var result = 0 /* False */;
56997 var saveErrorInfo = captureErrorCalculationState();
56998 // Note that these checks are specifically ordered to produce correct results. In particular,
56999 // we need to deconstruct unions before intersections (because unions are always at the top),
57000 // and we need to handle "each" relations before "some" relations for the same kind of type.
57001 if (source.flags & 1048576 /* Union */) {
57002 result = relation === comparableRelation ?
57003 someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
57004 eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
57005 }
57006 else {
57007 if (target.flags & 1048576 /* Union */) {
57008 result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
57009 }
57010 else if (target.flags & 2097152 /* Intersection */) {
57011 result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
57012 }
57013 else if (source.flags & 2097152 /* Intersection */) {
57014 // Check to see if any constituents of the intersection are immediately related to the target.
57015 //
57016 // Don't report errors though. Checking whether a constituent is related to the source is not actually
57017 // useful and leads to some confusing error messages. Instead it is better to let the below checks
57018 // take care of this, or to not elaborate at all. For instance,
57019 //
57020 // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
57021 //
57022 // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
57023 // than to report that 'D' is not assignable to 'A' or 'B'.
57024 //
57025 // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
57026 // breaking the intersection apart.
57027 result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
57028 }
57029 if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
57030 if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
57031 resetErrorInfo(saveErrorInfo);
57032 }
57033 }
57034 }
57035 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
57036 // The combined constraint of an intersection type is the intersection of the constraints of
57037 // the constituents. When an intersection type contains instantiable types with union type
57038 // constraints, there are situations where we need to examine the combined constraint. One is
57039 // when the target is a union type. Another is when the intersection contains types belonging
57040 // to one of the disjoint domains. For example, given type variables T and U, each with the
57041 // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
57042 // we need to check this constraint against a union on the target side. Also, given a type
57043 // variable V constrained to 'string | number', 'V & number' has a combined constraint of
57044 // 'string & number | number & number' which reduces to just 'number'.
57045 // This also handles type parameters, as a type parameter with a union constraint compared against a union
57046 // needs to have its constraint hoisted into an intersection with said type parameter, this way
57047 // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
57048 // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
57049 var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
57050 if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
57051 if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
57052 // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
57053 if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
57054 resetErrorInfo(saveErrorInfo);
57055 }
57056 }
57057 }
57058 }
57059 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
57060 // an extra property check where the intersection is viewed as a single object. The following are motivating
57061 // examples that all should be errors, but aren't without this extra property check:
57062 //
57063 // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property
57064 //
57065 // declare let wrong: { a: { y: string } };
57066 // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type
57067 //
57068 // function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
57069 // x = y; // Mismatched property in source intersection
57070 // }
57071 //
57072 // We suppress recursive intersection property checks because they can generate lots of work when relating
57073 // recursive intersections that are structurally similar but not exactly identical. See #37854.
57074 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
57075 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 */); }))) {
57076 inPropertyCheck = true;
57077 result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
57078 inPropertyCheck = false;
57079 }
57080 reportErrorResults(source, target, result, isComparingJsxAttributes);
57081 return result;
57082 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
57083 if (!result && reportErrors) {
57084 source = originalSource.aliasSymbol ? originalSource : source;
57085 target = originalTarget.aliasSymbol ? originalTarget : target;
57086 var maybeSuppress = overrideNextErrorInfo > 0;
57087 if (maybeSuppress) {
57088 overrideNextErrorInfo--;
57089 }
57090 if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
57091 var currentError = errorInfo;
57092 tryElaborateArrayLikeErrors(source, target, reportErrors);
57093 if (errorInfo !== currentError) {
57094 maybeSuppress = !!errorInfo;
57095 }
57096 }
57097 if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
57098 tryElaborateErrorsForPrimitivesAndObjects(source, target);
57099 }
57100 else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
57101 reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
57102 }
57103 else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
57104 var targetTypes = target.types;
57105 var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
57106 var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
57107 if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
57108 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
57109 // do not report top error
57110 return result;
57111 }
57112 }
57113 else {
57114 errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
57115 }
57116 if (!headMessage && maybeSuppress) {
57117 lastSkippedInfo = [source, target];
57118 // Used by, eg, missing property checking to replace the top-level message with a more informative one
57119 return result;
57120 }
57121 reportRelationError(headMessage, source, target);
57122 }
57123 }
57124 }
57125 function isIdenticalTo(source, target) {
57126 var flags = source.flags & target.flags;
57127 if (!(flags & 66584576 /* Substructure */)) {
57128 return 0 /* False */;
57129 }
57130 if (flags & 3145728 /* UnionOrIntersection */) {
57131 var result_6 = eachTypeRelatedToSomeType(source, target);
57132 if (result_6) {
57133 result_6 &= eachTypeRelatedToSomeType(target, source);
57134 }
57135 return result_6;
57136 }
57137 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
57138 }
57139 function getTypeOfPropertyInTypes(types, name) {
57140 var appendPropType = function (propTypes, type) {
57141 type = getApparentType(type);
57142 var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
57143 var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
57144 return ts.append(propTypes, propType);
57145 };
57146 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
57147 }
57148 function hasExcessProperties(source, target, reportErrors) {
57149 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
57150 return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
57151 }
57152 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
57153 if ((relation === assignableRelation || relation === comparableRelation) &&
57154 (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
57155 return false;
57156 }
57157 var reducedTarget = target;
57158 var checkTypes;
57159 if (target.flags & 1048576 /* Union */) {
57160 reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
57161 checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
57162 }
57163 var _loop_15 = function (prop) {
57164 if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
57165 if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
57166 if (reportErrors) {
57167 // Report error in terms of object types in the target as those are the only ones
57168 // we check in isKnownProperty.
57169 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
57170 // We know *exactly* where things went wrong when comparing the types.
57171 // Use this property as the error node as this will be more helpful in
57172 // reasoning about what went wrong.
57173 if (!errorNode)
57174 return { value: ts.Debug.fail() };
57175 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
57176 // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
57177 // However, using an object-literal error message will be very confusing to the users so we give different a message.
57178 if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
57179 // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
57180 // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
57181 errorNode = prop.valueDeclaration.name;
57182 }
57183 var propName = symbolToString(prop);
57184 var suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
57185 var suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : undefined;
57186 if (suggestion) {
57187 reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
57188 }
57189 else {
57190 reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
57191 }
57192 }
57193 else {
57194 // use the property's value declaration if the property is assigned inside the literal itself
57195 var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
57196 var suggestion = void 0;
57197 if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
57198 var propDeclaration = prop.valueDeclaration;
57199 ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
57200 errorNode = propDeclaration;
57201 var name = propDeclaration.name;
57202 if (ts.isIdentifier(name)) {
57203 suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
57204 }
57205 }
57206 if (suggestion !== undefined) {
57207 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);
57208 }
57209 else {
57210 reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
57211 }
57212 }
57213 }
57214 return { value: true };
57215 }
57216 if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
57217 if (reportErrors) {
57218 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
57219 }
57220 return { value: true };
57221 }
57222 }
57223 };
57224 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
57225 var prop = _a[_i];
57226 var state_5 = _loop_15(prop);
57227 if (typeof state_5 === "object")
57228 return state_5.value;
57229 }
57230 return false;
57231 }
57232 function shouldCheckAsExcessProperty(prop, container) {
57233 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
57234 }
57235 function eachTypeRelatedToSomeType(source, target) {
57236 var result = -1 /* True */;
57237 var sourceTypes = source.types;
57238 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
57239 var sourceType = sourceTypes_1[_i];
57240 var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
57241 if (!related) {
57242 return 0 /* False */;
57243 }
57244 result &= related;
57245 }
57246 return result;
57247 }
57248 function typeRelatedToSomeType(source, target, reportErrors) {
57249 var targetTypes = target.types;
57250 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
57251 return -1 /* True */;
57252 }
57253 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
57254 var type = targetTypes_1[_i];
57255 var related = isRelatedTo(source, type, /*reportErrors*/ false);
57256 if (related) {
57257 return related;
57258 }
57259 }
57260 if (reportErrors) {
57261 var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
57262 isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
57263 }
57264 return 0 /* False */;
57265 }
57266 function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
57267 var result = -1 /* True */;
57268 var targetTypes = target.types;
57269 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
57270 var targetType = targetTypes_2[_i];
57271 var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
57272 if (!related) {
57273 return 0 /* False */;
57274 }
57275 result &= related;
57276 }
57277 return result;
57278 }
57279 function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
57280 var sourceTypes = source.types;
57281 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
57282 return -1 /* True */;
57283 }
57284 var len = sourceTypes.length;
57285 for (var i = 0; i < len; i++) {
57286 var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
57287 if (related) {
57288 return related;
57289 }
57290 }
57291 return 0 /* False */;
57292 }
57293 function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
57294 var result = -1 /* True */;
57295 var sourceTypes = source.types;
57296 for (var i = 0; i < sourceTypes.length; i++) {
57297 var sourceType = sourceTypes[i];
57298 if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
57299 // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
57300 var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
57301 if (related_1) {
57302 result &= related_1;
57303 continue;
57304 }
57305 }
57306 var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
57307 if (!related) {
57308 return 0 /* False */;
57309 }
57310 result &= related;
57311 }
57312 return result;
57313 }
57314 function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
57315 if (sources === void 0) { sources = ts.emptyArray; }
57316 if (targets === void 0) { targets = ts.emptyArray; }
57317 if (variances === void 0) { variances = ts.emptyArray; }
57318 if (sources.length !== targets.length && relation === identityRelation) {
57319 return 0 /* False */;
57320 }
57321 var length = sources.length <= targets.length ? sources.length : targets.length;
57322 var result = -1 /* True */;
57323 for (var i = 0; i < length; i++) {
57324 // When variance information isn't available we default to covariance. This happens
57325 // in the process of computing variance information for recursive types and when
57326 // comparing 'this' type arguments.
57327 var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
57328 var variance = varianceFlags & 7 /* VarianceMask */;
57329 // We ignore arguments for independent type parameters (because they're never witnessed).
57330 if (variance !== 4 /* Independent */) {
57331 var s = sources[i];
57332 var t = targets[i];
57333 var related = -1 /* True */;
57334 if (varianceFlags & 8 /* Unmeasurable */) {
57335 // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
57336 // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
57337 // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
57338 related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
57339 }
57340 else if (variance === 1 /* Covariant */) {
57341 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
57342 }
57343 else if (variance === 2 /* Contravariant */) {
57344 related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
57345 }
57346 else if (variance === 3 /* Bivariant */) {
57347 // In the bivariant case we first compare contravariantly without reporting
57348 // errors. Then, if that doesn't succeed, we compare covariantly with error
57349 // reporting. Thus, error elaboration will be based on the the covariant check,
57350 // which is generally easier to reason about.
57351 related = isRelatedTo(t, s, /*reportErrors*/ false);
57352 if (!related) {
57353 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
57354 }
57355 }
57356 else {
57357 // In the invariant case we first compare covariantly, and only when that
57358 // succeeds do we proceed to compare contravariantly. Thus, error elaboration
57359 // will typically be based on the covariant check.
57360 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
57361 if (related) {
57362 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
57363 }
57364 }
57365 if (!related) {
57366 return 0 /* False */;
57367 }
57368 result &= related;
57369 }
57370 }
57371 return result;
57372 }
57373 // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
57374 // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
57375 // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
57376 // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
57377 // and issue an error. Otherwise, actually compare the structure of the two types.
57378 function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
57379 if (overflow) {
57380 return 0 /* False */;
57381 }
57382 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
57383 var entry = relation.get(id);
57384 if (entry !== undefined) {
57385 if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
57386 // We are elaborating errors and the cached result is an unreported failure. The result will be reported
57387 // as a failure, and should be updated as a reported failure by the bottom of this function.
57388 }
57389 else {
57390 if (outofbandVarianceMarkerHandler) {
57391 // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
57392 var saved = entry & 24 /* ReportsMask */;
57393 if (saved & 8 /* ReportsUnmeasurable */) {
57394 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
57395 }
57396 if (saved & 16 /* ReportsUnreliable */) {
57397 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
57398 }
57399 }
57400 return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
57401 }
57402 }
57403 if (!maybeKeys) {
57404 maybeKeys = [];
57405 sourceStack = [];
57406 targetStack = [];
57407 }
57408 else {
57409 for (var i = 0; i < maybeCount; i++) {
57410 // If source and target are already being compared, consider them related with assumptions
57411 if (id === maybeKeys[i]) {
57412 return 1 /* Maybe */;
57413 }
57414 }
57415 if (depth === 100) {
57416 overflow = true;
57417 return 0 /* False */;
57418 }
57419 }
57420 var maybeStart = maybeCount;
57421 maybeKeys[maybeCount] = id;
57422 maybeCount++;
57423 sourceStack[depth] = source;
57424 targetStack[depth] = target;
57425 depth++;
57426 var saveExpandingFlags = expandingFlags;
57427 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
57428 expandingFlags |= 1 /* Source */;
57429 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
57430 expandingFlags |= 2 /* Target */;
57431 var originalHandler;
57432 var propagatingVarianceFlags = 0;
57433 if (outofbandVarianceMarkerHandler) {
57434 originalHandler = outofbandVarianceMarkerHandler;
57435 outofbandVarianceMarkerHandler = function (onlyUnreliable) {
57436 propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
57437 return originalHandler(onlyUnreliable);
57438 };
57439 }
57440 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
57441 if (outofbandVarianceMarkerHandler) {
57442 outofbandVarianceMarkerHandler = originalHandler;
57443 }
57444 expandingFlags = saveExpandingFlags;
57445 depth--;
57446 if (result) {
57447 if (result === -1 /* True */ || depth === 0) {
57448 // If result is definitely true, record all maybe keys as having succeeded
57449 for (var i = maybeStart; i < maybeCount; i++) {
57450 relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
57451 }
57452 maybeCount = maybeStart;
57453 }
57454 }
57455 else {
57456 // A false result goes straight into global cache (when something is false under
57457 // assumptions it will also be false without assumptions)
57458 relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
57459 maybeCount = maybeStart;
57460 }
57461 return result;
57462 }
57463 function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
57464 if (intersectionState & 4 /* PropertyCheck */) {
57465 return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
57466 }
57467 var flags = source.flags & target.flags;
57468 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
57469 if (flags & 4194304 /* Index */) {
57470 return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
57471 }
57472 var result_7 = 0 /* False */;
57473 if (flags & 8388608 /* IndexedAccess */) {
57474 if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
57475 if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
57476 return result_7;
57477 }
57478 }
57479 }
57480 if (flags & 16777216 /* Conditional */) {
57481 if (source.root.isDistributive === target.root.isDistributive) {
57482 if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
57483 if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
57484 if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
57485 if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
57486 return result_7;
57487 }
57488 }
57489 }
57490 }
57491 }
57492 }
57493 if (flags & 33554432 /* Substitution */) {
57494 return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
57495 }
57496 return 0 /* False */;
57497 }
57498 var result;
57499 var originalErrorInfo;
57500 var varianceCheckFailed = false;
57501 var saveErrorInfo = captureErrorCalculationState();
57502 // We limit alias variance probing to only object and conditional types since their alias behavior
57503 // is more predictable than other, interned types, which may or may not have an alias depending on
57504 // the order in which things were checked.
57505 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
57506 source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
57507 !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
57508 var variances = getAliasVariances(source.aliasSymbol);
57509 if (variances === ts.emptyArray) {
57510 return 1 /* Maybe */;
57511 }
57512 var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
57513 if (varianceResult !== undefined) {
57514 return varianceResult;
57515 }
57516 }
57517 // 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],
57518 // and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
57519 if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
57520 isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0]))) {
57521 return result;
57522 }
57523 if (target.flags & 262144 /* TypeParameter */) {
57524 // 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].
57525 if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
57526 if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
57527 var templateType = getTemplateTypeFromMappedType(source);
57528 var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
57529 if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
57530 return result;
57531 }
57532 }
57533 }
57534 }
57535 else if (target.flags & 4194304 /* Index */) {
57536 var targetType = target.type;
57537 // A keyof S is related to a keyof T if T is related to S.
57538 if (source.flags & 4194304 /* Index */) {
57539 if (result = isRelatedTo(targetType, source.type, /*reportErrors*/ false)) {
57540 return result;
57541 }
57542 }
57543 if (isTupleType(targetType)) {
57544 // An index type can have a tuple type target when the tuple type contains variadic elements.
57545 // Check if the source is related to the known keys of the tuple type.
57546 if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType), reportErrors)) {
57547 return result;
57548 }
57549 }
57550 else {
57551 // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
57552 // simplified form of T or, if T doesn't simplify, the constraint of T.
57553 var constraint = getSimplifiedTypeOrConstraint(targetType);
57554 if (constraint) {
57555 // We require Ternary.True here such that circular constraints don't cause
57556 // false positives. For example, given 'T extends { [K in keyof T]: string }',
57557 // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
57558 // related to other types.
57559 if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
57560 return -1 /* True */;
57561 }
57562 }
57563 }
57564 }
57565 else if (target.flags & 8388608 /* IndexedAccess */) {
57566 // A type S is related to a type T[K] if S is related to C, where C is the base
57567 // constraint of T[K] for writing.
57568 if (relation === assignableRelation || relation === comparableRelation) {
57569 var objectType = target.objectType;
57570 var indexType = target.indexType;
57571 var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
57572 var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
57573 if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
57574 var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
57575 var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
57576 if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
57577 return result;
57578 }
57579 }
57580 }
57581 }
57582 else if (isGenericMappedType(target)) {
57583 // A source type T is related to a target type { [P in X]: T[P] }
57584 var template = getTemplateTypeFromMappedType(target);
57585 var modifiers = getMappedTypeModifiers(target);
57586 if (!(modifiers & 8 /* ExcludeOptional */)) {
57587 if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
57588 template.indexType === getTypeParameterFromMappedType(target)) {
57589 return -1 /* True */;
57590 }
57591 if (!isGenericMappedType(source)) {
57592 var targetConstraint = getConstraintTypeFromMappedType(target);
57593 var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
57594 var includeOptional = modifiers & 4 /* IncludeOptional */;
57595 var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
57596 // 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.
57597 // 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.
57598 if (includeOptional
57599 ? !(filteredByApplicability.flags & 131072 /* Never */)
57600 : isRelatedTo(targetConstraint, sourceKeys)) {
57601 var templateType = getTemplateTypeFromMappedType(target);
57602 var typeParameter = getTypeParameterFromMappedType(target);
57603 // Fastpath: When the template has the form Obj[P] where P is the mapped type parameter, directly compare `source` with `Obj`
57604 // to avoid creating the (potentially very large) number of new intermediate types made by manufacturing `source[P]`
57605 var nonNullComponent = extractTypesOfKind(templateType, ~98304 /* Nullable */);
57606 if (nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
57607 if (result = isRelatedTo(source, nonNullComponent.objectType, reportErrors)) {
57608 return result;
57609 }
57610 }
57611 else {
57612 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
57613 var indexedAccessType = getIndexedAccessType(source, indexingType);
57614 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
57615 return result;
57616 }
57617 }
57618 }
57619 originalErrorInfo = errorInfo;
57620 resetErrorInfo(saveErrorInfo);
57621 }
57622 }
57623 }
57624 if (source.flags & 8650752 /* TypeVariable */) {
57625 if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
57626 // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
57627 if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
57628 result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
57629 }
57630 if (result) {
57631 resetErrorInfo(saveErrorInfo);
57632 return result;
57633 }
57634 }
57635 else {
57636 var constraint = getConstraintOfType(source);
57637 if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
57638 // A type variable with no constraint is not related to the non-primitive object type.
57639 if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
57640 resetErrorInfo(saveErrorInfo);
57641 return result;
57642 }
57643 }
57644 // 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
57645 else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
57646 resetErrorInfo(saveErrorInfo);
57647 return result;
57648 }
57649 // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
57650 else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
57651 resetErrorInfo(saveErrorInfo);
57652 return result;
57653 }
57654 }
57655 }
57656 else if (source.flags & 4194304 /* Index */) {
57657 if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
57658 resetErrorInfo(saveErrorInfo);
57659 return result;
57660 }
57661 }
57662 else if (source.flags & 16777216 /* Conditional */) {
57663 if (target.flags & 16777216 /* Conditional */) {
57664 // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
57665 // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
57666 // and Y1 is related to Y2.
57667 var sourceParams = source.root.inferTypeParameters;
57668 var sourceExtends = source.extendsType;
57669 var mapper = void 0;
57670 if (sourceParams) {
57671 // If the source has infer type parameters, we instantiate them in the context of the target
57672 var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
57673 inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
57674 sourceExtends = instantiateType(sourceExtends, ctx.mapper);
57675 mapper = ctx.mapper;
57676 }
57677 if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
57678 (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
57679 if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
57680 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
57681 }
57682 if (result) {
57683 resetErrorInfo(saveErrorInfo);
57684 return result;
57685 }
57686 }
57687 }
57688 else {
57689 // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
57690 // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
57691 var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
57692 if (distributiveConstraint) {
57693 if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
57694 resetErrorInfo(saveErrorInfo);
57695 return result;
57696 }
57697 }
57698 }
57699 // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
57700 // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
57701 var defaultConstraint = getDefaultConstraintOfConditionalType(source);
57702 if (defaultConstraint) {
57703 if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
57704 resetErrorInfo(saveErrorInfo);
57705 return result;
57706 }
57707 }
57708 }
57709 else {
57710 // An empty object type is related to any mapped type that includes a '?' modifier.
57711 if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
57712 return -1 /* True */;
57713 }
57714 if (isGenericMappedType(target)) {
57715 if (isGenericMappedType(source)) {
57716 if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
57717 resetErrorInfo(saveErrorInfo);
57718 return result;
57719 }
57720 }
57721 return 0 /* False */;
57722 }
57723 var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
57724 if (relation !== identityRelation) {
57725 source = getApparentType(source);
57726 }
57727 else if (isGenericMappedType(source)) {
57728 return 0 /* False */;
57729 }
57730 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
57731 !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
57732 // We have type references to the same generic type, and the type references are not marker
57733 // type references (which are intended by be compared structurally). Obtain the variance
57734 // information for the type parameters and relate the type arguments accordingly.
57735 var variances = getVariances(source.target);
57736 // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
57737 // effectively means we measure variance only from type parameter occurrences that aren't nested in
57738 // recursive instantiations of the generic type.
57739 if (variances === ts.emptyArray) {
57740 return 1 /* Maybe */;
57741 }
57742 var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
57743 if (varianceResult !== undefined) {
57744 return varianceResult;
57745 }
57746 }
57747 else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
57748 if (relation !== identityRelation) {
57749 return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
57750 }
57751 else {
57752 // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
57753 // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
57754 return 0 /* False */;
57755 }
57756 }
57757 // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
57758 // and not `{} <- fresh({}) <- {[idx: string]: any}`
57759 else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
57760 return 0 /* False */;
57761 }
57762 // Even if relationship doesn't hold for unions, intersections, or generic type references,
57763 // it may hold in a structural comparison.
57764 // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
57765 // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
57766 // relates to X. Thus, we include intersection types on the source side here.
57767 if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
57768 // Report structural errors only if we haven't reported any errors yet
57769 var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
57770 result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
57771 if (result) {
57772 result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
57773 if (result) {
57774 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
57775 if (result) {
57776 result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
57777 if (result) {
57778 result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
57779 }
57780 }
57781 }
57782 }
57783 if (varianceCheckFailed && result) {
57784 errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
57785 }
57786 else if (result) {
57787 return result;
57788 }
57789 }
57790 // If S is an object type and T is a discriminated union, S may be related to T if
57791 // there exists a constituent of T for every combination of the discriminants of S
57792 // with respect to T. We do not report errors here, as we will use the existing
57793 // error result from checking each constituent of the union.
57794 if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
57795 var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
57796 if (objectOnlyTarget.flags & 1048576 /* Union */) {
57797 var result_8 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
57798 if (result_8) {
57799 return result_8;
57800 }
57801 }
57802 }
57803 }
57804 return 0 /* False */;
57805 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
57806 if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
57807 return result;
57808 }
57809 if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
57810 // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
57811 // have to allow a structural fallback check
57812 // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
57813 // be assuming identity of the type parameter.
57814 originalErrorInfo = undefined;
57815 resetErrorInfo(saveErrorInfo);
57816 return undefined;
57817 }
57818 var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
57819 varianceCheckFailed = !allowStructuralFallback;
57820 // The type arguments did not relate appropriately, but it may be because we have no variance
57821 // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
57822 // arguments). It might also be the case that the target type has a 'void' type argument for
57823 // a covariant type parameter that is only used in return positions within the generic type
57824 // (in which case any type argument is permitted on the source side). In those cases we proceed
57825 // with a structural comparison. Otherwise, we know for certain the instantiations aren't
57826 // related and we can return here.
57827 if (variances !== ts.emptyArray && !allowStructuralFallback) {
57828 // In some cases generic types that are covariant in regular type checking mode become
57829 // invariant in --strictFunctionTypes mode because one or more type parameters are used in
57830 // both co- and contravariant positions. In order to make it easier to diagnose *why* such
57831 // types are invariant, if any of the type parameters are invariant we reset the reported
57832 // errors and instead force a structural comparison (which will include elaborations that
57833 // reveal the reason).
57834 // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
57835 // we can return `False` early here to skip calculating the structural error message we don't need.
57836 if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
57837 return 0 /* False */;
57838 }
57839 // We remember the original error information so we can restore it in case the structural
57840 // comparison unexpectedly succeeds. This can happen when the structural comparison result
57841 // is a Ternary.Maybe for example caused by the recursion depth limiter.
57842 originalErrorInfo = errorInfo;
57843 resetErrorInfo(saveErrorInfo);
57844 }
57845 }
57846 }
57847 function reportUnmeasurableMarkers(p) {
57848 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
57849 outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
57850 }
57851 return p;
57852 }
57853 function reportUnreliableMarkers(p) {
57854 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
57855 outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
57856 }
57857 return p;
57858 }
57859 // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
57860 // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
57861 // that S and T are contra-variant whereas X and Y are co-variant.
57862 function mappedTypeRelatedTo(source, target, reportErrors) {
57863 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
57864 getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
57865 if (modifiersRelated) {
57866 var result_9;
57867 var targetConstraint = getConstraintTypeFromMappedType(target);
57868 var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
57869 if (result_9 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
57870 var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
57871 return result_9 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
57872 }
57873 }
57874 return 0 /* False */;
57875 }
57876 function typeRelatedToDiscriminatedType(source, target) {
57877 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
57878 // a. If the number of combinations is above a set limit, the comparison is too complex.
57879 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
57880 // a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
57881 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
57882 // 'target' are related to a property in 'source'.
57883 //
57884 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
57885 // for examples.
57886 var sourceProperties = getPropertiesOfType(source);
57887 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
57888 if (!sourcePropertiesFiltered)
57889 return 0 /* False */;
57890 // Though we could compute the number of combinations as we generate
57891 // the matrix, this would incur additional memory overhead due to
57892 // array allocations. To reduce this overhead, we first compute
57893 // the number of combinations to ensure we will not surpass our
57894 // fixed limit before incurring the cost of any allocations:
57895 var numCombinations = 1;
57896 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
57897 var sourceProperty = sourcePropertiesFiltered_1[_i];
57898 numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
57899 if (numCombinations > 25) {
57900 // We've reached the complexity limit.
57901 return 0 /* False */;
57902 }
57903 }
57904 // Compute the set of types for each discriminant property.
57905 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
57906 var excludedProperties = new ts.Set();
57907 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
57908 var sourceProperty = sourcePropertiesFiltered[i];
57909 var sourcePropertyType = getTypeOfSymbol(sourceProperty);
57910 sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
57911 ? sourcePropertyType.types
57912 : [sourcePropertyType];
57913 excludedProperties.add(sourceProperty.escapedName);
57914 }
57915 // Match each combination of the cartesian product of discriminant properties to one or more
57916 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
57917 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
57918 var matchingTypes = [];
57919 var _loop_16 = function (combination) {
57920 var hasMatch = false;
57921 outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
57922 var type = _a[_i];
57923 var _loop_17 = function (i) {
57924 var sourceProperty = sourcePropertiesFiltered[i];
57925 var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
57926 if (!targetProperty)
57927 return "continue-outer";
57928 if (sourceProperty === targetProperty)
57929 return "continue";
57930 // We compare the source property to the target in the context of a single discriminant type.
57931 var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
57932 // If the target property could not be found, or if the properties were not related,
57933 // then this constituent is not a match.
57934 if (!related) {
57935 return "continue-outer";
57936 }
57937 };
57938 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
57939 var state_7 = _loop_17(i);
57940 switch (state_7) {
57941 case "continue-outer": continue outer;
57942 }
57943 }
57944 ts.pushIfUnique(matchingTypes, type, ts.equateValues);
57945 hasMatch = true;
57946 }
57947 if (!hasMatch) {
57948 return { value: 0 /* False */ };
57949 }
57950 };
57951 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
57952 var combination = discriminantCombinations_1[_a];
57953 var state_6 = _loop_16(combination);
57954 if (typeof state_6 === "object")
57955 return state_6.value;
57956 }
57957 // Compare the remaining non-discriminant properties of each match.
57958 var result = -1 /* True */;
57959 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
57960 var type = matchingTypes_1[_b];
57961 result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
57962 if (result) {
57963 result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
57964 if (result) {
57965 result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
57966 if (result) {
57967 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
57968 // Comparing numeric index types when both `source` and `type` are tuples is unnecessary as the
57969 // element types should be sufficiently covered by `propertiesRelatedTo`. It also causes problems
57970 // with index type assignability as the types for the excluded discriminants are still included
57971 // in the index type.
57972 if (result && !(isTupleType(source) && isTupleType(type))) {
57973 result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
57974 }
57975 }
57976 }
57977 }
57978 if (!result) {
57979 return result;
57980 }
57981 }
57982 return result;
57983 }
57984 function excludeProperties(properties, excludedProperties) {
57985 if (!excludedProperties || properties.length === 0)
57986 return properties;
57987 var result;
57988 for (var i = 0; i < properties.length; i++) {
57989 if (!excludedProperties.has(properties[i].escapedName)) {
57990 if (result) {
57991 result.push(properties[i]);
57992 }
57993 }
57994 else if (!result) {
57995 result = properties.slice(0, i);
57996 }
57997 }
57998 return result || properties;
57999 }
58000 function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
58001 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
58002 var source = getTypeOfSourceProperty(sourceProp);
58003 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
58004 // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
58005 var links = getSymbolLinks(targetProp);
58006 ts.Debug.assertIsDefined(links.deferralParent);
58007 ts.Debug.assertIsDefined(links.deferralConstituents);
58008 var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
58009 var result_10 = unionParent ? 0 /* False */ : -1 /* True */;
58010 var targetTypes = links.deferralConstituents;
58011 for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
58012 var targetType = targetTypes_3[_i];
58013 var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
58014 if (!unionParent) {
58015 if (!related) {
58016 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
58017 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
58018 }
58019 result_10 &= related;
58020 }
58021 else {
58022 if (related) {
58023 return related;
58024 }
58025 }
58026 }
58027 if (unionParent && !result_10 && targetIsOptional) {
58028 result_10 = isRelatedTo(source, undefinedType);
58029 }
58030 if (unionParent && !result_10 && reportErrors) {
58031 // The easiest way to get the right errors here is to un-defer (which may be costly)
58032 // If it turns out this is too costly too often, we can replicate the error handling logic within
58033 // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
58034 // type on which to hand discriminable properties, which we are expressly trying to avoid here)
58035 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
58036 }
58037 return result_10;
58038 }
58039 else {
58040 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
58041 }
58042 }
58043 function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
58044 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
58045 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
58046 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
58047 if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
58048 if (reportErrors) {
58049 if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
58050 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
58051 }
58052 else {
58053 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));
58054 }
58055 }
58056 return 0 /* False */;
58057 }
58058 }
58059 else if (targetPropFlags & 16 /* Protected */) {
58060 if (!isValidOverrideOf(sourceProp, targetProp)) {
58061 if (reportErrors) {
58062 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));
58063 }
58064 return 0 /* False */;
58065 }
58066 }
58067 else if (sourcePropFlags & 16 /* Protected */) {
58068 if (reportErrors) {
58069 reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
58070 }
58071 return 0 /* False */;
58072 }
58073 // If the target comes from a partial union prop, allow `undefined` in the target type
58074 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
58075 if (!related) {
58076 if (reportErrors) {
58077 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
58078 }
58079 return 0 /* False */;
58080 }
58081 // When checking for comparability, be more lenient with optional properties.
58082 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
58083 // TypeScript 1.0 spec (April 2014): 3.8.3
58084 // S is a subtype of a type T, and T is a supertype of S if ...
58085 // S' and T are object types and, for each member M in T..
58086 // M is a property and S' contains a property N where
58087 // if M is a required property, N is also a required property
58088 // (M - property in T)
58089 // (N - property in S)
58090 if (reportErrors) {
58091 reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
58092 }
58093 return 0 /* False */;
58094 }
58095 return related;
58096 }
58097 function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
58098 var shouldSkipElaboration = false;
58099 // give specific error in case where private names have the same description
58100 if (unmatchedProperty.valueDeclaration
58101 && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
58102 && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
58103 && source.symbol
58104 && source.symbol.flags & 32 /* Class */) {
58105 var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
58106 var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
58107 if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
58108 var sourceName = ts.factory.getDeclarationName(source.symbol.valueDeclaration);
58109 var targetName = ts.factory.getDeclarationName(target.symbol.valueDeclaration);
58110 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));
58111 return;
58112 }
58113 }
58114 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
58115 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
58116 headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
58117 shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
58118 }
58119 if (props.length === 1) {
58120 var propName = symbolToString(unmatchedProperty);
58121 reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
58122 if (ts.length(unmatchedProperty.declarations)) {
58123 associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
58124 }
58125 if (shouldSkipElaboration && errorInfo) {
58126 overrideNextErrorInfo++;
58127 }
58128 }
58129 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
58130 if (props.length > 5) { // arbitrary cutoff for too-long list form
58131 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);
58132 }
58133 else {
58134 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(", "));
58135 }
58136 if (shouldSkipElaboration && errorInfo) {
58137 overrideNextErrorInfo++;
58138 }
58139 }
58140 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
58141 }
58142 function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
58143 if (relation === identityRelation) {
58144 return propertiesIdenticalTo(source, target, excludedProperties);
58145 }
58146 var result = -1 /* True */;
58147 if (isTupleType(target)) {
58148 if (isArrayType(source) || isTupleType(source)) {
58149 if (!target.target.readonly && (isReadonlyArrayType(source) || isTupleType(source) && source.target.readonly)) {
58150 return 0 /* False */;
58151 }
58152 var sourceArity = getTypeReferenceArity(source);
58153 var targetArity = getTypeReferenceArity(target);
58154 var sourceRestFlag = isTupleType(source) ? source.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
58155 var targetRestFlag = target.target.combinedFlags & 4 /* Rest */;
58156 var sourceMinLength = isTupleType(source) ? source.target.minLength : 0;
58157 var targetMinLength = target.target.minLength;
58158 if (!sourceRestFlag && sourceArity < targetMinLength) {
58159 if (reportErrors) {
58160 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
58161 }
58162 return 0 /* False */;
58163 }
58164 if (!targetRestFlag && targetArity < sourceMinLength) {
58165 if (reportErrors) {
58166 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
58167 }
58168 return 0 /* False */;
58169 }
58170 if (!targetRestFlag && sourceRestFlag) {
58171 if (reportErrors) {
58172 if (sourceMinLength < targetMinLength) {
58173 reportError(ts.Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
58174 }
58175 else {
58176 reportError(ts.Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
58177 }
58178 }
58179 return 0 /* False */;
58180 }
58181 var maxArity = Math.max(sourceArity, targetArity);
58182 for (var i = 0; i < maxArity; i++) {
58183 var targetFlags = i < targetArity ? target.target.elementFlags[i] : targetRestFlag;
58184 var sourceFlags = isTupleType(source) && i < sourceArity ? source.target.elementFlags[i] : sourceRestFlag;
58185 var canExcludeDiscriminants = !!excludedProperties;
58186 if (sourceFlags && targetFlags) {
58187 if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */) ||
58188 (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */))) {
58189 if (reportErrors) {
58190 reportError(ts.Diagnostics.Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other, i);
58191 }
58192 return 0 /* False */;
58193 }
58194 if (targetFlags & 1 /* Required */) {
58195 if (!(sourceFlags & 1 /* Required */)) {
58196 if (reportErrors) {
58197 reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, i, typeToString(source), typeToString(target));
58198 }
58199 return 0 /* False */;
58200 }
58201 }
58202 // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
58203 if (canExcludeDiscriminants) {
58204 if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
58205 canExcludeDiscriminants = false;
58206 }
58207 if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
58208 continue;
58209 }
58210 }
58211 var sourceType = getTypeArguments(source)[Math.min(i, sourceArity - 1)];
58212 var targetType = getTypeArguments(target)[Math.min(i, targetArity - 1)];
58213 var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
58214 var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
58215 if (!related) {
58216 if (reportErrors) {
58217 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, i);
58218 }
58219 return 0 /* False */;
58220 }
58221 result &= related;
58222 }
58223 }
58224 return result;
58225 }
58226 if (target.target.combinedFlags & 12 /* Variable */) {
58227 return 0 /* False */;
58228 }
58229 }
58230 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
58231 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
58232 if (unmatchedProperty) {
58233 if (reportErrors) {
58234 reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
58235 }
58236 return 0 /* False */;
58237 }
58238 if (isObjectLiteralType(target)) {
58239 for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
58240 var sourceProp = _a[_i];
58241 if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
58242 var sourceType = getTypeOfSymbol(sourceProp);
58243 if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
58244 if (reportErrors) {
58245 reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
58246 }
58247 return 0 /* False */;
58248 }
58249 }
58250 }
58251 }
58252 // 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_
58253 // from the target union, across all members
58254 var properties = getPropertiesOfType(target);
58255 var numericNamesOnly = isTupleType(source) && isTupleType(target);
58256 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
58257 var targetProp = _c[_b];
58258 var name = targetProp.escapedName;
58259 if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
58260 var sourceProp = getPropertyOfType(source, name);
58261 if (sourceProp && sourceProp !== targetProp) {
58262 var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
58263 if (!related) {
58264 return 0 /* False */;
58265 }
58266 result &= related;
58267 }
58268 }
58269 }
58270 return result;
58271 }
58272 function propertiesIdenticalTo(source, target, excludedProperties) {
58273 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
58274 return 0 /* False */;
58275 }
58276 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
58277 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
58278 if (sourceProperties.length !== targetProperties.length) {
58279 return 0 /* False */;
58280 }
58281 var result = -1 /* True */;
58282 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
58283 var sourceProp = sourceProperties_1[_i];
58284 var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
58285 if (!targetProp) {
58286 return 0 /* False */;
58287 }
58288 var related = compareProperties(sourceProp, targetProp, isRelatedTo);
58289 if (!related) {
58290 return 0 /* False */;
58291 }
58292 result &= related;
58293 }
58294 return result;
58295 }
58296 function signaturesRelatedTo(source, target, kind, reportErrors) {
58297 if (relation === identityRelation) {
58298 return signaturesIdenticalTo(source, target, kind);
58299 }
58300 if (target === anyFunctionType || source === anyFunctionType) {
58301 return -1 /* True */;
58302 }
58303 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
58304 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
58305 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
58306 0 /* Call */ : kind);
58307 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
58308 0 /* Call */ : kind);
58309 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
58310 if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
58311 // An abstract constructor type is not assignable to a non-abstract constructor type
58312 // as it would otherwise be possible to new an abstract class. Note that the assignability
58313 // check we perform for an extends clause excludes construct signatures from the target,
58314 // so this check never proceeds.
58315 if (reportErrors) {
58316 reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
58317 }
58318 return 0 /* False */;
58319 }
58320 if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
58321 return 0 /* False */;
58322 }
58323 }
58324 var result = -1 /* True */;
58325 var saveErrorInfo = captureErrorCalculationState();
58326 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
58327 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
58328 // We have instantiations of the same anonymous type (which typically will be the type of a
58329 // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
58330 // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
58331 // as they are known to always be the same.
58332 for (var i = 0; i < targetSignatures.length; i++) {
58333 var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
58334 if (!related) {
58335 return 0 /* False */;
58336 }
58337 result &= related;
58338 }
58339 }
58340 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
58341 // For simple functions (functions with a single signature) we only erase type parameters for
58342 // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
58343 // in the context of the target signature before checking the relationship. Ideally we'd do
58344 // this regardless of the number of signatures, but the potential costs are prohibitive due
58345 // to the quadratic nature of the logic below.
58346 var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
58347 result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
58348 }
58349 else {
58350 outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
58351 var t = targetSignatures_1[_i];
58352 // Only elaborate errors from the first failure
58353 var shouldElaborateErrors = reportErrors;
58354 for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
58355 var s = sourceSignatures_1[_a];
58356 var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
58357 if (related) {
58358 result &= related;
58359 resetErrorInfo(saveErrorInfo);
58360 continue outer;
58361 }
58362 shouldElaborateErrors = false;
58363 }
58364 if (shouldElaborateErrors) {
58365 reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
58366 }
58367 return 0 /* False */;
58368 }
58369 }
58370 return result;
58371 }
58372 function reportIncompatibleCallSignatureReturn(siga, sigb) {
58373 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
58374 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
58375 }
58376 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
58377 }
58378 function reportIncompatibleConstructSignatureReturn(siga, sigb) {
58379 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
58380 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
58381 }
58382 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
58383 }
58384 /**
58385 * See signatureAssignableTo, compareSignaturesIdentical
58386 */
58387 function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
58388 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
58389 }
58390 function signaturesIdenticalTo(source, target, kind) {
58391 var sourceSignatures = getSignaturesOfType(source, kind);
58392 var targetSignatures = getSignaturesOfType(target, kind);
58393 if (sourceSignatures.length !== targetSignatures.length) {
58394 return 0 /* False */;
58395 }
58396 var result = -1 /* True */;
58397 for (var i = 0; i < sourceSignatures.length; i++) {
58398 var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
58399 if (!related) {
58400 return 0 /* False */;
58401 }
58402 result &= related;
58403 }
58404 return result;
58405 }
58406 function eachPropertyRelatedTo(source, target, kind, reportErrors) {
58407 var result = -1 /* True */;
58408 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
58409 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
58410 var prop = props_2[_i];
58411 // Skip over ignored JSX and symbol-named members
58412 if (isIgnoredJsxProperty(source, prop)) {
58413 continue;
58414 }
58415 var nameType = getSymbolLinks(prop).nameType;
58416 if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
58417 continue;
58418 }
58419 if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
58420 var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
58421 if (!related) {
58422 if (reportErrors) {
58423 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
58424 }
58425 return 0 /* False */;
58426 }
58427 result &= related;
58428 }
58429 }
58430 return result;
58431 }
58432 function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
58433 var related = isRelatedTo(sourceType, targetType, reportErrors);
58434 if (!related && reportErrors) {
58435 reportError(ts.Diagnostics.Index_signatures_are_incompatible);
58436 }
58437 return related;
58438 }
58439 function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
58440 if (relation === identityRelation) {
58441 return indexTypesIdenticalTo(source, target, kind);
58442 }
58443 var targetType = getIndexTypeOfType(target, kind);
58444 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
58445 // Index signature of type any permits assignment from everything but primitives
58446 return -1 /* True */;
58447 }
58448 if (isGenericMappedType(source)) {
58449 // A generic mapped type { [P in K]: T } is related to a type with an index signature
58450 // { [x: string]: U }, and optionally with an index signature { [x: number]: V },
58451 // if T is related to U and V.
58452 return getIndexTypeOfType(target, 0 /* String */) ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
58453 }
58454 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
58455 if (indexType) {
58456 return indexTypeRelatedTo(indexType, targetType, reportErrors);
58457 }
58458 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
58459 // Intersection constituents are never considered to have an inferred index signature
58460 var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
58461 if (related && kind === 0 /* String */) {
58462 var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
58463 if (numberIndexType) {
58464 related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
58465 }
58466 }
58467 return related;
58468 }
58469 if (reportErrors) {
58470 reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
58471 }
58472 return 0 /* False */;
58473 }
58474 function indexTypesIdenticalTo(source, target, indexKind) {
58475 var targetInfo = getIndexInfoOfType(target, indexKind);
58476 var sourceInfo = getIndexInfoOfType(source, indexKind);
58477 if (!sourceInfo && !targetInfo) {
58478 return -1 /* True */;
58479 }
58480 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
58481 return isRelatedTo(sourceInfo.type, targetInfo.type);
58482 }
58483 return 0 /* False */;
58484 }
58485 function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
58486 if (!sourceSignature.declaration || !targetSignature.declaration) {
58487 return true;
58488 }
58489 var sourceAccessibility = ts.getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
58490 var targetAccessibility = ts.getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
58491 // A public, protected and private signature is assignable to a private signature.
58492 if (targetAccessibility === 8 /* Private */) {
58493 return true;
58494 }
58495 // A public and protected signature is assignable to a protected signature.
58496 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
58497 return true;
58498 }
58499 // Only a public signature is assignable to public signature.
58500 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
58501 return true;
58502 }
58503 if (reportErrors) {
58504 reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
58505 }
58506 return false;
58507 }
58508 }
58509 function typeCouldHaveTopLevelSingletonTypes(type) {
58510 // Okay, yes, 'boolean' is a union of 'true | false', but that's not useful
58511 // in error reporting scenarios. If you need to use this function but that detail matters,
58512 // feel free to add a flag.
58513 if (type.flags & 16 /* Boolean */) {
58514 return false;
58515 }
58516 if (type.flags & 3145728 /* UnionOrIntersection */) {
58517 return !!ts.forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
58518 }
58519 if (type.flags & 63176704 /* Instantiable */) {
58520 var constraint = getConstraintOfType(type);
58521 if (constraint) {
58522 return typeCouldHaveTopLevelSingletonTypes(constraint);
58523 }
58524 }
58525 return isUnitType(type);
58526 }
58527 function getBestMatchingType(source, target, isRelatedTo) {
58528 if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
58529 return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
58530 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
58531 findBestTypeForObjectLiteral(source, target) ||
58532 findBestTypeForInvokable(source, target) ||
58533 findMostOverlappyType(source, target);
58534 }
58535 function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
58536 // undefined=unknown, true=discriminated, false=not discriminated
58537 // The state of each type progresses from left to right. Discriminated types stop at 'true'.
58538 var discriminable = target.types.map(function (_) { return undefined; });
58539 for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
58540 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
58541 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
58542 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
58543 continue;
58544 }
58545 var i = 0;
58546 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
58547 var type = _c[_b];
58548 var targetType = getTypeOfPropertyOfType(type, propertyName);
58549 if (targetType && related(getDiscriminatingType(), targetType)) {
58550 discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
58551 }
58552 else {
58553 discriminable[i] = false;
58554 }
58555 i++;
58556 }
58557 }
58558 var match = discriminable.indexOf(/*searchElement*/ true);
58559 // make sure exactly 1 matches before returning it
58560 return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
58561 }
58562 /**
58563 * A type is 'weak' if it is an object type with at least one optional property
58564 * and no required properties, call/construct signatures or index signatures
58565 */
58566 function isWeakType(type) {
58567 if (type.flags & 524288 /* Object */) {
58568 var resolved = resolveStructuredTypeMembers(type);
58569 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
58570 !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
58571 resolved.properties.length > 0 &&
58572 ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
58573 }
58574 if (type.flags & 2097152 /* Intersection */) {
58575 return ts.every(type.types, isWeakType);
58576 }
58577 return false;
58578 }
58579 function hasCommonProperties(source, target, isComparingJsxAttributes) {
58580 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
58581 var prop = _a[_i];
58582 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
58583 return true;
58584 }
58585 }
58586 return false;
58587 }
58588 // Return a type reference where the source type parameter is replaced with the target marker
58589 // type, and flag the result as a marker type reference.
58590 function getMarkerTypeReference(type, source, target) {
58591 var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
58592 result.objectFlags |= 8192 /* MarkerType */;
58593 return result;
58594 }
58595 function getAliasVariances(symbol) {
58596 var links = getSymbolLinks(symbol);
58597 return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
58598 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
58599 type.aliasTypeArgumentsContainsMarker = true;
58600 return type;
58601 });
58602 }
58603 // Return an array containing the variance of each type parameter. The variance is effectively
58604 // a digest of the type comparisons that occur for each type argument when instantiations of the
58605 // generic type are structurally compared. We infer the variance information by comparing
58606 // instantiations of the generic type for type arguments with known relations. The function
58607 // returns the emptyArray singleton when invoked recursively for the given generic type.
58608 function getVariancesWorker(typeParameters, cache, createMarkerType) {
58609 if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
58610 var variances = cache.variances;
58611 if (!variances) {
58612 // The emptyArray singleton is used to signal a recursive invocation.
58613 cache.variances = ts.emptyArray;
58614 variances = [];
58615 var _loop_18 = function (tp) {
58616 var unmeasurable = false;
58617 var unreliable = false;
58618 var oldHandler = outofbandVarianceMarkerHandler;
58619 outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
58620 // We first compare instantiations where the type parameter is replaced with
58621 // marker types that have a known subtype relationship. From this we can infer
58622 // invariance, covariance, contravariance or bivariance.
58623 var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
58624 var typeWithSub = createMarkerType(cache, tp, markerSubType);
58625 var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
58626 (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
58627 // If the instantiations appear to be related bivariantly it may be because the
58628 // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
58629 // type). To determine this we compare instantiations where the type parameter is
58630 // replaced with marker types that are known to be unrelated.
58631 if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
58632 variance = 4 /* Independent */;
58633 }
58634 outofbandVarianceMarkerHandler = oldHandler;
58635 if (unmeasurable || unreliable) {
58636 if (unmeasurable) {
58637 variance |= 8 /* Unmeasurable */;
58638 }
58639 if (unreliable) {
58640 variance |= 16 /* Unreliable */;
58641 }
58642 }
58643 variances.push(variance);
58644 };
58645 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
58646 var tp = typeParameters_1[_i];
58647 _loop_18(tp);
58648 }
58649 cache.variances = variances;
58650 }
58651 return variances;
58652 }
58653 function getVariances(type) {
58654 // Arrays and tuples are known to be covariant, no need to spend time computing this.
58655 if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
58656 return arrayVariances;
58657 }
58658 return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
58659 }
58660 // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
58661 // See comment at call in recursiveTypeRelatedTo for when this case matters.
58662 function hasCovariantVoidArgument(typeArguments, variances) {
58663 for (var i = 0; i < variances.length; i++) {
58664 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
58665 return true;
58666 }
58667 }
58668 return false;
58669 }
58670 function isUnconstrainedTypeParameter(type) {
58671 return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
58672 }
58673 function isNonDeferredTypeReference(type) {
58674 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
58675 }
58676 function isTypeReferenceWithGenericArguments(type) {
58677 return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
58678 }
58679 /**
58680 * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
58681 * where A.id=111 and number.id=12
58682 */
58683 function getTypeReferenceId(type, typeParameters, depth) {
58684 if (depth === void 0) { depth = 0; }
58685 var result = "" + type.target.id;
58686 for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
58687 var t = _a[_i];
58688 if (isUnconstrainedTypeParameter(t)) {
58689 var index = typeParameters.indexOf(t);
58690 if (index < 0) {
58691 index = typeParameters.length;
58692 typeParameters.push(t);
58693 }
58694 result += "=" + index;
58695 }
58696 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
58697 result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
58698 }
58699 else {
58700 result += "-" + t.id;
58701 }
58702 }
58703 return result;
58704 }
58705 /**
58706 * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
58707 * For other cases, the types ids are used.
58708 */
58709 function getRelationKey(source, target, intersectionState, relation) {
58710 if (relation === identityRelation && source.id > target.id) {
58711 var temp = source;
58712 source = target;
58713 target = temp;
58714 }
58715 var postFix = intersectionState ? ":" + intersectionState : "";
58716 if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
58717 var typeParameters = [];
58718 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
58719 }
58720 return source.id + "," + target.id + postFix;
58721 }
58722 // Invoke the callback for each underlying property symbol of the given symbol and return the first
58723 // value that isn't undefined.
58724 function forEachProperty(prop, callback) {
58725 if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
58726 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
58727 var t = _a[_i];
58728 var p = getPropertyOfType(t, prop.escapedName);
58729 var result = p && forEachProperty(p, callback);
58730 if (result) {
58731 return result;
58732 }
58733 }
58734 return undefined;
58735 }
58736 return callback(prop);
58737 }
58738 // Return the declaring class type of a property or undefined if property not declared in class
58739 function getDeclaringClass(prop) {
58740 return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
58741 }
58742 // Return the inherited type of the given property or undefined if property doesn't exist in a base class.
58743 function getTypeOfPropertyInBaseClass(property) {
58744 var classType = getDeclaringClass(property);
58745 var baseClassType = classType && getBaseTypes(classType)[0];
58746 return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
58747 }
58748 // Return true if some underlying source property is declared in a class that derives
58749 // from the given base class.
58750 function isPropertyInClassDerivedFrom(prop, baseClass) {
58751 return forEachProperty(prop, function (sp) {
58752 var sourceClass = getDeclaringClass(sp);
58753 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
58754 });
58755 }
58756 // Return true if source property is a valid override of protected parts of target property.
58757 function isValidOverrideOf(sourceProp, targetProp) {
58758 return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
58759 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
58760 }
58761 // Return true if the given class derives from each of the declaring classes of the protected
58762 // constituents of the given property.
58763 function isClassDerivedFromDeclaringClasses(checkClass, prop) {
58764 return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
58765 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
58766 }
58767 // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
58768 // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
58769 // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
58770 // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
58771 // levels, but unequal at some level beyond that.
58772 // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
58773 // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
58774 // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
58775 // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of
58776 // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]`
58777 // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`
58778 // in such cases we need to terminate the expansion, and we do so here.
58779 function isDeeplyNestedType(type, stack, depth) {
58780 // We track all object types that have an associated symbol (representing the origin of the type)
58781 if (depth >= 5 && type.flags & 524288 /* Object */) {
58782 if (!isObjectOrArrayLiteralType(type)) {
58783 var symbol = type.symbol;
58784 if (symbol) {
58785 var count = 0;
58786 for (var i = 0; i < depth; i++) {
58787 var t = stack[i];
58788 if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
58789 count++;
58790 if (count >= 5)
58791 return true;
58792 }
58793 }
58794 }
58795 }
58796 if (ts.getObjectFlags(type) && 4 /* Reference */ && !!type.node) {
58797 var root = type.target;
58798 var count = 0;
58799 for (var i = 0; i < depth; i++) {
58800 var t = stack[i];
58801 if (ts.getObjectFlags(t) && 4 /* Reference */ && !!t.node && t.target === root) {
58802 count++;
58803 if (count >= 5)
58804 return true;
58805 }
58806 }
58807 }
58808 }
58809 if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
58810 var root = getRootObjectTypeFromIndexedAccessChain(type);
58811 var count = 0;
58812 for (var i = 0; i < depth; i++) {
58813 var t = stack[i];
58814 if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
58815 count++;
58816 if (count >= 5)
58817 return true;
58818 }
58819 }
58820 }
58821 return false;
58822 }
58823 /**
58824 * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
58825 */
58826 function getRootObjectTypeFromIndexedAccessChain(type) {
58827 var t = type;
58828 while (t.flags & 8388608 /* IndexedAccess */) {
58829 t = t.objectType;
58830 }
58831 return t;
58832 }
58833 function isPropertyIdenticalTo(sourceProp, targetProp) {
58834 return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
58835 }
58836 function compareProperties(sourceProp, targetProp, compareTypes) {
58837 // Two members are considered identical when
58838 // - they are public properties with identical names, optionality, and types,
58839 // - they are private or protected properties originating in the same declaration and having identical types
58840 if (sourceProp === targetProp) {
58841 return -1 /* True */;
58842 }
58843 var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
58844 var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
58845 if (sourcePropAccessibility !== targetPropAccessibility) {
58846 return 0 /* False */;
58847 }
58848 if (sourcePropAccessibility) {
58849 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
58850 return 0 /* False */;
58851 }
58852 }
58853 else {
58854 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
58855 return 0 /* False */;
58856 }
58857 }
58858 if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
58859 return 0 /* False */;
58860 }
58861 return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
58862 }
58863 function isMatchingSignature(source, target, partialMatch) {
58864 var sourceParameterCount = getParameterCount(source);
58865 var targetParameterCount = getParameterCount(target);
58866 var sourceMinArgumentCount = getMinArgumentCount(source);
58867 var targetMinArgumentCount = getMinArgumentCount(target);
58868 var sourceHasRestParameter = hasEffectiveRestParameter(source);
58869 var targetHasRestParameter = hasEffectiveRestParameter(target);
58870 // A source signature matches a target signature if the two signatures have the same number of required,
58871 // optional, and rest parameters.
58872 if (sourceParameterCount === targetParameterCount &&
58873 sourceMinArgumentCount === targetMinArgumentCount &&
58874 sourceHasRestParameter === targetHasRestParameter) {
58875 return true;
58876 }
58877 // A source signature partially matches a target signature if the target signature has no fewer required
58878 // parameters
58879 if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
58880 return true;
58881 }
58882 return false;
58883 }
58884 /**
58885 * See signatureRelatedTo, compareSignaturesIdentical
58886 */
58887 function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
58888 // TODO (drosen): De-duplicate code between related functions.
58889 if (source === target) {
58890 return -1 /* True */;
58891 }
58892 if (!(isMatchingSignature(source, target, partialMatch))) {
58893 return 0 /* False */;
58894 }
58895 // Check that the two signatures have the same number of type parameters.
58896 if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
58897 return 0 /* False */;
58898 }
58899 // Check that type parameter constraints and defaults match. If they do, instantiate the source
58900 // signature with the type parameters of the target signature and continue the comparison.
58901 if (target.typeParameters) {
58902 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
58903 for (var i = 0; i < target.typeParameters.length; i++) {
58904 var s = source.typeParameters[i];
58905 var t = target.typeParameters[i];
58906 if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
58907 compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
58908 return 0 /* False */;
58909 }
58910 }
58911 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
58912 }
58913 var result = -1 /* True */;
58914 if (!ignoreThisTypes) {
58915 var sourceThisType = getThisTypeOfSignature(source);
58916 if (sourceThisType) {
58917 var targetThisType = getThisTypeOfSignature(target);
58918 if (targetThisType) {
58919 var related = compareTypes(sourceThisType, targetThisType);
58920 if (!related) {
58921 return 0 /* False */;
58922 }
58923 result &= related;
58924 }
58925 }
58926 }
58927 var targetLen = getParameterCount(target);
58928 for (var i = 0; i < targetLen; i++) {
58929 var s = getTypeAtPosition(source, i);
58930 var t = getTypeAtPosition(target, i);
58931 var related = compareTypes(t, s);
58932 if (!related) {
58933 return 0 /* False */;
58934 }
58935 result &= related;
58936 }
58937 if (!ignoreReturnTypes) {
58938 var sourceTypePredicate = getTypePredicateOfSignature(source);
58939 var targetTypePredicate = getTypePredicateOfSignature(target);
58940 result &= sourceTypePredicate || targetTypePredicate ?
58941 compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
58942 compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
58943 }
58944 return result;
58945 }
58946 function compareTypePredicatesIdentical(source, target, compareTypes) {
58947 return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
58948 source.type === target.type ? -1 /* True */ :
58949 source.type && target.type ? compareTypes(source.type, target.type) :
58950 0 /* False */;
58951 }
58952 function literalTypesWithSameBaseType(types) {
58953 var commonBaseType;
58954 for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
58955 var t = types_12[_i];
58956 var baseType = getBaseTypeOfLiteralType(t);
58957 if (!commonBaseType) {
58958 commonBaseType = baseType;
58959 }
58960 if (baseType === t || baseType !== commonBaseType) {
58961 return false;
58962 }
58963 }
58964 return true;
58965 }
58966 // When the candidate types are all literal types with the same base type, return a union
58967 // of those literal types. Otherwise, return the leftmost type for which no type to the
58968 // right is a supertype.
58969 function getSupertypeOrUnion(types) {
58970 return literalTypesWithSameBaseType(types) ?
58971 getUnionType(types) :
58972 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
58973 }
58974 function getCommonSupertype(types) {
58975 if (!strictNullChecks) {
58976 return getSupertypeOrUnion(types);
58977 }
58978 var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
58979 return primaryTypes.length ?
58980 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
58981 getUnionType(types, 2 /* Subtype */);
58982 }
58983 // Return the leftmost type for which no type to the right is a subtype.
58984 function getCommonSubtype(types) {
58985 return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
58986 }
58987 function isArrayType(type) {
58988 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
58989 }
58990 function isReadonlyArrayType(type) {
58991 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
58992 }
58993 function isMutableArrayOrTuple(type) {
58994 return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
58995 }
58996 function getElementTypeOfArrayType(type) {
58997 return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
58998 }
58999 function isArrayLikeType(type) {
59000 // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
59001 // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
59002 return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
59003 }
59004 function isEmptyArrayLiteralType(type) {
59005 var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
59006 return elementType === undefinedWideningType || elementType === implicitNeverType;
59007 }
59008 function isTupleLikeType(type) {
59009 return isTupleType(type) || !!getPropertyOfType(type, "0");
59010 }
59011 function isArrayOrTupleLikeType(type) {
59012 return isArrayLikeType(type) || isTupleLikeType(type);
59013 }
59014 function getTupleElementType(type, index) {
59015 var propType = getTypeOfPropertyOfType(type, "" + index);
59016 if (propType) {
59017 return propType;
59018 }
59019 if (everyType(type, isTupleType)) {
59020 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
59021 }
59022 return undefined;
59023 }
59024 function isNeitherUnitTypeNorNever(type) {
59025 return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
59026 }
59027 function isUnitType(type) {
59028 return !!(type.flags & 109440 /* Unit */);
59029 }
59030 function isLiteralType(type) {
59031 return type.flags & 16 /* Boolean */ ? true :
59032 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
59033 isUnitType(type);
59034 }
59035 function getBaseTypeOfLiteralType(type) {
59036 return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
59037 type.flags & 128 /* StringLiteral */ ? stringType :
59038 type.flags & 256 /* NumberLiteral */ ? numberType :
59039 type.flags & 2048 /* BigIntLiteral */ ? bigintType :
59040 type.flags & 512 /* BooleanLiteral */ ? booleanType :
59041 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
59042 type;
59043 }
59044 function getWidenedLiteralType(type) {
59045 return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
59046 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
59047 type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
59048 type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
59049 type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
59050 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
59051 type;
59052 }
59053 function getWidenedUniqueESSymbolType(type) {
59054 return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
59055 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
59056 type;
59057 }
59058 function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
59059 if (!isLiteralOfContextualType(type, contextualType)) {
59060 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
59061 }
59062 return type;
59063 }
59064 function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
59065 if (type && isUnitType(type)) {
59066 var contextualType = !contextualSignatureReturnType ? undefined :
59067 isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
59068 contextualSignatureReturnType;
59069 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
59070 }
59071 return type;
59072 }
59073 function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
59074 if (type && isUnitType(type)) {
59075 var contextualType = !contextualSignatureReturnType ? undefined :
59076 getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
59077 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
59078 }
59079 return type;
59080 }
59081 /**
59082 * Check if a Type was written as a tuple type literal.
59083 * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
59084 */
59085 function isTupleType(type) {
59086 return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
59087 }
59088 function isGenericTupleType(type) {
59089 return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
59090 }
59091 function isSingleElementGenericTupleType(type) {
59092 return isGenericTupleType(type) && type.target.elementFlags.length === 1;
59093 }
59094 function getRestTypeOfTupleType(type) {
59095 return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
59096 }
59097 function getRestArrayTypeOfTupleType(type) {
59098 var restType = getRestTypeOfTupleType(type);
59099 return restType && createArrayType(restType);
59100 }
59101 function getEndLengthOfType(type) {
59102 return isTupleType(type) ? getTypeReferenceArity(type) - ts.findLastIndex(type.target.elementFlags, function (f) { return !(f & (1 /* Required */ | 2 /* Optional */)); }) - 1 : 0;
59103 }
59104 function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
59105 if (endSkipCount === void 0) { endSkipCount = 0; }
59106 if (writing === void 0) { writing = false; }
59107 var length = getTypeReferenceArity(type) - endSkipCount;
59108 if (index < length) {
59109 var typeArguments = getTypeArguments(type);
59110 var elementTypes = [];
59111 for (var i = index; i < length; i++) {
59112 var t = typeArguments[i];
59113 elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
59114 }
59115 return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes);
59116 }
59117 return undefined;
59118 }
59119 function isTupleTypeStructureMatching(t1, t2) {
59120 return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) &&
59121 ts.every(t1.target.elementFlags, function (f, i) { return (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */); });
59122 }
59123 function isZeroBigInt(_a) {
59124 var value = _a.value;
59125 return value.base10Value === "0";
59126 }
59127 function getFalsyFlagsOfTypes(types) {
59128 var result = 0;
59129 for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
59130 var t = types_13[_i];
59131 result |= getFalsyFlags(t);
59132 }
59133 return result;
59134 }
59135 // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
59136 // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
59137 // no flags for all other types (including non-falsy literal types).
59138 function getFalsyFlags(type) {
59139 return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
59140 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
59141 type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
59142 type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
59143 type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
59144 type.flags & 117724 /* PossiblyFalsy */;
59145 }
59146 function removeDefinitelyFalsyTypes(type) {
59147 return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
59148 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
59149 type;
59150 }
59151 function extractDefinitelyFalsyTypes(type) {
59152 return mapType(type, getDefinitelyFalsyPartOfType);
59153 }
59154 function getDefinitelyFalsyPartOfType(type) {
59155 return type.flags & 4 /* String */ ? emptyStringType :
59156 type.flags & 8 /* Number */ ? zeroType :
59157 type.flags & 64 /* BigInt */ ? zeroBigIntType :
59158 type === regularFalseType ||
59159 type === falseType ||
59160 type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
59161 type.flags & 128 /* StringLiteral */ && type.value === "" ||
59162 type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
59163 type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
59164 neverType;
59165 }
59166 /**
59167 * Add undefined or null or both to a type if they are missing.
59168 * @param type - type to add undefined and/or null to if not present
59169 * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
59170 */
59171 function getNullableType(type, flags) {
59172 var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
59173 return missing === 0 ? type :
59174 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
59175 missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
59176 getUnionType([type, undefinedType, nullType]);
59177 }
59178 function getOptionalType(type) {
59179 ts.Debug.assert(strictNullChecks);
59180 return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
59181 }
59182 function getGlobalNonNullableTypeInstantiation(type) {
59183 if (!deferredGlobalNonNullableTypeAlias) {
59184 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
59185 }
59186 // Use NonNullable global type alias if available to improve quick info/declaration emit
59187 if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
59188 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
59189 }
59190 return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
59191 }
59192 function getNonNullableType(type) {
59193 return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
59194 }
59195 function addOptionalTypeMarker(type) {
59196 return strictNullChecks ? getUnionType([type, optionalType]) : type;
59197 }
59198 function isNotOptionalTypeMarker(type) {
59199 return type !== optionalType;
59200 }
59201 function removeOptionalTypeMarker(type) {
59202 return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
59203 }
59204 function propagateOptionalTypeMarker(type, node, wasOptional) {
59205 return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
59206 }
59207 function getOptionalExpressionType(exprType, expression) {
59208 return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
59209 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
59210 exprType;
59211 }
59212 /**
59213 * Is source potentially coercible to target type under `==`.
59214 * Assumes that `source` is a constituent of a union, hence
59215 * the boolean literal flag on the LHS, but not on the RHS.
59216 *
59217 * This does not fully replicate the semantics of `==`. The
59218 * intention is to catch cases that are clearly not right.
59219 *
59220 * Comparing (string | number) to number should not remove the
59221 * string element.
59222 *
59223 * Comparing (string | number) to 1 will remove the string
59224 * element, though this is not sound. This is a pragmatic
59225 * choice.
59226 *
59227 * @see narrowTypeByEquality
59228 *
59229 * @param source
59230 * @param target
59231 */
59232 function isCoercibleUnderDoubleEquals(source, target) {
59233 return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
59234 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
59235 }
59236 /**
59237 * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
59238 * with no call or construct signatures.
59239 */
59240 function isObjectTypeWithInferableIndex(type) {
59241 return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
59242 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
59243 !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
59244 }
59245 function createSymbolWithType(source, type) {
59246 var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
59247 symbol.declarations = source.declarations;
59248 symbol.parent = source.parent;
59249 symbol.type = type;
59250 symbol.target = source;
59251 if (source.valueDeclaration) {
59252 symbol.valueDeclaration = source.valueDeclaration;
59253 }
59254 var nameType = getSymbolLinks(source).nameType;
59255 if (nameType) {
59256 symbol.nameType = nameType;
59257 }
59258 return symbol;
59259 }
59260 function transformTypeOfMembers(type, f) {
59261 var members = ts.createSymbolTable();
59262 for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
59263 var property = _a[_i];
59264 var original = getTypeOfSymbol(property);
59265 var updated = f(original);
59266 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
59267 }
59268 return members;
59269 }
59270 /**
59271 * If the the provided object literal is subject to the excess properties check,
59272 * create a new that is exempt. Recursively mark object literal members as exempt.
59273 * Leave signatures alone since they are not subject to the check.
59274 */
59275 function getRegularTypeOfObjectLiteral(type) {
59276 if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
59277 return type;
59278 }
59279 var regularType = type.regularType;
59280 if (regularType) {
59281 return regularType;
59282 }
59283 var resolved = type;
59284 var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
59285 var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
59286 regularNew.flags = resolved.flags;
59287 regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
59288 type.regularType = regularNew;
59289 return regularNew;
59290 }
59291 function createWideningContext(parent, propertyName, siblings) {
59292 return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
59293 }
59294 function getSiblingsOfContext(context) {
59295 if (!context.siblings) {
59296 var siblings_1 = [];
59297 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
59298 var type = _a[_i];
59299 if (isObjectLiteralType(type)) {
59300 var prop = getPropertyOfObjectType(type, context.propertyName);
59301 if (prop) {
59302 forEachType(getTypeOfSymbol(prop), function (t) {
59303 siblings_1.push(t);
59304 });
59305 }
59306 }
59307 }
59308 context.siblings = siblings_1;
59309 }
59310 return context.siblings;
59311 }
59312 function getPropertiesOfContext(context) {
59313 if (!context.resolvedProperties) {
59314 var names = new ts.Map();
59315 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
59316 var t = _a[_i];
59317 if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
59318 for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
59319 var prop = _c[_b];
59320 names.set(prop.escapedName, prop);
59321 }
59322 }
59323 }
59324 context.resolvedProperties = ts.arrayFrom(names.values());
59325 }
59326 return context.resolvedProperties;
59327 }
59328 function getWidenedProperty(prop, context) {
59329 if (!(prop.flags & 4 /* Property */)) {
59330 // Since get accessors already widen their return value there is no need to
59331 // widen accessor based properties here.
59332 return prop;
59333 }
59334 var original = getTypeOfSymbol(prop);
59335 var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
59336 var widened = getWidenedTypeWithContext(original, propContext);
59337 return widened === original ? prop : createSymbolWithType(prop, widened);
59338 }
59339 function getUndefinedProperty(prop) {
59340 var cached = undefinedProperties.get(prop.escapedName);
59341 if (cached) {
59342 return cached;
59343 }
59344 var result = createSymbolWithType(prop, undefinedType);
59345 result.flags |= 16777216 /* Optional */;
59346 undefinedProperties.set(prop.escapedName, result);
59347 return result;
59348 }
59349 function getWidenedTypeOfObjectLiteral(type, context) {
59350 var members = ts.createSymbolTable();
59351 for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
59352 var prop = _a[_i];
59353 members.set(prop.escapedName, getWidenedProperty(prop, context));
59354 }
59355 if (context) {
59356 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
59357 var prop = _c[_b];
59358 if (!members.has(prop.escapedName)) {
59359 members.set(prop.escapedName, getUndefinedProperty(prop));
59360 }
59361 }
59362 }
59363 var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
59364 var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
59365 var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
59366 result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
59367 return result;
59368 }
59369 function getWidenedType(type) {
59370 return getWidenedTypeWithContext(type, /*context*/ undefined);
59371 }
59372 function getWidenedTypeWithContext(type, context) {
59373 if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
59374 if (context === undefined && type.widened) {
59375 return type.widened;
59376 }
59377 var result = void 0;
59378 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
59379 result = anyType;
59380 }
59381 else if (isObjectLiteralType(type)) {
59382 result = getWidenedTypeOfObjectLiteral(type, context);
59383 }
59384 else if (type.flags & 1048576 /* Union */) {
59385 var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
59386 var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
59387 // Widening an empty object literal transitions from a highly restrictive type to
59388 // a highly inclusive one. For that reason we perform subtype reduction here if the
59389 // union includes empty object types (e.g. reducing {} | string to just {}).
59390 result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
59391 }
59392 else if (type.flags & 2097152 /* Intersection */) {
59393 result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
59394 }
59395 else if (isArrayType(type) || isTupleType(type)) {
59396 result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
59397 }
59398 if (result && context === undefined) {
59399 type.widened = result;
59400 }
59401 return result || type;
59402 }
59403 return type;
59404 }
59405 /**
59406 * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
59407 * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
59408 * getWidenedType. But in some cases getWidenedType is called without reporting errors
59409 * (type argument inference is an example).
59410 *
59411 * The return value indicates whether an error was in fact reported. The particular circumstances
59412 * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
59413 * an object literal property (arbitrarily deeply), this function reports an error. If no error is
59414 * reported, reportImplicitAnyError is a suitable fallback to report a general error.
59415 */
59416 function reportWideningErrorsInType(type) {
59417 var errorReported = false;
59418 if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
59419 if (type.flags & 1048576 /* Union */) {
59420 if (ts.some(type.types, isEmptyObjectType)) {
59421 errorReported = true;
59422 }
59423 else {
59424 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
59425 var t = _a[_i];
59426 if (reportWideningErrorsInType(t)) {
59427 errorReported = true;
59428 }
59429 }
59430 }
59431 }
59432 if (isArrayType(type) || isTupleType(type)) {
59433 for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
59434 var t = _c[_b];
59435 if (reportWideningErrorsInType(t)) {
59436 errorReported = true;
59437 }
59438 }
59439 }
59440 if (isObjectLiteralType(type)) {
59441 for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
59442 var p = _e[_d];
59443 var t = getTypeOfSymbol(p);
59444 if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
59445 if (!reportWideningErrorsInType(t)) {
59446 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
59447 }
59448 errorReported = true;
59449 }
59450 }
59451 }
59452 }
59453 return errorReported;
59454 }
59455 function reportImplicitAny(declaration, type, wideningKind) {
59456 var typeAsString = typeToString(getWidenedType(type));
59457 if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
59458 // Only report implicit any errors/suggestions in TS and ts-check JS files
59459 return;
59460 }
59461 var diagnostic;
59462 switch (declaration.kind) {
59463 case 213 /* BinaryExpression */:
59464 case 162 /* PropertyDeclaration */:
59465 case 161 /* PropertySignature */:
59466 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;
59467 break;
59468 case 159 /* Parameter */:
59469 var param = declaration;
59470 if (ts.isIdentifier(param.name) &&
59471 (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
59472 param.parent.parameters.indexOf(param) > -1 &&
59473 (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
59474 param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
59475 var newName = "arg" + param.parent.parameters.indexOf(param);
59476 errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
59477 return;
59478 }
59479 diagnostic = declaration.dotDotDotToken ?
59480 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 :
59481 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;
59482 break;
59483 case 195 /* BindingElement */:
59484 diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
59485 if (!noImplicitAny) {
59486 // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
59487 return;
59488 }
59489 break;
59490 case 304 /* JSDocFunctionType */:
59491 error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
59492 return;
59493 case 248 /* FunctionDeclaration */:
59494 case 164 /* MethodDeclaration */:
59495 case 163 /* MethodSignature */:
59496 case 166 /* GetAccessor */:
59497 case 167 /* SetAccessor */:
59498 case 205 /* FunctionExpression */:
59499 case 206 /* ArrowFunction */:
59500 if (noImplicitAny && !declaration.name) {
59501 if (wideningKind === 3 /* GeneratorYield */) {
59502 error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
59503 }
59504 else {
59505 error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
59506 }
59507 return;
59508 }
59509 diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
59510 wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
59511 ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
59512 break;
59513 case 189 /* MappedType */:
59514 if (noImplicitAny) {
59515 error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
59516 }
59517 return;
59518 default:
59519 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;
59520 }
59521 errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
59522 }
59523 function reportErrorsFromWidening(declaration, type, wideningKind) {
59524 if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
59525 // Report implicit any error within type if possible, otherwise report error on declaration
59526 if (!reportWideningErrorsInType(type)) {
59527 reportImplicitAny(declaration, type, wideningKind);
59528 }
59529 }
59530 }
59531 function applyToParameterTypes(source, target, callback) {
59532 var sourceCount = getParameterCount(source);
59533 var targetCount = getParameterCount(target);
59534 var sourceRestType = getEffectiveRestType(source);
59535 var targetRestType = getEffectiveRestType(target);
59536 var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
59537 var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
59538 var sourceThisType = getThisTypeOfSignature(source);
59539 if (sourceThisType) {
59540 var targetThisType = getThisTypeOfSignature(target);
59541 if (targetThisType) {
59542 callback(sourceThisType, targetThisType);
59543 }
59544 }
59545 for (var i = 0; i < paramCount; i++) {
59546 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
59547 }
59548 if (targetRestType) {
59549 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
59550 }
59551 }
59552 function applyToReturnTypes(source, target, callback) {
59553 var sourceTypePredicate = getTypePredicateOfSignature(source);
59554 var targetTypePredicate = getTypePredicateOfSignature(target);
59555 if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
59556 callback(sourceTypePredicate.type, targetTypePredicate.type);
59557 }
59558 else {
59559 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
59560 }
59561 }
59562 function createInferenceContext(typeParameters, signature, flags, compareTypes) {
59563 return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
59564 }
59565 function cloneInferenceContext(context, extraFlags) {
59566 if (extraFlags === void 0) { extraFlags = 0; }
59567 return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
59568 }
59569 function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
59570 var context = {
59571 inferences: inferences,
59572 signature: signature,
59573 flags: flags,
59574 compareTypes: compareTypes,
59575 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
59576 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
59577 };
59578 return context;
59579 }
59580 function mapToInferredType(context, t, fix) {
59581 var inferences = context.inferences;
59582 for (var i = 0; i < inferences.length; i++) {
59583 var inference = inferences[i];
59584 if (t === inference.typeParameter) {
59585 if (fix && !inference.isFixed) {
59586 clearCachedInferences(inferences);
59587 inference.isFixed = true;
59588 }
59589 return getInferredType(context, i);
59590 }
59591 }
59592 return t;
59593 }
59594 function clearCachedInferences(inferences) {
59595 for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
59596 var inference = inferences_1[_i];
59597 if (!inference.isFixed) {
59598 inference.inferredType = undefined;
59599 }
59600 }
59601 }
59602 function createInferenceInfo(typeParameter) {
59603 return {
59604 typeParameter: typeParameter,
59605 candidates: undefined,
59606 contraCandidates: undefined,
59607 inferredType: undefined,
59608 priority: undefined,
59609 topLevel: true,
59610 isFixed: false,
59611 impliedArity: undefined
59612 };
59613 }
59614 function cloneInferenceInfo(inference) {
59615 return {
59616 typeParameter: inference.typeParameter,
59617 candidates: inference.candidates && inference.candidates.slice(),
59618 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
59619 inferredType: inference.inferredType,
59620 priority: inference.priority,
59621 topLevel: inference.topLevel,
59622 isFixed: inference.isFixed,
59623 impliedArity: inference.impliedArity
59624 };
59625 }
59626 function cloneInferredPartOfContext(context) {
59627 var inferences = ts.filter(context.inferences, hasInferenceCandidates);
59628 return inferences.length ?
59629 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
59630 undefined;
59631 }
59632 function getMapperFromContext(context) {
59633 return context && context.mapper;
59634 }
59635 // Return true if the given type could possibly reference a type parameter for which
59636 // we perform type inference (i.e. a type parameter of a generic function). We cache
59637 // results for union and intersection types for performance reasons.
59638 function couldContainTypeVariables(type) {
59639 var objectFlags = ts.getObjectFlags(type);
59640 if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
59641 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
59642 }
59643 var result = !!(type.flags & 63176704 /* Instantiable */ ||
59644 type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
59645 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
59646 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) ||
59647 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables));
59648 if (type.flags & 3899393 /* ObjectFlagsType */) {
59649 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
59650 }
59651 return result;
59652 }
59653 function isNonGenericTopLevelType(type) {
59654 if (type.aliasSymbol && !type.aliasTypeArguments) {
59655 var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 251 /* TypeAliasDeclaration */);
59656 return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 294 /* SourceFile */ ? true : n.kind === 253 /* ModuleDeclaration */ ? false : "quit"; }));
59657 }
59658 return false;
59659 }
59660 function isTypeParameterAtTopLevel(type, typeParameter) {
59661 return !!(type === typeParameter ||
59662 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
59663 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
59664 isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
59665 }
59666 /** Create an object with properties named in the string literal type. Every property has type `any` */
59667 function createEmptyObjectTypeFromStringLiteral(type) {
59668 var members = ts.createSymbolTable();
59669 forEachType(type, function (t) {
59670 if (!(t.flags & 128 /* StringLiteral */)) {
59671 return;
59672 }
59673 var name = ts.escapeLeadingUnderscores(t.value);
59674 var literalProp = createSymbol(4 /* Property */, name);
59675 literalProp.type = anyType;
59676 if (t.symbol) {
59677 literalProp.declarations = t.symbol.declarations;
59678 literalProp.valueDeclaration = t.symbol.valueDeclaration;
59679 }
59680 members.set(name, literalProp);
59681 });
59682 var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
59683 return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
59684 }
59685 /**
59686 * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
59687 * an object type with the same set of properties as the source type, where the type of each
59688 * property is computed by inferring from the source property type to X for the type
59689 * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
59690 */
59691 function inferTypeForHomomorphicMappedType(source, target, constraint) {
59692 if (inInferTypeForHomomorphicMappedType) {
59693 return undefined;
59694 }
59695 var key = source.id + "," + target.id + "," + constraint.id;
59696 if (reverseMappedCache.has(key)) {
59697 return reverseMappedCache.get(key);
59698 }
59699 inInferTypeForHomomorphicMappedType = true;
59700 var type = createReverseMappedType(source, target, constraint);
59701 inInferTypeForHomomorphicMappedType = false;
59702 reverseMappedCache.set(key, type);
59703 return type;
59704 }
59705 // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
59706 // an object literal type with at least one property of an inferable type. For example, an object
59707 // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
59708 // arrow function, but is considered partially inferable because property 'a' has an inferable type.
59709 function isPartiallyInferableType(type) {
59710 return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
59711 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
59712 }
59713 function createReverseMappedType(source, target, constraint) {
59714 // We consider a source type reverse mappable if it has a string index signature or if
59715 // it has one or more properties and is of a partially inferable type.
59716 if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
59717 return undefined;
59718 }
59719 // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
59720 // applied to the element type(s).
59721 if (isArrayType(source)) {
59722 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
59723 }
59724 if (isTupleType(source)) {
59725 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
59726 var elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
59727 ts.sameMap(source.target.elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
59728 source.target.elementFlags;
59729 return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
59730 }
59731 // For all other object types we infer a new object type where the reverse mapping has been
59732 // applied to the type of each property.
59733 var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
59734 reversed.source = source;
59735 reversed.mappedType = target;
59736 reversed.constraintType = constraint;
59737 return reversed;
59738 }
59739 function getTypeOfReverseMappedSymbol(symbol) {
59740 return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
59741 }
59742 function inferReverseMappedType(sourceType, target, constraint) {
59743 var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
59744 var templateType = getTemplateTypeFromMappedType(target);
59745 var inference = createInferenceInfo(typeParameter);
59746 inferTypes([inference], sourceType, templateType);
59747 return getTypeFromInference(inference) || unknownType;
59748 }
59749 function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
59750 var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
59751 return __generator(this, function (_a) {
59752 switch (_a.label) {
59753 case 0:
59754 properties = getPropertiesOfType(target);
59755 _i = 0, properties_2 = properties;
59756 _a.label = 1;
59757 case 1:
59758 if (!(_i < properties_2.length)) return [3 /*break*/, 6];
59759 targetProp = properties_2[_i];
59760 // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
59761 if (isStaticPrivateIdentifierProperty(targetProp)) {
59762 return [3 /*break*/, 5];
59763 }
59764 if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
59765 sourceProp = getPropertyOfType(source, targetProp.escapedName);
59766 if (!!sourceProp) return [3 /*break*/, 3];
59767 return [4 /*yield*/, targetProp];
59768 case 2:
59769 _a.sent();
59770 return [3 /*break*/, 5];
59771 case 3:
59772 if (!matchDiscriminantProperties) return [3 /*break*/, 5];
59773 targetType = getTypeOfSymbol(targetProp);
59774 if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
59775 sourceType = getTypeOfSymbol(sourceProp);
59776 if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
59777 return [4 /*yield*/, targetProp];
59778 case 4:
59779 _a.sent();
59780 _a.label = 5;
59781 case 5:
59782 _i++;
59783 return [3 /*break*/, 1];
59784 case 6: return [2 /*return*/];
59785 }
59786 });
59787 }
59788 function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
59789 var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
59790 if (!result.done)
59791 return result.value;
59792 }
59793 function tupleTypesDefinitelyUnrelated(source, target) {
59794 return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength ||
59795 !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength);
59796 }
59797 function typesDefinitelyUnrelated(source, target) {
59798 // Two tuple types with incompatible arities are definitely unrelated.
59799 // Two object types that each have a property that is unmatched in the other are definitely unrelated.
59800 return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
59801 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
59802 !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
59803 }
59804 function getTypeFromInference(inference) {
59805 return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
59806 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
59807 undefined;
59808 }
59809 function hasSkipDirectInferenceFlag(node) {
59810 return !!getNodeLinks(node).skipDirectInference;
59811 }
59812 function isFromInferenceBlockedSource(type) {
59813 return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
59814 }
59815 function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
59816 if (priority === void 0) { priority = 0; }
59817 if (contravariant === void 0) { contravariant = false; }
59818 var symbolOrTypeStack;
59819 var visited;
59820 var bivariant = false;
59821 var propagationType;
59822 var inferencePriority = 1024 /* MaxValue */;
59823 var allowComplexConstraintInference = true;
59824 var objectTypeComparisonDepth = 0;
59825 var targetStack = [];
59826 inferFromTypes(originalSource, originalTarget);
59827 function inferFromTypes(source, target) {
59828 if (!couldContainTypeVariables(target)) {
59829 return;
59830 }
59831 if (source === wildcardType) {
59832 // We are inferring from an 'any' type. We want to infer this type for every type parameter
59833 // referenced in the target type, so we record it as the propagation type and infer from the
59834 // target to itself. Then, as we find candidates we substitute the propagation type.
59835 var savePropagationType = propagationType;
59836 propagationType = source;
59837 inferFromTypes(target, target);
59838 propagationType = savePropagationType;
59839 return;
59840 }
59841 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
59842 // Source and target are types originating in the same generic type alias declaration.
59843 // Simply infer from source type arguments to target type arguments.
59844 inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
59845 return;
59846 }
59847 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
59848 // When source and target are the same union or intersection type, just relate each constituent
59849 // type to itself.
59850 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
59851 var t = _a[_i];
59852 inferFromTypes(t, t);
59853 }
59854 return;
59855 }
59856 if (target.flags & 1048576 /* Union */) {
59857 // First, infer between identically matching source and target constituents and remove the
59858 // matching types.
59859 var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
59860 // Next, infer between closely matching source and target constituents and remove
59861 // the matching types. Types closely match when they are instantiations of the same
59862 // object type or instantiations of the same type alias.
59863 var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
59864 if (targets.length === 0) {
59865 return;
59866 }
59867 target = getUnionType(targets);
59868 if (sources.length === 0) {
59869 // All source constituents have been matched and there is nothing further to infer from.
59870 // However, simply making no inferences is undesirable because it could ultimately mean
59871 // inferring a type parameter constraint. Instead, make a lower priority inference from
59872 // the full source to whatever remains in the target. For example, when inferring from
59873 // string to 'string | T', make a lower priority inference of string for T.
59874 inferWithPriority(source, target, 1 /* NakedTypeVariable */);
59875 return;
59876 }
59877 source = getUnionType(sources);
59878 }
59879 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
59880 // We reduce intersection types only when they contain naked type parameters. For example, when
59881 // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
59882 // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
59883 // string[] on the source side and infer string for T.
59884 // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
59885 // in such scenarios.
59886 if (!(source.flags & 1048576 /* Union */)) {
59887 // Infer between identically matching source and target constituents and remove the matching types.
59888 var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
59889 if (sources.length === 0 || targets.length === 0) {
59890 return;
59891 }
59892 source = getIntersectionType(sources);
59893 target = getIntersectionType(targets);
59894 }
59895 }
59896 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
59897 target = getActualTypeVariable(target);
59898 }
59899 if (target.flags & 8650752 /* TypeVariable */) {
59900 // If target is a type parameter, make an inference, unless the source type contains
59901 // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
59902 // Because the anyFunctionType is internal, it should not be exposed to the user by adding
59903 // it as an inference candidate. Hopefully, a better candidate will come along that does
59904 // not contain anyFunctionType when we come back to this argument for its second round
59905 // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
59906 // when constructing types from type parameters that had no inference candidates).
59907 if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
59908 (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
59909 return;
59910 }
59911 var inference = getInferenceInfoForType(target);
59912 if (inference) {
59913 if (!inference.isFixed) {
59914 if (inference.priority === undefined || priority < inference.priority) {
59915 inference.candidates = undefined;
59916 inference.contraCandidates = undefined;
59917 inference.topLevel = true;
59918 inference.priority = priority;
59919 }
59920 if (priority === inference.priority) {
59921 var candidate = propagationType || source;
59922 // We make contravariant inferences only if we are in a pure contravariant position,
59923 // i.e. only if we have not descended into a bivariant position.
59924 if (contravariant && !bivariant) {
59925 if (!ts.contains(inference.contraCandidates, candidate)) {
59926 inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
59927 clearCachedInferences(inferences);
59928 }
59929 }
59930 else if (!ts.contains(inference.candidates, candidate)) {
59931 inference.candidates = ts.append(inference.candidates, candidate);
59932 clearCachedInferences(inferences);
59933 }
59934 }
59935 if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
59936 inference.topLevel = false;
59937 clearCachedInferences(inferences);
59938 }
59939 }
59940 inferencePriority = Math.min(inferencePriority, priority);
59941 return;
59942 }
59943 else {
59944 // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
59945 var simplified = getSimplifiedType(target, /*writing*/ false);
59946 if (simplified !== target) {
59947 invokeOnce(source, simplified, inferFromTypes);
59948 }
59949 else if (target.flags & 8388608 /* IndexedAccess */) {
59950 var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
59951 // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
59952 // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
59953 if (indexType.flags & 63176704 /* Instantiable */) {
59954 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
59955 if (simplified_1 && simplified_1 !== target) {
59956 invokeOnce(source, simplified_1, inferFromTypes);
59957 }
59958 }
59959 }
59960 }
59961 }
59962 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
59963 !(source.node && target.node)) {
59964 // If source and target are references to the same generic type, infer from type arguments
59965 inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
59966 }
59967 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
59968 contravariant = !contravariant;
59969 inferFromTypes(source.type, target.type);
59970 contravariant = !contravariant;
59971 }
59972 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
59973 var empty = createEmptyObjectTypeFromStringLiteral(source);
59974 contravariant = !contravariant;
59975 inferWithPriority(empty, target.type, 128 /* LiteralKeyof */);
59976 contravariant = !contravariant;
59977 }
59978 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
59979 inferFromTypes(source.objectType, target.objectType);
59980 inferFromTypes(source.indexType, target.indexType);
59981 }
59982 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
59983 inferFromTypes(source.checkType, target.checkType);
59984 inferFromTypes(source.extendsType, target.extendsType);
59985 inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
59986 inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
59987 }
59988 else if (target.flags & 16777216 /* Conditional */) {
59989 var savePriority = priority;
59990 priority |= contravariant ? 32 /* ContravariantConditional */ : 0;
59991 var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
59992 inferToMultipleTypes(source, targetTypes, target.flags);
59993 priority = savePriority;
59994 }
59995 else if (target.flags & 3145728 /* UnionOrIntersection */) {
59996 inferToMultipleTypes(source, target.types, target.flags);
59997 }
59998 else if (source.flags & 1048576 /* Union */) {
59999 // Source is a union or intersection type, infer from each constituent type
60000 var sourceTypes = source.types;
60001 for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
60002 var sourceType = sourceTypes_2[_e];
60003 inferFromTypes(sourceType, target);
60004 }
60005 }
60006 else {
60007 source = getReducedType(source);
60008 if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
60009 var apparentSource = getApparentType(source);
60010 // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
60011 // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
60012 // with the simplified source.
60013 if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
60014 // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
60015 // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
60016 // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
60017 // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
60018 // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
60019 // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
60020 // remove this `allowComplexConstraintInference` flag.
60021 allowComplexConstraintInference = false;
60022 return inferFromTypes(apparentSource, target);
60023 }
60024 source = apparentSource;
60025 }
60026 if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
60027 invokeOnce(source, target, inferFromObjectTypes);
60028 }
60029 }
60030 if (source.flags & 25165824 /* Simplifiable */) {
60031 var simplified = getSimplifiedType(source, contravariant);
60032 if (simplified !== source) {
60033 inferFromTypes(simplified, target);
60034 }
60035 }
60036 }
60037 function inferWithPriority(source, target, newPriority) {
60038 var savePriority = priority;
60039 priority |= newPriority;
60040 inferFromTypes(source, target);
60041 priority = savePriority;
60042 }
60043 function invokeOnce(source, target, action) {
60044 var key = source.id + "," + target.id;
60045 var status = visited && visited.get(key);
60046 if (status !== undefined) {
60047 inferencePriority = Math.min(inferencePriority, status);
60048 return;
60049 }
60050 (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */);
60051 var saveInferencePriority = inferencePriority;
60052 inferencePriority = 1024 /* MaxValue */;
60053 action(source, target);
60054 visited.set(key, inferencePriority);
60055 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
60056 }
60057 function inferFromMatchingTypes(sources, targets, matches) {
60058 var matchedSources;
60059 var matchedTargets;
60060 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
60061 var t = targets_1[_i];
60062 for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
60063 var s = sources_1[_a];
60064 if (matches(s, t)) {
60065 inferFromTypes(s, t);
60066 matchedSources = ts.appendIfUnique(matchedSources, s);
60067 matchedTargets = ts.appendIfUnique(matchedTargets, t);
60068 }
60069 }
60070 }
60071 return [
60072 matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
60073 matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
60074 ];
60075 }
60076 function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
60077 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
60078 for (var i = 0; i < count; i++) {
60079 if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
60080 inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
60081 }
60082 else {
60083 inferFromTypes(sourceTypes[i], targetTypes[i]);
60084 }
60085 }
60086 }
60087 function inferFromContravariantTypes(source, target) {
60088 if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) {
60089 contravariant = !contravariant;
60090 inferFromTypes(source, target);
60091 contravariant = !contravariant;
60092 }
60093 else {
60094 inferFromTypes(source, target);
60095 }
60096 }
60097 function getInferenceInfoForType(type) {
60098 if (type.flags & 8650752 /* TypeVariable */) {
60099 for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
60100 var inference = inferences_2[_i];
60101 if (type === inference.typeParameter) {
60102 return inference;
60103 }
60104 }
60105 }
60106 return undefined;
60107 }
60108 function getSingleTypeVariableFromIntersectionTypes(types) {
60109 var typeVariable;
60110 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
60111 var type = types_14[_i];
60112 var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
60113 if (!t || typeVariable && t !== typeVariable) {
60114 return undefined;
60115 }
60116 typeVariable = t;
60117 }
60118 return typeVariable;
60119 }
60120 function inferToMultipleTypes(source, targets, targetFlags) {
60121 var typeVariableCount = 0;
60122 if (targetFlags & 1048576 /* Union */) {
60123 var nakedTypeVariable = void 0;
60124 var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
60125 var matched_1 = new Array(sources.length);
60126 var inferenceCircularity = false;
60127 // First infer to types that are not naked type variables. For each source type we
60128 // track whether inferences were made from that particular type to some target with
60129 // equal priority (i.e. of equal quality) to what we would infer for a naked type
60130 // parameter.
60131 for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
60132 var t = targets_2[_i];
60133 if (getInferenceInfoForType(t)) {
60134 nakedTypeVariable = t;
60135 typeVariableCount++;
60136 }
60137 else {
60138 for (var i = 0; i < sources.length; i++) {
60139 var saveInferencePriority = inferencePriority;
60140 inferencePriority = 1024 /* MaxValue */;
60141 inferFromTypes(sources[i], t);
60142 if (inferencePriority === priority)
60143 matched_1[i] = true;
60144 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
60145 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
60146 }
60147 }
60148 }
60149 if (typeVariableCount === 0) {
60150 // If every target is an intersection of types containing a single naked type variable,
60151 // make a lower priority inference to that type variable. This handles inferring from
60152 // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
60153 var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
60154 if (intersectionTypeVariable) {
60155 inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
60156 }
60157 return;
60158 }
60159 // If the target has a single naked type variable and no inference circularities were
60160 // encountered above (meaning we explored the types fully), create a union of the source
60161 // types from which no inferences have been made so far and infer from that union to the
60162 // naked type variable.
60163 if (typeVariableCount === 1 && !inferenceCircularity) {
60164 var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
60165 if (unmatched.length) {
60166 inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
60167 return;
60168 }
60169 }
60170 }
60171 else {
60172 // We infer from types that are not naked type variables first so that inferences we
60173 // make from nested naked type variables and given slightly higher priority by virtue
60174 // of being first in the candidates array.
60175 for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
60176 var t = targets_3[_a];
60177 if (getInferenceInfoForType(t)) {
60178 typeVariableCount++;
60179 }
60180 else {
60181 inferFromTypes(source, t);
60182 }
60183 }
60184 }
60185 // Inferences directly to naked type variables are given lower priority as they are
60186 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
60187 // we want to infer string for T, not Promise<string> | string. For intersection types
60188 // we only infer to single naked type variables.
60189 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
60190 for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
60191 var t = targets_4[_b];
60192 if (getInferenceInfoForType(t)) {
60193 inferWithPriority(source, t, 1 /* NakedTypeVariable */);
60194 }
60195 }
60196 }
60197 }
60198 function inferToMappedType(source, target, constraintType) {
60199 if (constraintType.flags & 1048576 /* Union */) {
60200 var result = false;
60201 for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
60202 var type = _a[_i];
60203 result = inferToMappedType(source, target, type) || result;
60204 }
60205 return result;
60206 }
60207 if (constraintType.flags & 4194304 /* Index */) {
60208 // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
60209 // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
60210 // type and then make a secondary inference from that type to T. We make a secondary inference
60211 // such that direct inferences to T get priority over inferences to Partial<T>, for example.
60212 var inference = getInferenceInfoForType(constraintType.type);
60213 if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
60214 var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
60215 if (inferredType) {
60216 // We assign a lower priority to inferences made from types containing non-inferrable
60217 // types because we may only have a partial result (i.e. we may have failed to make
60218 // reverse inferences for some properties).
60219 inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
60220 8 /* PartialHomomorphicMappedType */ :
60221 4 /* HomomorphicMappedType */);
60222 }
60223 }
60224 return true;
60225 }
60226 if (constraintType.flags & 262144 /* TypeParameter */) {
60227 // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
60228 // parameter. First infer from 'keyof S' to K.
60229 inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */);
60230 // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
60231 // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
60232 // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
60233 // Pick<T, K>.
60234 var extendedConstraint = getConstraintOfType(constraintType);
60235 if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
60236 return true;
60237 }
60238 // If no inferences can be made to K's constraint, infer from a union of the property types
60239 // in the source to the template type X.
60240 var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
60241 var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
60242 var numberIndexInfo = getNonEnumNumberIndexInfo(source);
60243 var numberIndexType = numberIndexInfo && numberIndexInfo.type;
60244 inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
60245 return true;
60246 }
60247 return false;
60248 }
60249 function inferFromObjectTypes(source, target) {
60250 // If we are already processing another target type with the same associated symbol (such as
60251 // an instantiation of the same generic type), we do not explore this target as it would yield
60252 // no further inferences. We exclude the static side of classes from this check since it shares
60253 // its symbol with the instance side which would lead to false positives.
60254 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
60255 !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
60256 var symbolOrType = ts.getObjectFlags(target) & 4 /* Reference */ && target.node ? getNormalizedType(target, /*writing*/ false) : isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
60257 if (symbolOrType) {
60258 if (ts.contains(symbolOrTypeStack, symbolOrType)) {
60259 if (ts.getObjectFlags(target) & 4 /* Reference */ && target.node) {
60260 // Don't set the circularity flag for re-encountered recursive type references just because we're already exploring them
60261 return;
60262 }
60263 inferencePriority = -1 /* Circularity */;
60264 return;
60265 }
60266 targetStack[objectTypeComparisonDepth] = target;
60267 objectTypeComparisonDepth++;
60268 if (isDeeplyNestedType(target, targetStack, objectTypeComparisonDepth)) {
60269 inferencePriority = -1 /* Circularity */;
60270 objectTypeComparisonDepth--;
60271 return;
60272 }
60273 (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
60274 inferFromObjectTypesWorker(source, target);
60275 symbolOrTypeStack.pop();
60276 objectTypeComparisonDepth--;
60277 }
60278 else {
60279 inferFromObjectTypesWorker(source, target);
60280 }
60281 }
60282 function inferFromObjectTypesWorker(source, target) {
60283 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
60284 // If source and target are references to the same generic type, infer from type arguments
60285 inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
60286 return;
60287 }
60288 if (isGenericMappedType(source) && isGenericMappedType(target)) {
60289 // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
60290 // from S to T and from X to Y.
60291 inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
60292 inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
60293 }
60294 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
60295 var constraintType = getConstraintTypeFromMappedType(target);
60296 if (inferToMappedType(source, target, constraintType)) {
60297 return;
60298 }
60299 }
60300 // Infer from the members of source and target only if the two types are possibly related
60301 if (!typesDefinitelyUnrelated(source, target)) {
60302 if (isArrayType(source) || isTupleType(source)) {
60303 if (isTupleType(target)) {
60304 var sourceArity = getTypeReferenceArity(source);
60305 var targetArity = getTypeReferenceArity(target);
60306 var elementTypes = getTypeArguments(target);
60307 var elementFlags = target.target.elementFlags;
60308 // When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
60309 // to the same kind in each position), simply infer between the element types.
60310 if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
60311 for (var i = 0; i < targetArity; i++) {
60312 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
60313 }
60314 return;
60315 }
60316 var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
60317 var sourceRestType = !isTupleType(source) || sourceArity > 0 && source.target.elementFlags[sourceArity - 1] & 4 /* Rest */ ?
60318 getTypeArguments(source)[sourceArity - 1] : undefined;
60319 var endLength = !(target.target.combinedFlags & 12 /* Variable */) ? 0 :
60320 sourceRestType ? getEndLengthOfType(target) :
60321 Math.min(getEndLengthOfType(source), getEndLengthOfType(target));
60322 var sourceEndLength = sourceRestType ? 0 : endLength;
60323 // Infer between starting fixed elements.
60324 for (var i = 0; i < startLength; i++) {
60325 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
60326 }
60327 if (sourceRestType && sourceArity - startLength === 1) {
60328 // Single rest element remains in source, infer from that to every element in target
60329 for (var i = startLength; i < targetArity - endLength; i++) {
60330 inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(sourceRestType) : sourceRestType, elementTypes[i]);
60331 }
60332 }
60333 else {
60334 var middleLength = targetArity - startLength - endLength;
60335 if (middleLength === 2 && elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */ && isTupleType(source)) {
60336 // Middle of target is [...T, ...U] and source is tuple type
60337 var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
60338 if (targetInfo && targetInfo.impliedArity !== undefined) {
60339 // Infer slices from source based on implied arity of T.
60340 inferFromTypes(sliceTupleType(source, startLength, sourceEndLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
60341 inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, sourceEndLength), elementTypes[startLength + 1]);
60342 }
60343 }
60344 else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
60345 // Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
60346 // If target ends in optional element(s), make a lower priority a speculative inference.
60347 var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
60348 var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, sourceEndLength) : createArrayType(sourceRestType);
60349 inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
60350 }
60351 else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
60352 // Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
60353 var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, sourceEndLength) : sourceRestType;
60354 if (restType) {
60355 inferFromTypes(restType, elementTypes[startLength]);
60356 }
60357 }
60358 }
60359 // Infer between ending fixed elements
60360 for (var i = 0; i < endLength; i++) {
60361 inferFromTypes(sourceRestType || getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
60362 }
60363 return;
60364 }
60365 if (isArrayType(target)) {
60366 inferFromIndexTypes(source, target);
60367 return;
60368 }
60369 }
60370 inferFromProperties(source, target);
60371 inferFromSignatures(source, target, 0 /* Call */);
60372 inferFromSignatures(source, target, 1 /* Construct */);
60373 inferFromIndexTypes(source, target);
60374 }
60375 }
60376 function inferFromProperties(source, target) {
60377 var properties = getPropertiesOfObjectType(target);
60378 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
60379 var targetProp = properties_3[_i];
60380 var sourceProp = getPropertyOfType(source, targetProp.escapedName);
60381 if (sourceProp) {
60382 inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
60383 }
60384 }
60385 }
60386 function inferFromSignatures(source, target, kind) {
60387 var sourceSignatures = getSignaturesOfType(source, kind);
60388 var targetSignatures = getSignaturesOfType(target, kind);
60389 var sourceLen = sourceSignatures.length;
60390 var targetLen = targetSignatures.length;
60391 var len = sourceLen < targetLen ? sourceLen : targetLen;
60392 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
60393 for (var i = 0; i < len; i++) {
60394 inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
60395 }
60396 }
60397 function inferFromSignature(source, target, skipParameters) {
60398 if (!skipParameters) {
60399 var saveBivariant = bivariant;
60400 var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
60401 // Once we descend into a bivariant signature we remain bivariant for all nested inferences
60402 bivariant = bivariant || kind === 164 /* MethodDeclaration */ || kind === 163 /* MethodSignature */ || kind === 165 /* Constructor */;
60403 applyToParameterTypes(source, target, inferFromContravariantTypes);
60404 bivariant = saveBivariant;
60405 }
60406 applyToReturnTypes(source, target, inferFromTypes);
60407 }
60408 function inferFromIndexTypes(source, target) {
60409 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
60410 if (targetStringIndexType) {
60411 var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
60412 getImplicitIndexTypeOfType(source, 0 /* String */);
60413 if (sourceIndexType) {
60414 inferFromTypes(sourceIndexType, targetStringIndexType);
60415 }
60416 }
60417 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
60418 if (targetNumberIndexType) {
60419 var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
60420 getIndexTypeOfType(source, 0 /* String */) ||
60421 getImplicitIndexTypeOfType(source, 1 /* Number */);
60422 if (sourceIndexType) {
60423 inferFromTypes(sourceIndexType, targetNumberIndexType);
60424 }
60425 }
60426 }
60427 }
60428 function isTypeOrBaseIdenticalTo(s, t) {
60429 return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
60430 }
60431 function isTypeCloselyMatchedBy(s, t) {
60432 return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
60433 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
60434 }
60435 function hasPrimitiveConstraint(type) {
60436 var constraint = getConstraintOfTypeParameter(type);
60437 return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
60438 }
60439 function isObjectLiteralType(type) {
60440 return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
60441 }
60442 function isObjectOrArrayLiteralType(type) {
60443 return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
60444 }
60445 function unionObjectAndArrayLiteralCandidates(candidates) {
60446 if (candidates.length > 1) {
60447 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
60448 if (objectLiterals.length) {
60449 var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
60450 return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
60451 }
60452 }
60453 return candidates;
60454 }
60455 function getContravariantInference(inference) {
60456 return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
60457 }
60458 function getCovariantInference(inference, signature) {
60459 // Extract all object and array literal types and replace them with a single widened and normalized type.
60460 var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
60461 // We widen inferred literal types if
60462 // all inferences were made to top-level occurrences of the type parameter, and
60463 // the type parameter has no constraint or its constraint includes no primitive or literal types, and
60464 // the type parameter was fixed during inference or does not occur at top-level in the return type.
60465 var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
60466 var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
60467 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
60468 var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
60469 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
60470 candidates;
60471 // If all inferences were made from a position that implies a combined result, infer a union type.
60472 // Otherwise, infer a common supertype.
60473 var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ?
60474 getUnionType(baseCandidates, 2 /* Subtype */) :
60475 getCommonSupertype(baseCandidates);
60476 return getWidenedType(unwidenedType);
60477 }
60478 function getInferredType(context, index) {
60479 var inference = context.inferences[index];
60480 if (!inference.inferredType) {
60481 var inferredType = void 0;
60482 var signature = context.signature;
60483 if (signature) {
60484 var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
60485 if (inference.contraCandidates) {
60486 var inferredContravariantType = getContravariantInference(inference);
60487 // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
60488 // unless the co-variant inference is a subtype and not 'never'.
60489 inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
60490 isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
60491 inferredCovariantType : inferredContravariantType;
60492 }
60493 else if (inferredCovariantType) {
60494 inferredType = inferredCovariantType;
60495 }
60496 else if (context.flags & 1 /* NoDefault */) {
60497 // We use silentNeverType as the wildcard that signals no inferences.
60498 inferredType = silentNeverType;
60499 }
60500 else {
60501 // Infer either the default or the empty object type when no inferences were
60502 // made. It is important to remember that in this case, inference still
60503 // succeeds, meaning there is no error for not having inference candidates. An
60504 // inference error only occurs when there are *conflicting* candidates, i.e.
60505 // candidates with no common supertype.
60506 var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
60507 if (defaultType) {
60508 // Instantiate the default type. Any forward reference to a type
60509 // parameter should be instantiated to the empty object type.
60510 inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
60511 }
60512 }
60513 }
60514 else {
60515 inferredType = getTypeFromInference(inference);
60516 }
60517 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
60518 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
60519 if (constraint) {
60520 var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
60521 if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
60522 inference.inferredType = inferredType = instantiatedConstraint;
60523 }
60524 }
60525 }
60526 return inference.inferredType;
60527 }
60528 function getDefaultTypeArgumentType(isInJavaScriptFile) {
60529 return isInJavaScriptFile ? anyType : unknownType;
60530 }
60531 function getInferredTypes(context) {
60532 var result = [];
60533 for (var i = 0; i < context.inferences.length; i++) {
60534 result.push(getInferredType(context, i));
60535 }
60536 return result;
60537 }
60538 // EXPRESSION TYPE CHECKING
60539 function getCannotFindNameDiagnosticForName(node) {
60540 switch (node.escapedText) {
60541 case "document":
60542 case "console":
60543 return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
60544 case "$":
60545 return compilerOptions.types
60546 ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
60547 : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
60548 case "describe":
60549 case "suite":
60550 case "it":
60551 case "test":
60552 return compilerOptions.types
60553 ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
60554 : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
60555 case "process":
60556 case "require":
60557 case "Buffer":
60558 case "module":
60559 return compilerOptions.types
60560 ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
60561 : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
60562 case "Map":
60563 case "Set":
60564 case "Promise":
60565 case "Symbol":
60566 case "WeakMap":
60567 case "WeakSet":
60568 case "Iterator":
60569 case "AsyncIterator":
60570 return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
60571 default:
60572 if (node.parent.kind === 286 /* ShorthandPropertyAssignment */) {
60573 return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
60574 }
60575 else {
60576 return ts.Diagnostics.Cannot_find_name_0;
60577 }
60578 }
60579 }
60580 function getResolvedSymbol(node) {
60581 var links = getNodeLinks(node);
60582 if (!links.resolvedSymbol) {
60583 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
60584 resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node),
60585 /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
60586 }
60587 return links.resolvedSymbol;
60588 }
60589 function isInTypeQuery(node) {
60590 // TypeScript 1.0 spec (April 2014): 3.6.3
60591 // A type query consists of the keyword typeof followed by an expression.
60592 // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
60593 return !!ts.findAncestor(node, function (n) { return n.kind === 175 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 156 /* QualifiedName */ ? false : "quit"; });
60594 }
60595 // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
60596 // separated by dots). The key consists of the id of the symbol referenced by the
60597 // leftmost identifier followed by zero or more property names separated by dots.
60598 // The result is undefined if the reference isn't a dotted name. We prefix nodes
60599 // occurring in an apparent type position with '@' because the control flow type
60600 // of such nodes may be based on the apparent type instead of the declared type.
60601 function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
60602 switch (node.kind) {
60603 case 78 /* Identifier */:
60604 var symbol = getResolvedSymbol(node);
60605 return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
60606 case 107 /* ThisKeyword */:
60607 return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType);
60608 case 222 /* NonNullExpression */:
60609 case 204 /* ParenthesizedExpression */:
60610 return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
60611 case 198 /* PropertyAccessExpression */:
60612 case 199 /* ElementAccessExpression */:
60613 var propName = getAccessedPropertyName(node);
60614 if (propName !== undefined) {
60615 var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
60616 return key && key + "." + propName;
60617 }
60618 }
60619 return undefined;
60620 }
60621 function isMatchingReference(source, target) {
60622 switch (target.kind) {
60623 case 204 /* ParenthesizedExpression */:
60624 case 222 /* NonNullExpression */:
60625 return isMatchingReference(source, target.expression);
60626 case 213 /* BinaryExpression */:
60627 return ts.isAssignmentExpression(target) && isMatchingReference(source, target.left);
60628 }
60629 switch (source.kind) {
60630 case 78 /* Identifier */:
60631 return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
60632 (target.kind === 246 /* VariableDeclaration */ || target.kind === 195 /* BindingElement */) &&
60633 getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
60634 case 107 /* ThisKeyword */:
60635 return target.kind === 107 /* ThisKeyword */;
60636 case 105 /* SuperKeyword */:
60637 return target.kind === 105 /* SuperKeyword */;
60638 case 222 /* NonNullExpression */:
60639 case 204 /* ParenthesizedExpression */:
60640 return isMatchingReference(source.expression, target);
60641 case 198 /* PropertyAccessExpression */:
60642 case 199 /* ElementAccessExpression */:
60643 return ts.isAccessExpression(target) &&
60644 getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
60645 isMatchingReference(source.expression, target.expression);
60646 }
60647 return false;
60648 }
60649 // Given a source x, check if target matches x or is an && operation with an operand that matches x.
60650 function containsTruthyCheck(source, target) {
60651 return isMatchingReference(source, target) ||
60652 (target.kind === 213 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
60653 (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
60654 }
60655 function getAccessedPropertyName(access) {
60656 return access.kind === 198 /* PropertyAccessExpression */ ? access.name.escapedText :
60657 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
60658 undefined;
60659 }
60660 function containsMatchingReference(source, target) {
60661 while (ts.isAccessExpression(source)) {
60662 source = source.expression;
60663 if (isMatchingReference(source, target)) {
60664 return true;
60665 }
60666 }
60667 return false;
60668 }
60669 function optionalChainContainsReference(source, target) {
60670 while (ts.isOptionalChain(source)) {
60671 source = source.expression;
60672 if (isMatchingReference(source, target)) {
60673 return true;
60674 }
60675 }
60676 return false;
60677 }
60678 function isDiscriminantProperty(type, name) {
60679 if (type && type.flags & 1048576 /* Union */) {
60680 var prop = getUnionOrIntersectionProperty(type, name);
60681 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
60682 if (prop.isDiscriminantProperty === undefined) {
60683 prop.isDiscriminantProperty =
60684 (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
60685 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
60686 }
60687 return !!prop.isDiscriminantProperty;
60688 }
60689 }
60690 return false;
60691 }
60692 function findDiscriminantProperties(sourceProperties, target) {
60693 var result;
60694 for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
60695 var sourceProperty = sourceProperties_2[_i];
60696 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
60697 if (result) {
60698 result.push(sourceProperty);
60699 continue;
60700 }
60701 result = [sourceProperty];
60702 }
60703 }
60704 return result;
60705 }
60706 function isOrContainsMatchingReference(source, target) {
60707 return isMatchingReference(source, target) || containsMatchingReference(source, target);
60708 }
60709 function hasMatchingArgument(callExpression, reference) {
60710 if (callExpression.arguments) {
60711 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
60712 var argument = _a[_i];
60713 if (isOrContainsMatchingReference(reference, argument)) {
60714 return true;
60715 }
60716 }
60717 }
60718 if (callExpression.expression.kind === 198 /* PropertyAccessExpression */ &&
60719 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
60720 return true;
60721 }
60722 return false;
60723 }
60724 function getFlowNodeId(flow) {
60725 if (!flow.id || flow.id < 0) {
60726 flow.id = nextFlowId;
60727 nextFlowId++;
60728 }
60729 return flow.id;
60730 }
60731 function typeMaybeAssignableTo(source, target) {
60732 if (!(source.flags & 1048576 /* Union */)) {
60733 return isTypeAssignableTo(source, target);
60734 }
60735 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
60736 var t = _a[_i];
60737 if (isTypeAssignableTo(t, target)) {
60738 return true;
60739 }
60740 }
60741 return false;
60742 }
60743 // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
60744 // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
60745 // we remove type string.
60746 function getAssignmentReducedType(declaredType, assignedType) {
60747 if (declaredType !== assignedType) {
60748 if (assignedType.flags & 131072 /* Never */) {
60749 return assignedType;
60750 }
60751 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
60752 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
60753 reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
60754 }
60755 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
60756 // For now, when that happens, we give up and don't narrow at all. (This also
60757 // means we'll never narrow for erroneous assignments where the assigned type
60758 // is not assignable to the declared type.)
60759 if (isTypeAssignableTo(assignedType, reducedType)) {
60760 return reducedType;
60761 }
60762 }
60763 return declaredType;
60764 }
60765 function getTypeFactsOfTypes(types) {
60766 var result = 0 /* None */;
60767 for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
60768 var t = types_15[_i];
60769 result |= getTypeFacts(t);
60770 }
60771 return result;
60772 }
60773 function isFunctionObjectType(type) {
60774 // We do a quick check for a "bind" property before performing the more expensive subtype
60775 // check. This gives us a quicker out in the common case where an object type is not a function.
60776 var resolved = resolveStructuredTypeMembers(type);
60777 return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
60778 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
60779 }
60780 function getTypeFacts(type) {
60781 var flags = type.flags;
60782 if (flags & 4 /* String */) {
60783 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
60784 }
60785 if (flags & 128 /* StringLiteral */) {
60786 var isEmpty = type.value === "";
60787 return strictNullChecks ?
60788 isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
60789 isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
60790 }
60791 if (flags & (8 /* Number */ | 32 /* Enum */)) {
60792 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
60793 }
60794 if (flags & 256 /* NumberLiteral */) {
60795 var isZero = type.value === 0;
60796 return strictNullChecks ?
60797 isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
60798 isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
60799 }
60800 if (flags & 64 /* BigInt */) {
60801 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
60802 }
60803 if (flags & 2048 /* BigIntLiteral */) {
60804 var isZero = isZeroBigInt(type);
60805 return strictNullChecks ?
60806 isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
60807 isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
60808 }
60809 if (flags & 16 /* Boolean */) {
60810 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
60811 }
60812 if (flags & 528 /* BooleanLike */) {
60813 return strictNullChecks ?
60814 (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
60815 (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
60816 }
60817 if (flags & 524288 /* Object */) {
60818 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
60819 strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
60820 isFunctionObjectType(type) ?
60821 strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
60822 strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
60823 }
60824 if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
60825 return 9830144 /* UndefinedFacts */;
60826 }
60827 if (flags & 65536 /* Null */) {
60828 return 9363232 /* NullFacts */;
60829 }
60830 if (flags & 12288 /* ESSymbolLike */) {
60831 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
60832 }
60833 if (flags & 67108864 /* NonPrimitive */) {
60834 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
60835 }
60836 if (flags & 131072 /* Never */) {
60837 return 0 /* None */;
60838 }
60839 if (flags & 63176704 /* Instantiable */) {
60840 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
60841 }
60842 if (flags & 3145728 /* UnionOrIntersection */) {
60843 return getTypeFactsOfTypes(type.types);
60844 }
60845 return 16777215 /* All */;
60846 }
60847 function getTypeWithFacts(type, include) {
60848 return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
60849 }
60850 function getTypeWithDefault(type, defaultExpression) {
60851 if (defaultExpression) {
60852 var defaultType = getTypeOfExpression(defaultExpression);
60853 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
60854 }
60855 return type;
60856 }
60857 function getTypeOfDestructuredProperty(type, name) {
60858 var nameType = getLiteralTypeFromPropertyName(name);
60859 if (!isTypeUsableAsPropertyName(nameType))
60860 return errorType;
60861 var text = getPropertyNameFromType(nameType);
60862 return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
60863 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
60864 getIndexTypeOfType(type, 0 /* String */) ||
60865 errorType;
60866 }
60867 function getTypeOfDestructuredArrayElement(type, index) {
60868 return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
60869 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
60870 errorType;
60871 }
60872 function getTypeOfDestructuredSpreadExpression(type) {
60873 return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
60874 }
60875 function getAssignedTypeOfBinaryExpression(node) {
60876 var isDestructuringDefaultAssignment = node.parent.kind === 196 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
60877 node.parent.kind === 285 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
60878 return isDestructuringDefaultAssignment ?
60879 getTypeWithDefault(getAssignedType(node), node.right) :
60880 getTypeOfExpression(node.right);
60881 }
60882 function isDestructuringAssignmentTarget(parent) {
60883 return parent.parent.kind === 213 /* BinaryExpression */ && parent.parent.left === parent ||
60884 parent.parent.kind === 236 /* ForOfStatement */ && parent.parent.initializer === parent;
60885 }
60886 function getAssignedTypeOfArrayLiteralElement(node, element) {
60887 return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
60888 }
60889 function getAssignedTypeOfSpreadExpression(node) {
60890 return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
60891 }
60892 function getAssignedTypeOfPropertyAssignment(node) {
60893 return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
60894 }
60895 function getAssignedTypeOfShorthandPropertyAssignment(node) {
60896 return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
60897 }
60898 function getAssignedType(node) {
60899 var parent = node.parent;
60900 switch (parent.kind) {
60901 case 235 /* ForInStatement */:
60902 return stringType;
60903 case 236 /* ForOfStatement */:
60904 return checkRightHandSideOfForOf(parent) || errorType;
60905 case 213 /* BinaryExpression */:
60906 return getAssignedTypeOfBinaryExpression(parent);
60907 case 207 /* DeleteExpression */:
60908 return undefinedType;
60909 case 196 /* ArrayLiteralExpression */:
60910 return getAssignedTypeOfArrayLiteralElement(parent, node);
60911 case 217 /* SpreadElement */:
60912 return getAssignedTypeOfSpreadExpression(parent);
60913 case 285 /* PropertyAssignment */:
60914 return getAssignedTypeOfPropertyAssignment(parent);
60915 case 286 /* ShorthandPropertyAssignment */:
60916 return getAssignedTypeOfShorthandPropertyAssignment(parent);
60917 }
60918 return errorType;
60919 }
60920 function getInitialTypeOfBindingElement(node) {
60921 var pattern = node.parent;
60922 var parentType = getInitialType(pattern.parent);
60923 var type = pattern.kind === 193 /* ObjectBindingPattern */ ?
60924 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
60925 !node.dotDotDotToken ?
60926 getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
60927 getTypeOfDestructuredSpreadExpression(parentType);
60928 return getTypeWithDefault(type, node.initializer);
60929 }
60930 function getTypeOfInitializer(node) {
60931 // Return the cached type if one is available. If the type of the variable was inferred
60932 // from its initializer, we'll already have cached the type. Otherwise we compute it now
60933 // without caching such that transient types are reflected.
60934 var links = getNodeLinks(node);
60935 return links.resolvedType || getTypeOfExpression(node);
60936 }
60937 function getInitialTypeOfVariableDeclaration(node) {
60938 if (node.initializer) {
60939 return getTypeOfInitializer(node.initializer);
60940 }
60941 if (node.parent.parent.kind === 235 /* ForInStatement */) {
60942 return stringType;
60943 }
60944 if (node.parent.parent.kind === 236 /* ForOfStatement */) {
60945 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
60946 }
60947 return errorType;
60948 }
60949 function getInitialType(node) {
60950 return node.kind === 246 /* VariableDeclaration */ ?
60951 getInitialTypeOfVariableDeclaration(node) :
60952 getInitialTypeOfBindingElement(node);
60953 }
60954 function isEmptyArrayAssignment(node) {
60955 return node.kind === 246 /* VariableDeclaration */ && node.initializer &&
60956 isEmptyArrayLiteral(node.initializer) ||
60957 node.kind !== 195 /* BindingElement */ && node.parent.kind === 213 /* BinaryExpression */ &&
60958 isEmptyArrayLiteral(node.parent.right);
60959 }
60960 function getReferenceCandidate(node) {
60961 switch (node.kind) {
60962 case 204 /* ParenthesizedExpression */:
60963 return getReferenceCandidate(node.expression);
60964 case 213 /* BinaryExpression */:
60965 switch (node.operatorToken.kind) {
60966 case 62 /* EqualsToken */:
60967 case 74 /* BarBarEqualsToken */:
60968 case 75 /* AmpersandAmpersandEqualsToken */:
60969 case 76 /* QuestionQuestionEqualsToken */:
60970 return getReferenceCandidate(node.left);
60971 case 27 /* CommaToken */:
60972 return getReferenceCandidate(node.right);
60973 }
60974 }
60975 return node;
60976 }
60977 function getReferenceRoot(node) {
60978 var parent = node.parent;
60979 return parent.kind === 204 /* ParenthesizedExpression */ ||
60980 parent.kind === 213 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
60981 parent.kind === 213 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
60982 getReferenceRoot(parent) : node;
60983 }
60984 function getTypeOfSwitchClause(clause) {
60985 if (clause.kind === 281 /* CaseClause */) {
60986 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
60987 }
60988 return neverType;
60989 }
60990 function getSwitchClauseTypes(switchStatement) {
60991 var links = getNodeLinks(switchStatement);
60992 if (!links.switchTypes) {
60993 links.switchTypes = [];
60994 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
60995 var clause = _a[_i];
60996 links.switchTypes.push(getTypeOfSwitchClause(clause));
60997 }
60998 }
60999 return links.switchTypes;
61000 }
61001 function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
61002 var witnesses = [];
61003 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
61004 var clause = _a[_i];
61005 if (clause.kind === 281 /* CaseClause */) {
61006 if (ts.isStringLiteralLike(clause.expression)) {
61007 witnesses.push(clause.expression.text);
61008 continue;
61009 }
61010 return ts.emptyArray;
61011 }
61012 if (retainDefault)
61013 witnesses.push(/*explicitDefaultStatement*/ undefined);
61014 }
61015 return witnesses;
61016 }
61017 function eachTypeContainedIn(source, types) {
61018 return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
61019 }
61020 function isTypeSubsetOf(source, target) {
61021 return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
61022 }
61023 function isTypeSubsetOfUnion(source, target) {
61024 if (source.flags & 1048576 /* Union */) {
61025 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
61026 var t = _a[_i];
61027 if (!containsType(target.types, t)) {
61028 return false;
61029 }
61030 }
61031 return true;
61032 }
61033 if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
61034 return true;
61035 }
61036 return containsType(target.types, source);
61037 }
61038 function forEachType(type, f) {
61039 return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
61040 }
61041 function everyType(type, f) {
61042 return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
61043 }
61044 function filterType(type, f) {
61045 if (type.flags & 1048576 /* Union */) {
61046 var types = type.types;
61047 var filtered = ts.filter(types, f);
61048 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
61049 }
61050 return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
61051 }
61052 function countTypes(type) {
61053 return type.flags & 1048576 /* Union */ ? type.types.length : 1;
61054 }
61055 function mapType(type, mapper, noReductions) {
61056 if (type.flags & 131072 /* Never */) {
61057 return type;
61058 }
61059 if (!(type.flags & 1048576 /* Union */)) {
61060 return mapper(type);
61061 }
61062 var mappedTypes;
61063 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
61064 var t = _a[_i];
61065 var mapped = mapper(t);
61066 if (mapped) {
61067 if (!mappedTypes) {
61068 mappedTypes = [mapped];
61069 }
61070 else {
61071 mappedTypes.push(mapped);
61072 }
61073 }
61074 }
61075 return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
61076 }
61077 function extractTypesOfKind(type, kind) {
61078 return filterType(type, function (t) { return (t.flags & kind) !== 0; });
61079 }
61080 // Return a new type in which occurrences of the string and number primitive types in
61081 // typeWithPrimitives have been replaced with occurrences of string literals and numeric
61082 // literals in typeWithLiterals, respectively.
61083 function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
61084 if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
61085 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
61086 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
61087 return mapType(typeWithPrimitives, function (t) {
61088 return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
61089 t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
61090 t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
61091 });
61092 }
61093 return typeWithPrimitives;
61094 }
61095 function isIncomplete(flowType) {
61096 return flowType.flags === 0;
61097 }
61098 function getTypeFromFlowType(flowType) {
61099 return flowType.flags === 0 ? flowType.type : flowType;
61100 }
61101 function createFlowType(type, incomplete) {
61102 return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
61103 }
61104 // An evolving array type tracks the element types that have so far been seen in an
61105 // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
61106 // array types are ultimately converted into manifest array types (using getFinalArrayType)
61107 // and never escape the getFlowTypeOfReference function.
61108 function createEvolvingArrayType(elementType) {
61109 var result = createObjectType(256 /* EvolvingArray */);
61110 result.elementType = elementType;
61111 return result;
61112 }
61113 function getEvolvingArrayType(elementType) {
61114 return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
61115 }
61116 // When adding evolving array element types we do not perform subtype reduction. Instead,
61117 // we defer subtype reduction until the evolving array type is finalized into a manifest
61118 // array type.
61119 function addEvolvingArrayElementType(evolvingArrayType, node) {
61120 var elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
61121 return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
61122 }
61123 function createFinalArrayType(elementType) {
61124 return elementType.flags & 131072 /* Never */ ?
61125 autoArrayType :
61126 createArrayType(elementType.flags & 1048576 /* Union */ ?
61127 getUnionType(elementType.types, 2 /* Subtype */) :
61128 elementType);
61129 }
61130 // We perform subtype reduction upon obtaining the final array type from an evolving array type.
61131 function getFinalArrayType(evolvingArrayType) {
61132 return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
61133 }
61134 function finalizeEvolvingArrayType(type) {
61135 return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
61136 }
61137 function getElementTypeOfEvolvingArrayType(type) {
61138 return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
61139 }
61140 function isEvolvingArrayTypeList(types) {
61141 var hasEvolvingArrayType = false;
61142 for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
61143 var t = types_16[_i];
61144 if (!(t.flags & 131072 /* Never */)) {
61145 if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
61146 return false;
61147 }
61148 hasEvolvingArrayType = true;
61149 }
61150 }
61151 return hasEvolvingArrayType;
61152 }
61153 // At flow control branch or loop junctions, if the type along every antecedent code path
61154 // is an evolving array type, we construct a combined evolving array type. Otherwise we
61155 // finalize all evolving array types.
61156 function getUnionOrEvolvingArrayType(types, subtypeReduction) {
61157 return isEvolvingArrayTypeList(types) ?
61158 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
61159 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
61160 }
61161 // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
61162 // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
61163 function isEvolvingArrayOperationTarget(node) {
61164 var root = getReferenceRoot(node);
61165 var parent = root.parent;
61166 var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
61167 parent.parent.kind === 200 /* CallExpression */
61168 && ts.isIdentifier(parent.name)
61169 && ts.isPushOrUnshiftIdentifier(parent.name));
61170 var isElementAssignment = parent.kind === 199 /* ElementAccessExpression */ &&
61171 parent.expression === root &&
61172 parent.parent.kind === 213 /* BinaryExpression */ &&
61173 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
61174 parent.parent.left === parent &&
61175 !ts.isAssignmentTarget(parent.parent) &&
61176 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
61177 return isLengthPushOrUnshift || isElementAssignment;
61178 }
61179 function isDeclarationWithExplicitTypeAnnotation(declaration) {
61180 return (declaration.kind === 246 /* VariableDeclaration */ || declaration.kind === 159 /* Parameter */ ||
61181 declaration.kind === 162 /* PropertyDeclaration */ || declaration.kind === 161 /* PropertySignature */) &&
61182 !!ts.getEffectiveTypeAnnotationNode(declaration);
61183 }
61184 function getExplicitTypeOfSymbol(symbol, diagnostic) {
61185 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
61186 return getTypeOfSymbol(symbol);
61187 }
61188 if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
61189 var declaration = symbol.valueDeclaration;
61190 if (declaration) {
61191 if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
61192 return getTypeOfSymbol(symbol);
61193 }
61194 if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 236 /* ForOfStatement */) {
61195 var statement = declaration.parent.parent;
61196 var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
61197 if (expressionType) {
61198 var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
61199 return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
61200 }
61201 }
61202 if (diagnostic) {
61203 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
61204 }
61205 }
61206 }
61207 }
61208 // We require the dotted function name in an assertion expression to be comprised of identifiers
61209 // that reference function, method, class or value module symbols; or variable, property or
61210 // parameter symbols with declarations that have explicit type annotations. Such references are
61211 // resolvable with no possibility of triggering circularities in control flow analysis.
61212 function getTypeOfDottedName(node, diagnostic) {
61213 if (!(node.flags & 16777216 /* InWithStatement */)) {
61214 switch (node.kind) {
61215 case 78 /* Identifier */:
61216 var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
61217 return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
61218 case 107 /* ThisKeyword */:
61219 return getExplicitThisType(node);
61220 case 105 /* SuperKeyword */:
61221 return checkSuperExpression(node);
61222 case 198 /* PropertyAccessExpression */:
61223 var type = getTypeOfDottedName(node.expression, diagnostic);
61224 var prop = type && getPropertyOfType(type, node.name.escapedText);
61225 return prop && getExplicitTypeOfSymbol(prop, diagnostic);
61226 case 204 /* ParenthesizedExpression */:
61227 return getTypeOfDottedName(node.expression, diagnostic);
61228 }
61229 }
61230 }
61231 function getEffectsSignature(node) {
61232 var links = getNodeLinks(node);
61233 var signature = links.effectsSignature;
61234 if (signature === undefined) {
61235 // A call expression parented by an expression statement is a potential assertion. Other call
61236 // expressions are potential type predicate function calls. In order to avoid triggering
61237 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
61238 // target expression of an assertion.
61239 var funcType = void 0;
61240 if (node.parent.kind === 230 /* ExpressionStatement */) {
61241 funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
61242 }
61243 else if (node.expression.kind !== 105 /* SuperKeyword */) {
61244 if (ts.isOptionalChain(node)) {
61245 funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
61246 }
61247 else {
61248 funcType = checkNonNullExpression(node.expression);
61249 }
61250 }
61251 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
61252 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
61253 ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
61254 undefined;
61255 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
61256 }
61257 return signature === unknownSignature ? undefined : signature;
61258 }
61259 function hasTypePredicateOrNeverReturnType(signature) {
61260 return !!(getTypePredicateOfSignature(signature) ||
61261 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
61262 }
61263 function getTypePredicateArgument(predicate, callExpression) {
61264 if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
61265 return callExpression.arguments[predicate.parameterIndex];
61266 }
61267 var invokedExpression = ts.skipParentheses(callExpression.expression);
61268 return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
61269 }
61270 function reportFlowControlError(node) {
61271 var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
61272 var sourceFile = ts.getSourceFileOfNode(node);
61273 var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
61274 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
61275 }
61276 function isReachableFlowNode(flow) {
61277 var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
61278 lastFlowNode = flow;
61279 lastFlowNodeReachable = result;
61280 return result;
61281 }
61282 function isFalseExpression(expr) {
61283 var node = ts.skipParentheses(expr);
61284 return node.kind === 94 /* FalseKeyword */ || node.kind === 213 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
61285 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
61286 }
61287 function isReachableFlowNodeWorker(flow, noCacheCheck) {
61288 while (true) {
61289 if (flow === lastFlowNode) {
61290 return lastFlowNodeReachable;
61291 }
61292 var flags = flow.flags;
61293 if (flags & 4096 /* Shared */) {
61294 if (!noCacheCheck) {
61295 var id = getFlowNodeId(flow);
61296 var reachable = flowNodeReachable[id];
61297 return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
61298 }
61299 noCacheCheck = false;
61300 }
61301 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
61302 flow = flow.antecedent;
61303 }
61304 else if (flags & 512 /* Call */) {
61305 var signature = getEffectsSignature(flow.node);
61306 if (signature) {
61307 var predicate = getTypePredicateOfSignature(signature);
61308 if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
61309 var predicateArgument = flow.node.arguments[predicate.parameterIndex];
61310 if (predicateArgument && isFalseExpression(predicateArgument)) {
61311 return false;
61312 }
61313 }
61314 if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
61315 return false;
61316 }
61317 }
61318 flow = flow.antecedent;
61319 }
61320 else if (flags & 4 /* BranchLabel */) {
61321 // A branching point is reachable if any branch is reachable.
61322 return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
61323 }
61324 else if (flags & 8 /* LoopLabel */) {
61325 // A loop is reachable if the control flow path that leads to the top is reachable.
61326 flow = flow.antecedents[0];
61327 }
61328 else if (flags & 128 /* SwitchClause */) {
61329 // The control flow path representing an unmatched value in a switch statement with
61330 // no default clause is unreachable if the switch statement is exhaustive.
61331 if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
61332 return false;
61333 }
61334 flow = flow.antecedent;
61335 }
61336 else if (flags & 1024 /* ReduceLabel */) {
61337 // Cache is unreliable once we start adjusting labels
61338 lastFlowNode = undefined;
61339 var target = flow.target;
61340 var saveAntecedents = target.antecedents;
61341 target.antecedents = flow.antecedents;
61342 var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
61343 target.antecedents = saveAntecedents;
61344 return result;
61345 }
61346 else {
61347 return !(flags & 1 /* Unreachable */);
61348 }
61349 }
61350 }
61351 // Return true if the given flow node is preceded by a 'super(...)' call in every possible code path
61352 // leading to the node.
61353 function isPostSuperFlowNode(flow, noCacheCheck) {
61354 while (true) {
61355 var flags = flow.flags;
61356 if (flags & 4096 /* Shared */) {
61357 if (!noCacheCheck) {
61358 var id = getFlowNodeId(flow);
61359 var postSuper = flowNodePostSuper[id];
61360 return postSuper !== undefined ? postSuper : (flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ true));
61361 }
61362 noCacheCheck = false;
61363 }
61364 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
61365 flow = flow.antecedent;
61366 }
61367 else if (flags & 512 /* Call */) {
61368 if (flow.node.expression.kind === 105 /* SuperKeyword */) {
61369 return true;
61370 }
61371 flow = flow.antecedent;
61372 }
61373 else if (flags & 4 /* BranchLabel */) {
61374 // A branching point is post-super if every branch is post-super.
61375 return ts.every(flow.antecedents, function (f) { return isPostSuperFlowNode(f, /*noCacheCheck*/ false); });
61376 }
61377 else if (flags & 8 /* LoopLabel */) {
61378 // A loop is post-super if the control flow path that leads to the top is post-super.
61379 flow = flow.antecedents[0];
61380 }
61381 else if (flags & 1024 /* ReduceLabel */) {
61382 var target = flow.target;
61383 var saveAntecedents = target.antecedents;
61384 target.antecedents = flow.antecedents;
61385 var result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ false);
61386 target.antecedents = saveAntecedents;
61387 return result;
61388 }
61389 else {
61390 // Unreachable nodes are considered post-super to silence errors
61391 return !!(flags & 1 /* Unreachable */);
61392 }
61393 }
61394 }
61395 function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
61396 if (initialType === void 0) { initialType = declaredType; }
61397 var key;
61398 var isKeySet = false;
61399 var flowDepth = 0;
61400 if (flowAnalysisDisabled) {
61401 return errorType;
61402 }
61403 if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
61404 return declaredType;
61405 }
61406 flowInvocationCount++;
61407 var sharedFlowStart = sharedFlowCount;
61408 var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
61409 sharedFlowCount = sharedFlowStart;
61410 // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
61411 // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
61412 // on empty arrays are possible without implicit any errors and new element types can be inferred without
61413 // type mismatch errors.
61414 var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
61415 if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 222 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
61416 return declaredType;
61417 }
61418 return resultType;
61419 function getOrSetCacheKey() {
61420 if (isKeySet) {
61421 return key;
61422 }
61423 isKeySet = true;
61424 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
61425 }
61426 function getTypeAtFlowNode(flow) {
61427 if (flowDepth === 2000) {
61428 // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
61429 // and disable further control flow analysis in the containing function or module body.
61430 flowAnalysisDisabled = true;
61431 reportFlowControlError(reference);
61432 return errorType;
61433 }
61434 flowDepth++;
61435 while (true) {
61436 var flags = flow.flags;
61437 if (flags & 4096 /* Shared */) {
61438 // We cache results of flow type resolution for shared nodes that were previously visited in
61439 // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
61440 // antecedent of more than one node.
61441 for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
61442 if (sharedFlowNodes[i] === flow) {
61443 flowDepth--;
61444 return sharedFlowTypes[i];
61445 }
61446 }
61447 }
61448 var type = void 0;
61449 if (flags & 16 /* Assignment */) {
61450 type = getTypeAtFlowAssignment(flow);
61451 if (!type) {
61452 flow = flow.antecedent;
61453 continue;
61454 }
61455 }
61456 else if (flags & 512 /* Call */) {
61457 type = getTypeAtFlowCall(flow);
61458 if (!type) {
61459 flow = flow.antecedent;
61460 continue;
61461 }
61462 }
61463 else if (flags & 96 /* Condition */) {
61464 type = getTypeAtFlowCondition(flow);
61465 }
61466 else if (flags & 128 /* SwitchClause */) {
61467 type = getTypeAtSwitchClause(flow);
61468 }
61469 else if (flags & 12 /* Label */) {
61470 if (flow.antecedents.length === 1) {
61471 flow = flow.antecedents[0];
61472 continue;
61473 }
61474 type = flags & 4 /* BranchLabel */ ?
61475 getTypeAtFlowBranchLabel(flow) :
61476 getTypeAtFlowLoopLabel(flow);
61477 }
61478 else if (flags & 256 /* ArrayMutation */) {
61479 type = getTypeAtFlowArrayMutation(flow);
61480 if (!type) {
61481 flow = flow.antecedent;
61482 continue;
61483 }
61484 }
61485 else if (flags & 1024 /* ReduceLabel */) {
61486 var target = flow.target;
61487 var saveAntecedents = target.antecedents;
61488 target.antecedents = flow.antecedents;
61489 type = getTypeAtFlowNode(flow.antecedent);
61490 target.antecedents = saveAntecedents;
61491 }
61492 else if (flags & 2 /* Start */) {
61493 // Check if we should continue with the control flow of the containing function.
61494 var container = flow.node;
61495 if (container && container !== flowContainer &&
61496 reference.kind !== 198 /* PropertyAccessExpression */ &&
61497 reference.kind !== 199 /* ElementAccessExpression */ &&
61498 reference.kind !== 107 /* ThisKeyword */) {
61499 flow = container.flowNode;
61500 continue;
61501 }
61502 // At the top of the flow we have the initial type.
61503 type = initialType;
61504 }
61505 else {
61506 // Unreachable code errors are reported in the binding phase. Here we
61507 // simply return the non-auto declared type to reduce follow-on errors.
61508 type = convertAutoToAny(declaredType);
61509 }
61510 if (flags & 4096 /* Shared */) {
61511 // Record visited node and the associated type in the cache.
61512 sharedFlowNodes[sharedFlowCount] = flow;
61513 sharedFlowTypes[sharedFlowCount] = type;
61514 sharedFlowCount++;
61515 }
61516 flowDepth--;
61517 return type;
61518 }
61519 }
61520 function getInitialOrAssignedType(flow) {
61521 var node = flow.node;
61522 return getConstraintForLocation(node.kind === 246 /* VariableDeclaration */ || node.kind === 195 /* BindingElement */ ?
61523 getInitialType(node) :
61524 getAssignedType(node), reference);
61525 }
61526 function getTypeAtFlowAssignment(flow) {
61527 var node = flow.node;
61528 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
61529 // only need to evaluate the assigned type if the declared type is a union type.
61530 if (isMatchingReference(reference, node)) {
61531 if (!isReachableFlowNode(flow)) {
61532 return unreachableNeverType;
61533 }
61534 if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
61535 var flowType = getTypeAtFlowNode(flow.antecedent);
61536 return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
61537 }
61538 if (declaredType === autoType || declaredType === autoArrayType) {
61539 if (isEmptyArrayAssignment(node)) {
61540 return getEvolvingArrayType(neverType);
61541 }
61542 var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
61543 return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
61544 }
61545 if (declaredType.flags & 1048576 /* Union */) {
61546 return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
61547 }
61548 return declaredType;
61549 }
61550 // We didn't have a direct match. However, if the reference is a dotted name, this
61551 // may be an assignment to a left hand part of the reference. For example, for a
61552 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
61553 // return the declared type.
61554 if (containsMatchingReference(reference, node)) {
61555 if (!isReachableFlowNode(flow)) {
61556 return unreachableNeverType;
61557 }
61558 // A matching dotted name might also be an expando property on a function *expression*,
61559 // in which case we continue control flow analysis back to the function's declaration
61560 if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
61561 var init = ts.getDeclaredExpandoInitializer(node);
61562 if (init && (init.kind === 205 /* FunctionExpression */ || init.kind === 206 /* ArrowFunction */)) {
61563 return getTypeAtFlowNode(flow.antecedent);
61564 }
61565 }
61566 return declaredType;
61567 }
61568 // for (const _ in ref) acts as a nonnull on ref
61569 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 235 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
61570 return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
61571 }
61572 // Assignment doesn't affect reference
61573 return undefined;
61574 }
61575 function narrowTypeByAssertion(type, expr) {
61576 var node = ts.skipParentheses(expr);
61577 if (node.kind === 94 /* FalseKeyword */) {
61578 return unreachableNeverType;
61579 }
61580 if (node.kind === 213 /* BinaryExpression */) {
61581 if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
61582 return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
61583 }
61584 if (node.operatorToken.kind === 56 /* BarBarToken */) {
61585 return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
61586 }
61587 }
61588 return narrowType(type, node, /*assumeTrue*/ true);
61589 }
61590 function getTypeAtFlowCall(flow) {
61591 var signature = getEffectsSignature(flow.node);
61592 if (signature) {
61593 var predicate = getTypePredicateOfSignature(signature);
61594 if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
61595 var flowType = getTypeAtFlowNode(flow.antecedent);
61596 var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
61597 var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
61598 predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
61599 type;
61600 return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
61601 }
61602 if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
61603 return unreachableNeverType;
61604 }
61605 }
61606 return undefined;
61607 }
61608 function getTypeAtFlowArrayMutation(flow) {
61609 if (declaredType === autoType || declaredType === autoArrayType) {
61610 var node = flow.node;
61611 var expr = node.kind === 200 /* CallExpression */ ?
61612 node.expression.expression :
61613 node.left.expression;
61614 if (isMatchingReference(reference, getReferenceCandidate(expr))) {
61615 var flowType = getTypeAtFlowNode(flow.antecedent);
61616 var type = getTypeFromFlowType(flowType);
61617 if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
61618 var evolvedType_1 = type;
61619 if (node.kind === 200 /* CallExpression */) {
61620 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
61621 var arg = _a[_i];
61622 evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
61623 }
61624 }
61625 else {
61626 // 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)
61627 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
61628 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
61629 evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
61630 }
61631 }
61632 return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
61633 }
61634 return flowType;
61635 }
61636 }
61637 return undefined;
61638 }
61639 function getTypeAtFlowCondition(flow) {
61640 var flowType = getTypeAtFlowNode(flow.antecedent);
61641 var type = getTypeFromFlowType(flowType);
61642 if (type.flags & 131072 /* Never */) {
61643 return flowType;
61644 }
61645 // If we have an antecedent type (meaning we're reachable in some way), we first
61646 // attempt to narrow the antecedent type. If that produces the never type, and if
61647 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
61648 // take the type guard as an indication that control *could* reach here once we
61649 // have the complete type. We proceed by switching to the silent never type which
61650 // doesn't report errors when operators are applied to it. Note that this is the
61651 // *only* place a silent never type is ever generated.
61652 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
61653 var nonEvolvingType = finalizeEvolvingArrayType(type);
61654 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
61655 if (narrowedType === nonEvolvingType) {
61656 return flowType;
61657 }
61658 return createFlowType(narrowedType, isIncomplete(flowType));
61659 }
61660 function getTypeAtSwitchClause(flow) {
61661 var expr = flow.switchStatement.expression;
61662 var flowType = getTypeAtFlowNode(flow.antecedent);
61663 var type = getTypeFromFlowType(flowType);
61664 if (isMatchingReference(reference, expr)) {
61665 type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
61666 }
61667 else if (expr.kind === 208 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
61668 type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
61669 }
61670 else {
61671 if (strictNullChecks) {
61672 if (optionalChainContainsReference(expr, reference)) {
61673 type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
61674 }
61675 else if (expr.kind === 208 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
61676 type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
61677 }
61678 }
61679 if (isMatchingReferenceDiscriminant(expr, type)) {
61680 type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
61681 }
61682 }
61683 return createFlowType(type, isIncomplete(flowType));
61684 }
61685 function getTypeAtFlowBranchLabel(flow) {
61686 var antecedentTypes = [];
61687 var subtypeReduction = false;
61688 var seenIncomplete = false;
61689 var bypassFlow;
61690 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
61691 var antecedent = _a[_i];
61692 if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
61693 // The antecedent is the bypass branch of a potentially exhaustive switch statement.
61694 bypassFlow = antecedent;
61695 continue;
61696 }
61697 var flowType = getTypeAtFlowNode(antecedent);
61698 var type = getTypeFromFlowType(flowType);
61699 // If the type at a particular antecedent path is the declared type and the
61700 // reference is known to always be assigned (i.e. when declared and initial types
61701 // are the same), there is no reason to process more antecedents since the only
61702 // possible outcome is subtypes that will be removed in the final union type anyway.
61703 if (type === declaredType && declaredType === initialType) {
61704 return type;
61705 }
61706 ts.pushIfUnique(antecedentTypes, type);
61707 // If an antecedent type is not a subset of the declared type, we need to perform
61708 // subtype reduction. This happens when a "foreign" type is injected into the control
61709 // flow using the instanceof operator or a user defined type predicate.
61710 if (!isTypeSubsetOf(type, declaredType)) {
61711 subtypeReduction = true;
61712 }
61713 if (isIncomplete(flowType)) {
61714 seenIncomplete = true;
61715 }
61716 }
61717 if (bypassFlow) {
61718 var flowType = getTypeAtFlowNode(bypassFlow);
61719 var type = getTypeFromFlowType(flowType);
61720 // If the bypass flow contributes a type we haven't seen yet and the switch statement
61721 // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
61722 // the risk of circularities, we only want to perform them when they make a difference.
61723 if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
61724 if (type === declaredType && declaredType === initialType) {
61725 return type;
61726 }
61727 antecedentTypes.push(type);
61728 if (!isTypeSubsetOf(type, declaredType)) {
61729 subtypeReduction = true;
61730 }
61731 if (isIncomplete(flowType)) {
61732 seenIncomplete = true;
61733 }
61734 }
61735 }
61736 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
61737 }
61738 function getTypeAtFlowLoopLabel(flow) {
61739 // If we have previously computed the control flow type for the reference at
61740 // this flow loop junction, return the cached type.
61741 var id = getFlowNodeId(flow);
61742 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = new ts.Map());
61743 var key = getOrSetCacheKey();
61744 if (!key) {
61745 // No cache key is generated when binding patterns are in unnarrowable situations
61746 return declaredType;
61747 }
61748 var cached = cache.get(key);
61749 if (cached) {
61750 return cached;
61751 }
61752 // If this flow loop junction and reference are already being processed, return
61753 // the union of the types computed for each branch so far, marked as incomplete.
61754 // It is possible to see an empty array in cases where loops are nested and the
61755 // back edge of the outer loop reaches an inner loop that is already being analyzed.
61756 // In such cases we restart the analysis of the inner loop, which will then see
61757 // a non-empty in-process array for the outer loop and eventually terminate because
61758 // the first antecedent of a loop junction is always the non-looping control flow
61759 // path that leads to the top.
61760 for (var i = flowLoopStart; i < flowLoopCount; i++) {
61761 if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
61762 return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
61763 }
61764 }
61765 // Add the flow loop junction and reference to the in-process stack and analyze
61766 // each antecedent code path.
61767 var antecedentTypes = [];
61768 var subtypeReduction = false;
61769 var firstAntecedentType;
61770 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
61771 var antecedent = _a[_i];
61772 var flowType = void 0;
61773 if (!firstAntecedentType) {
61774 // The first antecedent of a loop junction is always the non-looping control
61775 // flow path that leads to the top.
61776 flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
61777 }
61778 else {
61779 // All but the first antecedent are the looping control flow paths that lead
61780 // back to the loop junction. We track these on the flow loop stack.
61781 flowLoopNodes[flowLoopCount] = flow;
61782 flowLoopKeys[flowLoopCount] = key;
61783 flowLoopTypes[flowLoopCount] = antecedentTypes;
61784 flowLoopCount++;
61785 var saveFlowTypeCache = flowTypeCache;
61786 flowTypeCache = undefined;
61787 flowType = getTypeAtFlowNode(antecedent);
61788 flowTypeCache = saveFlowTypeCache;
61789 flowLoopCount--;
61790 // If we see a value appear in the cache it is a sign that control flow analysis
61791 // was restarted and completed by checkExpressionCached. We can simply pick up
61792 // the resulting type and bail out.
61793 var cached_1 = cache.get(key);
61794 if (cached_1) {
61795 return cached_1;
61796 }
61797 }
61798 var type = getTypeFromFlowType(flowType);
61799 ts.pushIfUnique(antecedentTypes, type);
61800 // If an antecedent type is not a subset of the declared type, we need to perform
61801 // subtype reduction. This happens when a "foreign" type is injected into the control
61802 // flow using the instanceof operator or a user defined type predicate.
61803 if (!isTypeSubsetOf(type, declaredType)) {
61804 subtypeReduction = true;
61805 }
61806 // If the type at a particular antecedent path is the declared type there is no
61807 // reason to process more antecedents since the only possible outcome is subtypes
61808 // that will be removed in the final union type anyway.
61809 if (type === declaredType) {
61810 break;
61811 }
61812 }
61813 // The result is incomplete if the first antecedent (the non-looping control flow path)
61814 // is incomplete.
61815 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
61816 if (isIncomplete(firstAntecedentType)) {
61817 return createFlowType(result, /*incomplete*/ true);
61818 }
61819 cache.set(key, result);
61820 return result;
61821 }
61822 function isMatchingReferenceDiscriminant(expr, computedType) {
61823 var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
61824 if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
61825 return false;
61826 }
61827 var name = getAccessedPropertyName(expr);
61828 if (name === undefined) {
61829 return false;
61830 }
61831 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name);
61832 }
61833 function narrowTypeByDiscriminant(type, access, narrowType) {
61834 var propName = getAccessedPropertyName(access);
61835 if (propName === undefined) {
61836 return type;
61837 }
61838 var propType = getTypeOfPropertyOfType(type, propName);
61839 if (!propType) {
61840 return type;
61841 }
61842 var narrowedPropType = narrowType(propType);
61843 return filterType(type, function (t) {
61844 var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
61845 return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
61846 });
61847 }
61848 function narrowTypeByTruthiness(type, expr, assumeTrue) {
61849 if (isMatchingReference(reference, expr)) {
61850 return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
61851 }
61852 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
61853 type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
61854 }
61855 if (isMatchingReferenceDiscriminant(expr, type)) {
61856 return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
61857 }
61858 return type;
61859 }
61860 function isTypePresencePossible(type, propName, assumeTrue) {
61861 if (getIndexInfoOfType(type, 0 /* String */)) {
61862 return true;
61863 }
61864 var prop = getPropertyOfType(type, propName);
61865 if (prop) {
61866 return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
61867 }
61868 return !assumeTrue;
61869 }
61870 function narrowByInKeyword(type, literal, assumeTrue) {
61871 if (type.flags & (1048576 /* Union */ | 524288 /* Object */)
61872 || isThisTypeParameter(type)
61873 || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) {
61874 var propName_1 = ts.escapeLeadingUnderscores(literal.text);
61875 return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
61876 }
61877 return type;
61878 }
61879 function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
61880 switch (expr.operatorToken.kind) {
61881 case 62 /* EqualsToken */:
61882 case 74 /* BarBarEqualsToken */:
61883 case 75 /* AmpersandAmpersandEqualsToken */:
61884 case 76 /* QuestionQuestionEqualsToken */:
61885 return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
61886 case 34 /* EqualsEqualsToken */:
61887 case 35 /* ExclamationEqualsToken */:
61888 case 36 /* EqualsEqualsEqualsToken */:
61889 case 37 /* ExclamationEqualsEqualsToken */:
61890 var operator_1 = expr.operatorToken.kind;
61891 var left_1 = getReferenceCandidate(expr.left);
61892 var right_1 = getReferenceCandidate(expr.right);
61893 if (left_1.kind === 208 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
61894 return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
61895 }
61896 if (right_1.kind === 208 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
61897 return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
61898 }
61899 if (isMatchingReference(reference, left_1)) {
61900 return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
61901 }
61902 if (isMatchingReference(reference, right_1)) {
61903 return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
61904 }
61905 if (strictNullChecks) {
61906 if (optionalChainContainsReference(left_1, reference)) {
61907 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
61908 }
61909 else if (optionalChainContainsReference(right_1, reference)) {
61910 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
61911 }
61912 }
61913 if (isMatchingReferenceDiscriminant(left_1, type)) {
61914 return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
61915 }
61916 if (isMatchingReferenceDiscriminant(right_1, type)) {
61917 return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
61918 }
61919 if (isMatchingConstructorReference(left_1)) {
61920 return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
61921 }
61922 if (isMatchingConstructorReference(right_1)) {
61923 return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
61924 }
61925 break;
61926 case 101 /* InstanceOfKeyword */:
61927 return narrowTypeByInstanceof(type, expr, assumeTrue);
61928 case 100 /* InKeyword */:
61929 var target = getReferenceCandidate(expr.right);
61930 if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
61931 return narrowByInKeyword(type, expr.left, assumeTrue);
61932 }
61933 break;
61934 case 27 /* CommaToken */:
61935 return narrowType(type, expr.right, assumeTrue);
61936 }
61937 return type;
61938 }
61939 function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
61940 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
61941 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
61942 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
61943 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
61944 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
61945 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
61946 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
61947 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
61948 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
61949 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
61950 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
61951 var valueType = getTypeOfExpression(value);
61952 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
61953 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
61954 equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
61955 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
61956 }
61957 function narrowTypeByEquality(type, operator, value, assumeTrue) {
61958 if (type.flags & 1 /* Any */) {
61959 return type;
61960 }
61961 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
61962 assumeTrue = !assumeTrue;
61963 }
61964 var valueType = getTypeOfExpression(value);
61965 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
61966 if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
61967 return valueType;
61968 }
61969 if (valueType.flags & 524288 /* Object */) {
61970 return nonPrimitiveType;
61971 }
61972 return type;
61973 }
61974 if (valueType.flags & 98304 /* Nullable */) {
61975 if (!strictNullChecks) {
61976 return type;
61977 }
61978 var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
61979 var facts = doubleEquals ?
61980 assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
61981 valueType.flags & 65536 /* Null */ ?
61982 assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
61983 assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
61984 return getTypeWithFacts(type, facts);
61985 }
61986 if (assumeTrue) {
61987 var filterFn = operator === 34 /* EqualsEqualsToken */ ?
61988 (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
61989 function (t) { return areTypesComparable(t, valueType); };
61990 return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType);
61991 }
61992 if (isUnitType(valueType)) {
61993 var regularType_1 = getRegularTypeOfLiteralType(valueType);
61994 return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
61995 }
61996 return type;
61997 }
61998 function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
61999 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
62000 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
62001 assumeTrue = !assumeTrue;
62002 }
62003 var target = getReferenceCandidate(typeOfExpr.expression);
62004 if (!isMatchingReference(reference, target)) {
62005 if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
62006 return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
62007 }
62008 return type;
62009 }
62010 if (type.flags & 1 /* Any */ && literal.text === "function") {
62011 return type;
62012 }
62013 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
62014 // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
62015 // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
62016 if (typeOfExpr.parent.parent.kind === 213 /* BinaryExpression */) {
62017 var expr = typeOfExpr.parent.parent;
62018 if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
62019 return nonPrimitiveType;
62020 }
62021 }
62022 return getUnionType([nonPrimitiveType, nullType]);
62023 }
62024 var facts = assumeTrue ?
62025 typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
62026 typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
62027 var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text);
62028 return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts);
62029 }
62030 function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
62031 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
62032 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
62033 }
62034 function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
62035 // We only narrow if all case expressions specify
62036 // values with unit types, except for the case where
62037 // `type` is unknown. In this instance we map object
62038 // types to the nonPrimitive type and narrow with that.
62039 var switchTypes = getSwitchClauseTypes(switchStatement);
62040 if (!switchTypes.length) {
62041 return type;
62042 }
62043 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
62044 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
62045 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
62046 var groundClauseTypes = void 0;
62047 for (var i = 0; i < clauseTypes.length; i += 1) {
62048 var t = clauseTypes[i];
62049 if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
62050 if (groundClauseTypes !== undefined) {
62051 groundClauseTypes.push(t);
62052 }
62053 }
62054 else if (t.flags & 524288 /* Object */) {
62055 if (groundClauseTypes === undefined) {
62056 groundClauseTypes = clauseTypes.slice(0, i);
62057 }
62058 groundClauseTypes.push(nonPrimitiveType);
62059 }
62060 else {
62061 return type;
62062 }
62063 }
62064 return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
62065 }
62066 var discriminantType = getUnionType(clauseTypes);
62067 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
62068 replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
62069 if (!hasDefaultClause) {
62070 return caseType;
62071 }
62072 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
62073 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
62074 }
62075 function getImpliedTypeFromTypeofGuard(type, text) {
62076 switch (text) {
62077 case "function":
62078 return type.flags & 1 /* Any */ ? type : globalFunctionType;
62079 case "object":
62080 return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
62081 default:
62082 return typeofTypesByName.get(text);
62083 }
62084 }
62085 // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are
62086 // super-types of the implied guard will be retained in the final type: this is because type-facts only
62087 // filter. Instead, we would like to replace those union constituents with the more precise type implied by
62088 // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not
62089 // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to
62090 // filtering by type-facts.
62091 function narrowUnionMemberByTypeof(candidate) {
62092 return function (type) {
62093 if (isTypeSubtypeOf(type, candidate)) {
62094 return type;
62095 }
62096 if (isTypeSubtypeOf(candidate, type)) {
62097 return candidate;
62098 }
62099 if (type.flags & 63176704 /* Instantiable */) {
62100 var constraint = getBaseConstraintOfType(type) || anyType;
62101 if (isTypeSubtypeOf(candidate, constraint)) {
62102 return getIntersectionType([type, candidate]);
62103 }
62104 }
62105 return type;
62106 };
62107 }
62108 function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
62109 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
62110 if (!switchWitnesses.length) {
62111 return type;
62112 }
62113 // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
62114 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
62115 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
62116 var clauseWitnesses;
62117 var switchFacts;
62118 if (defaultCaseLocation > -1) {
62119 // We no longer need the undefined denoting an explicit default case. Remove the undefined and
62120 // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the
62121 // witness array.
62122 var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
62123 // The adjusted clause start and end after removing the `default` statement.
62124 var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
62125 var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
62126 clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
62127 switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
62128 }
62129 else {
62130 clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
62131 switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
62132 }
62133 if (hasDefaultClause) {
62134 return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
62135 }
62136 /*
62137 The implied type is the raw type suggested by a
62138 value being caught in this clause.
62139
62140 When the clause contains a default case we ignore
62141 the implied type and try to narrow using any facts
62142 we can learn: see `switchFacts`.
62143
62144 Example:
62145 switch (typeof x) {
62146 case 'number':
62147 case 'string': break;
62148 default: break;
62149 case 'number':
62150 case 'boolean': break
62151 }
62152
62153 In the first clause (case `number` and `string`) the
62154 implied type is number | string.
62155
62156 In the default clause we de not compute an implied type.
62157
62158 In the third clause (case `number` and `boolean`)
62159 the naive implied type is number | boolean, however
62160 we use the type facts to narrow the implied type to
62161 boolean. We know that number cannot be selected
62162 because it is caught in the first clause.
62163 */
62164 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts);
62165 return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts);
62166 }
62167 function isMatchingConstructorReference(expr) {
62168 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
62169 ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
62170 isMatchingReference(reference, expr.expression);
62171 }
62172 function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
62173 // Do not narrow when checking inequality.
62174 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
62175 return type;
62176 }
62177 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
62178 var identifierType = getTypeOfExpression(identifier);
62179 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
62180 return type;
62181 }
62182 // Get the prototype property of the type identifier so we can find out its type.
62183 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
62184 if (!prototypeProperty) {
62185 return type;
62186 }
62187 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
62188 var prototypeType = getTypeOfSymbol(prototypeProperty);
62189 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
62190 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
62191 return type;
62192 }
62193 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
62194 if (isTypeAny(type)) {
62195 return candidate;
62196 }
62197 // Filter out types that are not considered to be "constructed by" the `candidate` type.
62198 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
62199 function isConstructedBy(source, target) {
62200 // If either the source or target type are a class type then we need to check that they are the same exact type.
62201 // This is because you may have a class `A` that defines some set of properties, and another class `B`
62202 // that defines the same set of properties as class `A`, in that case they are structurally the same
62203 // type, but when you do something like `instanceOfA.constructor === B` it will return false.
62204 if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
62205 target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
62206 return source.symbol === target.symbol;
62207 }
62208 // For all other types just check that the `source` type is a subtype of the `target` type.
62209 return isTypeSubtypeOf(source, target);
62210 }
62211 }
62212 function narrowTypeByInstanceof(type, expr, assumeTrue) {
62213 var left = getReferenceCandidate(expr.left);
62214 if (!isMatchingReference(reference, left)) {
62215 if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
62216 return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
62217 }
62218 return type;
62219 }
62220 // Check that right operand is a function type with a prototype property
62221 var rightType = getTypeOfExpression(expr.right);
62222 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
62223 return type;
62224 }
62225 var targetType;
62226 var prototypeProperty = getPropertyOfType(rightType, "prototype");
62227 if (prototypeProperty) {
62228 // Target type is type of the prototype property
62229 var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
62230 if (!isTypeAny(prototypePropertyType)) {
62231 targetType = prototypePropertyType;
62232 }
62233 }
62234 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
62235 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
62236 return type;
62237 }
62238 if (!targetType) {
62239 var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
62240 targetType = constructSignatures.length ?
62241 getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
62242 emptyObjectType;
62243 }
62244 // We can't narrow a union based off instanceof without negated types see #31576 for more info
62245 if (!assumeTrue && rightType.flags & 1048576 /* Union */) {
62246 var nonConstructorTypeInUnion = ts.find(rightType.types, function (t) { return !isConstructorType(t); });
62247 if (!nonConstructorTypeInUnion)
62248 return type;
62249 }
62250 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
62251 }
62252 function getNarrowedType(type, candidate, assumeTrue, isRelated) {
62253 if (!assumeTrue) {
62254 return filterType(type, function (t) { return !isRelated(t, candidate); });
62255 }
62256 // If the current type is a union type, remove all constituents that couldn't be instances of
62257 // the candidate type. If one or more constituents remain, return a union of those.
62258 if (type.flags & 1048576 /* Union */) {
62259 var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
62260 if (!(assignableType.flags & 131072 /* Never */)) {
62261 return assignableType;
62262 }
62263 }
62264 // If the candidate type is a subtype of the target type, narrow to the candidate type.
62265 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
62266 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
62267 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
62268 // two types.
62269 return isTypeSubtypeOf(candidate, type) ? candidate :
62270 isTypeAssignableTo(type, candidate) ? type :
62271 isTypeAssignableTo(candidate, type) ? candidate :
62272 getIntersectionType([type, candidate]);
62273 }
62274 function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
62275 if (hasMatchingArgument(callExpression, reference)) {
62276 var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
62277 var predicate = signature && getTypePredicateOfSignature(signature);
62278 if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
62279 return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
62280 }
62281 }
62282 return type;
62283 }
62284 function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
62285 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
62286 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
62287 var predicateArgument = getTypePredicateArgument(predicate, callExpression);
62288 if (predicateArgument) {
62289 if (isMatchingReference(reference, predicateArgument)) {
62290 return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
62291 }
62292 if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
62293 !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
62294 type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
62295 }
62296 if (isMatchingReferenceDiscriminant(predicateArgument, type)) {
62297 return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
62298 }
62299 }
62300 }
62301 return type;
62302 }
62303 // Narrow the given type based on the given expression having the assumed boolean value. The returned type
62304 // will be a subtype or the same type as the argument.
62305 function narrowType(type, expr, assumeTrue) {
62306 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
62307 if (ts.isExpressionOfOptionalChainRoot(expr) ||
62308 ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
62309 return narrowTypeByOptionality(type, expr, assumeTrue);
62310 }
62311 switch (expr.kind) {
62312 case 78 /* Identifier */:
62313 case 107 /* ThisKeyword */:
62314 case 105 /* SuperKeyword */:
62315 case 198 /* PropertyAccessExpression */:
62316 case 199 /* ElementAccessExpression */:
62317 return narrowTypeByTruthiness(type, expr, assumeTrue);
62318 case 200 /* CallExpression */:
62319 return narrowTypeByCallExpression(type, expr, assumeTrue);
62320 case 204 /* ParenthesizedExpression */:
62321 return narrowType(type, expr.expression, assumeTrue);
62322 case 213 /* BinaryExpression */:
62323 return narrowTypeByBinaryExpression(type, expr, assumeTrue);
62324 case 211 /* PrefixUnaryExpression */:
62325 if (expr.operator === 53 /* ExclamationToken */) {
62326 return narrowType(type, expr.operand, !assumeTrue);
62327 }
62328 break;
62329 }
62330 return type;
62331 }
62332 function narrowTypeByOptionality(type, expr, assumePresent) {
62333 if (isMatchingReference(reference, expr)) {
62334 return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
62335 }
62336 if (isMatchingReferenceDiscriminant(expr, type)) {
62337 return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
62338 }
62339 return type;
62340 }
62341 }
62342 function getTypeOfSymbolAtLocation(symbol, location) {
62343 symbol = symbol.exportSymbol || symbol;
62344 // If we have an identifier or a property access at the given location, if the location is
62345 // an dotted name expression, and if the location is not an assignment target, obtain the type
62346 // of the expression (which will reflect control flow analysis). If the expression indeed
62347 // resolved to the given symbol, return the narrowed type.
62348 if (location.kind === 78 /* Identifier */) {
62349 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
62350 location = location.parent;
62351 }
62352 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
62353 var type = getTypeOfExpression(location);
62354 if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
62355 return type;
62356 }
62357 }
62358 }
62359 // The location isn't a reference to the given symbol, meaning we're being asked
62360 // a hypothetical question of what type the symbol would have if there was a reference
62361 // to it at the given location. Since we have no control flow information for the
62362 // hypothetical reference (control flow information is created and attached by the
62363 // binder), we simply return the declared type of the symbol.
62364 return getTypeOfSymbol(symbol);
62365 }
62366 function getControlFlowContainer(node) {
62367 return ts.findAncestor(node.parent, function (node) {
62368 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
62369 node.kind === 254 /* ModuleBlock */ ||
62370 node.kind === 294 /* SourceFile */ ||
62371 node.kind === 162 /* PropertyDeclaration */;
62372 });
62373 }
62374 // Check if a parameter is assigned anywhere within its declaring function.
62375 function isParameterAssigned(symbol) {
62376 var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
62377 var links = getNodeLinks(func);
62378 if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
62379 links.flags |= 8388608 /* AssignmentsMarked */;
62380 if (!hasParentWithAssignmentsMarked(func)) {
62381 markParameterAssignments(func);
62382 }
62383 }
62384 return symbol.isAssigned || false;
62385 }
62386 function hasParentWithAssignmentsMarked(node) {
62387 return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
62388 }
62389 function markParameterAssignments(node) {
62390 if (node.kind === 78 /* Identifier */) {
62391 if (ts.isAssignmentTarget(node)) {
62392 var symbol = getResolvedSymbol(node);
62393 if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 159 /* Parameter */) {
62394 symbol.isAssigned = true;
62395 }
62396 }
62397 }
62398 else {
62399 ts.forEachChild(node, markParameterAssignments);
62400 }
62401 }
62402 function isConstVariable(symbol) {
62403 return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
62404 }
62405 /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
62406 function removeOptionalityFromDeclaredType(declaredType, declaration) {
62407 if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
62408 var annotationIncludesUndefined = strictNullChecks &&
62409 declaration.kind === 159 /* Parameter */ &&
62410 declaration.initializer &&
62411 getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
62412 !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
62413 popTypeResolution();
62414 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
62415 }
62416 else {
62417 reportCircularityError(declaration.symbol);
62418 return declaredType;
62419 }
62420 }
62421 function isConstraintPosition(node) {
62422 var parent = node.parent;
62423 return parent.kind === 198 /* PropertyAccessExpression */ ||
62424 parent.kind === 200 /* CallExpression */ && parent.expression === node ||
62425 parent.kind === 199 /* ElementAccessExpression */ && parent.expression === node ||
62426 parent.kind === 195 /* BindingElement */ && parent.name === node && !!parent.initializer;
62427 }
62428 function typeHasNullableConstraint(type) {
62429 return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
62430 }
62431 function getConstraintForLocation(type, node) {
62432 // When a node is the left hand expression of a property access, element access, or call expression,
62433 // and the type of the node includes type variables with constraints that are nullable, we fetch the
62434 // apparent type of the node *before* performing control flow analysis such that narrowings apply to
62435 // the constraint type.
62436 if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
62437 return mapType(getWidenedType(type), getBaseConstraintOrType);
62438 }
62439 return type;
62440 }
62441 function isExportOrExportExpression(location) {
62442 return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
62443 }
62444 function markAliasReferenced(symbol, location) {
62445 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
62446 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
62447 markAliasSymbolAsReferenced(symbol);
62448 }
62449 else {
62450 markConstEnumAliasAsReferenced(symbol);
62451 }
62452 }
62453 }
62454 function checkIdentifier(node) {
62455 var symbol = getResolvedSymbol(node);
62456 if (symbol === unknownSymbol) {
62457 return errorType;
62458 }
62459 // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
62460 // Although in down-level emit of arrow function, we emit it using function expression which means that
62461 // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
62462 // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
62463 // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
62464 // can explicitly bound arguments objects
62465 if (symbol === argumentsSymbol) {
62466 var container = ts.getContainingFunction(node);
62467 if (languageVersion < 2 /* ES2015 */) {
62468 if (container.kind === 206 /* ArrowFunction */) {
62469 error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
62470 }
62471 else if (ts.hasSyntacticModifier(container, 256 /* Async */)) {
62472 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);
62473 }
62474 }
62475 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
62476 return getTypeOfSymbol(symbol);
62477 }
62478 // We should only mark aliases as referenced if there isn't a local value declaration
62479 // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
62480 if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
62481 markAliasReferenced(symbol, node);
62482 }
62483 var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
62484 var declaration = localOrExportSymbol.valueDeclaration;
62485 if (declaration && ts.getCombinedNodeFlags(declaration) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node.parent, localOrExportSymbol)) {
62486 errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText);
62487 ;
62488 }
62489 if (localOrExportSymbol.flags & 32 /* Class */) {
62490 // Due to the emit for class decorators, any reference to the class from inside of the class body
62491 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
62492 // behavior of class names in ES6.
62493 if (declaration.kind === 249 /* ClassDeclaration */
62494 && ts.nodeIsDecorated(declaration)) {
62495 var container = ts.getContainingClass(node);
62496 while (container !== undefined) {
62497 if (container === declaration && container.name !== node) {
62498 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
62499 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
62500 break;
62501 }
62502 container = ts.getContainingClass(container);
62503 }
62504 }
62505 else if (declaration.kind === 218 /* ClassExpression */) {
62506 // When we emit a class expression with static members that contain a reference
62507 // to the constructor in the initializer, we will need to substitute that
62508 // binding with an alias as the class name is not in scope.
62509 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
62510 while (container.kind !== 294 /* SourceFile */) {
62511 if (container.parent === declaration) {
62512 if (container.kind === 162 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) {
62513 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
62514 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
62515 }
62516 break;
62517 }
62518 container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
62519 }
62520 }
62521 }
62522 checkNestedBlockScopedBinding(node, symbol);
62523 var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
62524 var assignmentKind = ts.getAssignmentTargetKind(node);
62525 if (assignmentKind) {
62526 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
62527 !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
62528 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
62529 return errorType;
62530 }
62531 if (isReadonlySymbol(localOrExportSymbol)) {
62532 if (localOrExportSymbol.flags & 3 /* Variable */) {
62533 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
62534 }
62535 else {
62536 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
62537 }
62538 return errorType;
62539 }
62540 }
62541 var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
62542 // We only narrow variables and parameters occurring in a non-assignment position. For all other
62543 // entities we simply return the declared type.
62544 if (localOrExportSymbol.flags & 3 /* Variable */) {
62545 if (assignmentKind === 1 /* Definite */) {
62546 return type;
62547 }
62548 }
62549 else if (isAlias) {
62550 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
62551 }
62552 else {
62553 return type;
62554 }
62555 if (!declaration) {
62556 return type;
62557 }
62558 // The declaration container is the innermost function that encloses the declaration of the variable
62559 // or parameter. The flow container is the innermost function starting with which we analyze the control
62560 // flow graph to determine the control flow based type.
62561 var isParameter = ts.getRootDeclaration(declaration).kind === 159 /* Parameter */;
62562 var declarationContainer = getControlFlowContainer(declaration);
62563 var flowContainer = getControlFlowContainer(node);
62564 var isOuterVariable = flowContainer !== declarationContainer;
62565 var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
62566 var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
62567 // When the control flow originates in a function expression or arrow function and we are referencing
62568 // a const variable or parameter from an outer function, we extend the origin of the control flow
62569 // analysis to include the immediately enclosing function.
62570 while (flowContainer !== declarationContainer && (flowContainer.kind === 205 /* FunctionExpression */ ||
62571 flowContainer.kind === 206 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
62572 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
62573 flowContainer = getControlFlowContainer(flowContainer);
62574 }
62575 // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
62576 // the entire control flow graph from the variable's declaration (i.e. when the flow container and
62577 // declaration container are the same).
62578 var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
62579 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
62580 isInTypeQuery(node) || node.parent.kind === 267 /* ExportSpecifier */) ||
62581 node.parent.kind === 222 /* NonNullExpression */ ||
62582 declaration.kind === 246 /* VariableDeclaration */ && declaration.exclamationToken ||
62583 declaration.flags & 8388608 /* Ambient */;
62584 var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
62585 type === autoType || type === autoArrayType ? undefinedType :
62586 getOptionalType(type);
62587 var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
62588 // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
62589 // from declaration to use, and when the variable's declared type doesn't include undefined but the
62590 // control flow based type does include undefined.
62591 if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
62592 if (flowType === autoType || flowType === autoArrayType) {
62593 if (noImplicitAny) {
62594 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));
62595 error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
62596 }
62597 return convertAutoToAny(flowType);
62598 }
62599 }
62600 else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
62601 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
62602 // Return the declared type to reduce follow-on errors
62603 return type;
62604 }
62605 return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
62606 }
62607 function isInsideFunction(node, threshold) {
62608 return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
62609 }
62610 function getPartOfForStatementContainingNode(node, container) {
62611 return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
62612 }
62613 function checkNestedBlockScopedBinding(node, symbol) {
62614 if (languageVersion >= 2 /* ES2015 */ ||
62615 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
62616 ts.isSourceFile(symbol.valueDeclaration) ||
62617 symbol.valueDeclaration.parent.kind === 284 /* CatchClause */) {
62618 return;
62619 }
62620 // 1. walk from the use site up to the declaration and check
62621 // if there is anything function like between declaration and use-site (is binding/class is captured in function).
62622 // 2. walk from the declaration up to the boundary of lexical environment and check
62623 // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
62624 var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
62625 var usedInFunction = isInsideFunction(node.parent, container);
62626 var current = container;
62627 var containedInIterationStatement = false;
62628 while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
62629 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
62630 containedInIterationStatement = true;
62631 break;
62632 }
62633 current = current.parent;
62634 }
62635 if (containedInIterationStatement) {
62636 if (usedInFunction) {
62637 // mark iteration statement as containing block-scoped binding captured in some function
62638 var capturesBlockScopeBindingInLoopBody = true;
62639 if (ts.isForStatement(container)) {
62640 var varDeclList = ts.getAncestor(symbol.valueDeclaration, 247 /* VariableDeclarationList */);
62641 if (varDeclList && varDeclList.parent === container) {
62642 var part = getPartOfForStatementContainingNode(node.parent, container);
62643 if (part) {
62644 var links = getNodeLinks(part);
62645 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
62646 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
62647 ts.pushIfUnique(capturedBindings, symbol);
62648 if (part === container.initializer) {
62649 capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
62650 }
62651 }
62652 }
62653 }
62654 if (capturesBlockScopeBindingInLoopBody) {
62655 getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
62656 }
62657 }
62658 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
62659 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
62660 if (ts.isForStatement(container)) {
62661 var varDeclList = ts.getAncestor(symbol.valueDeclaration, 247 /* VariableDeclarationList */);
62662 if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
62663 getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
62664 }
62665 }
62666 // set 'declared inside loop' bit on the block-scoped binding
62667 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
62668 }
62669 if (usedInFunction) {
62670 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
62671 }
62672 }
62673 function isBindingCapturedByNode(node, decl) {
62674 var links = getNodeLinks(node);
62675 return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
62676 }
62677 function isAssignedInBodyOfForStatement(node, container) {
62678 // skip parenthesized nodes
62679 var current = node;
62680 while (current.parent.kind === 204 /* ParenthesizedExpression */) {
62681 current = current.parent;
62682 }
62683 // check if node is used as LHS in some assignment expression
62684 var isAssigned = false;
62685 if (ts.isAssignmentTarget(current)) {
62686 isAssigned = true;
62687 }
62688 else if ((current.parent.kind === 211 /* PrefixUnaryExpression */ || current.parent.kind === 212 /* PostfixUnaryExpression */)) {
62689 var expr = current.parent;
62690 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
62691 }
62692 if (!isAssigned) {
62693 return false;
62694 }
62695 // at this point we know that node is the target of assignment
62696 // now check that modification happens inside the statement part of the ForStatement
62697 return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
62698 }
62699 function captureLexicalThis(node, container) {
62700 getNodeLinks(node).flags |= 2 /* LexicalThis */;
62701 if (container.kind === 162 /* PropertyDeclaration */ || container.kind === 165 /* Constructor */) {
62702 var classNode = container.parent;
62703 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
62704 }
62705 else {
62706 getNodeLinks(container).flags |= 4 /* CaptureThis */;
62707 }
62708 }
62709 function findFirstSuperCall(node) {
62710 return ts.isSuperCall(node) ? node :
62711 ts.isFunctionLike(node) ? undefined :
62712 ts.forEachChild(node, findFirstSuperCall);
62713 }
62714 /**
62715 * Check if the given class-declaration extends null then return true.
62716 * Otherwise, return false
62717 * @param classDecl a class declaration to check if it extends null
62718 */
62719 function classDeclarationExtendsNull(classDecl) {
62720 var classSymbol = getSymbolOfNode(classDecl);
62721 var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
62722 var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
62723 return baseConstructorType === nullWideningType;
62724 }
62725 function checkThisBeforeSuper(node, container, diagnosticMessage) {
62726 var containingClassDecl = container.parent;
62727 var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
62728 // If a containing class does not have extends clause or the class extends null
62729 // skip checking whether super statement is called before "this" accessing.
62730 if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
62731 if (node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) {
62732 error(node, diagnosticMessage);
62733 }
62734 }
62735 }
62736 function checkThisExpression(node) {
62737 // Stop at the first arrow function so that we can
62738 // tell whether 'this' needs to be captured.
62739 var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
62740 var capturedByArrowFunction = false;
62741 if (container.kind === 165 /* Constructor */) {
62742 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
62743 }
62744 // Now skip arrow functions to get the "real" owner of 'this'.
62745 if (container.kind === 206 /* ArrowFunction */) {
62746 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
62747 capturedByArrowFunction = true;
62748 }
62749 switch (container.kind) {
62750 case 253 /* ModuleDeclaration */:
62751 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
62752 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
62753 break;
62754 case 252 /* EnumDeclaration */:
62755 error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
62756 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
62757 break;
62758 case 165 /* Constructor */:
62759 if (isInConstructorArgumentInitializer(node, container)) {
62760 error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
62761 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
62762 }
62763 break;
62764 case 162 /* PropertyDeclaration */:
62765 case 161 /* PropertySignature */:
62766 if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
62767 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
62768 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
62769 }
62770 break;
62771 case 157 /* ComputedPropertyName */:
62772 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
62773 break;
62774 }
62775 // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
62776 if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
62777 captureLexicalThis(node, container);
62778 }
62779 var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
62780 if (noImplicitThis) {
62781 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
62782 if (type === globalThisType_1 && capturedByArrowFunction) {
62783 error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
62784 }
62785 else if (!type) {
62786 // With noImplicitThis, functions may not reference 'this' if it has type 'any'
62787 var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
62788 if (!ts.isSourceFile(container)) {
62789 var outsideThis = tryGetThisTypeAt(container);
62790 if (outsideThis && outsideThis !== globalThisType_1) {
62791 ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
62792 }
62793 }
62794 }
62795 }
62796 return type || anyType;
62797 }
62798 function tryGetThisTypeAt(node, includeGlobalThis, container) {
62799 if (includeGlobalThis === void 0) { includeGlobalThis = true; }
62800 if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
62801 var isInJS = ts.isInJSFile(node);
62802 if (ts.isFunctionLike(container) &&
62803 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
62804 var thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
62805 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
62806 // If this is a function in a JS file, it might be a class method.
62807 if (!thisType) {
62808 var className = getClassNameFromPrototypeMethod(container);
62809 if (isInJS && className) {
62810 var classSymbol = checkExpression(className).symbol;
62811 if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
62812 thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
62813 }
62814 }
62815 else if (isJSConstructor(container)) {
62816 thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
62817 }
62818 thisType || (thisType = getContextualThisParameterType(container));
62819 }
62820 if (thisType) {
62821 return getFlowTypeOfReference(node, thisType);
62822 }
62823 }
62824 if (ts.isClassLike(container.parent)) {
62825 var symbol = getSymbolOfNode(container.parent);
62826 var type = ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
62827 return getFlowTypeOfReference(node, type);
62828 }
62829 if (ts.isSourceFile(container)) {
62830 // look up in the source file's locals or exports
62831 if (container.commonJsModuleIndicator) {
62832 var fileSymbol = getSymbolOfNode(container);
62833 return fileSymbol && getTypeOfSymbol(fileSymbol);
62834 }
62835 else if (container.externalModuleIndicator) {
62836 // TODO: Maybe issue a better error than 'object is possibly undefined'
62837 return undefinedType;
62838 }
62839 else if (includeGlobalThis) {
62840 return getTypeOfSymbol(globalThisSymbol);
62841 }
62842 }
62843 }
62844 function getExplicitThisType(node) {
62845 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
62846 if (ts.isFunctionLike(container)) {
62847 var signature = getSignatureFromDeclaration(container);
62848 if (signature.thisParameter) {
62849 return getExplicitTypeOfSymbol(signature.thisParameter);
62850 }
62851 }
62852 if (ts.isClassLike(container.parent)) {
62853 var symbol = getSymbolOfNode(container.parent);
62854 return ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
62855 }
62856 }
62857 function getClassNameFromPrototypeMethod(container) {
62858 // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
62859 if (container.kind === 205 /* FunctionExpression */ &&
62860 ts.isBinaryExpression(container.parent) &&
62861 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
62862 // Get the 'x' of 'x.prototype.y = container'
62863 return container.parent // x.prototype.y = container
62864 .left // x.prototype.y
62865 .expression // x.prototype
62866 .expression; // x
62867 }
62868 // x.prototype = { method() { } }
62869 else if (container.kind === 164 /* MethodDeclaration */ &&
62870 container.parent.kind === 197 /* ObjectLiteralExpression */ &&
62871 ts.isBinaryExpression(container.parent.parent) &&
62872 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
62873 return container.parent.parent.left.expression;
62874 }
62875 // x.prototype = { method: function() { } }
62876 else if (container.kind === 205 /* FunctionExpression */ &&
62877 container.parent.kind === 285 /* PropertyAssignment */ &&
62878 container.parent.parent.kind === 197 /* ObjectLiteralExpression */ &&
62879 ts.isBinaryExpression(container.parent.parent.parent) &&
62880 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
62881 return container.parent.parent.parent.left.expression;
62882 }
62883 // Object.defineProperty(x, "method", { value: function() { } });
62884 // Object.defineProperty(x, "method", { set: (x: () => void) => void });
62885 // Object.defineProperty(x, "method", { get: () => function() { }) });
62886 else if (container.kind === 205 /* FunctionExpression */ &&
62887 ts.isPropertyAssignment(container.parent) &&
62888 ts.isIdentifier(container.parent.name) &&
62889 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
62890 ts.isObjectLiteralExpression(container.parent.parent) &&
62891 ts.isCallExpression(container.parent.parent.parent) &&
62892 container.parent.parent.parent.arguments[2] === container.parent.parent &&
62893 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
62894 return container.parent.parent.parent.arguments[0].expression;
62895 }
62896 // Object.defineProperty(x, "method", { value() { } });
62897 // Object.defineProperty(x, "method", { set(x: () => void) {} });
62898 // Object.defineProperty(x, "method", { get() { return () => {} } });
62899 else if (ts.isMethodDeclaration(container) &&
62900 ts.isIdentifier(container.name) &&
62901 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
62902 ts.isObjectLiteralExpression(container.parent) &&
62903 ts.isCallExpression(container.parent.parent) &&
62904 container.parent.parent.arguments[2] === container.parent &&
62905 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
62906 return container.parent.parent.arguments[0].expression;
62907 }
62908 }
62909 function getTypeForThisExpressionFromJSDoc(node) {
62910 var jsdocType = ts.getJSDocType(node);
62911 if (jsdocType && jsdocType.kind === 304 /* JSDocFunctionType */) {
62912 var jsDocFunctionType = jsdocType;
62913 if (jsDocFunctionType.parameters.length > 0 &&
62914 jsDocFunctionType.parameters[0].name &&
62915 jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
62916 return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
62917 }
62918 }
62919 var thisTag = ts.getJSDocThisTag(node);
62920 if (thisTag && thisTag.typeExpression) {
62921 return getTypeFromTypeNode(thisTag.typeExpression);
62922 }
62923 }
62924 function isInConstructorArgumentInitializer(node, constructorDecl) {
62925 return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 159 /* Parameter */ && n.parent === constructorDecl; });
62926 }
62927 function checkSuperExpression(node) {
62928 var isCallExpression = node.parent.kind === 200 /* CallExpression */ && node.parent.expression === node;
62929 var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
62930 var container = immediateContainer;
62931 var needToCaptureLexicalThis = false;
62932 // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
62933 if (!isCallExpression) {
62934 while (container && container.kind === 206 /* ArrowFunction */) {
62935 container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
62936 needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
62937 }
62938 }
62939 var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
62940 var nodeCheckFlag = 0;
62941 if (!canUseSuperExpression) {
62942 // issue more specific error if super is used in computed property name
62943 // class A { foo() { return "1" }}
62944 // class B {
62945 // [super.foo()]() {}
62946 // }
62947 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 157 /* ComputedPropertyName */; });
62948 if (current && current.kind === 157 /* ComputedPropertyName */) {
62949 error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
62950 }
62951 else if (isCallExpression) {
62952 error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
62953 }
62954 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 197 /* ObjectLiteralExpression */)) {
62955 error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
62956 }
62957 else {
62958 error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
62959 }
62960 return errorType;
62961 }
62962 if (!isCallExpression && immediateContainer.kind === 165 /* Constructor */) {
62963 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
62964 }
62965 if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) {
62966 nodeCheckFlag = 512 /* SuperStatic */;
62967 }
62968 else {
62969 nodeCheckFlag = 256 /* SuperInstance */;
62970 }
62971 getNodeLinks(node).flags |= nodeCheckFlag;
62972 // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
62973 // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
62974 // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
62975 // uses an arrow function, which is permitted to reference `super`.
62976 //
62977 // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
62978 // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
62979 // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
62980 //
62981 // The simplest case is reading a value, in which case we will emit something like the following:
62982 //
62983 // // ts
62984 // ...
62985 // async asyncMethod() {
62986 // let x = await super.asyncMethod();
62987 // return x;
62988 // }
62989 // ...
62990 //
62991 // // js
62992 // ...
62993 // asyncMethod() {
62994 // const _super = Object.create(null, {
62995 // asyncMethod: { get: () => super.asyncMethod },
62996 // });
62997 // return __awaiter(this, arguments, Promise, function *() {
62998 // let x = yield _super.asyncMethod.call(this);
62999 // return x;
63000 // });
63001 // }
63002 // ...
63003 //
63004 // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
63005 // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
63006 //
63007 // // ts
63008 // ...
63009 // async asyncMethod(ar: Promise<any[]>) {
63010 // [super.a, super.b] = await ar;
63011 // }
63012 // ...
63013 //
63014 // // js
63015 // ...
63016 // asyncMethod(ar) {
63017 // const _super = Object.create(null, {
63018 // a: { get: () => super.a, set: (v) => super.a = v },
63019 // b: { get: () => super.b, set: (v) => super.b = v }
63020 // };
63021 // return __awaiter(this, arguments, Promise, function *() {
63022 // [_super.a, _super.b] = yield ar;
63023 // });
63024 // }
63025 // ...
63026 //
63027 // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
63028 // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
63029 //
63030 // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
63031 if (container.kind === 164 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) {
63032 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
63033 getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
63034 }
63035 else {
63036 getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
63037 }
63038 }
63039 if (needToCaptureLexicalThis) {
63040 // call expressions are allowed only in constructors so they should always capture correct 'this'
63041 // super property access expressions can also appear in arrow functions -
63042 // in this case they should also use correct lexical this
63043 captureLexicalThis(node.parent, container);
63044 }
63045 if (container.parent.kind === 197 /* ObjectLiteralExpression */) {
63046 if (languageVersion < 2 /* ES2015 */) {
63047 error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
63048 return errorType;
63049 }
63050 else {
63051 // for object literal assume that type of 'super' is 'any'
63052 return anyType;
63053 }
63054 }
63055 // at this point the only legal case for parent is ClassLikeDeclaration
63056 var classLikeDeclaration = container.parent;
63057 if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
63058 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
63059 return errorType;
63060 }
63061 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
63062 var baseClassType = classType && getBaseTypes(classType)[0];
63063 if (!baseClassType) {
63064 return errorType;
63065 }
63066 if (container.kind === 165 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
63067 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
63068 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
63069 return errorType;
63070 }
63071 return nodeCheckFlag === 512 /* SuperStatic */
63072 ? getBaseConstructorTypeOfClass(classType)
63073 : getTypeWithThisArgument(baseClassType, classType.thisType);
63074 function isLegalUsageOfSuperExpression(container) {
63075 if (!container) {
63076 return false;
63077 }
63078 if (isCallExpression) {
63079 // TS 1.0 SPEC (April 2014): 4.8.1
63080 // Super calls are only permitted in constructors of derived classes
63081 return container.kind === 165 /* Constructor */;
63082 }
63083 else {
63084 // TS 1.0 SPEC (April 2014)
63085 // 'super' property access is allowed
63086 // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
63087 // - In a static member function or static member accessor
63088 // topmost container must be something that is directly nested in the class declaration\object literal expression
63089 if (ts.isClassLike(container.parent) || container.parent.kind === 197 /* ObjectLiteralExpression */) {
63090 if (ts.hasSyntacticModifier(container, 32 /* Static */)) {
63091 return container.kind === 164 /* MethodDeclaration */ ||
63092 container.kind === 163 /* MethodSignature */ ||
63093 container.kind === 166 /* GetAccessor */ ||
63094 container.kind === 167 /* SetAccessor */;
63095 }
63096 else {
63097 return container.kind === 164 /* MethodDeclaration */ ||
63098 container.kind === 163 /* MethodSignature */ ||
63099 container.kind === 166 /* GetAccessor */ ||
63100 container.kind === 167 /* SetAccessor */ ||
63101 container.kind === 162 /* PropertyDeclaration */ ||
63102 container.kind === 161 /* PropertySignature */ ||
63103 container.kind === 165 /* Constructor */;
63104 }
63105 }
63106 }
63107 return false;
63108 }
63109 }
63110 function getContainingObjectLiteral(func) {
63111 return (func.kind === 164 /* MethodDeclaration */ ||
63112 func.kind === 166 /* GetAccessor */ ||
63113 func.kind === 167 /* SetAccessor */) && func.parent.kind === 197 /* ObjectLiteralExpression */ ? func.parent :
63114 func.kind === 205 /* FunctionExpression */ && func.parent.kind === 285 /* PropertyAssignment */ ? func.parent.parent :
63115 undefined;
63116 }
63117 function getThisTypeArgument(type) {
63118 return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
63119 }
63120 function getThisTypeFromContextualType(type) {
63121 return mapType(type, function (t) {
63122 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
63123 });
63124 }
63125 function getContextualThisParameterType(func) {
63126 if (func.kind === 206 /* ArrowFunction */) {
63127 return undefined;
63128 }
63129 if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
63130 var contextualSignature = getContextualSignature(func);
63131 if (contextualSignature) {
63132 var thisParameter = contextualSignature.thisParameter;
63133 if (thisParameter) {
63134 return getTypeOfSymbol(thisParameter);
63135 }
63136 }
63137 }
63138 var inJs = ts.isInJSFile(func);
63139 if (noImplicitThis || inJs) {
63140 var containingLiteral = getContainingObjectLiteral(func);
63141 if (containingLiteral) {
63142 // We have an object literal method. Check if the containing object literal has a contextual type
63143 // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
63144 // any directly enclosing object literals.
63145 var contextualType = getApparentTypeOfContextualType(containingLiteral);
63146 var literal = containingLiteral;
63147 var type = contextualType;
63148 while (type) {
63149 var thisType = getThisTypeFromContextualType(type);
63150 if (thisType) {
63151 return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
63152 }
63153 if (literal.parent.kind !== 285 /* PropertyAssignment */) {
63154 break;
63155 }
63156 literal = literal.parent.parent;
63157 type = getApparentTypeOfContextualType(literal);
63158 }
63159 // There was no contextual ThisType<T> for the containing object literal, so the contextual type
63160 // for 'this' is the non-null form of the contextual type for the containing object literal or
63161 // the type of the object literal itself.
63162 return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
63163 }
63164 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
63165 // contextual type for 'this' is 'obj'.
63166 var parent = ts.walkUpParenthesizedExpressions(func.parent);
63167 if (parent.kind === 213 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
63168 var target = parent.left;
63169 if (ts.isAccessExpression(target)) {
63170 var expression = target.expression;
63171 // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
63172 if (inJs && ts.isIdentifier(expression)) {
63173 var sourceFile = ts.getSourceFileOfNode(parent);
63174 if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
63175 return undefined;
63176 }
63177 }
63178 return getWidenedType(checkExpressionCached(expression));
63179 }
63180 }
63181 }
63182 return undefined;
63183 }
63184 // Return contextual type of parameter or undefined if no contextual type is available
63185 function getContextuallyTypedParameterType(parameter) {
63186 var func = parameter.parent;
63187 if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
63188 return undefined;
63189 }
63190 var iife = ts.getImmediatelyInvokedFunctionExpression(func);
63191 if (iife && iife.arguments) {
63192 var args = getEffectiveCallArguments(iife);
63193 var indexOfParameter = func.parameters.indexOf(parameter);
63194 if (parameter.dotDotDotToken) {
63195 return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined, 0 /* Normal */);
63196 }
63197 var links = getNodeLinks(iife);
63198 var cached = links.resolvedSignature;
63199 links.resolvedSignature = anySignature;
63200 var type = indexOfParameter < args.length ?
63201 getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
63202 parameter.initializer ? undefined : undefinedWideningType;
63203 links.resolvedSignature = cached;
63204 return type;
63205 }
63206 var contextualSignature = getContextualSignature(func);
63207 if (contextualSignature) {
63208 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
63209 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
63210 getRestTypeAtPosition(contextualSignature, index) :
63211 tryGetTypeAtPosition(contextualSignature, index);
63212 }
63213 }
63214 function getContextualTypeForVariableLikeDeclaration(declaration) {
63215 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
63216 if (typeNode) {
63217 return getTypeFromTypeNode(typeNode);
63218 }
63219 switch (declaration.kind) {
63220 case 159 /* Parameter */:
63221 return getContextuallyTypedParameterType(declaration);
63222 case 195 /* BindingElement */:
63223 return getContextualTypeForBindingElement(declaration);
63224 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
63225 }
63226 }
63227 function getContextualTypeForBindingElement(declaration) {
63228 var parent = declaration.parent.parent;
63229 var name = declaration.propertyName || declaration.name;
63230 var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
63231 parent.kind !== 195 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
63232 if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
63233 var nameType = getLiteralTypeFromPropertyName(name);
63234 if (isTypeUsableAsPropertyName(nameType)) {
63235 var text = getPropertyNameFromType(nameType);
63236 return getTypeOfPropertyOfType(parentType, text);
63237 }
63238 }
63239 }
63240 // In a variable, parameter or property declaration with a type annotation,
63241 // the contextual type of an initializer expression is the type of the variable, parameter or property.
63242 // Otherwise, in a parameter declaration of a contextually typed function expression,
63243 // the contextual type of an initializer expression is the contextual type of the parameter.
63244 // Otherwise, in a variable or parameter declaration with a binding pattern name,
63245 // the contextual type of an initializer expression is the type implied by the binding pattern.
63246 // Otherwise, in a binding pattern inside a variable or parameter declaration,
63247 // the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
63248 function getContextualTypeForInitializerExpression(node, contextFlags) {
63249 var declaration = node.parent;
63250 if (ts.hasInitializer(declaration) && node === declaration.initializer) {
63251 var result = getContextualTypeForVariableLikeDeclaration(declaration);
63252 if (result) {
63253 return result;
63254 }
63255 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
63256 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
63257 }
63258 }
63259 return undefined;
63260 }
63261 function getContextualTypeForReturnExpression(node) {
63262 var func = ts.getContainingFunction(node);
63263 if (func) {
63264 var contextualReturnType = getContextualReturnType(func);
63265 if (contextualReturnType) {
63266 var functionFlags = ts.getFunctionFlags(func);
63267 if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
63268 var use = functionFlags & 2 /* Async */ ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
63269 var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined);
63270 if (!iterationTypes) {
63271 return undefined;
63272 }
63273 contextualReturnType = iterationTypes.returnType;
63274 // falls through to unwrap Promise for AsyncGenerators
63275 }
63276 if (functionFlags & 2 /* Async */) { // Async function or AsyncGenerator function
63277 var contextualAwaitedType = mapType(contextualReturnType, getAwaitedType);
63278 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
63279 }
63280 return contextualReturnType; // Regular function or Generator function
63281 }
63282 }
63283 return undefined;
63284 }
63285 function getContextualTypeForAwaitOperand(node, contextFlags) {
63286 var contextualType = getContextualType(node, contextFlags);
63287 if (contextualType) {
63288 var contextualAwaitedType = getAwaitedType(contextualType);
63289 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
63290 }
63291 return undefined;
63292 }
63293 function getContextualTypeForYieldOperand(node) {
63294 var func = ts.getContainingFunction(node);
63295 if (func) {
63296 var functionFlags = ts.getFunctionFlags(func);
63297 var contextualReturnType = getContextualReturnType(func);
63298 if (contextualReturnType) {
63299 return node.asteriskToken
63300 ? contextualReturnType
63301 : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
63302 }
63303 }
63304 return undefined;
63305 }
63306 function isInParameterInitializerBeforeContainingFunction(node) {
63307 var inBindingInitializer = false;
63308 while (node.parent && !ts.isFunctionLike(node.parent)) {
63309 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
63310 return true;
63311 }
63312 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
63313 inBindingInitializer = true;
63314 }
63315 node = node.parent;
63316 }
63317 return false;
63318 }
63319 function getContextualIterationType(kind, functionDecl) {
63320 var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
63321 var contextualReturnType = getContextualReturnType(functionDecl);
63322 if (contextualReturnType) {
63323 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
63324 || undefined;
63325 }
63326 return undefined;
63327 }
63328 function getContextualReturnType(functionDecl) {
63329 // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
63330 // corresponding set accessor has a type annotation, return statements in the function are contextually typed
63331 var returnType = getReturnTypeFromAnnotation(functionDecl);
63332 if (returnType) {
63333 return returnType;
63334 }
63335 // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
63336 // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
63337 var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
63338 if (signature && !isResolvingReturnTypeOfSignature(signature)) {
63339 return getReturnTypeOfSignature(signature);
63340 }
63341 return undefined;
63342 }
63343 // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
63344 function getContextualTypeForArgument(callTarget, arg) {
63345 var args = getEffectiveCallArguments(callTarget);
63346 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
63347 return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
63348 }
63349 function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
63350 // If we're already in the process of resolving the given signature, don't resolve again as
63351 // that could cause infinite recursion. Instead, return anySignature.
63352 var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
63353 if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
63354 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
63355 }
63356 return getTypeAtPosition(signature, argIndex);
63357 }
63358 function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
63359 if (template.parent.kind === 202 /* TaggedTemplateExpression */) {
63360 return getContextualTypeForArgument(template.parent, substitutionExpression);
63361 }
63362 return undefined;
63363 }
63364 function getContextualTypeForBinaryOperand(node, contextFlags) {
63365 var binaryExpression = node.parent;
63366 var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
63367 switch (operatorToken.kind) {
63368 case 62 /* EqualsToken */:
63369 case 75 /* AmpersandAmpersandEqualsToken */:
63370 case 74 /* BarBarEqualsToken */:
63371 case 76 /* QuestionQuestionEqualsToken */:
63372 if (node !== right) {
63373 return undefined;
63374 }
63375 var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
63376 if (!contextSensitive) {
63377 return undefined;
63378 }
63379 return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
63380 case 56 /* BarBarToken */:
63381 case 60 /* QuestionQuestionToken */:
63382 // When an || expression has a contextual type, the operands are contextually typed by that type, except
63383 // when that type originates in a binding pattern, the right operand is contextually typed by the type of
63384 // the left operand. When an || expression has no contextual type, the right operand is contextually typed
63385 // by the type of the left operand, except for the special case of Javascript declarations of the form
63386 // `namespace.prop = namespace.prop || {}`.
63387 var type = getContextualType(binaryExpression, contextFlags);
63388 return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
63389 getTypeOfExpression(left) : type;
63390 case 55 /* AmpersandAmpersandToken */:
63391 case 27 /* CommaToken */:
63392 return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
63393 default:
63394 return undefined;
63395 }
63396 }
63397 // In an assignment expression, the right operand is contextually typed by the type of the left operand.
63398 // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
63399 function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
63400 var kind = ts.getAssignmentDeclarationKind(binaryExpression);
63401 switch (kind) {
63402 case 0 /* None */:
63403 return true;
63404 case 5 /* Property */:
63405 case 1 /* ExportsProperty */:
63406 case 6 /* Prototype */:
63407 case 3 /* PrototypeProperty */:
63408 // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
63409 // See `bindStaticPropertyAssignment` in `binder.ts`.
63410 if (!binaryExpression.left.symbol) {
63411 return true;
63412 }
63413 else {
63414 var decl = binaryExpression.left.symbol.valueDeclaration;
63415 if (!decl) {
63416 return false;
63417 }
63418 var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
63419 var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
63420 if (overallAnnotation) {
63421 return getTypeFromTypeNode(overallAnnotation);
63422 }
63423 else if (ts.isIdentifier(lhs.expression)) {
63424 var id = lhs.expression;
63425 var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
63426 if (parentSymbol) {
63427 var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
63428 if (annotated) {
63429 var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
63430 if (nameStr_1 !== undefined) {
63431 var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
63432 return type || false;
63433 }
63434 }
63435 return false;
63436 }
63437 }
63438 return !ts.isInJSFile(decl);
63439 }
63440 case 2 /* ModuleExports */:
63441 case 4 /* ThisProperty */:
63442 if (!binaryExpression.symbol)
63443 return true;
63444 if (binaryExpression.symbol.valueDeclaration) {
63445 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
63446 if (annotated) {
63447 var type = getTypeFromTypeNode(annotated);
63448 if (type) {
63449 return type;
63450 }
63451 }
63452 }
63453 if (kind === 2 /* ModuleExports */)
63454 return false;
63455 var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
63456 if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
63457 return false;
63458 }
63459 var thisType = checkThisExpression(thisAccess.expression);
63460 var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
63461 return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
63462 case 7 /* ObjectDefinePropertyValue */:
63463 case 8 /* ObjectDefinePropertyExports */:
63464 case 9 /* ObjectDefinePrototypeProperty */:
63465 return ts.Debug.fail("Does not apply");
63466 default:
63467 return ts.Debug.assertNever(kind);
63468 }
63469 }
63470 function isCircularMappedProperty(symbol) {
63471 return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
63472 }
63473 function getTypeOfPropertyOfContextualType(type, name) {
63474 return mapType(type, function (t) {
63475 if (isGenericMappedType(t)) {
63476 var constraint = getConstraintTypeFromMappedType(t);
63477 var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
63478 var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
63479 if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
63480 return substituteIndexedMappedType(t, propertyNameType);
63481 }
63482 }
63483 else if (t.flags & 3670016 /* StructuredType */) {
63484 var prop = getPropertyOfType(t, name);
63485 if (prop) {
63486 return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
63487 }
63488 if (isTupleType(t)) {
63489 var restType = getRestTypeOfTupleType(t);
63490 if (restType && isNumericLiteralName(name) && +name >= 0) {
63491 return restType;
63492 }
63493 }
63494 return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
63495 getIndexTypeOfContextualType(t, 0 /* String */);
63496 }
63497 return undefined;
63498 }, /*noReductions*/ true);
63499 }
63500 function getIndexTypeOfContextualType(type, kind) {
63501 return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
63502 }
63503 // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
63504 // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
63505 // exists. Otherwise, it is the type of the string index signature in T, if one exists.
63506 function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
63507 ts.Debug.assert(ts.isObjectLiteralMethod(node));
63508 if (node.flags & 16777216 /* InWithStatement */) {
63509 // We cannot answer semantic questions within a with block, do not proceed any further
63510 return undefined;
63511 }
63512 return getContextualTypeForObjectLiteralElement(node, contextFlags);
63513 }
63514 function getContextualTypeForObjectLiteralElement(element, contextFlags) {
63515 var objectLiteral = element.parent;
63516 var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
63517 if (type) {
63518 if (!hasNonBindableDynamicName(element)) {
63519 // For a (non-symbol) computed property, there is no reason to look up the name
63520 // in the type. It will just be "__computed", which does not appear in any
63521 // SymbolTable.
63522 var symbolName_3 = getSymbolOfNode(element).escapedName;
63523 var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
63524 if (propertyType) {
63525 return propertyType;
63526 }
63527 }
63528 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
63529 getIndexTypeOfContextualType(type, 0 /* String */);
63530 }
63531 return undefined;
63532 }
63533 // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
63534 // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
63535 // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
63536 // type of T.
63537 function getContextualTypeForElementExpression(arrayContextualType, index) {
63538 return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
63539 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
63540 }
63541 // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
63542 function getContextualTypeForConditionalOperand(node, contextFlags) {
63543 var conditional = node.parent;
63544 return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
63545 }
63546 function getContextualTypeForChildJsxExpression(node, child) {
63547 var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
63548 // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
63549 var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
63550 if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
63551 return undefined;
63552 }
63553 var realChildren = getSemanticJsxChildren(node.children);
63554 var childIndex = realChildren.indexOf(child);
63555 var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
63556 return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
63557 if (isArrayLikeType(t)) {
63558 return getIndexedAccessType(t, getLiteralType(childIndex));
63559 }
63560 else {
63561 return t;
63562 }
63563 }, /*noReductions*/ true));
63564 }
63565 function getContextualTypeForJsxExpression(node) {
63566 var exprParent = node.parent;
63567 return ts.isJsxAttributeLike(exprParent)
63568 ? getContextualType(node)
63569 : ts.isJsxElement(exprParent)
63570 ? getContextualTypeForChildJsxExpression(exprParent, node)
63571 : undefined;
63572 }
63573 function getContextualTypeForJsxAttribute(attribute) {
63574 // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
63575 // which is a type of the parameter of the signature we are trying out.
63576 // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
63577 if (ts.isJsxAttribute(attribute)) {
63578 var attributesType = getApparentTypeOfContextualType(attribute.parent);
63579 if (!attributesType || isTypeAny(attributesType)) {
63580 return undefined;
63581 }
63582 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
63583 }
63584 else {
63585 return getContextualType(attribute.parent);
63586 }
63587 }
63588 // Return true if the given expression is possibly a discriminant value. We limit the kinds of
63589 // expressions we check to those that don't depend on their contextual type in order not to cause
63590 // recursive (and possibly infinite) invocations of getContextualType.
63591 function isPossiblyDiscriminantValue(node) {
63592 switch (node.kind) {
63593 case 10 /* StringLiteral */:
63594 case 8 /* NumericLiteral */:
63595 case 9 /* BigIntLiteral */:
63596 case 14 /* NoSubstitutionTemplateLiteral */:
63597 case 109 /* TrueKeyword */:
63598 case 94 /* FalseKeyword */:
63599 case 103 /* NullKeyword */:
63600 case 78 /* Identifier */:
63601 case 149 /* UndefinedKeyword */:
63602 return true;
63603 case 198 /* PropertyAccessExpression */:
63604 case 204 /* ParenthesizedExpression */:
63605 return isPossiblyDiscriminantValue(node.expression);
63606 case 280 /* JsxExpression */:
63607 return !node.expression || isPossiblyDiscriminantValue(node.expression);
63608 }
63609 return false;
63610 }
63611 function discriminateContextualTypeByObjectMembers(node, contextualType) {
63612 return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 285 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
63613 }
63614 function discriminateContextualTypeByJSXAttributes(node, contextualType) {
63615 return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 277 /* 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);
63616 }
63617 // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
63618 // be "pushed" onto a node using the contextualType property.
63619 function getApparentTypeOfContextualType(node, contextFlags) {
63620 var contextualType = ts.isObjectLiteralMethod(node) ?
63621 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
63622 getContextualType(node, contextFlags);
63623 var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
63624 if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
63625 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
63626 if (apparentType.flags & 1048576 /* Union */) {
63627 if (ts.isObjectLiteralExpression(node)) {
63628 return discriminateContextualTypeByObjectMembers(node, apparentType);
63629 }
63630 else if (ts.isJsxAttributes(node)) {
63631 return discriminateContextualTypeByJSXAttributes(node, apparentType);
63632 }
63633 }
63634 return apparentType;
63635 }
63636 }
63637 // If the given contextual type contains instantiable types and if a mapper representing
63638 // return type inferences is available, instantiate those types using that mapper.
63639 function instantiateContextualType(contextualType, node, contextFlags) {
63640 if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
63641 var inferenceContext = getInferenceContext(node);
63642 // If no inferences have been made, nothing is gained from instantiating as type parameters
63643 // would just be replaced with their defaults similar to the apparent type.
63644 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
63645 // For contextual signatures we incorporate all inferences made so far, e.g. from return
63646 // types as well as arguments to the left in a function call.
63647 if (contextFlags && contextFlags & 1 /* Signature */) {
63648 return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
63649 }
63650 // For other purposes (e.g. determining whether to produce literal types) we only
63651 // incorporate inferences made from the return type in a function call.
63652 if (inferenceContext.returnMapper) {
63653 return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
63654 }
63655 }
63656 }
63657 return contextualType;
63658 }
63659 // This function is similar to instantiateType, except that (a) it only instantiates types that
63660 // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
63661 // no reductions on instantiated union types.
63662 function instantiateInstantiableTypes(type, mapper) {
63663 if (type.flags & 63176704 /* Instantiable */) {
63664 return instantiateType(type, mapper);
63665 }
63666 if (type.flags & 1048576 /* Union */) {
63667 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
63668 }
63669 if (type.flags & 2097152 /* Intersection */) {
63670 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
63671 }
63672 return type;
63673 }
63674 /**
63675 * Whoa! Do you really want to use this function?
63676 *
63677 * Unless you're trying to get the *non-apparent* type for a
63678 * value-literal type or you're authoring relevant portions of this algorithm,
63679 * you probably meant to use 'getApparentTypeOfContextualType'.
63680 * Otherwise this may not be very useful.
63681 *
63682 * In cases where you *are* working on this function, you should understand
63683 * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
63684 *
63685 * - Use 'getContextualType' when you are simply going to propagate the result to the expression.
63686 * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
63687 *
63688 * @param node the expression whose contextual type will be returned.
63689 * @returns the contextual type of an expression.
63690 */
63691 function getContextualType(node, contextFlags) {
63692 if (node.flags & 16777216 /* InWithStatement */) {
63693 // We cannot answer semantic questions within a with block, do not proceed any further
63694 return undefined;
63695 }
63696 if (node.contextualType) {
63697 return node.contextualType;
63698 }
63699 var parent = node.parent;
63700 switch (parent.kind) {
63701 case 246 /* VariableDeclaration */:
63702 case 159 /* Parameter */:
63703 case 162 /* PropertyDeclaration */:
63704 case 161 /* PropertySignature */:
63705 case 195 /* BindingElement */:
63706 return getContextualTypeForInitializerExpression(node, contextFlags);
63707 case 206 /* ArrowFunction */:
63708 case 239 /* ReturnStatement */:
63709 return getContextualTypeForReturnExpression(node);
63710 case 216 /* YieldExpression */:
63711 return getContextualTypeForYieldOperand(parent);
63712 case 210 /* AwaitExpression */:
63713 return getContextualTypeForAwaitOperand(parent, contextFlags);
63714 case 200 /* CallExpression */:
63715 if (parent.expression.kind === 99 /* ImportKeyword */) {
63716 return stringType;
63717 }
63718 /* falls through */
63719 case 201 /* NewExpression */:
63720 return getContextualTypeForArgument(parent, node);
63721 case 203 /* TypeAssertionExpression */:
63722 case 221 /* AsExpression */:
63723 return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type);
63724 case 213 /* BinaryExpression */:
63725 return getContextualTypeForBinaryOperand(node, contextFlags);
63726 case 285 /* PropertyAssignment */:
63727 case 286 /* ShorthandPropertyAssignment */:
63728 return getContextualTypeForObjectLiteralElement(parent, contextFlags);
63729 case 287 /* SpreadAssignment */:
63730 return getApparentTypeOfContextualType(parent.parent, contextFlags);
63731 case 196 /* ArrayLiteralExpression */: {
63732 var arrayLiteral = parent;
63733 var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
63734 return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
63735 }
63736 case 214 /* ConditionalExpression */:
63737 return getContextualTypeForConditionalOperand(node, contextFlags);
63738 case 225 /* TemplateSpan */:
63739 ts.Debug.assert(parent.parent.kind === 215 /* TemplateExpression */);
63740 return getContextualTypeForSubstitutionExpression(parent.parent, node);
63741 case 204 /* ParenthesizedExpression */: {
63742 // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
63743 var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
63744 return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
63745 }
63746 case 280 /* JsxExpression */:
63747 return getContextualTypeForJsxExpression(parent);
63748 case 277 /* JsxAttribute */:
63749 case 279 /* JsxSpreadAttribute */:
63750 return getContextualTypeForJsxAttribute(parent);
63751 case 272 /* JsxOpeningElement */:
63752 case 271 /* JsxSelfClosingElement */:
63753 return getContextualJsxElementAttributesType(parent, contextFlags);
63754 }
63755 return undefined;
63756 function tryFindWhenConstTypeReference(node) {
63757 if (ts.isCallLikeExpression(node.parent)) {
63758 return getContextualTypeForArgument(node.parent, node);
63759 }
63760 return undefined;
63761 }
63762 }
63763 function getInferenceContext(node) {
63764 var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
63765 return ancestor && ancestor.inferenceContext;
63766 }
63767 function getContextualJsxElementAttributesType(node, contextFlags) {
63768 if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
63769 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
63770 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
63771 // (as below) instead!
63772 return node.parent.contextualType;
63773 }
63774 return getContextualTypeForArgumentAtIndex(node, 0);
63775 }
63776 function getEffectiveFirstArgumentForJsxSignature(signature, node) {
63777 return getJsxReferenceKind(node) !== 0 /* Component */
63778 ? getJsxPropsTypeFromCallSignature(signature, node)
63779 : getJsxPropsTypeFromClassType(signature, node);
63780 }
63781 function getJsxPropsTypeFromCallSignature(sig, context) {
63782 var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
63783 propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
63784 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
63785 if (intrinsicAttribs !== errorType) {
63786 propsType = intersectTypes(intrinsicAttribs, propsType);
63787 }
63788 return propsType;
63789 }
63790 function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
63791 if (sig.unionSignatures) {
63792 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
63793 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
63794 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
63795 // 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.
63796 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
63797 var results = [];
63798 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
63799 var signature = _a[_i];
63800 var instance = getReturnTypeOfSignature(signature);
63801 if (isTypeAny(instance)) {
63802 return instance;
63803 }
63804 var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
63805 if (!propType) {
63806 return;
63807 }
63808 results.push(propType);
63809 }
63810 return getIntersectionType(results);
63811 }
63812 var instanceType = getReturnTypeOfSignature(sig);
63813 return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
63814 }
63815 function getStaticTypeOfReferencedJsxConstructor(context) {
63816 if (isJsxIntrinsicIdentifier(context.tagName)) {
63817 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
63818 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
63819 return getOrCreateTypeFromSignature(fakeSignature);
63820 }
63821 var tagType = checkExpressionCached(context.tagName);
63822 if (tagType.flags & 128 /* StringLiteral */) {
63823 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
63824 if (!result) {
63825 return errorType;
63826 }
63827 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
63828 return getOrCreateTypeFromSignature(fakeSignature);
63829 }
63830 return tagType;
63831 }
63832 function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
63833 var managedSym = getJsxLibraryManagedAttributes(ns);
63834 if (managedSym) {
63835 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
63836 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
63837 if (ts.length(declaredManagedType.typeParameters) >= 2) {
63838 var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
63839 return createTypeReference(declaredManagedType, args);
63840 }
63841 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
63842 var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
63843 return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
63844 }
63845 }
63846 return attributesType;
63847 }
63848 function getJsxPropsTypeFromClassType(sig, context) {
63849 var ns = getJsxNamespaceAt(context);
63850 var forcedLookupLocation = getJsxElementPropertiesName(ns);
63851 var attributesType = forcedLookupLocation === undefined
63852 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
63853 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
63854 : forcedLookupLocation === ""
63855 // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
63856 ? getReturnTypeOfSignature(sig)
63857 // Otherwise get the type of the property on the signature return type
63858 : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
63859 if (!attributesType) {
63860 // There is no property named 'props' on this instance type
63861 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
63862 error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
63863 }
63864 return unknownType;
63865 }
63866 attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
63867 if (isTypeAny(attributesType)) {
63868 // Props is of type 'any' or unknown
63869 return attributesType;
63870 }
63871 else {
63872 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
63873 var apparentAttributesType = attributesType;
63874 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
63875 if (intrinsicClassAttribs !== errorType) {
63876 var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
63877 var hostClassType = getReturnTypeOfSignature(sig);
63878 apparentAttributesType = intersectTypes(typeParams
63879 ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
63880 : intrinsicClassAttribs, apparentAttributesType);
63881 }
63882 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
63883 if (intrinsicAttribs !== errorType) {
63884 apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
63885 }
63886 return apparentAttributesType;
63887 }
63888 }
63889 // If the given type is an object or union type with a single signature, and if that signature has at
63890 // least as many parameters as the given function, return the signature. Otherwise return undefined.
63891 function getContextualCallSignature(type, node) {
63892 var signatures = getSignaturesOfType(type, 0 /* Call */);
63893 if (signatures.length === 1) {
63894 var signature = signatures[0];
63895 if (!isAritySmaller(signature, node)) {
63896 return signature;
63897 }
63898 }
63899 }
63900 /** If the contextual signature has fewer parameters than the function expression, do not use it */
63901 function isAritySmaller(signature, target) {
63902 var targetParameterCount = 0;
63903 for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
63904 var param = target.parameters[targetParameterCount];
63905 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
63906 break;
63907 }
63908 }
63909 if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
63910 targetParameterCount--;
63911 }
63912 return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
63913 }
63914 function isFunctionExpressionOrArrowFunction(node) {
63915 return node.kind === 205 /* FunctionExpression */ || node.kind === 206 /* ArrowFunction */;
63916 }
63917 function getContextualSignatureForFunctionLikeDeclaration(node) {
63918 // Only function expressions, arrow functions, and object literal methods are contextually typed.
63919 return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
63920 ? getContextualSignature(node)
63921 : undefined;
63922 }
63923 // Return the contextual signature for a given expression node. A contextual type provides a
63924 // contextual signature if it has a single call signature and if that call signature is non-generic.
63925 // If the contextual type is a union type, get the signature from each type possible and if they are
63926 // all identical ignoring their return type, the result is same signature but with return type as
63927 // union type of return types from these signatures
63928 function getContextualSignature(node) {
63929 ts.Debug.assert(node.kind !== 164 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
63930 var typeTagSignature = getSignatureOfTypeTag(node);
63931 if (typeTagSignature) {
63932 return typeTagSignature;
63933 }
63934 var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
63935 if (!type) {
63936 return undefined;
63937 }
63938 if (!(type.flags & 1048576 /* Union */)) {
63939 return getContextualCallSignature(type, node);
63940 }
63941 var signatureList;
63942 var types = type.types;
63943 for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
63944 var current = types_17[_i];
63945 var signature = getContextualCallSignature(current, node);
63946 if (signature) {
63947 if (!signatureList) {
63948 // This signature will contribute to contextual union signature
63949 signatureList = [signature];
63950 }
63951 else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
63952 // Signatures aren't identical, do not use
63953 return undefined;
63954 }
63955 else {
63956 // Use this signature for contextual union signature
63957 signatureList.push(signature);
63958 }
63959 }
63960 }
63961 // Result is union of signatures collected (return type is union of return types of this signature set)
63962 if (signatureList) {
63963 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
63964 }
63965 }
63966 function checkSpreadExpression(node, checkMode) {
63967 if (languageVersion < 2 /* ES2015 */) {
63968 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
63969 }
63970 var arrayOrIterableType = checkExpression(node.expression, checkMode);
63971 return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
63972 }
63973 function checkSyntheticExpression(node) {
63974 return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
63975 }
63976 function hasDefaultValue(node) {
63977 return (node.kind === 195 /* BindingElement */ && !!node.initializer) ||
63978 (node.kind === 213 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
63979 }
63980 function checkArrayLiteral(node, checkMode, forceTuple) {
63981 var elements = node.elements;
63982 var elementCount = elements.length;
63983 var elementTypes = [];
63984 var elementFlags = [];
63985 var contextualType = getApparentTypeOfContextualType(node);
63986 var inDestructuringPattern = ts.isAssignmentTarget(node);
63987 var inConstContext = isConstContext(node);
63988 for (var i = 0; i < elementCount; i++) {
63989 var e = elements[i];
63990 if (e.kind === 217 /* SpreadElement */) {
63991 if (languageVersion < 2 /* ES2015 */) {
63992 checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
63993 }
63994 var spreadType = checkExpression(e.expression, checkMode, forceTuple);
63995 if (isArrayLikeType(spreadType)) {
63996 elementTypes.push(spreadType);
63997 elementFlags.push(8 /* Variadic */);
63998 }
63999 else if (inDestructuringPattern) {
64000 // Given the following situation:
64001 // var c: {};
64002 // [...c] = ["", 0];
64003 //
64004 // c is represented in the tree as a spread element in an array literal.
64005 // But c really functions as a rest element, and its purpose is to provide
64006 // a contextual type for the right hand side of the assignment. Therefore,
64007 // instead of calling checkExpression on "...c", which will give an error
64008 // if c is not iterable/array-like, we need to act as if we are trying to
64009 // get the contextual element type from it. So we do something similar to
64010 // getContextualTypeForElementExpression, which will crucially not error
64011 // if there is no index type / iterated type.
64012 var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
64013 getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false) ||
64014 unknownType;
64015 elementTypes.push(restElementType);
64016 elementFlags.push(4 /* Rest */);
64017 }
64018 else {
64019 elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
64020 elementFlags.push(4 /* Rest */);
64021 }
64022 }
64023 else {
64024 var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
64025 var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
64026 elementTypes.push(type);
64027 elementFlags.push(1 /* Required */);
64028 }
64029 }
64030 if (inDestructuringPattern) {
64031 return createTupleType(elementTypes, elementFlags);
64032 }
64033 if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) {
64034 return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext));
64035 }
64036 return createArrayLiteralType(createArrayType(elementTypes.length ?
64037 getUnionType(ts.sameMap(elementTypes, function (t, i) { return elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t; }), 2 /* Subtype */) :
64038 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
64039 }
64040 function createArrayLiteralType(type) {
64041 if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
64042 return type;
64043 }
64044 var literalType = type.literalType;
64045 if (!literalType) {
64046 literalType = type.literalType = cloneTypeReference(type);
64047 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
64048 }
64049 return literalType;
64050 }
64051 function isNumericName(name) {
64052 switch (name.kind) {
64053 case 157 /* ComputedPropertyName */:
64054 return isNumericComputedName(name);
64055 case 78 /* Identifier */:
64056 return isNumericLiteralName(name.escapedText);
64057 case 8 /* NumericLiteral */:
64058 case 10 /* StringLiteral */:
64059 return isNumericLiteralName(name.text);
64060 default:
64061 return false;
64062 }
64063 }
64064 function isNumericComputedName(name) {
64065 // It seems odd to consider an expression of type Any to result in a numeric name,
64066 // but this behavior is consistent with checkIndexedAccess
64067 return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
64068 }
64069 function isInfinityOrNaNString(name) {
64070 return name === "Infinity" || name === "-Infinity" || name === "NaN";
64071 }
64072 function isNumericLiteralName(name) {
64073 // The intent of numeric names is that
64074 // - they are names with text in a numeric form, and that
64075 // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
64076 // acquired by applying the abstract 'ToNumber' operation on the name's text.
64077 //
64078 // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
64079 // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
64080 //
64081 // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
64082 // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
64083 // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
64084 // because their 'ToString' representation is not equal to their original text.
64085 // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
64086 //
64087 // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
64088 // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
64089 // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
64090 //
64091 // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
64092 // This is desired behavior, because when indexing with them as numeric entities, you are indexing
64093 // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
64094 return (+name).toString() === name;
64095 }
64096 function checkComputedPropertyName(node) {
64097 var links = getNodeLinks(node.expression);
64098 if (!links.resolvedType) {
64099 links.resolvedType = checkExpression(node.expression);
64100 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
64101 // type, and any union of these types (like string | number).
64102 if (links.resolvedType.flags & 98304 /* Nullable */ ||
64103 !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
64104 !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
64105 error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
64106 }
64107 else {
64108 checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
64109 }
64110 }
64111 return links.resolvedType;
64112 }
64113 function isSymbolWithNumericName(symbol) {
64114 var _a;
64115 var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
64116 return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name));
64117 }
64118 function getObjectLiteralIndexInfo(node, offset, properties, kind) {
64119 var propTypes = [];
64120 for (var i = offset; i < properties.length; i++) {
64121 if (kind === 0 /* String */ || isSymbolWithNumericName(properties[i])) {
64122 propTypes.push(getTypeOfSymbol(properties[i]));
64123 }
64124 }
64125 var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
64126 return createIndexInfo(unionType, isConstContext(node));
64127 }
64128 function getImmediateAliasedSymbol(symbol) {
64129 ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
64130 var links = getSymbolLinks(symbol);
64131 if (!links.immediateTarget) {
64132 var node = getDeclarationOfAliasSymbol(symbol);
64133 if (!node)
64134 return ts.Debug.fail();
64135 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
64136 }
64137 return links.immediateTarget;
64138 }
64139 function checkObjectLiteral(node, checkMode) {
64140 var inDestructuringPattern = ts.isAssignmentTarget(node);
64141 // Grammar checking
64142 checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
64143 var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
64144 var propertiesTable = ts.createSymbolTable();
64145 var propertiesArray = [];
64146 var spread = emptyObjectType;
64147 var contextualType = getApparentTypeOfContextualType(node);
64148 var contextualTypeHasPattern = contextualType && contextualType.pattern &&
64149 (contextualType.pattern.kind === 193 /* ObjectBindingPattern */ || contextualType.pattern.kind === 197 /* ObjectLiteralExpression */);
64150 var inConstContext = isConstContext(node);
64151 var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
64152 var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
64153 var enumTag = ts.getJSDocEnumTag(node);
64154 var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
64155 var objectFlags = freshObjectLiteralFlag;
64156 var patternWithComputedProperties = false;
64157 var hasComputedStringProperty = false;
64158 var hasComputedNumberProperty = false;
64159 // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
64160 // As otherwise they may not be checked until exports for the type at this position are retrieved,
64161 // which may never occur.
64162 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
64163 var elem = _a[_i];
64164 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
64165 checkComputedPropertyName(elem.name);
64166 }
64167 }
64168 var offset = 0;
64169 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
64170 var memberDecl = _c[_b];
64171 var member = getSymbolOfNode(memberDecl);
64172 var computedNameType = memberDecl.name && memberDecl.name.kind === 157 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
64173 checkComputedPropertyName(memberDecl.name) : undefined;
64174 if (memberDecl.kind === 285 /* PropertyAssignment */ ||
64175 memberDecl.kind === 286 /* ShorthandPropertyAssignment */ ||
64176 ts.isObjectLiteralMethod(memberDecl)) {
64177 var type = memberDecl.kind === 285 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
64178 // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
64179 // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
64180 // we don't want to say "could not find 'a'".
64181 memberDecl.kind === 286 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) :
64182 checkObjectLiteralMethod(memberDecl, checkMode);
64183 if (isInJavascript) {
64184 var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
64185 if (jsDocType) {
64186 checkTypeAssignableTo(type, jsDocType, memberDecl);
64187 type = jsDocType;
64188 }
64189 else if (enumTag && enumTag.typeExpression) {
64190 checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
64191 }
64192 }
64193 objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
64194 var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
64195 var prop = nameType ?
64196 createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
64197 createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
64198 if (nameType) {
64199 prop.nameType = nameType;
64200 }
64201 if (inDestructuringPattern) {
64202 // If object literal is an assignment pattern and if the assignment pattern specifies a default value
64203 // for the property, make the property optional.
64204 var isOptional = (memberDecl.kind === 285 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
64205 (memberDecl.kind === 286 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
64206 if (isOptional) {
64207 prop.flags |= 16777216 /* Optional */;
64208 }
64209 }
64210 else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
64211 // If object literal is contextually typed by the implied type of a binding pattern, and if the
64212 // binding pattern specifies a default value for the property, make the property optional.
64213 var impliedProp = getPropertyOfType(contextualType, member.escapedName);
64214 if (impliedProp) {
64215 prop.flags |= impliedProp.flags & 16777216 /* Optional */;
64216 }
64217 else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
64218 error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
64219 }
64220 }
64221 prop.declarations = member.declarations;
64222 prop.parent = member.parent;
64223 if (member.valueDeclaration) {
64224 prop.valueDeclaration = member.valueDeclaration;
64225 }
64226 prop.type = type;
64227 prop.target = member;
64228 member = prop;
64229 allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
64230 }
64231 else if (memberDecl.kind === 287 /* SpreadAssignment */) {
64232 if (languageVersion < 2 /* ES2015 */) {
64233 checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
64234 }
64235 if (propertiesArray.length > 0) {
64236 spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
64237 propertiesArray = [];
64238 propertiesTable = ts.createSymbolTable();
64239 hasComputedStringProperty = false;
64240 hasComputedNumberProperty = false;
64241 }
64242 var type = getReducedType(checkExpression(memberDecl.expression));
64243 if (!isValidSpreadType(type)) {
64244 error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
64245 return errorType;
64246 }
64247 if (allPropertiesTable) {
64248 checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
64249 }
64250 spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
64251 offset = propertiesArray.length;
64252 continue;
64253 }
64254 else {
64255 // TypeScript 1.0 spec (April 2014)
64256 // A get accessor declaration is processed in the same manner as
64257 // an ordinary function declaration(section 6.1) with no parameters.
64258 // A set accessor declaration is processed in the same manner
64259 // as an ordinary function declaration with a single parameter and a Void return type.
64260 ts.Debug.assert(memberDecl.kind === 166 /* GetAccessor */ || memberDecl.kind === 167 /* SetAccessor */);
64261 checkNodeDeferred(memberDecl);
64262 }
64263 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
64264 if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
64265 if (isTypeAssignableTo(computedNameType, numberType)) {
64266 hasComputedNumberProperty = true;
64267 }
64268 else {
64269 hasComputedStringProperty = true;
64270 }
64271 if (inDestructuringPattern) {
64272 patternWithComputedProperties = true;
64273 }
64274 }
64275 }
64276 else {
64277 propertiesTable.set(member.escapedName, member);
64278 }
64279 propertiesArray.push(member);
64280 }
64281 // If object literal is contextually typed by the implied type of a binding pattern, augment the result
64282 // type with those properties for which the binding pattern specifies a default value.
64283 // If the object literal is spread into another object literal, skip this step and let the top-level object
64284 // literal handle it instead.
64285 if (contextualTypeHasPattern && node.parent.kind !== 287 /* SpreadAssignment */) {
64286 for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) {
64287 var prop = _e[_d];
64288 if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
64289 if (!(prop.flags & 16777216 /* Optional */)) {
64290 error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
64291 }
64292 propertiesTable.set(prop.escapedName, prop);
64293 propertiesArray.push(prop);
64294 }
64295 }
64296 }
64297 if (spread !== emptyObjectType) {
64298 if (propertiesArray.length > 0) {
64299 spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
64300 propertiesArray = [];
64301 propertiesTable = ts.createSymbolTable();
64302 hasComputedStringProperty = false;
64303 hasComputedNumberProperty = false;
64304 }
64305 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
64306 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
64307 }
64308 return createObjectLiteralType();
64309 function createObjectLiteralType() {
64310 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
64311 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
64312 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
64313 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
64314 if (isJSObjectLiteral) {
64315 result.objectFlags |= 16384 /* JSLiteral */;
64316 }
64317 if (patternWithComputedProperties) {
64318 result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
64319 }
64320 if (inDestructuringPattern) {
64321 result.pattern = node;
64322 }
64323 return result;
64324 }
64325 }
64326 function isValidSpreadType(type) {
64327 if (type.flags & 63176704 /* Instantiable */) {
64328 var constraint = getBaseConstraintOfType(type);
64329 if (constraint !== undefined) {
64330 return isValidSpreadType(constraint);
64331 }
64332 }
64333 return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
64334 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
64335 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
64336 }
64337 function checkJsxSelfClosingElementDeferred(node) {
64338 checkJsxOpeningLikeElementOrOpeningFragment(node);
64339 resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
64340 }
64341 function checkJsxSelfClosingElement(node, _checkMode) {
64342 checkNodeDeferred(node);
64343 return getJsxElementTypeAt(node) || anyType;
64344 }
64345 function checkJsxElementDeferred(node) {
64346 // Check attributes
64347 checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
64348 // Perform resolution on the closing tag so that rename/go to definition/etc work
64349 if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
64350 getIntrinsicTagSymbol(node.closingElement);
64351 }
64352 else {
64353 checkExpression(node.closingElement.tagName);
64354 }
64355 checkJsxChildren(node);
64356 }
64357 function checkJsxElement(node, _checkMode) {
64358 checkNodeDeferred(node);
64359 return getJsxElementTypeAt(node) || anyType;
64360 }
64361 function checkJsxFragment(node) {
64362 checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
64363 // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment
64364 // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too
64365 var nodeSourceFile = ts.getSourceFileOfNode(node);
64366 if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx"))
64367 && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
64368 error(node, compilerOptions.jsxFactory
64369 ? ts.Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option
64370 : ts.Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments);
64371 }
64372 checkJsxChildren(node);
64373 return getJsxElementTypeAt(node) || anyType;
64374 }
64375 /**
64376 * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
64377 */
64378 function isUnhyphenatedJsxName(name) {
64379 // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
64380 return !ts.stringContains(name, "-");
64381 }
64382 /**
64383 * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
64384 */
64385 function isJsxIntrinsicIdentifier(tagName) {
64386 return tagName.kind === 78 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
64387 }
64388 function checkJsxAttribute(node, checkMode) {
64389 return node.initializer
64390 ? checkExpressionForMutableLocation(node.initializer, checkMode)
64391 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
64392 }
64393 /**
64394 * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
64395 *
64396 * @param openingLikeElement a JSX opening-like element
64397 * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
64398 * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
64399 * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
64400 * which also calls getSpreadType.
64401 */
64402 function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
64403 var attributes = openingLikeElement.attributes;
64404 var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
64405 var attributesTable = ts.createSymbolTable();
64406 var spread = emptyJsxObjectType;
64407 var hasSpreadAnyType = false;
64408 var typeToIntersect;
64409 var explicitlySpecifyChildrenAttribute = false;
64410 var objectFlags = 4096 /* JsxAttributes */;
64411 var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
64412 for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
64413 var attributeDecl = _a[_i];
64414 var member = attributeDecl.symbol;
64415 if (ts.isJsxAttribute(attributeDecl)) {
64416 var exprType = checkJsxAttribute(attributeDecl, checkMode);
64417 objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
64418 var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
64419 attributeSymbol.declarations = member.declarations;
64420 attributeSymbol.parent = member.parent;
64421 if (member.valueDeclaration) {
64422 attributeSymbol.valueDeclaration = member.valueDeclaration;
64423 }
64424 attributeSymbol.type = exprType;
64425 attributeSymbol.target = member;
64426 attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
64427 allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
64428 if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
64429 explicitlySpecifyChildrenAttribute = true;
64430 }
64431 }
64432 else {
64433 ts.Debug.assert(attributeDecl.kind === 279 /* JsxSpreadAttribute */);
64434 if (attributesTable.size > 0) {
64435 spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
64436 attributesTable = ts.createSymbolTable();
64437 }
64438 var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
64439 if (isTypeAny(exprType)) {
64440 hasSpreadAnyType = true;
64441 }
64442 if (isValidSpreadType(exprType)) {
64443 spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
64444 if (allAttributesTable) {
64445 checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
64446 }
64447 }
64448 else {
64449 typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
64450 }
64451 }
64452 }
64453 if (!hasSpreadAnyType) {
64454 if (attributesTable.size > 0) {
64455 spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
64456 }
64457 }
64458 // Handle children attribute
64459 var parent = openingLikeElement.parent.kind === 270 /* JsxElement */ ? openingLikeElement.parent : undefined;
64460 // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
64461 if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
64462 var childrenTypes = checkJsxChildren(parent, checkMode);
64463 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
64464 // Error if there is a attribute named "children" explicitly specified and children element.
64465 // This is because children element will overwrite the value from attributes.
64466 // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
64467 if (explicitlySpecifyChildrenAttribute) {
64468 error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
64469 }
64470 var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
64471 var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
64472 // 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
64473 var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
64474 childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] :
64475 childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
64476 createArrayType(getUnionType(childrenTypes));
64477 // Fake up a property declaration for the children
64478 childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
64479 ts.setParent(childrenPropSymbol.valueDeclaration, attributes);
64480 childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
64481 var childPropMap = ts.createSymbolTable();
64482 childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
64483 spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
64484 }
64485 }
64486 if (hasSpreadAnyType) {
64487 return anyType;
64488 }
64489 if (typeToIntersect && spread !== emptyJsxObjectType) {
64490 return getIntersectionType([typeToIntersect, spread]);
64491 }
64492 return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
64493 /**
64494 * Create anonymous type from given attributes symbol table.
64495 * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
64496 * @param attributesTable a symbol table of attributes property
64497 */
64498 function createJsxAttributesType() {
64499 objectFlags |= freshObjectLiteralFlag;
64500 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
64501 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
64502 return result;
64503 }
64504 }
64505 function checkJsxChildren(node, checkMode) {
64506 var childrenTypes = [];
64507 for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
64508 var child = _a[_i];
64509 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
64510 // because then type of children property will have constituent of string type.
64511 if (child.kind === 11 /* JsxText */) {
64512 if (!child.containsOnlyTriviaWhiteSpaces) {
64513 childrenTypes.push(stringType);
64514 }
64515 }
64516 else {
64517 childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
64518 }
64519 }
64520 return childrenTypes;
64521 }
64522 function checkSpreadPropOverrides(type, props, spread) {
64523 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
64524 var right = _a[_i];
64525 var left = props.get(right.escapedName);
64526 var rightType = getTypeOfSymbol(right);
64527 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
64528 var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
64529 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
64530 }
64531 }
64532 }
64533 /**
64534 * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
64535 * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
64536 * @param node a JSXAttributes to be resolved of its type
64537 */
64538 function checkJsxAttributes(node, checkMode) {
64539 return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
64540 }
64541 function getJsxType(name, location) {
64542 var namespace = getJsxNamespaceAt(location);
64543 var exports = namespace && getExportsOfSymbol(namespace);
64544 var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
64545 return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
64546 }
64547 /**
64548 * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
64549 * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
64550 * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
64551 * May also return unknownSymbol if both of these lookups fail.
64552 */
64553 function getIntrinsicTagSymbol(node) {
64554 var links = getNodeLinks(node);
64555 if (!links.resolvedSymbol) {
64556 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
64557 if (intrinsicElementsType !== errorType) {
64558 // Property case
64559 if (!ts.isIdentifier(node.tagName))
64560 return ts.Debug.fail();
64561 var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
64562 if (intrinsicProp) {
64563 links.jsxFlags |= 1 /* IntrinsicNamedElement */;
64564 return links.resolvedSymbol = intrinsicProp;
64565 }
64566 // Intrinsic string indexer case
64567 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
64568 if (indexSignatureType) {
64569 links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
64570 return links.resolvedSymbol = intrinsicElementsType.symbol;
64571 }
64572 // Wasn't found
64573 error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
64574 return links.resolvedSymbol = unknownSymbol;
64575 }
64576 else {
64577 if (noImplicitAny) {
64578 error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
64579 }
64580 return links.resolvedSymbol = unknownSymbol;
64581 }
64582 }
64583 return links.resolvedSymbol;
64584 }
64585 function getJsxNamespaceAt(location) {
64586 var links = location && getNodeLinks(location);
64587 if (links && links.jsxNamespace) {
64588 return links.jsxNamespace;
64589 }
64590 if (!links || links.jsxNamespace !== false) {
64591 var namespaceName = getJsxNamespace(location);
64592 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
64593 if (resolvedNamespace) {
64594 var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
64595 if (candidate) {
64596 if (links) {
64597 links.jsxNamespace = candidate;
64598 }
64599 return candidate;
64600 }
64601 if (links) {
64602 links.jsxNamespace = false;
64603 }
64604 }
64605 }
64606 // JSX global fallback
64607 return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
64608 }
64609 /**
64610 * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
64611 * Get a single property from that container if existed. Report an error if there are more than one property.
64612 *
64613 * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
64614 * if other string is given or the container doesn't exist, return undefined.
64615 */
64616 function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
64617 // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
64618 var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
64619 // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
64620 var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
64621 // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
64622 var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
64623 if (propertiesOfJsxElementAttribPropInterface) {
64624 // Element Attributes has zero properties, so the element attributes type will be the class instance type
64625 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
64626 return "";
64627 }
64628 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
64629 // property of the class instance type
64630 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
64631 return propertiesOfJsxElementAttribPropInterface[0].escapedName;
64632 }
64633 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
64634 // More than one property on ElementAttributesProperty is an error
64635 error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
64636 }
64637 }
64638 return undefined;
64639 }
64640 function getJsxLibraryManagedAttributes(jsxNamespace) {
64641 // JSX.LibraryManagedAttributes [symbol]
64642 return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
64643 }
64644 /// e.g. "props" for React.d.ts,
64645 /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
64646 /// non-intrinsic elements' attributes type is 'any'),
64647 /// or '' if it has 0 properties (which means every
64648 /// non-intrinsic elements' attributes type is the element instance type)
64649 function getJsxElementPropertiesName(jsxNamespace) {
64650 return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
64651 }
64652 function getJsxElementChildrenPropertyName(jsxNamespace) {
64653 return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
64654 }
64655 function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
64656 if (elementType.flags & 4 /* String */) {
64657 return [anySignature];
64658 }
64659 else if (elementType.flags & 128 /* StringLiteral */) {
64660 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
64661 if (!intrinsicType) {
64662 error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
64663 return ts.emptyArray;
64664 }
64665 else {
64666 var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
64667 return [fakeSignature];
64668 }
64669 }
64670 var apparentElemType = getApparentType(elementType);
64671 // Resolve the signatures, preferring constructor
64672 var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
64673 if (signatures.length === 0) {
64674 // No construct signatures, try call signatures
64675 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
64676 }
64677 if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
64678 // If each member has some combination of new/call signatures; make a union signature list for those
64679 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
64680 }
64681 return signatures;
64682 }
64683 function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
64684 // 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
64685 // For example:
64686 // var CustomTag: "h1" = "h1";
64687 // <CustomTag> Hello World </CustomTag>
64688 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
64689 if (intrinsicElementsType !== errorType) {
64690 var stringLiteralTypeName = type.value;
64691 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
64692 if (intrinsicProp) {
64693 return getTypeOfSymbol(intrinsicProp);
64694 }
64695 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
64696 if (indexSignatureType) {
64697 return indexSignatureType;
64698 }
64699 return undefined;
64700 }
64701 // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
64702 return anyType;
64703 }
64704 function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
64705 if (refKind === 1 /* Function */) {
64706 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
64707 if (sfcReturnConstraint) {
64708 checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
64709 }
64710 }
64711 else if (refKind === 0 /* Component */) {
64712 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
64713 if (classConstraint) {
64714 // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
64715 checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
64716 }
64717 }
64718 else { // Mixed
64719 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
64720 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
64721 if (!sfcReturnConstraint || !classConstraint) {
64722 return;
64723 }
64724 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
64725 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
64726 }
64727 function generateInitialErrorChain() {
64728 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
64729 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
64730 }
64731 }
64732 /**
64733 * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
64734 * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
64735 * @param node an intrinsic JSX opening-like element
64736 */
64737 function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
64738 ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
64739 var links = getNodeLinks(node);
64740 if (!links.resolvedJsxElementAttributesType) {
64741 var symbol = getIntrinsicTagSymbol(node);
64742 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
64743 return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
64744 }
64745 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
64746 return links.resolvedJsxElementAttributesType =
64747 getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
64748 }
64749 else {
64750 return links.resolvedJsxElementAttributesType = errorType;
64751 }
64752 }
64753 return links.resolvedJsxElementAttributesType;
64754 }
64755 function getJsxElementClassTypeAt(location) {
64756 var type = getJsxType(JsxNames.ElementClass, location);
64757 if (type === errorType)
64758 return undefined;
64759 return type;
64760 }
64761 function getJsxElementTypeAt(location) {
64762 return getJsxType(JsxNames.Element, location);
64763 }
64764 function getJsxStatelessElementTypeAt(location) {
64765 var jsxElementType = getJsxElementTypeAt(location);
64766 if (jsxElementType) {
64767 return getUnionType([jsxElementType, nullType]);
64768 }
64769 }
64770 /**
64771 * Returns all the properties of the Jsx.IntrinsicElements interface
64772 */
64773 function getJsxIntrinsicTagNamesAt(location) {
64774 var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
64775 return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
64776 }
64777 function checkJsxPreconditions(errorNode) {
64778 // Preconditions for using JSX
64779 if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
64780 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
64781 }
64782 if (getJsxElementTypeAt(errorNode) === undefined) {
64783 if (noImplicitAny) {
64784 error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
64785 }
64786 }
64787 }
64788 function checkJsxOpeningLikeElementOrOpeningFragment(node) {
64789 var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
64790 if (isNodeOpeningLikeElement) {
64791 checkGrammarJsxElement(node);
64792 }
64793 checkJsxPreconditions(node);
64794 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
64795 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
64796 var jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
64797 var jsxFactoryNamespace = getJsxNamespace(node);
64798 var jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node;
64799 // allow null as jsxFragmentFactory
64800 var jsxFactorySym;
64801 if (!(ts.isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
64802 jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true);
64803 }
64804 if (jsxFactorySym) {
64805 // Mark local symbol as referenced here because it might not have been marked
64806 // if jsx emit was not jsxFactory as there wont be error being emitted
64807 jsxFactorySym.isReferenced = 67108863 /* All */;
64808 // If react/jsxFactory symbol is alias, mark it as refereced
64809 if (jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
64810 markAliasSymbolAsReferenced(jsxFactorySym);
64811 }
64812 }
64813 if (isNodeOpeningLikeElement) {
64814 var jsxOpeningLikeNode = node;
64815 var sig = getResolvedSignature(jsxOpeningLikeNode);
64816 checkDeprecatedSignature(sig, node);
64817 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
64818 }
64819 }
64820 /**
64821 * Check if a property with the given name is known anywhere in the given type. In an object type, a property
64822 * is considered known if
64823 * 1. the object type is empty and the check is for assignability, or
64824 * 2. if the object type has index signatures, or
64825 * 3. if the property is actually declared in the object type
64826 * (this means that 'toString', for example, is not usually a known property).
64827 * 4. In a union or intersection type,
64828 * a property is considered known if it is known in any constituent type.
64829 * @param targetType a type to search a given name in
64830 * @param name a property name to search
64831 * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
64832 */
64833 function isKnownProperty(targetType, name, isComparingJsxAttributes) {
64834 if (targetType.flags & 524288 /* Object */) {
64835 var resolved = resolveStructuredTypeMembers(targetType);
64836 if (resolved.stringIndexInfo ||
64837 resolved.numberIndexInfo && isNumericLiteralName(name) ||
64838 getPropertyOfObjectType(targetType, name) ||
64839 isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
64840 // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
64841 return true;
64842 }
64843 }
64844 else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
64845 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
64846 var t = _a[_i];
64847 if (isKnownProperty(t, name, isComparingJsxAttributes)) {
64848 return true;
64849 }
64850 }
64851 }
64852 return false;
64853 }
64854 function isExcessPropertyCheckTarget(type) {
64855 return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
64856 type.flags & 67108864 /* NonPrimitive */ ||
64857 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
64858 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
64859 }
64860 function checkJsxExpression(node, checkMode) {
64861 checkGrammarJsxExpression(node);
64862 if (node.expression) {
64863 var type = checkExpression(node.expression, checkMode);
64864 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
64865 error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
64866 }
64867 return type;
64868 }
64869 else {
64870 return errorType;
64871 }
64872 }
64873 function getDeclarationNodeFlagsFromSymbol(s) {
64874 return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
64875 }
64876 /**
64877 * Return whether this symbol is a member of a prototype somewhere
64878 * Note that this is not tracked well within the compiler, so the answer may be incorrect.
64879 */
64880 function isPrototypeProperty(symbol) {
64881 if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
64882 return true;
64883 }
64884 if (ts.isInJSFile(symbol.valueDeclaration)) {
64885 var parent = symbol.valueDeclaration.parent;
64886 return parent && ts.isBinaryExpression(parent) &&
64887 ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
64888 }
64889 }
64890 /**
64891 * Check whether the requested property access is valid.
64892 * Returns true if node is a valid property access, and false otherwise.
64893 * @param node The node to be checked.
64894 * @param isSuper True if the access is from `super.`.
64895 * @param type The type of the object whose property is being accessed. (Not the type of the property.)
64896 * @param prop The symbol for the property being accessed.
64897 */
64898 function checkPropertyAccessibility(node, isSuper, type, prop) {
64899 var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
64900 var errorNode = node.kind === 156 /* QualifiedName */ ? node.right : node.kind === 192 /* ImportType */ ? node : node.name;
64901 if (isSuper) {
64902 // TS 1.0 spec (April 2014): 4.8.2
64903 // - In a constructor, instance member function, instance member accessor, or
64904 // instance member variable initializer where this references a derived class instance,
64905 // a super property access is permitted and must specify a public instance member function of the base class.
64906 // - In a static member function or static member accessor
64907 // where this references the constructor function object of a derived class,
64908 // a super property access is permitted and must specify a public static member function of the base class.
64909 if (languageVersion < 2 /* ES2015 */) {
64910 if (symbolHasNonMethodDeclaration(prop)) {
64911 error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
64912 return false;
64913 }
64914 }
64915 if (flags & 128 /* Abstract */) {
64916 // A method cannot be accessed in a super property access if the method is abstract.
64917 // This error could mask a private property access error. But, a member
64918 // cannot simultaneously be private and abstract, so this will trigger an
64919 // additional error elsewhere.
64920 error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
64921 return false;
64922 }
64923 }
64924 // Referencing abstract properties within their own constructors is not allowed
64925 if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
64926 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
64927 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
64928 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
64929 return false;
64930 }
64931 }
64932 if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
64933 if (!ts.getContainingClass(node)) {
64934 error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
64935 return false;
64936 }
64937 return true;
64938 }
64939 // Public properties are otherwise accessible.
64940 if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
64941 return true;
64942 }
64943 // Property is known to be private or protected at this point
64944 // Private property is accessible if the property is within the declaring class
64945 if (flags & 8 /* Private */) {
64946 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
64947 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
64948 error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
64949 return false;
64950 }
64951 return true;
64952 }
64953 // Property is known to be protected at this point
64954 // All protected properties of a supertype are accessible in a super access
64955 if (isSuper) {
64956 return true;
64957 }
64958 // Find the first enclosing class that has the declaring classes of the protected constituents
64959 // of the property as base classes
64960 var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
64961 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
64962 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
64963 });
64964 // A protected property is accessible if the property is within the declaring class or classes derived from it
64965 if (!enclosingClass) {
64966 // allow PropertyAccessibility if context is in function with this parameter
64967 // static member access is disallow
64968 var thisParameter = void 0;
64969 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
64970 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
64971 return false;
64972 }
64973 var thisType = getTypeFromTypeNode(thisParameter.type);
64974 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
64975 }
64976 // No further restrictions for static properties
64977 if (flags & 32 /* Static */) {
64978 return true;
64979 }
64980 if (type.flags & 262144 /* TypeParameter */) {
64981 // get the original type -- represented as the type constraint of the 'this' type
64982 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
64983 }
64984 if (!type || !hasBaseType(type, enclosingClass)) {
64985 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
64986 return false;
64987 }
64988 return true;
64989 }
64990 function getThisParameterFromNodeContext(node) {
64991 var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
64992 return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
64993 }
64994 function symbolHasNonMethodDeclaration(symbol) {
64995 return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
64996 }
64997 function checkNonNullExpression(node) {
64998 return checkNonNullType(checkExpression(node), node);
64999 }
65000 function isNullableType(type) {
65001 return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
65002 }
65003 function getNonNullableTypeIfNeeded(type) {
65004 return isNullableType(type) ? getNonNullableType(type) : type;
65005 }
65006 function reportObjectPossiblyNullOrUndefinedError(node, flags) {
65007 error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
65008 ts.Diagnostics.Object_is_possibly_null_or_undefined :
65009 ts.Diagnostics.Object_is_possibly_undefined :
65010 ts.Diagnostics.Object_is_possibly_null);
65011 }
65012 function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
65013 error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
65014 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
65015 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
65016 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
65017 }
65018 function checkNonNullTypeWithReporter(type, node, reportError) {
65019 if (strictNullChecks && type.flags & 2 /* Unknown */) {
65020 error(node, ts.Diagnostics.Object_is_of_type_unknown);
65021 return errorType;
65022 }
65023 var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
65024 if (kind) {
65025 reportError(node, kind);
65026 var t = getNonNullableType(type);
65027 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
65028 }
65029 return type;
65030 }
65031 function checkNonNullType(type, node) {
65032 return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
65033 }
65034 function checkNonNullNonVoidType(type, node) {
65035 var nonNullType = checkNonNullType(type, node);
65036 if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
65037 error(node, ts.Diagnostics.Object_is_possibly_undefined);
65038 }
65039 return nonNullType;
65040 }
65041 function checkPropertyAccessExpression(node) {
65042 return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
65043 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
65044 }
65045 function checkPropertyAccessChain(node) {
65046 var leftType = checkExpression(node.expression);
65047 var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
65048 return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
65049 }
65050 function checkQualifiedName(node) {
65051 return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
65052 }
65053 function isMethodAccessForCall(node) {
65054 while (node.parent.kind === 204 /* ParenthesizedExpression */) {
65055 node = node.parent;
65056 }
65057 return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
65058 }
65059 // Lookup the private identifier lexically.
65060 function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
65061 for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
65062 var symbol = containingClass.symbol;
65063 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
65064 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
65065 if (prop) {
65066 return prop;
65067 }
65068 }
65069 }
65070 function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
65071 return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
65072 }
65073 function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
65074 // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
65075 // Find a private identifier with the same description on the type.
65076 var propertyOnType;
65077 var properties = getPropertiesOfType(leftType);
65078 if (properties) {
65079 ts.forEach(properties, function (symbol) {
65080 var decl = symbol.valueDeclaration;
65081 if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
65082 propertyOnType = symbol;
65083 return true;
65084 }
65085 });
65086 }
65087 var diagName = diagnosticName(right);
65088 if (propertyOnType) {
65089 var typeValueDecl = propertyOnType.valueDeclaration;
65090 var typeClass_1 = ts.getContainingClass(typeValueDecl);
65091 ts.Debug.assert(!!typeClass_1);
65092 // We found a private identifier property with the same description.
65093 // Either:
65094 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
65095 // - It is an attempt to access the private identifier outside of the class.
65096 if (lexicallyScopedIdentifier) {
65097 var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
65098 var lexicalClass = ts.getContainingClass(lexicalValueDecl);
65099 ts.Debug.assert(!!lexicalClass);
65100 if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
65101 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));
65102 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));
65103 return true;
65104 }
65105 }
65106 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
65107 return true;
65108 }
65109 return false;
65110 }
65111 function isThisPropertyAccessInConstructor(node, prop) {
65112 return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop);
65113 }
65114 function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
65115 var _a;
65116 var parentSymbol = getNodeLinks(left).resolvedSymbol;
65117 var assignmentKind = ts.getAssignmentTargetKind(node);
65118 var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
65119 if (ts.isPrivateIdentifier(right)) {
65120 checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldGet */);
65121 }
65122 var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
65123 var prop;
65124 if (ts.isPrivateIdentifier(right)) {
65125 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
65126 if (isAnyLike) {
65127 if (lexicallyScopedSymbol) {
65128 return apparentType;
65129 }
65130 if (!ts.getContainingClass(right)) {
65131 grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
65132 return anyType;
65133 }
65134 }
65135 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
65136 // Check for private-identifier-specific shadowing and lexical-scoping errors.
65137 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
65138 return errorType;
65139 }
65140 }
65141 else {
65142 if (isAnyLike) {
65143 if (ts.isIdentifier(left) && parentSymbol) {
65144 markAliasReferenced(parentSymbol, node);
65145 }
65146 return apparentType;
65147 }
65148 prop = getPropertyOfType(apparentType, right.escapedText);
65149 }
65150 if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
65151 markAliasReferenced(parentSymbol, node);
65152 }
65153 var propType;
65154 if (!prop) {
65155 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
65156 if (!(indexInfo && indexInfo.type)) {
65157 if (isJSLiteralType(leftType)) {
65158 return anyType;
65159 }
65160 if (leftType.symbol === globalThisSymbol) {
65161 if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
65162 error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
65163 }
65164 else if (noImplicitAny) {
65165 error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
65166 }
65167 return anyType;
65168 }
65169 if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
65170 reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
65171 }
65172 return errorType;
65173 }
65174 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
65175 error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
65176 }
65177 propType = indexInfo.type;
65178 }
65179 else {
65180 if (((_a = prop.valueDeclaration) === null || _a === void 0 ? void 0 : _a.flags) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
65181 errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText);
65182 }
65183 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
65184 markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */);
65185 getNodeLinks(node).resolvedSymbol = prop;
65186 checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop);
65187 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
65188 error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
65189 return errorType;
65190 }
65191 propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node);
65192 }
65193 return getFlowTypeOfAccessExpression(node, prop, propType, right);
65194 }
65195 function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
65196 // Only compute control flow type if this is a property access expression that isn't an
65197 // assignment target, and the referenced property was declared as a variable, property,
65198 // accessor, or optional method.
65199 var assignmentKind = ts.getAssignmentTargetKind(node);
65200 if (!ts.isAccessExpression(node) ||
65201 assignmentKind === 1 /* Definite */ ||
65202 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
65203 return propType;
65204 }
65205 if (propType === autoType) {
65206 return getFlowTypeOfProperty(node, prop);
65207 }
65208 // If strict null checks and strict property initialization checks are enabled, if we have
65209 // a this.xxx property access, if the property is an instance property without an initializer,
65210 // and if we are in a constructor of the same class as the property declaration, assume that
65211 // the property is uninitialized at the top of the control flow.
65212 var assumeUninitialized = false;
65213 if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) {
65214 var declaration = prop && prop.valueDeclaration;
65215 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
65216 var flowContainer = getControlFlowContainer(node);
65217 if (flowContainer.kind === 165 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
65218 assumeUninitialized = true;
65219 }
65220 }
65221 }
65222 else if (strictNullChecks && prop && prop.valueDeclaration &&
65223 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
65224 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
65225 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
65226 assumeUninitialized = true;
65227 }
65228 var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
65229 if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
65230 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
65231 // Return the declared type to reduce follow-on errors
65232 return propType;
65233 }
65234 return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
65235 }
65236 function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
65237 var valueDeclaration = prop.valueDeclaration;
65238 if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
65239 return;
65240 }
65241 var diagnosticMessage;
65242 var declarationName = ts.idText(right);
65243 if (isInPropertyInitializer(node)
65244 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
65245 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
65246 && !isPropertyDeclaredInAncestorClass(prop)) {
65247 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
65248 }
65249 else if (valueDeclaration.kind === 249 /* ClassDeclaration */ &&
65250 node.parent.kind !== 172 /* TypeReference */ &&
65251 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
65252 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
65253 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
65254 }
65255 if (diagnosticMessage) {
65256 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
65257 }
65258 }
65259 function isInPropertyInitializer(node) {
65260 return !!ts.findAncestor(node, function (node) {
65261 switch (node.kind) {
65262 case 162 /* PropertyDeclaration */:
65263 return true;
65264 case 285 /* PropertyAssignment */:
65265 case 164 /* MethodDeclaration */:
65266 case 166 /* GetAccessor */:
65267 case 167 /* SetAccessor */:
65268 case 287 /* SpreadAssignment */:
65269 case 157 /* ComputedPropertyName */:
65270 case 225 /* TemplateSpan */:
65271 case 280 /* JsxExpression */:
65272 case 277 /* JsxAttribute */:
65273 case 278 /* JsxAttributes */:
65274 case 279 /* JsxSpreadAttribute */:
65275 case 272 /* JsxOpeningElement */:
65276 case 220 /* ExpressionWithTypeArguments */:
65277 case 283 /* HeritageClause */:
65278 return false;
65279 default:
65280 return ts.isExpressionNode(node) ? false : "quit";
65281 }
65282 });
65283 }
65284 /**
65285 * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
65286 * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
65287 */
65288 function isPropertyDeclaredInAncestorClass(prop) {
65289 if (!(prop.parent.flags & 32 /* Class */)) {
65290 return false;
65291 }
65292 var classType = getTypeOfSymbol(prop.parent);
65293 while (true) {
65294 classType = classType.symbol && getSuperClass(classType);
65295 if (!classType) {
65296 return false;
65297 }
65298 var superProperty = getPropertyOfType(classType, prop.escapedName);
65299 if (superProperty && superProperty.valueDeclaration) {
65300 return true;
65301 }
65302 }
65303 }
65304 function getSuperClass(classType) {
65305 var x = getBaseTypes(classType);
65306 if (x.length === 0) {
65307 return undefined;
65308 }
65309 return getIntersectionType(x);
65310 }
65311 function reportNonexistentProperty(propNode, containingType) {
65312 var errorInfo;
65313 var relatedInfo;
65314 if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
65315 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
65316 var subtype = _a[_i];
65317 if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
65318 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
65319 break;
65320 }
65321 }
65322 }
65323 if (typeHasStaticProperty(propNode.escapedText, containingType)) {
65324 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
65325 }
65326 else {
65327 var promisedType = getPromisedTypeOfPromise(containingType);
65328 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
65329 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
65330 relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
65331 }
65332 else {
65333 var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
65334 if (suggestion !== undefined) {
65335 var suggestedName = ts.symbolName(suggestion);
65336 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
65337 relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
65338 }
65339 else {
65340 errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
65341 }
65342 }
65343 }
65344 var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
65345 if (relatedInfo) {
65346 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
65347 }
65348 diagnostics.add(resultDiagnostic);
65349 }
65350 function typeHasStaticProperty(propName, containingType) {
65351 var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
65352 return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */);
65353 }
65354 function getSuggestedSymbolForNonexistentProperty(name, containingType) {
65355 return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
65356 }
65357 function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
65358 var strName = ts.isString(name) ? name : ts.idText(name);
65359 var properties = getPropertiesOfType(containingType);
65360 var jsxSpecific = strName === "for" ? ts.find(properties, function (x) { return ts.symbolName(x) === "htmlFor"; })
65361 : strName === "class" ? ts.find(properties, function (x) { return ts.symbolName(x) === "className"; })
65362 : undefined;
65363 return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
65364 }
65365 function getSuggestionForNonexistentProperty(name, containingType) {
65366 var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
65367 return suggestion && ts.symbolName(suggestion);
65368 }
65369 function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
65370 ts.Debug.assert(outerName !== undefined, "outername should always be defined");
65371 var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
65372 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
65373 var symbol = getSymbol(symbols, name, meaning);
65374 // 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
65375 // So the table *contains* `x` but `x` isn't actually in scope.
65376 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
65377 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
65378 });
65379 return result;
65380 }
65381 function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
65382 var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
65383 return symbolResult && ts.symbolName(symbolResult);
65384 }
65385 function getSuggestedSymbolForNonexistentModule(name, targetModule) {
65386 return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
65387 }
65388 function getSuggestionForNonexistentExport(name, targetModule) {
65389 var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
65390 return suggestion && ts.symbolName(suggestion);
65391 }
65392 function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
65393 // check if object type has setter or getter
65394 function hasProp(name) {
65395 var prop = getPropertyOfObjectType(objectType, name);
65396 if (prop) {
65397 var s = getSingleCallSignature(getTypeOfSymbol(prop));
65398 return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
65399 }
65400 return false;
65401 }
65402 ;
65403 var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
65404 if (!hasProp(suggestedMethod)) {
65405 return undefined;
65406 }
65407 var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
65408 if (suggestion === undefined) {
65409 suggestion = suggestedMethod;
65410 }
65411 else {
65412 suggestion += "." + suggestedMethod;
65413 }
65414 return suggestion;
65415 }
65416 /**
65417 * 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.
65418 * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
65419 *
65420 * If there is a candidate that's the same except for case, return that.
65421 * If there is a candidate that's within one edit of the name, return that.
65422 * Otherwise, return the candidate with the smallest Levenshtein distance,
65423 * except for candidates:
65424 * * With no name
65425 * * Whose meaning doesn't match the `meaning` parameter.
65426 * * Whose length differs from the target name by more than 0.34 of the length of the name.
65427 * * Whose levenshtein distance is more than 0.4 of the length of the name
65428 * (0.4 allows 1 substitution/transposition for every 5 characters,
65429 * and 1 insertion/deletion at 3 characters)
65430 */
65431 function getSpellingSuggestionForName(name, symbols, meaning) {
65432 return ts.getSpellingSuggestion(name, symbols, getCandidateName);
65433 function getCandidateName(candidate) {
65434 var candidateName = ts.symbolName(candidate);
65435 if (ts.startsWith(candidateName, "\"")) {
65436 return undefined;
65437 }
65438 if (candidate.flags & meaning) {
65439 return candidateName;
65440 }
65441 if (candidate.flags & 2097152 /* Alias */) {
65442 var alias = tryResolveAlias(candidate);
65443 if (alias && alias.flags & meaning) {
65444 return candidateName;
65445 }
65446 }
65447 return undefined;
65448 }
65449 }
65450 function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
65451 var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
65452 if (!valueDeclaration) {
65453 return;
65454 }
65455 var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */);
65456 var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
65457 if (!hasPrivateModifier && !hasPrivateIdentifier) {
65458 return;
65459 }
65460 if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
65461 return;
65462 }
65463 if (isThisAccess) {
65464 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
65465 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
65466 if (containingMethod && containingMethod.symbol === prop) {
65467 return;
65468 }
65469 }
65470 (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
65471 }
65472 function isValidPropertyAccess(node, propertyName) {
65473 switch (node.kind) {
65474 case 198 /* PropertyAccessExpression */:
65475 return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
65476 case 156 /* QualifiedName */:
65477 return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
65478 case 192 /* ImportType */:
65479 return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
65480 }
65481 }
65482 function isValidPropertyAccessForCompletions(node, type, property) {
65483 return isValidPropertyAccessWithType(node, node.kind === 198 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type);
65484 // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
65485 }
65486 function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
65487 if (type === errorType || isTypeAny(type)) {
65488 return true;
65489 }
65490 var prop = getPropertyOfType(type, propertyName);
65491 if (prop) {
65492 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
65493 var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
65494 return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
65495 }
65496 return checkPropertyAccessibility(node, isSuper, type, prop);
65497 }
65498 // In js files properties of unions are allowed in completion
65499 return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
65500 }
65501 /**
65502 * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
65503 */
65504 function getForInVariableSymbol(node) {
65505 var initializer = node.initializer;
65506 if (initializer.kind === 247 /* VariableDeclarationList */) {
65507 var variable = initializer.declarations[0];
65508 if (variable && !ts.isBindingPattern(variable.name)) {
65509 return getSymbolOfNode(variable);
65510 }
65511 }
65512 else if (initializer.kind === 78 /* Identifier */) {
65513 return getResolvedSymbol(initializer);
65514 }
65515 return undefined;
65516 }
65517 /**
65518 * Return true if the given type is considered to have numeric property names.
65519 */
65520 function hasNumericPropertyNames(type) {
65521 return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
65522 }
65523 /**
65524 * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
65525 * that references a for-in variable for an object with numeric property names.
65526 */
65527 function isForInVariableForNumericPropertyNames(expr) {
65528 var e = ts.skipParentheses(expr);
65529 if (e.kind === 78 /* Identifier */) {
65530 var symbol = getResolvedSymbol(e);
65531 if (symbol.flags & 3 /* Variable */) {
65532 var child = expr;
65533 var node = expr.parent;
65534 while (node) {
65535 if (node.kind === 235 /* ForInStatement */ &&
65536 child === node.statement &&
65537 getForInVariableSymbol(node) === symbol &&
65538 hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
65539 return true;
65540 }
65541 child = node;
65542 node = node.parent;
65543 }
65544 }
65545 }
65546 return false;
65547 }
65548 function checkIndexedAccess(node) {
65549 return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
65550 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
65551 }
65552 function checkElementAccessChain(node) {
65553 var exprType = checkExpression(node.expression);
65554 var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
65555 return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
65556 }
65557 function checkElementAccessExpression(node, exprType) {
65558 var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
65559 var indexExpression = node.argumentExpression;
65560 var indexType = checkExpression(indexExpression);
65561 if (objectType === errorType || objectType === silentNeverType) {
65562 return objectType;
65563 }
65564 if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
65565 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
65566 return errorType;
65567 }
65568 var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
65569 var accessFlags = ts.isAssignmentTarget(node) ?
65570 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
65571 0 /* None */;
65572 var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
65573 return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
65574 }
65575 function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
65576 if (expressionType === errorType) {
65577 // There is already an error, so no need to report one.
65578 return false;
65579 }
65580 if (!ts.isWellKnownSymbolSyntactically(expression)) {
65581 return false;
65582 }
65583 // Make sure the property type is the primitive symbol type
65584 if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
65585 if (reportError) {
65586 error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
65587 }
65588 return false;
65589 }
65590 // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
65591 // global Symbol object
65592 var leftHandSide = expression.expression;
65593 var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
65594 if (!leftHandSideSymbol) {
65595 return false;
65596 }
65597 var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
65598 if (!globalESSymbol) {
65599 // Already errored when we tried to look up the symbol
65600 return false;
65601 }
65602 if (leftHandSideSymbol !== globalESSymbol) {
65603 if (reportError) {
65604 error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
65605 }
65606 return false;
65607 }
65608 return true;
65609 }
65610 function callLikeExpressionMayHaveTypeArguments(node) {
65611 return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
65612 }
65613 function resolveUntypedCall(node) {
65614 if (callLikeExpressionMayHaveTypeArguments(node)) {
65615 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
65616 // This gets us diagnostics for the type arguments and marks them as referenced.
65617 ts.forEach(node.typeArguments, checkSourceElement);
65618 }
65619 if (node.kind === 202 /* TaggedTemplateExpression */) {
65620 checkExpression(node.template);
65621 }
65622 else if (ts.isJsxOpeningLikeElement(node)) {
65623 checkExpression(node.attributes);
65624 }
65625 else if (node.kind !== 160 /* Decorator */) {
65626 ts.forEach(node.arguments, function (argument) {
65627 checkExpression(argument);
65628 });
65629 }
65630 return anySignature;
65631 }
65632 function resolveErrorCall(node) {
65633 resolveUntypedCall(node);
65634 return unknownSignature;
65635 }
65636 // Re-order candidate signatures into the result array. Assumes the result array to be empty.
65637 // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
65638 // A nit here is that we reorder only signatures that belong to the same symbol,
65639 // so order how inherited signatures are processed is still preserved.
65640 // interface A { (x: string): void }
65641 // interface B extends A { (x: 'foo'): string }
65642 // const b: B;
65643 // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
65644 function reorderCandidates(signatures, result, callChainFlags) {
65645 var lastParent;
65646 var lastSymbol;
65647 var cutoffIndex = 0;
65648 var index;
65649 var specializedIndex = -1;
65650 var spliceIndex;
65651 ts.Debug.assert(!result.length);
65652 for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
65653 var signature = signatures_7[_i];
65654 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
65655 var parent = signature.declaration && signature.declaration.parent;
65656 if (!lastSymbol || symbol === lastSymbol) {
65657 if (lastParent && parent === lastParent) {
65658 index = index + 1;
65659 }
65660 else {
65661 lastParent = parent;
65662 index = cutoffIndex;
65663 }
65664 }
65665 else {
65666 // current declaration belongs to a different symbol
65667 // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
65668 index = cutoffIndex = result.length;
65669 lastParent = parent;
65670 }
65671 lastSymbol = symbol;
65672 // specialized signatures always need to be placed before non-specialized signatures regardless
65673 // of the cutoff position; see GH#1133
65674 if (signatureHasLiteralTypes(signature)) {
65675 specializedIndex++;
65676 spliceIndex = specializedIndex;
65677 // The cutoff index always needs to be greater than or equal to the specialized signature index
65678 // in order to prevent non-specialized signatures from being added before a specialized
65679 // signature.
65680 cutoffIndex++;
65681 }
65682 else {
65683 spliceIndex = index;
65684 }
65685 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
65686 }
65687 }
65688 function isSpreadArgument(arg) {
65689 return !!arg && (arg.kind === 217 /* SpreadElement */ || arg.kind === 224 /* SyntheticExpression */ && arg.isSpread);
65690 }
65691 function getSpreadArgumentIndex(args) {
65692 return ts.findIndex(args, isSpreadArgument);
65693 }
65694 function acceptsVoid(t) {
65695 return !!(t.flags & 16384 /* Void */);
65696 }
65697 function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
65698 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
65699 var argCount;
65700 var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
65701 var effectiveParameterCount = getParameterCount(signature);
65702 var effectiveMinimumArguments = getMinArgumentCount(signature);
65703 if (node.kind === 202 /* TaggedTemplateExpression */) {
65704 argCount = args.length;
65705 if (node.template.kind === 215 /* TemplateExpression */) {
65706 // If a tagged template expression lacks a tail literal, the call is incomplete.
65707 // Specifically, a template only can end in a TemplateTail or a Missing literal.
65708 var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
65709 callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
65710 }
65711 else {
65712 // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
65713 // then this might actually turn out to be a TemplateHead in the future;
65714 // so we consider the call to be incomplete.
65715 var templateLiteral = node.template;
65716 ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
65717 callIsIncomplete = !!templateLiteral.isUnterminated;
65718 }
65719 }
65720 else if (node.kind === 160 /* Decorator */) {
65721 argCount = getDecoratorArgumentCount(node, signature);
65722 }
65723 else if (ts.isJsxOpeningLikeElement(node)) {
65724 callIsIncomplete = node.attributes.end === node.end;
65725 if (callIsIncomplete) {
65726 return true;
65727 }
65728 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
65729 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
65730 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
65731 }
65732 else if (!node.arguments) {
65733 // This only happens when we have something of the form: 'new C'
65734 ts.Debug.assert(node.kind === 201 /* NewExpression */);
65735 return getMinArgumentCount(signature) === 0;
65736 }
65737 else {
65738 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
65739 // If we are missing the close parenthesis, the call is incomplete.
65740 callIsIncomplete = node.arguments.end === node.end;
65741 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
65742 var spreadArgIndex = getSpreadArgumentIndex(args);
65743 if (spreadArgIndex >= 0) {
65744 return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
65745 }
65746 }
65747 // Too many arguments implies incorrect arity.
65748 if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
65749 return false;
65750 }
65751 // If the call is incomplete, we should skip the lower bound check.
65752 // JSX signatures can have extra parameters provided by the library which we don't check
65753 if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
65754 return true;
65755 }
65756 for (var i = argCount; i < effectiveMinimumArguments; i++) {
65757 var type = getTypeAtPosition(signature, i);
65758 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
65759 return false;
65760 }
65761 }
65762 return true;
65763 }
65764 function hasCorrectTypeArgumentArity(signature, typeArguments) {
65765 // If the user supplied type arguments, but the number of type arguments does not match
65766 // the declared number of type parameters, the call has an incorrect arity.
65767 var numTypeParameters = ts.length(signature.typeParameters);
65768 var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
65769 return !ts.some(typeArguments) ||
65770 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
65771 }
65772 // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
65773 function getSingleCallSignature(type) {
65774 return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
65775 }
65776 function getSingleCallOrConstructSignature(type) {
65777 return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
65778 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
65779 }
65780 function getSingleSignature(type, kind, allowMembers) {
65781 if (type.flags & 524288 /* Object */) {
65782 var resolved = resolveStructuredTypeMembers(type);
65783 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
65784 if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
65785 return resolved.callSignatures[0];
65786 }
65787 if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
65788 return resolved.constructSignatures[0];
65789 }
65790 }
65791 }
65792 return undefined;
65793 }
65794 // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
65795 function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
65796 var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
65797 // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
65798 // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
65799 // for T but leave it possible to later infer '[any]' back to A.
65800 var restType = getEffectiveRestType(contextualSignature);
65801 var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
65802 var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
65803 applyToParameterTypes(sourceSignature, signature, function (source, target) {
65804 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
65805 inferTypes(context.inferences, source, target);
65806 });
65807 if (!inferenceContext) {
65808 applyToReturnTypes(contextualSignature, signature, function (source, target) {
65809 inferTypes(context.inferences, source, target, 64 /* ReturnType */);
65810 });
65811 }
65812 return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
65813 }
65814 function inferJsxTypeArguments(node, signature, checkMode, context) {
65815 var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
65816 var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
65817 inferTypes(context.inferences, checkAttrType, paramType);
65818 return getInferredTypes(context);
65819 }
65820 function inferTypeArguments(node, signature, args, checkMode, context) {
65821 if (ts.isJsxOpeningLikeElement(node)) {
65822 return inferJsxTypeArguments(node, signature, checkMode, context);
65823 }
65824 // If a contextual type is available, infer from that type to the return type of the call expression. For
65825 // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
65826 // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
65827 // return type of 'wrap'.
65828 if (node.kind !== 160 /* Decorator */) {
65829 var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */);
65830 if (contextualType) {
65831 // We clone the inference context to avoid disturbing a resolution in progress for an
65832 // outer call expression. Effectively we just want a snapshot of whatever has been
65833 // inferred for any outer call expression so far.
65834 var outerContext = getInferenceContext(node);
65835 var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
65836 var instantiatedType = instantiateType(contextualType, outerMapper);
65837 // If the contextual type is a generic function type with a single call signature, we
65838 // instantiate the type with its own type parameters and type arguments. This ensures that
65839 // the type parameters are not erased to type any during type inference such that they can
65840 // be inferred as actual types from the contextual type. For example:
65841 // declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
65842 // const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
65843 // Above, the type of the 'value' parameter is inferred to be 'A'.
65844 var contextualSignature = getSingleCallSignature(instantiatedType);
65845 var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
65846 getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
65847 instantiatedType;
65848 var inferenceTargetType = getReturnTypeOfSignature(signature);
65849 // Inferences made from return types have lower priority than all other inferences.
65850 inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */);
65851 // Create a type mapper for instantiating generic contextual types using the inferences made
65852 // from the return type. We need a separate inference pass here because (a) instantiation of
65853 // the source type uses the outer context's return mapper (which excludes inferences made from
65854 // outer arguments), and (b) we don't want any further inferences going into this context.
65855 var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
65856 var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
65857 inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
65858 context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
65859 }
65860 }
65861 var restType = getNonArrayRestType(signature);
65862 var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
65863 if (restType && restType.flags & 262144 /* TypeParameter */) {
65864 var info = ts.find(context.inferences, function (info) { return info.typeParameter === restType; });
65865 if (info) {
65866 info.impliedArity = ts.findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : undefined;
65867 }
65868 }
65869 var thisType = getThisTypeOfSignature(signature);
65870 if (thisType) {
65871 var thisArgumentNode = getThisArgumentOfCall(node);
65872 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
65873 inferTypes(context.inferences, thisArgumentType, thisType);
65874 }
65875 for (var i = 0; i < argCount; i++) {
65876 var arg = args[i];
65877 if (arg.kind !== 219 /* OmittedExpression */) {
65878 var paramType = getTypeAtPosition(signature, i);
65879 var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
65880 inferTypes(context.inferences, argType, paramType);
65881 }
65882 }
65883 if (restType) {
65884 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
65885 inferTypes(context.inferences, spreadType, restType);
65886 }
65887 return getInferredTypes(context);
65888 }
65889 function getMutableArrayOrTupleType(type) {
65890 return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) :
65891 type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type :
65892 isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) :
65893 createTupleType([type], [8 /* Variadic */]);
65894 }
65895 function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
65896 if (index >= argCount - 1) {
65897 var arg = args[argCount - 1];
65898 if (isSpreadArgument(arg)) {
65899 // We are inferring from a spread expression in the last argument position, i.e. both the parameter
65900 // and the argument are ...x forms.
65901 return getMutableArrayOrTupleType(arg.kind === 224 /* SyntheticExpression */ ? arg.type :
65902 checkExpressionWithContextualType(arg.expression, restType, context, checkMode));
65903 }
65904 }
65905 var types = [];
65906 var flags = [];
65907 var names = [];
65908 for (var i = index; i < argCount; i++) {
65909 var arg = args[i];
65910 if (isSpreadArgument(arg)) {
65911 var spreadType = arg.kind === 224 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
65912 if (isArrayLikeType(spreadType)) {
65913 types.push(spreadType);
65914 flags.push(8 /* Variadic */);
65915 }
65916 else {
65917 types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 217 /* SpreadElement */ ? arg.expression : arg));
65918 flags.push(4 /* Rest */);
65919 }
65920 }
65921 else {
65922 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
65923 var argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
65924 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
65925 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
65926 flags.push(1 /* Required */);
65927 }
65928 if (arg.kind === 224 /* SyntheticExpression */ && arg.tupleNameSource) {
65929 names.push(arg.tupleNameSource);
65930 }
65931 }
65932 return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
65933 }
65934 function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
65935 var isJavascript = ts.isInJSFile(signature.declaration);
65936 var typeParameters = signature.typeParameters;
65937 var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
65938 var mapper;
65939 for (var i = 0; i < typeArgumentNodes.length; i++) {
65940 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
65941 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
65942 if (constraint) {
65943 var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
65944 var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
65945 if (!mapper) {
65946 mapper = createTypeMapper(typeParameters, typeArgumentTypes);
65947 }
65948 var typeArgument = typeArgumentTypes[i];
65949 if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
65950 return undefined;
65951 }
65952 }
65953 }
65954 return typeArgumentTypes;
65955 }
65956 function getJsxReferenceKind(node) {
65957 if (isJsxIntrinsicIdentifier(node.tagName)) {
65958 return 2 /* Mixed */;
65959 }
65960 var tagType = getApparentType(checkExpression(node.tagName));
65961 if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
65962 return 0 /* Component */;
65963 }
65964 if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
65965 return 1 /* Function */;
65966 }
65967 return 2 /* Mixed */;
65968 }
65969 /**
65970 * Check if the given signature can possibly be a signature called by the JSX opening-like element.
65971 * @param node a JSX opening-like element we are trying to figure its call signature
65972 * @param signature a candidate signature we are trying whether it is a call signature
65973 * @param relation a relationship to check parameter and argument type
65974 */
65975 function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
65976 // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
65977 // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
65978 // can be specified by users through attributes property.
65979 var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
65980 var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
65981 return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes,
65982 /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
65983 function checkTagNameDoesNotExpectTooManyArguments() {
65984 var _a;
65985 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
65986 if (!tagType) {
65987 return true;
65988 }
65989 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
65990 if (!ts.length(tagCallSignatures)) {
65991 return true;
65992 }
65993 var factory = getJsxFactoryEntity(node);
65994 if (!factory) {
65995 return true;
65996 }
65997 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
65998 if (!factorySymbol) {
65999 return true;
66000 }
66001 var factoryType = getTypeOfSymbol(factorySymbol);
66002 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
66003 if (!ts.length(callSignatures)) {
66004 return true;
66005 }
66006 var hasFirstParamSignatures = false;
66007 var maxParamCount = 0;
66008 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
66009 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
66010 var sig = callSignatures_1[_i];
66011 var firstparam = getTypeAtPosition(sig, 0);
66012 var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
66013 if (!ts.length(signaturesOfParam))
66014 continue;
66015 for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
66016 var paramSig = signaturesOfParam_1[_b];
66017 hasFirstParamSignatures = true;
66018 if (hasEffectiveRestParameter(paramSig)) {
66019 return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
66020 }
66021 var paramCount = getParameterCount(paramSig);
66022 if (paramCount > maxParamCount) {
66023 maxParamCount = paramCount;
66024 }
66025 }
66026 }
66027 if (!hasFirstParamSignatures) {
66028 // Not a single signature had a first parameter which expected a signature - for back compat, and
66029 // to guard against generic factories which won't have signatures directly, do not error
66030 return true;
66031 }
66032 var absoluteMinArgCount = Infinity;
66033 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
66034 var tagSig = tagCallSignatures_1[_c];
66035 var tagRequiredArgCount = getMinArgumentCount(tagSig);
66036 if (tagRequiredArgCount < absoluteMinArgCount) {
66037 absoluteMinArgCount = tagRequiredArgCount;
66038 }
66039 }
66040 if (absoluteMinArgCount <= maxParamCount) {
66041 return true; // some signature accepts the number of arguments the function component provides
66042 }
66043 if (reportErrors) {
66044 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);
66045 var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
66046 if (tagNameDeclaration) {
66047 ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
66048 }
66049 if (errorOutputContainer && errorOutputContainer.skipLogging) {
66050 (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
66051 }
66052 if (!errorOutputContainer.skipLogging) {
66053 diagnostics.add(diag);
66054 }
66055 }
66056 return false;
66057 }
66058 }
66059 function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
66060 var errorOutputContainer = { errors: undefined, skipLogging: true };
66061 if (ts.isJsxOpeningLikeElement(node)) {
66062 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
66063 ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
66064 return errorOutputContainer.errors || ts.emptyArray;
66065 }
66066 return undefined;
66067 }
66068 var thisType = getThisTypeOfSignature(signature);
66069 if (thisType && thisType !== voidType && node.kind !== 201 /* NewExpression */) {
66070 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
66071 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
66072 // If the expression is a new expression, then the check is skipped.
66073 var thisArgumentNode = getThisArgumentOfCall(node);
66074 var thisArgumentType = void 0;
66075 if (thisArgumentNode) {
66076 thisArgumentType = checkExpression(thisArgumentNode);
66077 if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
66078 thisArgumentType = getNonNullableType(thisArgumentType);
66079 }
66080 else if (ts.isOptionalChain(thisArgumentNode.parent)) {
66081 thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
66082 }
66083 }
66084 else {
66085 thisArgumentType = voidType;
66086 }
66087 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
66088 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
66089 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
66090 ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
66091 return errorOutputContainer.errors || ts.emptyArray;
66092 }
66093 }
66094 var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
66095 var restType = getNonArrayRestType(signature);
66096 var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
66097 for (var i = 0; i < argCount; i++) {
66098 var arg = args[i];
66099 if (arg.kind !== 219 /* OmittedExpression */) {
66100 var paramType = getTypeAtPosition(signature, i);
66101 var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
66102 // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
66103 // we obtain the regular type of any object literal arguments because we may not have inferred complete
66104 // parameter types yet and therefore excess property checks may yield false positives (see #17041).
66105 var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
66106 if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
66107 ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
66108 maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
66109 return errorOutputContainer.errors || ts.emptyArray;
66110 }
66111 }
66112 }
66113 if (restType) {
66114 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
66115 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
66116 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
66117 ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
66118 maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
66119 return errorOutputContainer.errors || ts.emptyArray;
66120 }
66121 }
66122 return undefined;
66123 function maybeAddMissingAwaitInfo(errorNode, source, target) {
66124 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
66125 // Bail if target is Promise-like---something else is wrong
66126 if (getAwaitedTypeOfPromise(target)) {
66127 return;
66128 }
66129 var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
66130 if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
66131 ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
66132 }
66133 }
66134 }
66135 }
66136 /**
66137 * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
66138 */
66139 function getThisArgumentOfCall(node) {
66140 if (node.kind === 200 /* CallExpression */) {
66141 var callee = ts.skipOuterExpressions(node.expression);
66142 if (ts.isAccessExpression(callee)) {
66143 return callee.expression;
66144 }
66145 }
66146 }
66147 function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
66148 var result = ts.parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
66149 ts.setTextRange(result, parent);
66150 ts.setParent(result, parent);
66151 return result;
66152 }
66153 /**
66154 * Returns the effective arguments for an expression that works like a function invocation.
66155 */
66156 function getEffectiveCallArguments(node) {
66157 if (node.kind === 202 /* TaggedTemplateExpression */) {
66158 var template = node.template;
66159 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
66160 if (template.kind === 215 /* TemplateExpression */) {
66161 ts.forEach(template.templateSpans, function (span) {
66162 args_3.push(span.expression);
66163 });
66164 }
66165 return args_3;
66166 }
66167 if (node.kind === 160 /* Decorator */) {
66168 return getEffectiveDecoratorArguments(node);
66169 }
66170 if (ts.isJsxOpeningLikeElement(node)) {
66171 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
66172 }
66173 var args = node.arguments || ts.emptyArray;
66174 var spreadIndex = getSpreadArgumentIndex(args);
66175 if (spreadIndex >= 0) {
66176 // Create synthetic arguments from spreads of tuple types.
66177 var effectiveArgs_1 = args.slice(0, spreadIndex);
66178 var _loop_19 = function (i) {
66179 var arg = args[i];
66180 // We can call checkExpressionCached because spread expressions never have a contextual type.
66181 var spreadType = arg.kind === 217 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
66182 if (spreadType && isTupleType(spreadType)) {
66183 ts.forEach(getTypeArguments(spreadType), function (t, i) {
66184 var _a;
66185 var flags = spreadType.target.elementFlags[i];
66186 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]);
66187 effectiveArgs_1.push(syntheticArg);
66188 });
66189 }
66190 else {
66191 effectiveArgs_1.push(arg);
66192 }
66193 };
66194 for (var i = spreadIndex; i < args.length; i++) {
66195 _loop_19(i);
66196 }
66197 return effectiveArgs_1;
66198 }
66199 return args;
66200 }
66201 /**
66202 * Returns the synthetic argument list for a decorator invocation.
66203 */
66204 function getEffectiveDecoratorArguments(node) {
66205 var parent = node.parent;
66206 var expr = node.expression;
66207 switch (parent.kind) {
66208 case 249 /* ClassDeclaration */:
66209 case 218 /* ClassExpression */:
66210 // For a class decorator, the `target` is the type of the class (e.g. the
66211 // "static" or "constructor" side of the class).
66212 return [
66213 createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
66214 ];
66215 case 159 /* Parameter */:
66216 // A parameter declaration decorator will have three arguments (see
66217 // `ParameterDecorator` in core.d.ts).
66218 var func = parent.parent;
66219 return [
66220 createSyntheticExpression(expr, parent.parent.kind === 165 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
66221 createSyntheticExpression(expr, anyType),
66222 createSyntheticExpression(expr, numberType)
66223 ];
66224 case 162 /* PropertyDeclaration */:
66225 case 164 /* MethodDeclaration */:
66226 case 166 /* GetAccessor */:
66227 case 167 /* SetAccessor */:
66228 // A method or accessor declaration decorator will have two or three arguments (see
66229 // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
66230 // for ES3, we will only pass two arguments.
66231 var hasPropDesc = parent.kind !== 162 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
66232 return [
66233 createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
66234 createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
66235 createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
66236 ];
66237 }
66238 return ts.Debug.fail();
66239 }
66240 /**
66241 * Returns the argument count for a decorator node that works like a function invocation.
66242 */
66243 function getDecoratorArgumentCount(node, signature) {
66244 switch (node.parent.kind) {
66245 case 249 /* ClassDeclaration */:
66246 case 218 /* ClassExpression */:
66247 return 1;
66248 case 162 /* PropertyDeclaration */:
66249 return 2;
66250 case 164 /* MethodDeclaration */:
66251 case 166 /* GetAccessor */:
66252 case 167 /* SetAccessor */:
66253 // For ES3 or decorators with only two parameters we supply only two arguments
66254 return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
66255 case 159 /* Parameter */:
66256 return 3;
66257 default:
66258 return ts.Debug.fail();
66259 }
66260 }
66261 function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
66262 var start;
66263 var length;
66264 var sourceFile = ts.getSourceFileOfNode(node);
66265 if (ts.isPropertyAccessExpression(node.expression)) {
66266 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
66267 start = nameSpan.start;
66268 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
66269 }
66270 else {
66271 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
66272 start = expressionSpan.start;
66273 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
66274 }
66275 return { start: start, length: length, sourceFile: sourceFile };
66276 }
66277 function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
66278 if (ts.isCallExpression(node)) {
66279 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
66280 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
66281 }
66282 else {
66283 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
66284 }
66285 }
66286 function getArgumentArityError(node, signatures, args) {
66287 var min = Number.POSITIVE_INFINITY;
66288 var max = Number.NEGATIVE_INFINITY;
66289 var belowArgCount = Number.NEGATIVE_INFINITY;
66290 var aboveArgCount = Number.POSITIVE_INFINITY;
66291 var argCount = args.length;
66292 var closestSignature;
66293 for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
66294 var sig = signatures_8[_i];
66295 var minCount = getMinArgumentCount(sig);
66296 var maxCount = getParameterCount(sig);
66297 if (minCount < argCount && minCount > belowArgCount)
66298 belowArgCount = minCount;
66299 if (argCount < maxCount && maxCount < aboveArgCount)
66300 aboveArgCount = maxCount;
66301 if (minCount < min) {
66302 min = minCount;
66303 closestSignature = sig;
66304 }
66305 max = Math.max(max, maxCount);
66306 }
66307 var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
66308 var paramRange = hasRestParameter ? min :
66309 min < max ? min + "-" + max :
66310 min;
66311 var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
66312 if (argCount <= max && hasSpreadArgument) {
66313 argCount--;
66314 }
66315 var spanArray;
66316 var related;
66317 var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
66318 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
66319 ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
66320 if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
66321 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
66322 if (paramDecl) {
66323 related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided :
66324 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);
66325 }
66326 }
66327 if (min < argCount && argCount < max) {
66328 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
66329 }
66330 if (!hasSpreadArgument && argCount < min) {
66331 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
66332 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
66333 }
66334 if (hasRestParameter || hasSpreadArgument) {
66335 spanArray = ts.factory.createNodeArray(args);
66336 if (hasSpreadArgument && argCount) {
66337 var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
66338 spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
66339 }
66340 }
66341 else {
66342 spanArray = ts.factory.createNodeArray(args.slice(max));
66343 }
66344 var pos = ts.first(spanArray).pos;
66345 var end = ts.last(spanArray).end;
66346 if (end === pos) {
66347 end++;
66348 }
66349 ts.setTextRangePosEnd(spanArray, pos, end);
66350 var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
66351 return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
66352 }
66353 function getTypeArgumentArityError(node, signatures, typeArguments) {
66354 var argCount = typeArguments.length;
66355 // No overloads exist
66356 if (signatures.length === 1) {
66357 var sig = signatures[0];
66358 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
66359 var max = ts.length(sig.typeParameters);
66360 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);
66361 }
66362 // Overloads exist
66363 var belowArgCount = -Infinity;
66364 var aboveArgCount = Infinity;
66365 for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
66366 var sig = signatures_9[_i];
66367 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
66368 var max = ts.length(sig.typeParameters);
66369 if (min_2 > argCount) {
66370 aboveArgCount = Math.min(aboveArgCount, min_2);
66371 }
66372 else if (max < argCount) {
66373 belowArgCount = Math.max(belowArgCount, max);
66374 }
66375 }
66376 if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
66377 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);
66378 }
66379 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
66380 }
66381 function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
66382 var isTaggedTemplate = node.kind === 202 /* TaggedTemplateExpression */;
66383 var isDecorator = node.kind === 160 /* Decorator */;
66384 var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
66385 var reportErrors = !candidatesOutArray && produceDiagnostics;
66386 var typeArguments;
66387 if (!isDecorator) {
66388 typeArguments = node.typeArguments;
66389 // We already perform checking on the type arguments on the class declaration itself.
66390 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 105 /* SuperKeyword */) {
66391 ts.forEach(typeArguments, checkSourceElement);
66392 }
66393 }
66394 var candidates = candidatesOutArray || [];
66395 // reorderCandidates fills up the candidates array directly
66396 reorderCandidates(signatures, candidates, callChainFlags);
66397 if (!candidates.length) {
66398 if (reportErrors) {
66399 diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
66400 }
66401 return resolveErrorCall(node);
66402 }
66403 var args = getEffectiveCallArguments(node);
66404 // The excludeArgument array contains true for each context sensitive argument (an argument
66405 // is context sensitive it is susceptible to a one-time permanent contextual typing).
66406 //
66407 // The idea is that we will perform type argument inference & assignability checking once
66408 // without using the susceptible parameters that are functions, and once more for those
66409 // parameters, contextually typing each as we go along.
66410 //
66411 // For a tagged template, then the first argument be 'undefined' if necessary because it
66412 // represents a TemplateStringsArray.
66413 //
66414 // For a decorator, no arguments are susceptible to contextual typing due to the fact
66415 // decorators are applied to a declaration by the emitter, and not to an expression.
66416 var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
66417 var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
66418 // The following variables are captured and modified by calls to chooseOverload.
66419 // If overload resolution or type argument inference fails, we want to report the
66420 // best error possible. The best error is one which says that an argument was not
66421 // assignable to a parameter. This implies that everything else about the overload
66422 // was fine. So if there is any overload that is only incorrect because of an
66423 // argument, we will report an error on that one.
66424 //
66425 // function foo(s: string): void;
66426 // function foo(n: number): void; // Report argument error on this overload
66427 // function foo(): void;
66428 // foo(true);
66429 //
66430 // If none of the overloads even made it that far, there are two possibilities.
66431 // There was a problem with type arguments for some overload, in which case
66432 // report an error on that. Or none of the overloads even had correct arity,
66433 // in which case give an arity error.
66434 //
66435 // function foo<T extends string>(x: T): void; // Report type argument error
66436 // function foo(): void;
66437 // foo<number>(0);
66438 //
66439 var candidatesForArgumentError;
66440 var candidateForArgumentArityError;
66441 var candidateForTypeArgumentError;
66442 var result;
66443 // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
66444 // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
66445 var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 200 /* CallExpression */ && node.arguments.hasTrailingComma;
66446 // Section 4.12.1:
66447 // if the candidate list contains one or more signatures for which the type of each argument
66448 // expression is a subtype of each corresponding parameter type, the return type of the first
66449 // of those signatures becomes the return type of the function call.
66450 // Otherwise, the return type of the first signature in the candidate list becomes the return
66451 // type of the function call.
66452 //
66453 // Whether the call is an error is determined by assignability of the arguments. The subtype pass
66454 // is just important for choosing the best signature. So in the case where there is only one
66455 // signature, the subtype pass is useless. So skipping it is an optimization.
66456 if (candidates.length > 1) {
66457 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
66458 }
66459 if (!result) {
66460 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
66461 }
66462 if (result) {
66463 return result;
66464 }
66465 // No signatures were applicable. Now report errors based on the last applicable signature with
66466 // no arguments excluded from assignability checks.
66467 // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
66468 // skip the checkApplicableSignature check.
66469 if (reportErrors) {
66470 if (candidatesForArgumentError) {
66471 if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
66472 var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
66473 var chain_1;
66474 if (candidatesForArgumentError.length > 3) {
66475 chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
66476 chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
66477 }
66478 var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
66479 if (diags) {
66480 for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
66481 var d = diags_1[_i];
66482 if (last_2.declaration && candidatesForArgumentError.length > 3) {
66483 ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
66484 }
66485 diagnostics.add(d);
66486 }
66487 }
66488 else {
66489 ts.Debug.fail("No error for last overload signature");
66490 }
66491 }
66492 else {
66493 var allDiagnostics = [];
66494 var max = 0;
66495 var min_3 = Number.MAX_VALUE;
66496 var minIndex = 0;
66497 var i_1 = 0;
66498 var _loop_20 = function (c) {
66499 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)); };
66500 var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
66501 if (diags_2) {
66502 if (diags_2.length <= min_3) {
66503 min_3 = diags_2.length;
66504 minIndex = i_1;
66505 }
66506 max = Math.max(max, diags_2.length);
66507 allDiagnostics.push(diags_2);
66508 }
66509 else {
66510 ts.Debug.fail("No error for 3 or fewer overload signatures");
66511 }
66512 i_1++;
66513 };
66514 for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
66515 var c = candidatesForArgumentError_1[_a];
66516 _loop_20(c);
66517 }
66518 var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
66519 ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
66520 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);
66521 var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
66522 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; })) {
66523 var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
66524 diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
66525 }
66526 else {
66527 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
66528 }
66529 }
66530 }
66531 else if (candidateForArgumentArityError) {
66532 diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
66533 }
66534 else if (candidateForTypeArgumentError) {
66535 checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
66536 }
66537 else {
66538 var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
66539 if (signaturesWithCorrectTypeArgumentArity.length === 0) {
66540 diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
66541 }
66542 else if (!isDecorator) {
66543 diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
66544 }
66545 else if (fallbackError) {
66546 diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
66547 }
66548 }
66549 }
66550 return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
66551 function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
66552 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
66553 candidatesForArgumentError = undefined;
66554 candidateForArgumentArityError = undefined;
66555 candidateForTypeArgumentError = undefined;
66556 if (isSingleNonGenericCandidate) {
66557 var candidate = candidates[0];
66558 if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
66559 return undefined;
66560 }
66561 if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
66562 candidatesForArgumentError = [candidate];
66563 return undefined;
66564 }
66565 return candidate;
66566 }
66567 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
66568 var candidate = candidates[candidateIndex];
66569 if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
66570 continue;
66571 }
66572 var checkCandidate = void 0;
66573 var inferenceContext = void 0;
66574 if (candidate.typeParameters) {
66575 var typeArgumentTypes = void 0;
66576 if (ts.some(typeArguments)) {
66577 typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
66578 if (!typeArgumentTypes) {
66579 candidateForTypeArgumentError = candidate;
66580 continue;
66581 }
66582 }
66583 else {
66584 inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
66585 typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
66586 argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
66587 }
66588 checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
66589 // If the original signature has a generic rest type, instantiation may produce a
66590 // signature with different arity and we need to perform another arity check.
66591 if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
66592 candidateForArgumentArityError = checkCandidate;
66593 continue;
66594 }
66595 }
66596 else {
66597 checkCandidate = candidate;
66598 }
66599 if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
66600 // Give preference to error candidates that have no rest parameters (as they are more specific)
66601 (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
66602 continue;
66603 }
66604 if (argCheckMode) {
66605 // If one or more context sensitive arguments were excluded, we start including
66606 // them now (and keeping do so for any subsequent candidates) and perform a second
66607 // round of type inference and applicability checking for this particular candidate.
66608 argCheckMode = 0 /* Normal */;
66609 if (inferenceContext) {
66610 var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
66611 checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
66612 // If the original signature has a generic rest type, instantiation may produce a
66613 // signature with different arity and we need to perform another arity check.
66614 if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
66615 candidateForArgumentArityError = checkCandidate;
66616 continue;
66617 }
66618 }
66619 if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
66620 // Give preference to error candidates that have no rest parameters (as they are more specific)
66621 (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
66622 continue;
66623 }
66624 }
66625 candidates[candidateIndex] = checkCandidate;
66626 return checkCandidate;
66627 }
66628 return undefined;
66629 }
66630 }
66631 // No signature was applicable. We have already reported the errors for the invalid signature.
66632 function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
66633 ts.Debug.assert(candidates.length > 0); // Else should not have called this.
66634 checkNodeDeferred(node);
66635 // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
66636 // Don't do this if there is a `candidatesOutArray`,
66637 // because then we want the chosen best candidate to be one of the overloads, not a combination.
66638 return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
66639 ? pickLongestCandidateSignature(node, candidates, args)
66640 : createUnionOfSignaturesForOverloadFailure(candidates);
66641 }
66642 function createUnionOfSignaturesForOverloadFailure(candidates) {
66643 var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
66644 var thisParameter;
66645 if (thisParameters.length) {
66646 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
66647 }
66648 var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
66649 var parameters = [];
66650 var _loop_21 = function (i) {
66651 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
66652 i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
66653 i < s.parameters.length ? s.parameters[i] : undefined; });
66654 ts.Debug.assert(symbols.length !== 0);
66655 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
66656 };
66657 for (var i = 0; i < maxNonRestParam; i++) {
66658 _loop_21(i);
66659 }
66660 var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
66661 var flags = 0 /* None */;
66662 if (restParameterSymbols.length !== 0) {
66663 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
66664 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
66665 flags |= 1 /* HasRestParameter */;
66666 }
66667 if (candidates.some(signatureHasLiteralTypes)) {
66668 flags |= 2 /* HasLiteralTypes */;
66669 }
66670 return createSignature(candidates[0].declaration,
66671 /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
66672 thisParameter, parameters,
66673 /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)),
66674 /*typePredicate*/ undefined, minArgumentCount, flags);
66675 }
66676 function getNumNonRestParameters(signature) {
66677 var numParams = signature.parameters.length;
66678 return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
66679 }
66680 function createCombinedSymbolFromTypes(sources, types) {
66681 return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
66682 }
66683 function createCombinedSymbolForOverloadFailure(sources, type) {
66684 // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
66685 return createSymbolWithType(ts.first(sources), type);
66686 }
66687 function pickLongestCandidateSignature(node, candidates, args) {
66688 // Pick the longest signature. This way we can get a contextual type for cases like:
66689 // declare function f(a: { xa: number; xb: number; }, b: number);
66690 // f({ |
66691 // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
66692 // declare function f<T>(k: keyof T);
66693 // f<Foo>("
66694 var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
66695 var candidate = candidates[bestIndex];
66696 var typeParameters = candidate.typeParameters;
66697 if (!typeParameters) {
66698 return candidate;
66699 }
66700 var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
66701 var instantiated = typeArgumentNodes
66702 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
66703 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
66704 candidates[bestIndex] = instantiated;
66705 return instantiated;
66706 }
66707 function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
66708 var typeArguments = typeArgumentNodes.map(getTypeOfNode);
66709 while (typeArguments.length > typeParameters.length) {
66710 typeArguments.pop();
66711 }
66712 while (typeArguments.length < typeParameters.length) {
66713 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
66714 }
66715 return typeArguments;
66716 }
66717 function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
66718 var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
66719 var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
66720 return createSignatureInstantiation(candidate, typeArgumentTypes);
66721 }
66722 function getLongestCandidateIndex(candidates, argsCount) {
66723 var maxParamsIndex = -1;
66724 var maxParams = -1;
66725 for (var i = 0; i < candidates.length; i++) {
66726 var candidate = candidates[i];
66727 var paramCount = getParameterCount(candidate);
66728 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
66729 return i;
66730 }
66731 if (paramCount > maxParams) {
66732 maxParams = paramCount;
66733 maxParamsIndex = i;
66734 }
66735 }
66736 return maxParamsIndex;
66737 }
66738 function resolveCallExpression(node, candidatesOutArray, checkMode) {
66739 if (node.expression.kind === 105 /* SuperKeyword */) {
66740 var superType = checkSuperExpression(node.expression);
66741 if (isTypeAny(superType)) {
66742 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
66743 var arg = _a[_i];
66744 checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
66745 }
66746 return anySignature;
66747 }
66748 if (superType !== errorType) {
66749 // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
66750 // with the type arguments specified in the extends clause.
66751 var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
66752 if (baseTypeNode) {
66753 var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
66754 return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
66755 }
66756 }
66757 return resolveUntypedCall(node);
66758 }
66759 var callChainFlags;
66760 var funcType = checkExpression(node.expression);
66761 if (ts.isCallChain(node)) {
66762 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
66763 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
66764 ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
66765 4 /* IsInnerCallChain */;
66766 funcType = nonOptionalType;
66767 }
66768 else {
66769 callChainFlags = 0 /* None */;
66770 }
66771 funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
66772 if (funcType === silentNeverType) {
66773 return silentNeverSignature;
66774 }
66775 var apparentType = getApparentType(funcType);
66776 if (apparentType === errorType) {
66777 // Another error has already been reported
66778 return resolveErrorCall(node);
66779 }
66780 // Technically, this signatures list may be incomplete. We are taking the apparent type,
66781 // but we are not including call signatures that may have been added to the Object or
66782 // Function interface, since they have none by default. This is a bit of a leap of faith
66783 // that the user will not add any.
66784 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
66785 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
66786 // TS 1.0 Spec: 4.12
66787 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
66788 // types are provided for the argument expressions, and the result is always of type Any.
66789 if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
66790 // The unknownType indicates that an error already occurred (and was reported). No
66791 // need to report another error in this case.
66792 if (funcType !== errorType && node.typeArguments) {
66793 error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
66794 }
66795 return resolveUntypedCall(node);
66796 }
66797 // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
66798 // TypeScript employs overload resolution in typed function calls in order to support functions
66799 // with multiple call signatures.
66800 if (!callSignatures.length) {
66801 if (numConstructSignatures) {
66802 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
66803 }
66804 else {
66805 var relatedInformation = void 0;
66806 if (node.arguments.length === 1) {
66807 var text = ts.getSourceFileOfNode(node).text;
66808 if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
66809 relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
66810 }
66811 }
66812 invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
66813 }
66814 return resolveErrorCall(node);
66815 }
66816 // When a call to a generic function is an argument to an outer call to a generic function for which
66817 // inference is in process, we have a choice to make. If the inner call relies on inferences made from
66818 // its contextual type to its return type, deferring the inner call processing allows the best possible
66819 // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
66820 // the inner call, the inner call should be processed early. There's no sure way to know which choice is
66821 // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
66822 // If no type arguments are specified in the inner call and at least one call signature is generic and
66823 // returns a function type, we choose to defer processing. This narrowly permits function composition
66824 // operators to flow inferences through return types, but otherwise processes calls right away. We
66825 // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
66826 // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
66827 // from which we never make inferences).
66828 if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
66829 skippedGenericFunction(node, checkMode);
66830 return resolvingSignature;
66831 }
66832 // If the function is explicitly marked with `@class`, then it must be constructed.
66833 if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
66834 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
66835 return resolveErrorCall(node);
66836 }
66837 return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
66838 }
66839 function isGenericFunctionReturningFunction(signature) {
66840 return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
66841 }
66842 /**
66843 * TS 1.0 spec: 4.12
66844 * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
66845 * but is a subtype of the Function interface, the call is an untyped function call.
66846 */
66847 function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
66848 // We exclude union types because we may have a union of function types that happen to have no common signatures.
66849 return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
66850 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
66851 }
66852 function resolveNewExpression(node, candidatesOutArray, checkMode) {
66853 if (node.arguments && languageVersion < 1 /* ES5 */) {
66854 var spreadIndex = getSpreadArgumentIndex(node.arguments);
66855 if (spreadIndex >= 0) {
66856 error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
66857 }
66858 }
66859 var expressionType = checkNonNullExpression(node.expression);
66860 if (expressionType === silentNeverType) {
66861 return silentNeverSignature;
66862 }
66863 // If expressionType's apparent type(section 3.8.1) is an object type with one or
66864 // more construct signatures, the expression is processed in the same manner as a
66865 // function call, but using the construct signatures as the initial set of candidate
66866 // signatures for overload resolution. The result type of the function call becomes
66867 // the result type of the operation.
66868 expressionType = getApparentType(expressionType);
66869 if (expressionType === errorType) {
66870 // Another error has already been reported
66871 return resolveErrorCall(node);
66872 }
66873 // TS 1.0 spec: 4.11
66874 // If expressionType is of type Any, Args can be any argument
66875 // list and the result of the operation is of type Any.
66876 if (isTypeAny(expressionType)) {
66877 if (node.typeArguments) {
66878 error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
66879 }
66880 return resolveUntypedCall(node);
66881 }
66882 // Technically, this signatures list may be incomplete. We are taking the apparent type,
66883 // but we are not including construct signatures that may have been added to the Object or
66884 // Function interface, since they have none by default. This is a bit of a leap of faith
66885 // that the user will not add any.
66886 var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
66887 if (constructSignatures.length) {
66888 if (!isConstructorAccessible(node, constructSignatures[0])) {
66889 return resolveErrorCall(node);
66890 }
66891 // If the expression is a class of abstract type, then it cannot be instantiated.
66892 // Note, only class declarations can be declared abstract.
66893 // In the case of a merged class-module or class-interface declaration,
66894 // only the class declaration node will have the Abstract flag set.
66895 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
66896 if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
66897 error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
66898 return resolveErrorCall(node);
66899 }
66900 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
66901 }
66902 // If expressionType's apparent type is an object type with no construct signatures but
66903 // one or more call signatures, the expression is processed as a function call. A compile-time
66904 // error occurs if the result of the function call is not Void. The type of the result of the
66905 // operation is Any. It is an error to have a Void this type.
66906 var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
66907 if (callSignatures.length) {
66908 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
66909 if (!noImplicitAny) {
66910 if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
66911 error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
66912 }
66913 if (getThisTypeOfSignature(signature) === voidType) {
66914 error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
66915 }
66916 }
66917 return signature;
66918 }
66919 invocationError(node.expression, expressionType, 1 /* Construct */);
66920 return resolveErrorCall(node);
66921 }
66922 function typeHasProtectedAccessibleBase(target, type) {
66923 var baseTypes = getBaseTypes(type);
66924 if (!ts.length(baseTypes)) {
66925 return false;
66926 }
66927 var firstBase = baseTypes[0];
66928 if (firstBase.flags & 2097152 /* Intersection */) {
66929 var types = firstBase.types;
66930 var mixinFlags = findMixins(types);
66931 var i = 0;
66932 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
66933 var intersectionMember = _a[_i];
66934 // We want to ignore mixin ctors
66935 if (!mixinFlags[i]) {
66936 if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
66937 if (intersectionMember.symbol === target) {
66938 return true;
66939 }
66940 if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
66941 return true;
66942 }
66943 }
66944 }
66945 i++;
66946 }
66947 return false;
66948 }
66949 if (firstBase.symbol === target) {
66950 return true;
66951 }
66952 return typeHasProtectedAccessibleBase(target, firstBase);
66953 }
66954 function isConstructorAccessible(node, signature) {
66955 if (!signature || !signature.declaration) {
66956 return true;
66957 }
66958 var declaration = signature.declaration;
66959 var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
66960 // (1) Public constructors and (2) constructor functions are always accessible.
66961 if (!modifiers || declaration.kind !== 165 /* Constructor */) {
66962 return true;
66963 }
66964 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
66965 var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
66966 // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
66967 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
66968 var containingClass = ts.getContainingClass(node);
66969 if (containingClass && modifiers & 16 /* Protected */) {
66970 var containingType = getTypeOfNode(containingClass);
66971 if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
66972 return true;
66973 }
66974 }
66975 if (modifiers & 8 /* Private */) {
66976 error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
66977 }
66978 if (modifiers & 16 /* Protected */) {
66979 error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
66980 }
66981 return false;
66982 }
66983 return true;
66984 }
66985 function invocationErrorDetails(errorTarget, apparentType, kind) {
66986 var errorInfo;
66987 var isCall = kind === 0 /* Call */;
66988 var awaitedType = getAwaitedType(apparentType);
66989 var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
66990 if (apparentType.flags & 1048576 /* Union */) {
66991 var types = apparentType.types;
66992 var hasSignatures = false;
66993 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
66994 var constituent = types_18[_i];
66995 var signatures = getSignaturesOfType(constituent, kind);
66996 if (signatures.length !== 0) {
66997 hasSignatures = true;
66998 if (errorInfo) {
66999 // Bail early if we already have an error, no chance of "No constituent of type is callable"
67000 break;
67001 }
67002 }
67003 else {
67004 // Error on the first non callable constituent only
67005 if (!errorInfo) {
67006 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
67007 ts.Diagnostics.Type_0_has_no_call_signatures :
67008 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
67009 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
67010 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
67011 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
67012 }
67013 if (hasSignatures) {
67014 // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
67015 break;
67016 }
67017 }
67018 }
67019 if (!hasSignatures) {
67020 errorInfo = ts.chainDiagnosticMessages(
67021 /* detials */ undefined, isCall ?
67022 ts.Diagnostics.No_constituent_of_type_0_is_callable :
67023 ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
67024 }
67025 if (!errorInfo) {
67026 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
67027 ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
67028 ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
67029 }
67030 }
67031 else {
67032 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
67033 ts.Diagnostics.Type_0_has_no_call_signatures :
67034 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
67035 }
67036 var headMessage = isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable;
67037 // Diagnose get accessors incorrectly called as functions
67038 if (ts.isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
67039 var resolvedSymbol = getNodeLinks(errorTarget).resolvedSymbol;
67040 if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
67041 headMessage = ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
67042 }
67043 }
67044 return {
67045 messageChain: ts.chainDiagnosticMessages(errorInfo, headMessage),
67046 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
67047 };
67048 }
67049 function invocationError(errorTarget, apparentType, kind, relatedInformation) {
67050 var _a = invocationErrorDetails(errorTarget, apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
67051 var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
67052 if (relatedInfo) {
67053 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
67054 }
67055 if (ts.isCallExpression(errorTarget.parent)) {
67056 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
67057 diagnostic.start = start;
67058 diagnostic.length = length_7;
67059 }
67060 diagnostics.add(diagnostic);
67061 invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
67062 }
67063 function invocationErrorRecovery(apparentType, kind, diagnostic) {
67064 if (!apparentType.symbol) {
67065 return;
67066 }
67067 var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
67068 // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
67069 // 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
67070 if (importNode && !ts.isImportCall(importNode)) {
67071 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
67072 if (!sigs || !sigs.length)
67073 return;
67074 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));
67075 }
67076 }
67077 function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
67078 var tagType = checkExpression(node.tag);
67079 var apparentType = getApparentType(tagType);
67080 if (apparentType === errorType) {
67081 // Another error has already been reported
67082 return resolveErrorCall(node);
67083 }
67084 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
67085 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
67086 if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
67087 return resolveUntypedCall(node);
67088 }
67089 if (!callSignatures.length) {
67090 invocationError(node.tag, apparentType, 0 /* Call */);
67091 return resolveErrorCall(node);
67092 }
67093 return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
67094 }
67095 /**
67096 * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
67097 */
67098 function getDiagnosticHeadMessageForDecoratorResolution(node) {
67099 switch (node.parent.kind) {
67100 case 249 /* ClassDeclaration */:
67101 case 218 /* ClassExpression */:
67102 return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
67103 case 159 /* Parameter */:
67104 return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
67105 case 162 /* PropertyDeclaration */:
67106 return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
67107 case 164 /* MethodDeclaration */:
67108 case 166 /* GetAccessor */:
67109 case 167 /* SetAccessor */:
67110 return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
67111 default:
67112 return ts.Debug.fail();
67113 }
67114 }
67115 /**
67116 * Resolves a decorator as if it were a call expression.
67117 */
67118 function resolveDecorator(node, candidatesOutArray, checkMode) {
67119 var funcType = checkExpression(node.expression);
67120 var apparentType = getApparentType(funcType);
67121 if (apparentType === errorType) {
67122 return resolveErrorCall(node);
67123 }
67124 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
67125 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
67126 if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
67127 return resolveUntypedCall(node);
67128 }
67129 if (isPotentiallyUncalledDecorator(node, callSignatures)) {
67130 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
67131 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);
67132 return resolveErrorCall(node);
67133 }
67134 var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
67135 if (!callSignatures.length) {
67136 var errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
67137 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
67138 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
67139 if (errorDetails.relatedMessage) {
67140 ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
67141 }
67142 diagnostics.add(diag);
67143 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
67144 return resolveErrorCall(node);
67145 }
67146 return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
67147 }
67148 function createSignatureForJSXIntrinsic(node, result) {
67149 var namespace = getJsxNamespaceAt(node);
67150 var exports = namespace && getExportsOfSymbol(namespace);
67151 // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
67152 // file would probably be preferable.
67153 var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
67154 var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
67155 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 */));
67156 var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
67157 parameterSymbol.type = result;
67158 return createSignature(declaration,
67159 /*typeParameters*/ undefined,
67160 /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
67161 /*returnTypePredicate*/ undefined, 1, 0 /* None */);
67162 }
67163 function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
67164 if (isJsxIntrinsicIdentifier(node.tagName)) {
67165 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
67166 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
67167 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
67168 return fakeSignature;
67169 }
67170 var exprTypes = checkExpression(node.tagName);
67171 var apparentType = getApparentType(exprTypes);
67172 if (apparentType === errorType) {
67173 return resolveErrorCall(node);
67174 }
67175 var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
67176 if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
67177 return resolveUntypedCall(node);
67178 }
67179 if (signatures.length === 0) {
67180 // We found no signatures at all, which is an error
67181 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
67182 return resolveErrorCall(node);
67183 }
67184 return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
67185 }
67186 /**
67187 * Sometimes, we have a decorator that could accept zero arguments,
67188 * but is receiving too many arguments as part of the decorator invocation.
67189 * In those cases, a user may have meant to *call* the expression before using it as a decorator.
67190 */
67191 function isPotentiallyUncalledDecorator(decorator, signatures) {
67192 return signatures.length && ts.every(signatures, function (signature) {
67193 return signature.minArgumentCount === 0 &&
67194 !signatureHasRestParameter(signature) &&
67195 signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
67196 });
67197 }
67198 function resolveSignature(node, candidatesOutArray, checkMode) {
67199 switch (node.kind) {
67200 case 200 /* CallExpression */:
67201 return resolveCallExpression(node, candidatesOutArray, checkMode);
67202 case 201 /* NewExpression */:
67203 return resolveNewExpression(node, candidatesOutArray, checkMode);
67204 case 202 /* TaggedTemplateExpression */:
67205 return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
67206 case 160 /* Decorator */:
67207 return resolveDecorator(node, candidatesOutArray, checkMode);
67208 case 272 /* JsxOpeningElement */:
67209 case 271 /* JsxSelfClosingElement */:
67210 return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
67211 }
67212 throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
67213 }
67214 /**
67215 * Resolve a signature of a given call-like expression.
67216 * @param node a call-like expression to try resolve a signature for
67217 * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
67218 * the function will fill it up with appropriate candidate signatures
67219 * @return a signature of the call-like expression or undefined if one can't be found
67220 */
67221 function getResolvedSignature(node, candidatesOutArray, checkMode) {
67222 var links = getNodeLinks(node);
67223 // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
67224 // However, it is possible that either candidatesOutArray was not passed in the first time,
67225 // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
67226 // to correctly fill the candidatesOutArray.
67227 var cached = links.resolvedSignature;
67228 if (cached && cached !== resolvingSignature && !candidatesOutArray) {
67229 return cached;
67230 }
67231 links.resolvedSignature = resolvingSignature;
67232 var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
67233 // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
67234 // resolution should be deferred.
67235 if (result !== resolvingSignature) {
67236 // If signature resolution originated in control flow type analysis (for example to compute the
67237 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
67238 // types from the control flow analysis.
67239 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
67240 }
67241 return result;
67242 }
67243 /**
67244 * Indicates whether a declaration can be treated as a constructor in a JavaScript
67245 * file.
67246 */
67247 function isJSConstructor(node) {
67248 var _a;
67249 if (!node || !ts.isInJSFile(node)) {
67250 return false;
67251 }
67252 var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
67253 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
67254 undefined;
67255 if (func) {
67256 // If the node has a @class tag, treat it like a constructor.
67257 if (ts.getJSDocClassTag(node))
67258 return true;
67259 // If the symbol of the node has members, treat it like a constructor.
67260 var symbol = getSymbolOfNode(func);
67261 return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size);
67262 }
67263 return false;
67264 }
67265 function mergeJSSymbols(target, source) {
67266 var _a, _b;
67267 if (source) {
67268 var links = getSymbolLinks(source);
67269 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
67270 var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
67271 inferred.exports = inferred.exports || ts.createSymbolTable();
67272 inferred.members = inferred.members || ts.createSymbolTable();
67273 inferred.flags |= source.flags & 32 /* Class */;
67274 if ((_a = source.exports) === null || _a === void 0 ? void 0 : _a.size) {
67275 mergeSymbolTable(inferred.exports, source.exports);
67276 }
67277 if ((_b = source.members) === null || _b === void 0 ? void 0 : _b.size) {
67278 mergeSymbolTable(inferred.members, source.members);
67279 }
67280 (links.inferredClassSymbol || (links.inferredClassSymbol = new ts.Map())).set(getSymbolId(inferred), inferred);
67281 return inferred;
67282 }
67283 return links.inferredClassSymbol.get(getSymbolId(target));
67284 }
67285 }
67286 function getAssignedClassSymbol(decl) {
67287 var assignmentSymbol = decl && decl.parent &&
67288 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
67289 ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
67290 ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
67291 var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
67292 var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
67293 return init ? getSymbolOfNode(init) : undefined;
67294 }
67295 function getAssignedJSPrototype(node) {
67296 if (!node.parent) {
67297 return false;
67298 }
67299 var parent = node.parent;
67300 while (parent && parent.kind === 198 /* PropertyAccessExpression */) {
67301 parent = parent.parent;
67302 }
67303 if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
67304 var right = ts.getInitializerOfBinaryExpression(parent);
67305 return ts.isObjectLiteralExpression(right) && right;
67306 }
67307 }
67308 /**
67309 * Syntactically and semantically checks a call or new expression.
67310 * @param node The call/new expression to be checked.
67311 * @returns On success, the expression's signature's return type. On failure, anyType.
67312 */
67313 function checkCallExpression(node, checkMode) {
67314 var _a;
67315 if (!checkGrammarTypeArguments(node, node.typeArguments))
67316 checkGrammarArguments(node.arguments);
67317 var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
67318 if (signature === resolvingSignature) {
67319 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
67320 // returns a function type. We defer checking and return nonInferrableType.
67321 return nonInferrableType;
67322 }
67323 checkDeprecatedSignature(signature, node);
67324 if (node.expression.kind === 105 /* SuperKeyword */) {
67325 return voidType;
67326 }
67327 if (node.kind === 201 /* NewExpression */) {
67328 var declaration = signature.declaration;
67329 if (declaration &&
67330 declaration.kind !== 165 /* Constructor */ &&
67331 declaration.kind !== 169 /* ConstructSignature */ &&
67332 declaration.kind !== 174 /* ConstructorType */ &&
67333 !ts.isJSDocConstructSignature(declaration) &&
67334 !isJSConstructor(declaration)) {
67335 // When resolved signature is a call signature (and not a construct signature) the result type is any
67336 if (noImplicitAny) {
67337 error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
67338 }
67339 return anyType;
67340 }
67341 }
67342 // In JavaScript files, calls to any identifier 'require' are treated as external module imports
67343 if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
67344 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
67345 }
67346 var returnType = getReturnTypeOfSignature(signature);
67347 // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
67348 // as a fresh unique symbol literal type.
67349 if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
67350 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
67351 }
67352 if (node.kind === 200 /* CallExpression */ && node.parent.kind === 230 /* ExpressionStatement */ &&
67353 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
67354 if (!ts.isDottedName(node.expression)) {
67355 error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
67356 }
67357 else if (!getEffectsSignature(node)) {
67358 var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
67359 getTypeOfDottedName(node.expression, diagnostic);
67360 }
67361 }
67362 if (ts.isInJSFile(node)) {
67363 var decl = ts.getDeclarationOfExpando(node);
67364 if (decl) {
67365 var jsSymbol = getSymbolOfNode(decl);
67366 if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) {
67367 var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
67368 jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
67369 return getIntersectionType([returnType, jsAssignmentType]);
67370 }
67371 }
67372 }
67373 return returnType;
67374 }
67375 function checkDeprecatedSignature(signature, node) {
67376 if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
67377 var suggestionNode = getDeprecatedSuggestionNode(node);
67378 errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature));
67379 }
67380 }
67381 function getDeprecatedSuggestionNode(node) {
67382 node = ts.skipParentheses(node);
67383 switch (node.kind) {
67384 case 200 /* CallExpression */:
67385 case 160 /* Decorator */:
67386 case 201 /* NewExpression */:
67387 return getDeprecatedSuggestionNode(node.expression);
67388 case 202 /* TaggedTemplateExpression */:
67389 return getDeprecatedSuggestionNode(node.tag);
67390 case 272 /* JsxOpeningElement */:
67391 case 271 /* JsxSelfClosingElement */:
67392 return getDeprecatedSuggestionNode(node.tagName);
67393 case 199 /* ElementAccessExpression */:
67394 return node.argumentExpression;
67395 case 198 /* PropertyAccessExpression */:
67396 return node.name;
67397 case 172 /* TypeReference */:
67398 var typeReference = node;
67399 return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
67400 default:
67401 return node;
67402 }
67403 }
67404 function isSymbolOrSymbolForCall(node) {
67405 if (!ts.isCallExpression(node))
67406 return false;
67407 var left = node.expression;
67408 if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
67409 left = left.expression;
67410 }
67411 if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
67412 return false;
67413 }
67414 // make sure `Symbol` is the global symbol
67415 var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
67416 if (!globalESSymbol) {
67417 return false;
67418 }
67419 return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
67420 }
67421 function checkImportCallExpression(node) {
67422 // Check grammar of dynamic import
67423 if (!checkGrammarArguments(node.arguments))
67424 checkGrammarImportCallExpression(node);
67425 if (node.arguments.length === 0) {
67426 return createPromiseReturnType(node, anyType);
67427 }
67428 var specifier = node.arguments[0];
67429 var specifierType = checkExpressionCached(specifier);
67430 // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
67431 for (var i = 1; i < node.arguments.length; ++i) {
67432 checkExpressionCached(node.arguments[i]);
67433 }
67434 if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
67435 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
67436 }
67437 // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
67438 var moduleSymbol = resolveExternalModuleName(node, specifier);
67439 if (moduleSymbol) {
67440 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
67441 if (esModuleSymbol) {
67442 return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
67443 }
67444 }
67445 return createPromiseReturnType(node, anyType);
67446 }
67447 function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
67448 if (allowSyntheticDefaultImports && type && type !== errorType) {
67449 var synthType = type;
67450 if (!synthType.syntheticType) {
67451 var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
67452 var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
67453 if (hasSyntheticDefault) {
67454 var memberTable = ts.createSymbolTable();
67455 var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
67456 newSymbol.nameType = getLiteralType("default");
67457 newSymbol.target = resolveSymbol(symbol);
67458 memberTable.set("default" /* Default */, newSymbol);
67459 var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
67460 var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
67461 anonymousSymbol.type = defaultContainingObject;
67462 synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
67463 }
67464 else {
67465 synthType.syntheticType = type;
67466 }
67467 }
67468 return synthType.syntheticType;
67469 }
67470 return type;
67471 }
67472 function isCommonJsRequire(node) {
67473 if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
67474 return false;
67475 }
67476 // Make sure require is not a local function
67477 if (!ts.isIdentifier(node.expression))
67478 return ts.Debug.fail();
67479 var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
67480 if (resolvedRequire === requireSymbol) {
67481 return true;
67482 }
67483 // project includes symbol named 'require' - make sure that it is ambient and local non-alias
67484 if (resolvedRequire.flags & 2097152 /* Alias */) {
67485 return false;
67486 }
67487 var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
67488 ? 248 /* FunctionDeclaration */
67489 : resolvedRequire.flags & 3 /* Variable */
67490 ? 246 /* VariableDeclaration */
67491 : 0 /* Unknown */;
67492 if (targetDeclarationKind !== 0 /* Unknown */) {
67493 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
67494 // function/variable declaration should be ambient
67495 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
67496 }
67497 return false;
67498 }
67499 function checkTaggedTemplateExpression(node) {
67500 if (!checkGrammarTaggedTemplateChain(node))
67501 checkGrammarTypeArguments(node, node.typeArguments);
67502 if (languageVersion < 2 /* ES2015 */) {
67503 checkExternalEmitHelpers(node, 524288 /* MakeTemplateObject */);
67504 }
67505 var signature = getResolvedSignature(node);
67506 checkDeprecatedSignature(signature, node);
67507 return getReturnTypeOfSignature(signature);
67508 }
67509 function checkAssertion(node) {
67510 return checkAssertionWorker(node, node.type, node.expression);
67511 }
67512 function isValidConstAssertionArgument(node) {
67513 switch (node.kind) {
67514 case 10 /* StringLiteral */:
67515 case 14 /* NoSubstitutionTemplateLiteral */:
67516 case 8 /* NumericLiteral */:
67517 case 9 /* BigIntLiteral */:
67518 case 109 /* TrueKeyword */:
67519 case 94 /* FalseKeyword */:
67520 case 196 /* ArrayLiteralExpression */:
67521 case 197 /* ObjectLiteralExpression */:
67522 return true;
67523 case 204 /* ParenthesizedExpression */:
67524 return isValidConstAssertionArgument(node.expression);
67525 case 211 /* PrefixUnaryExpression */:
67526 var op = node.operator;
67527 var arg = node.operand;
67528 return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
67529 op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
67530 case 198 /* PropertyAccessExpression */:
67531 case 199 /* ElementAccessExpression */:
67532 var expr = node.expression;
67533 if (ts.isIdentifier(expr)) {
67534 var symbol = getSymbolAtLocation(expr);
67535 if (symbol && symbol.flags & 2097152 /* Alias */) {
67536 symbol = resolveAlias(symbol);
67537 }
67538 return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
67539 }
67540 }
67541 return false;
67542 }
67543 function checkAssertionWorker(errNode, type, expression, checkMode) {
67544 var exprType = checkExpression(expression, checkMode);
67545 if (ts.isConstTypeReference(type)) {
67546 if (!isValidConstAssertionArgument(expression)) {
67547 error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
67548 }
67549 return getRegularTypeOfLiteralType(exprType);
67550 }
67551 checkSourceElement(type);
67552 exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
67553 var targetType = getTypeFromTypeNode(type);
67554 if (produceDiagnostics && targetType !== errorType) {
67555 var widenedType = getWidenedType(exprType);
67556 if (!isTypeComparableTo(targetType, widenedType)) {
67557 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);
67558 }
67559 }
67560 return targetType;
67561 }
67562 function checkNonNullChain(node) {
67563 var leftType = checkExpression(node.expression);
67564 var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
67565 return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
67566 }
67567 function checkNonNullAssertion(node) {
67568 return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
67569 getNonNullableType(checkExpression(node.expression));
67570 }
67571 function checkMetaProperty(node) {
67572 checkGrammarMetaProperty(node);
67573 if (node.keywordToken === 102 /* NewKeyword */) {
67574 return checkNewTargetMetaProperty(node);
67575 }
67576 if (node.keywordToken === 99 /* ImportKeyword */) {
67577 return checkImportMetaProperty(node);
67578 }
67579 return ts.Debug.assertNever(node.keywordToken);
67580 }
67581 function checkNewTargetMetaProperty(node) {
67582 var container = ts.getNewTargetContainer(node);
67583 if (!container) {
67584 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
67585 return errorType;
67586 }
67587 else if (container.kind === 165 /* Constructor */) {
67588 var symbol = getSymbolOfNode(container.parent);
67589 return getTypeOfSymbol(symbol);
67590 }
67591 else {
67592 var symbol = getSymbolOfNode(container);
67593 return getTypeOfSymbol(symbol);
67594 }
67595 }
67596 function checkImportMetaProperty(node) {
67597 if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
67598 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
67599 }
67600 var file = ts.getSourceFileOfNode(node);
67601 ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
67602 ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
67603 return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
67604 }
67605 function getTypeOfParameter(symbol) {
67606 var type = getTypeOfSymbol(symbol);
67607 if (strictNullChecks) {
67608 var declaration = symbol.valueDeclaration;
67609 if (declaration && ts.hasInitializer(declaration)) {
67610 return getOptionalType(type);
67611 }
67612 }
67613 return type;
67614 }
67615 function getTupleElementLabel(d) {
67616 ts.Debug.assert(ts.isIdentifier(d.name)); // Parameter declarations could be binding patterns, but we only allow identifier names
67617 return d.name.escapedText;
67618 }
67619 function getParameterNameAtPosition(signature, pos, overrideRestType) {
67620 var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
67621 if (pos < paramCount) {
67622 return signature.parameters[pos].escapedName;
67623 }
67624 var restParameter = signature.parameters[paramCount] || unknownSymbol;
67625 var restType = overrideRestType || getTypeOfSymbol(restParameter);
67626 if (isTupleType(restType)) {
67627 var associatedNames = restType.target.labeledElementDeclarations;
67628 var index = pos - paramCount;
67629 return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index;
67630 }
67631 return restParameter.escapedName;
67632 }
67633 function isValidDeclarationForTupleLabel(d) {
67634 return d.kind === 191 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name));
67635 }
67636 function getNameableDeclarationAtPosition(signature, pos) {
67637 var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
67638 if (pos < paramCount) {
67639 var decl = signature.parameters[pos].valueDeclaration;
67640 return decl && isValidDeclarationForTupleLabel(decl) ? decl : undefined;
67641 }
67642 var restParameter = signature.parameters[paramCount] || unknownSymbol;
67643 var restType = getTypeOfSymbol(restParameter);
67644 if (isTupleType(restType)) {
67645 var associatedNames = restType.target.labeledElementDeclarations;
67646 var index = pos - paramCount;
67647 return associatedNames && associatedNames[index];
67648 }
67649 return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : undefined;
67650 }
67651 function getTypeAtPosition(signature, pos) {
67652 return tryGetTypeAtPosition(signature, pos) || anyType;
67653 }
67654 function tryGetTypeAtPosition(signature, pos) {
67655 var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
67656 if (pos < paramCount) {
67657 return getTypeOfParameter(signature.parameters[pos]);
67658 }
67659 if (signatureHasRestParameter(signature)) {
67660 // We want to return the value undefined for an out of bounds parameter position,
67661 // so we need to check bounds here before calling getIndexedAccessType (which
67662 // otherwise would return the type 'undefined').
67663 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
67664 var index = pos - paramCount;
67665 if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) {
67666 return getIndexedAccessType(restType, getLiteralType(index));
67667 }
67668 }
67669 return undefined;
67670 }
67671 function getRestTypeAtPosition(source, pos) {
67672 var parameterCount = getParameterCount(source);
67673 var minArgumentCount = getMinArgumentCount(source);
67674 var restType = getEffectiveRestType(source);
67675 if (restType && pos >= parameterCount - 1) {
67676 return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
67677 }
67678 var types = [];
67679 var flags = [];
67680 var names = [];
67681 for (var i = pos; i < parameterCount; i++) {
67682 if (!restType || i < parameterCount - 1) {
67683 types.push(getTypeAtPosition(source, i));
67684 flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
67685 }
67686 else {
67687 types.push(restType);
67688 flags.push(8 /* Variadic */);
67689 }
67690 var name = getNameableDeclarationAtPosition(source, i);
67691 if (name) {
67692 names.push(name);
67693 }
67694 }
67695 return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
67696 }
67697 function getParameterCount(signature) {
67698 var length = signature.parameters.length;
67699 if (signatureHasRestParameter(signature)) {
67700 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
67701 if (isTupleType(restType)) {
67702 return length + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1);
67703 }
67704 }
67705 return length;
67706 }
67707 function getMinArgumentCount(signature, strongArityForUntypedJS) {
67708 if (signatureHasRestParameter(signature)) {
67709 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
67710 if (isTupleType(restType)) {
67711 var firstOptionalIndex = ts.findIndex(restType.target.elementFlags, function (f) { return !(f & 1 /* Required */); });
67712 var requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
67713 if (requiredCount > 0) {
67714 return signature.parameters.length - 1 + requiredCount;
67715 }
67716 }
67717 }
67718 if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
67719 return 0;
67720 }
67721 return signature.minArgumentCount;
67722 }
67723 function hasEffectiveRestParameter(signature) {
67724 if (signatureHasRestParameter(signature)) {
67725 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
67726 return !isTupleType(restType) || restType.target.hasRestElement;
67727 }
67728 return false;
67729 }
67730 function getEffectiveRestType(signature) {
67731 if (signatureHasRestParameter(signature)) {
67732 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
67733 if (!isTupleType(restType)) {
67734 return restType;
67735 }
67736 if (restType.target.hasRestElement) {
67737 return sliceTupleType(restType, restType.target.fixedLength);
67738 }
67739 }
67740 return undefined;
67741 }
67742 function getNonArrayRestType(signature) {
67743 var restType = getEffectiveRestType(signature);
67744 return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
67745 }
67746 function getTypeOfFirstParameterOfSignature(signature) {
67747 return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
67748 }
67749 function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
67750 return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
67751 }
67752 function inferFromAnnotatedParameters(signature, context, inferenceContext) {
67753 var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
67754 for (var i = 0; i < len; i++) {
67755 var declaration = signature.parameters[i].valueDeclaration;
67756 if (declaration.type) {
67757 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
67758 if (typeNode) {
67759 inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
67760 }
67761 }
67762 }
67763 var restType = getEffectiveRestType(context);
67764 if (restType && restType.flags & 262144 /* TypeParameter */) {
67765 // The contextual signature has a generic rest parameter. We first instantiate the contextual
67766 // signature (without fixing type parameters) and assign types to contextually typed parameters.
67767 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
67768 assignContextualParameterTypes(signature, instantiatedContext);
67769 // We then infer from a tuple type representing the parameters that correspond to the contextual
67770 // rest parameter.
67771 var restPos = getParameterCount(context) - 1;
67772 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
67773 }
67774 }
67775 function assignContextualParameterTypes(signature, context) {
67776 signature.typeParameters = context.typeParameters;
67777 if (context.thisParameter) {
67778 var parameter = signature.thisParameter;
67779 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
67780 if (!parameter) {
67781 signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
67782 }
67783 assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
67784 }
67785 }
67786 var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
67787 for (var i = 0; i < len; i++) {
67788 var parameter = signature.parameters[i];
67789 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
67790 var contextualParameterType = tryGetTypeAtPosition(context, i);
67791 assignParameterType(parameter, contextualParameterType);
67792 }
67793 }
67794 if (signatureHasRestParameter(signature)) {
67795 // parameter might be a transient symbol generated by use of `arguments` in the function body.
67796 var parameter = ts.last(signature.parameters);
67797 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
67798 var contextualParameterType = getRestTypeAtPosition(context, len);
67799 assignParameterType(parameter, contextualParameterType);
67800 }
67801 }
67802 }
67803 function assignNonContextualParameterTypes(signature) {
67804 if (signature.thisParameter) {
67805 assignParameterType(signature.thisParameter);
67806 }
67807 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
67808 var parameter = _a[_i];
67809 assignParameterType(parameter);
67810 }
67811 }
67812 function assignParameterType(parameter, type) {
67813 var links = getSymbolLinks(parameter);
67814 if (!links.type) {
67815 var declaration = parameter.valueDeclaration;
67816 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
67817 if (declaration.name.kind !== 78 /* Identifier */) {
67818 // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
67819 if (links.type === unknownType) {
67820 links.type = getTypeFromBindingPattern(declaration.name);
67821 }
67822 assignBindingElementTypes(declaration.name);
67823 }
67824 }
67825 }
67826 // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
67827 // the destructured type into the contained binding elements.
67828 function assignBindingElementTypes(pattern) {
67829 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
67830 var element = _a[_i];
67831 if (!ts.isOmittedExpression(element)) {
67832 if (element.name.kind === 78 /* Identifier */) {
67833 getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
67834 }
67835 else {
67836 assignBindingElementTypes(element.name);
67837 }
67838 }
67839 }
67840 }
67841 function createPromiseType(promisedType) {
67842 // creates a `Promise<T>` type where `T` is the promisedType argument
67843 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
67844 if (globalPromiseType !== emptyGenericType) {
67845 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
67846 promisedType = getAwaitedType(promisedType) || unknownType;
67847 return createTypeReference(globalPromiseType, [promisedType]);
67848 }
67849 return unknownType;
67850 }
67851 function createPromiseLikeType(promisedType) {
67852 // creates a `PromiseLike<T>` type where `T` is the promisedType argument
67853 var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
67854 if (globalPromiseLikeType !== emptyGenericType) {
67855 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
67856 promisedType = getAwaitedType(promisedType) || unknownType;
67857 return createTypeReference(globalPromiseLikeType, [promisedType]);
67858 }
67859 return unknownType;
67860 }
67861 function createPromiseReturnType(func, promisedType) {
67862 var promiseType = createPromiseType(promisedType);
67863 if (promiseType === unknownType) {
67864 error(func, ts.isImportCall(func) ?
67865 ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
67866 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);
67867 return errorType;
67868 }
67869 else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
67870 error(func, ts.isImportCall(func) ?
67871 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 :
67872 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);
67873 }
67874 return promiseType;
67875 }
67876 function getReturnTypeFromBody(func, checkMode) {
67877 if (!func.body) {
67878 return errorType;
67879 }
67880 var functionFlags = ts.getFunctionFlags(func);
67881 var isAsync = (functionFlags & 2 /* Async */) !== 0;
67882 var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
67883 var returnType;
67884 var yieldType;
67885 var nextType;
67886 var fallbackReturnType = voidType;
67887 if (func.body.kind !== 227 /* Block */) { // Async or normal arrow function
67888 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
67889 if (isAsync) {
67890 // From within an async function you can return either a non-promise value or a promise. Any
67891 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
67892 // return type of the body should be unwrapped to its awaited type, which we will wrap in
67893 // the native Promise<T> type later in this function.
67894 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);
67895 }
67896 }
67897 else if (isGenerator) { // Generator or AsyncGenerator function
67898 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
67899 if (!returnTypes) {
67900 fallbackReturnType = neverType;
67901 }
67902 else if (returnTypes.length > 0) {
67903 returnType = getUnionType(returnTypes, 2 /* Subtype */);
67904 }
67905 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
67906 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
67907 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
67908 }
67909 else { // Async or normal function
67910 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
67911 if (!types) {
67912 // For an async function, the return type will not be never, but rather a Promise for never.
67913 return functionFlags & 2 /* Async */
67914 ? createPromiseReturnType(func, neverType) // Async function
67915 : neverType; // Normal function
67916 }
67917 if (types.length === 0) {
67918 // For an async function, the return type will not be void, but rather a Promise for void.
67919 return functionFlags & 2 /* Async */
67920 ? createPromiseReturnType(func, voidType) // Async function
67921 : voidType; // Normal function
67922 }
67923 // Return a union of the return expression types.
67924 returnType = getUnionType(types, 2 /* Subtype */);
67925 }
67926 if (returnType || yieldType || nextType) {
67927 if (yieldType)
67928 reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
67929 if (returnType)
67930 reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
67931 if (nextType)
67932 reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
67933 if (returnType && isUnitType(returnType) ||
67934 yieldType && isUnitType(yieldType) ||
67935 nextType && isUnitType(nextType)) {
67936 var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
67937 var contextualType = !contextualSignature ? undefined :
67938 contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
67939 instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
67940 if (isGenerator) {
67941 yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
67942 returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
67943 nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
67944 }
67945 else {
67946 returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
67947 }
67948 }
67949 if (yieldType)
67950 yieldType = getWidenedType(yieldType);
67951 if (returnType)
67952 returnType = getWidenedType(returnType);
67953 if (nextType)
67954 nextType = getWidenedType(nextType);
67955 }
67956 if (isGenerator) {
67957 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
67958 }
67959 else {
67960 // From within an async function you can return either a non-promise value or a promise. Any
67961 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
67962 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
67963 return isAsync
67964 ? createPromiseType(returnType || fallbackReturnType)
67965 : returnType || fallbackReturnType;
67966 }
67967 }
67968 function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
67969 var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
67970 var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
67971 yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
67972 returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
67973 nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
67974 if (globalGeneratorType === emptyGenericType) {
67975 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
67976 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
67977 // nextType.
67978 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
67979 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
67980 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
67981 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
67982 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
67983 isTypeAssignableTo(iterableIteratorNextType, nextType)) {
67984 if (globalType !== emptyGenericType) {
67985 return createTypeFromGenericGlobalType(globalType, [yieldType]);
67986 }
67987 // The global IterableIterator type doesn't exist, so report an error
67988 resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
67989 return emptyObjectType;
67990 }
67991 // The global Generator type doesn't exist, so report an error
67992 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
67993 return emptyObjectType;
67994 }
67995 return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
67996 }
67997 function checkAndAggregateYieldOperandTypes(func, checkMode) {
67998 var yieldTypes = [];
67999 var nextTypes = [];
68000 var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
68001 ts.forEachYieldExpression(func.body, function (yieldExpression) {
68002 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
68003 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
68004 var nextType;
68005 if (yieldExpression.asteriskToken) {
68006 var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
68007 nextType = iterationTypes && iterationTypes.nextType;
68008 }
68009 else {
68010 nextType = getContextualType(yieldExpression);
68011 }
68012 if (nextType)
68013 ts.pushIfUnique(nextTypes, nextType);
68014 });
68015 return { yieldTypes: yieldTypes, nextTypes: nextTypes };
68016 }
68017 function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
68018 var errorNode = node.expression || node;
68019 // A `yield*` expression effectively yields everything that its operand yields
68020 var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
68021 return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
68022 ? 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
68023 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
68024 }
68025 /**
68026 * Collect the TypeFacts learned from a typeof switch with
68027 * total clauses `witnesses`, and the active clause ranging
68028 * from `start` to `end`. Parameter `hasDefault` denotes
68029 * whether the active clause contains a default clause.
68030 */
68031 function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
68032 var facts = 0 /* None */;
68033 // When in the default we only collect inequality facts
68034 // because default is 'in theory' a set of infinite
68035 // equalities.
68036 if (hasDefault) {
68037 // Value is not equal to any types after the active clause.
68038 for (var i = end; i < witnesses.length; i++) {
68039 facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
68040 }
68041 // Remove inequalities for types that appear in the
68042 // active clause because they appear before other
68043 // types collected so far.
68044 for (var i = start; i < end; i++) {
68045 facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
68046 }
68047 // Add inequalities for types before the active clause unconditionally.
68048 for (var i = 0; i < start; i++) {
68049 facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
68050 }
68051 }
68052 // When in an active clause without default the set of
68053 // equalities is finite.
68054 else {
68055 // Add equalities for all types in the active clause.
68056 for (var i = start; i < end; i++) {
68057 facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
68058 }
68059 // Remove equalities for types that appear before the
68060 // active clause.
68061 for (var i = 0; i < start; i++) {
68062 facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
68063 }
68064 }
68065 return facts;
68066 }
68067 function isExhaustiveSwitchStatement(node) {
68068 var links = getNodeLinks(node);
68069 return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
68070 }
68071 function computeExhaustiveSwitchStatement(node) {
68072 if (node.expression.kind === 208 /* TypeOfExpression */) {
68073 var operandType = getTypeOfExpression(node.expression.expression);
68074 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
68075 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
68076 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
68077 var type_4 = getBaseConstraintOfType(operandType) || operandType;
68078 // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
68079 if (type_4.flags & 3 /* AnyOrUnknown */) {
68080 return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
68081 }
68082 return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
68083 }
68084 var type = getTypeOfExpression(node.expression);
68085 if (!isLiteralType(type)) {
68086 return false;
68087 }
68088 var switchTypes = getSwitchClauseTypes(node);
68089 if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
68090 return false;
68091 }
68092 return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
68093 }
68094 function functionHasImplicitReturn(func) {
68095 return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
68096 }
68097 /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
68098 function checkAndAggregateReturnExpressionTypes(func, checkMode) {
68099 var functionFlags = ts.getFunctionFlags(func);
68100 var aggregatedTypes = [];
68101 var hasReturnWithNoExpression = functionHasImplicitReturn(func);
68102 var hasReturnOfTypeNever = false;
68103 ts.forEachReturnStatement(func.body, function (returnStatement) {
68104 var expr = returnStatement.expression;
68105 if (expr) {
68106 var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
68107 if (functionFlags & 2 /* Async */) {
68108 // From within an async function you can return either a non-promise value or a promise. Any
68109 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
68110 // return type of the body should be unwrapped to its awaited type, which should be wrapped in
68111 // the native Promise<T> type by the caller.
68112 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);
68113 }
68114 if (type.flags & 131072 /* Never */) {
68115 hasReturnOfTypeNever = true;
68116 }
68117 ts.pushIfUnique(aggregatedTypes, type);
68118 }
68119 else {
68120 hasReturnWithNoExpression = true;
68121 }
68122 });
68123 if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
68124 return undefined;
68125 }
68126 if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
68127 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
68128 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
68129 ts.pushIfUnique(aggregatedTypes, undefinedType);
68130 }
68131 return aggregatedTypes;
68132 }
68133 function mayReturnNever(func) {
68134 switch (func.kind) {
68135 case 205 /* FunctionExpression */:
68136 case 206 /* ArrowFunction */:
68137 return true;
68138 case 164 /* MethodDeclaration */:
68139 return func.parent.kind === 197 /* ObjectLiteralExpression */;
68140 default:
68141 return false;
68142 }
68143 }
68144 /**
68145 * TypeScript Specification 1.0 (6.3) - July 2014
68146 * An explicitly typed function whose return type isn't the Void type,
68147 * the Any type, or a union type containing the Void or Any type as a constituent
68148 * must have at least one return statement somewhere in its body.
68149 * An exception to this rule is if the function implementation consists of a single 'throw' statement.
68150 *
68151 * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
68152 */
68153 function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
68154 if (!produceDiagnostics) {
68155 return;
68156 }
68157 var functionFlags = ts.getFunctionFlags(func);
68158 var type = returnType && unwrapReturnType(returnType, functionFlags);
68159 // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
68160 if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
68161 return;
68162 }
68163 // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
68164 // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
68165 if (func.kind === 163 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 227 /* Block */ || !functionHasImplicitReturn(func)) {
68166 return;
68167 }
68168 var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
68169 if (type && type.flags & 131072 /* Never */) {
68170 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
68171 }
68172 else if (type && !hasExplicitReturn) {
68173 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
68174 // this function does not conform to the specification.
68175 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
68176 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
68177 }
68178 else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
68179 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
68180 }
68181 else if (compilerOptions.noImplicitReturns) {
68182 if (!type) {
68183 // If return type annotation is omitted check if function has any explicit return statements.
68184 // If it does not have any - its inferred return type is void - don't do any checks.
68185 // Otherwise get inferred return type from function body and report error only if it is not void / anytype
68186 if (!hasExplicitReturn) {
68187 return;
68188 }
68189 var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
68190 if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
68191 return;
68192 }
68193 }
68194 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
68195 }
68196 }
68197 function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
68198 ts.Debug.assert(node.kind !== 164 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
68199 checkNodeDeferred(node);
68200 // The identityMapper object is used to indicate that function expressions are wildcards
68201 if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
68202 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
68203 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
68204 // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
68205 var contextualSignature = getContextualSignature(node);
68206 if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
68207 var links = getNodeLinks(node);
68208 if (links.contextFreeType) {
68209 return links.contextFreeType;
68210 }
68211 var returnType = getReturnTypeFromBody(node, checkMode);
68212 var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
68213 var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
68214 returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
68215 return links.contextFreeType = returnOnlyType;
68216 }
68217 }
68218 return anyFunctionType;
68219 }
68220 // Grammar checking
68221 var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
68222 if (!hasGrammarError && node.kind === 205 /* FunctionExpression */) {
68223 checkGrammarForGenerator(node);
68224 }
68225 contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
68226 return getTypeOfSymbol(getSymbolOfNode(node));
68227 }
68228 function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
68229 var links = getNodeLinks(node);
68230 // Check if function expression is contextually typed and assign parameter types if so.
68231 if (!(links.flags & 1024 /* ContextChecked */)) {
68232 var contextualSignature = getContextualSignature(node);
68233 // If a type check is started at a function expression that is an argument of a function call, obtaining the
68234 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
68235 // already assigned contextual types.
68236 if (!(links.flags & 1024 /* ContextChecked */)) {
68237 links.flags |= 1024 /* ContextChecked */;
68238 var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
68239 if (!signature) {
68240 return;
68241 }
68242 if (isContextSensitive(node)) {
68243 if (contextualSignature) {
68244 var inferenceContext = getInferenceContext(node);
68245 if (checkMode && checkMode & 2 /* Inferential */) {
68246 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
68247 }
68248 var instantiatedContextualSignature = inferenceContext ?
68249 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
68250 assignContextualParameterTypes(signature, instantiatedContextualSignature);
68251 }
68252 else {
68253 // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
68254 assignNonContextualParameterTypes(signature);
68255 }
68256 }
68257 if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
68258 var returnType = getReturnTypeFromBody(node, checkMode);
68259 if (!signature.resolvedReturnType) {
68260 signature.resolvedReturnType = returnType;
68261 }
68262 }
68263 checkSignatureDeclaration(node);
68264 }
68265 }
68266 }
68267 function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
68268 ts.Debug.assert(node.kind !== 164 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
68269 var functionFlags = ts.getFunctionFlags(node);
68270 var returnType = getReturnTypeFromAnnotation(node);
68271 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
68272 if (node.body) {
68273 if (!ts.getEffectiveReturnTypeNode(node)) {
68274 // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
68275 // we need. An example is the noImplicitAny errors resulting from widening the return expression
68276 // of a function. Because checking of function expression bodies is deferred, there was never an
68277 // appropriate time to do this during the main walk of the file (see the comment at the top of
68278 // checkFunctionExpressionBodies). So it must be done now.
68279 getReturnTypeOfSignature(getSignatureFromDeclaration(node));
68280 }
68281 if (node.body.kind === 227 /* Block */) {
68282 checkSourceElement(node.body);
68283 }
68284 else {
68285 // From within an async function you can return either a non-promise value or a promise. Any
68286 // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
68287 // should not be checking assignability of a promise to the return type. Instead, we need to
68288 // check assignability of the awaited type of the expression body against the promised type of
68289 // its return type annotation.
68290 var exprType = checkExpression(node.body);
68291 var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
68292 if (returnOrPromisedType) {
68293 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
68294 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);
68295 checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
68296 }
68297 else { // Normal function
68298 checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
68299 }
68300 }
68301 }
68302 }
68303 }
68304 function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
68305 if (isAwaitValid === void 0) { isAwaitValid = false; }
68306 if (!isTypeAssignableTo(type, numberOrBigIntType)) {
68307 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
68308 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
68309 return false;
68310 }
68311 return true;
68312 }
68313 function isReadonlyAssignmentDeclaration(d) {
68314 if (!ts.isCallExpression(d)) {
68315 return false;
68316 }
68317 if (!ts.isBindableObjectDefinePropertyCall(d)) {
68318 return false;
68319 }
68320 var objectLitType = checkExpressionCached(d.arguments[2]);
68321 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
68322 if (valueType) {
68323 var writableProp = getPropertyOfType(objectLitType, "writable");
68324 var writableType = writableProp && getTypeOfSymbol(writableProp);
68325 if (!writableType || writableType === falseType || writableType === regularFalseType) {
68326 return true;
68327 }
68328 // We include this definition whereupon we walk back and check the type at the declaration because
68329 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
68330 // argument types, should the type be contextualized by the call itself.
68331 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
68332 var initializer = writableProp.valueDeclaration.initializer;
68333 var rawOriginalType = checkExpression(initializer);
68334 if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
68335 return true;
68336 }
68337 }
68338 return false;
68339 }
68340 var setProp = getPropertyOfType(objectLitType, "set");
68341 return !setProp;
68342 }
68343 function isReadonlySymbol(symbol) {
68344 // The following symbols are considered read-only:
68345 // Properties with a 'readonly' modifier
68346 // Variables declared with 'const'
68347 // Get accessors without matching set accessors
68348 // Enum members
68349 // Object.defineProperty assignments with writable false or no setter
68350 // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
68351 return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
68352 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
68353 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
68354 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
68355 symbol.flags & 8 /* EnumMember */ ||
68356 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
68357 }
68358 function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
68359 var _a, _b;
68360 if (assignmentKind === 0 /* None */) {
68361 // no assigment means it doesn't matter whether the entity is readonly
68362 return false;
68363 }
68364 if (isReadonlySymbol(symbol)) {
68365 // Allow assignments to readonly properties within constructors of the same class declaration.
68366 if (symbol.flags & 4 /* Property */ &&
68367 ts.isAccessExpression(expr) &&
68368 expr.expression.kind === 107 /* ThisKeyword */) {
68369 // Look for if this is the constructor for the class that `symbol` is a property of.
68370 var ctor = ts.getContainingFunction(expr);
68371 if (!(ctor && (ctor.kind === 165 /* Constructor */ || isJSConstructor(ctor)))) {
68372 return true;
68373 }
68374 if (symbol.valueDeclaration) {
68375 var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
68376 var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
68377 var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
68378 var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
68379 var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
68380 var isWriteableSymbol = isLocalPropertyDeclaration
68381 || isLocalParameterProperty
68382 || isLocalThisPropertyAssignment
68383 || isLocalThisPropertyAssignmentConstructorFunction;
68384 return !isWriteableSymbol;
68385 }
68386 }
68387 return true;
68388 }
68389 if (ts.isAccessExpression(expr)) {
68390 // references through namespace import should be readonly
68391 var node = ts.skipParentheses(expr.expression);
68392 if (node.kind === 78 /* Identifier */) {
68393 var symbol_2 = getNodeLinks(node).resolvedSymbol;
68394 if (symbol_2.flags & 2097152 /* Alias */) {
68395 var declaration = getDeclarationOfAliasSymbol(symbol_2);
68396 return !!declaration && declaration.kind === 260 /* NamespaceImport */;
68397 }
68398 }
68399 }
68400 return false;
68401 }
68402 function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
68403 // References are combinations of identifiers, parentheses, and property accesses.
68404 var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
68405 if (node.kind !== 78 /* Identifier */ && !ts.isAccessExpression(node)) {
68406 error(expr, invalidReferenceMessage);
68407 return false;
68408 }
68409 if (node.flags & 32 /* OptionalChain */) {
68410 error(expr, invalidOptionalChainMessage);
68411 return false;
68412 }
68413 return true;
68414 }
68415 function checkDeleteExpression(node) {
68416 checkExpression(node.expression);
68417 var expr = ts.skipParentheses(node.expression);
68418 if (!ts.isAccessExpression(expr)) {
68419 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
68420 return booleanType;
68421 }
68422 if (ts.isPropertyAccessExpression(expr) && ts.isPrivateIdentifier(expr.name)) {
68423 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
68424 }
68425 var links = getNodeLinks(expr);
68426 var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
68427 if (symbol) {
68428 if (isReadonlySymbol(symbol)) {
68429 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
68430 }
68431 checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol));
68432 }
68433 return booleanType;
68434 }
68435 function checkDeleteExpressionMustBeOptional(expr, type) {
68436 var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */;
68437 if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) {
68438 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
68439 }
68440 }
68441 function checkTypeOfExpression(node) {
68442 checkExpression(node.expression);
68443 return typeofType;
68444 }
68445 function checkVoidExpression(node) {
68446 checkExpression(node.expression);
68447 return undefinedWideningType;
68448 }
68449 function checkAwaitExpression(node) {
68450 // Grammar checking
68451 if (produceDiagnostics) {
68452 if (!(node.flags & 32768 /* AwaitContext */)) {
68453 if (ts.isInTopLevelContext(node)) {
68454 var sourceFile = ts.getSourceFileOfNode(node);
68455 if (!hasParseDiagnostics(sourceFile)) {
68456 var span = void 0;
68457 if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
68458 if (!span)
68459 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
68460 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);
68461 diagnostics.add(diagnostic);
68462 }
68463 if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
68464 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
68465 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);
68466 diagnostics.add(diagnostic);
68467 }
68468 }
68469 }
68470 else {
68471 // use of 'await' in non-async function
68472 var sourceFile = ts.getSourceFileOfNode(node);
68473 if (!hasParseDiagnostics(sourceFile)) {
68474 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
68475 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);
68476 var func = ts.getContainingFunction(node);
68477 if (func && func.kind !== 165 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
68478 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68479 ts.addRelatedInfo(diagnostic, relatedInfo);
68480 }
68481 diagnostics.add(diagnostic);
68482 }
68483 }
68484 }
68485 if (isInParameterInitializerBeforeContainingFunction(node)) {
68486 error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
68487 }
68488 }
68489 var operandType = checkExpression(node.expression);
68490 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);
68491 if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
68492 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
68493 }
68494 return awaitedType;
68495 }
68496 function checkPrefixUnaryExpression(node) {
68497 var operandType = checkExpression(node.operand);
68498 if (operandType === silentNeverType) {
68499 return silentNeverType;
68500 }
68501 switch (node.operand.kind) {
68502 case 8 /* NumericLiteral */:
68503 switch (node.operator) {
68504 case 40 /* MinusToken */:
68505 return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
68506 case 39 /* PlusToken */:
68507 return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
68508 }
68509 break;
68510 case 9 /* BigIntLiteral */:
68511 if (node.operator === 40 /* MinusToken */) {
68512 return getFreshTypeOfLiteralType(getLiteralType({
68513 negative: true,
68514 base10Value: ts.parsePseudoBigInt(node.operand.text)
68515 }));
68516 }
68517 }
68518 switch (node.operator) {
68519 case 39 /* PlusToken */:
68520 case 40 /* MinusToken */:
68521 case 54 /* TildeToken */:
68522 checkNonNullType(operandType, node.operand);
68523 if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
68524 error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
68525 }
68526 if (node.operator === 39 /* PlusToken */) {
68527 if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
68528 error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
68529 }
68530 return numberType;
68531 }
68532 return getUnaryResultType(operandType);
68533 case 53 /* ExclamationToken */:
68534 checkTruthinessExpression(node.operand);
68535 var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
68536 return facts === 4194304 /* Truthy */ ? falseType :
68537 facts === 8388608 /* Falsy */ ? trueType :
68538 booleanType;
68539 case 45 /* PlusPlusToken */:
68540 case 46 /* MinusMinusToken */:
68541 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);
68542 if (ok) {
68543 // run check only if former checks succeeded to avoid reporting cascading errors
68544 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);
68545 }
68546 return getUnaryResultType(operandType);
68547 }
68548 return errorType;
68549 }
68550 function checkPostfixUnaryExpression(node) {
68551 var operandType = checkExpression(node.operand);
68552 if (operandType === silentNeverType) {
68553 return silentNeverType;
68554 }
68555 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);
68556 if (ok) {
68557 // run check only if former checks succeeded to avoid reporting cascading errors
68558 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);
68559 }
68560 return getUnaryResultType(operandType);
68561 }
68562 function getUnaryResultType(operandType) {
68563 if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
68564 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
68565 ? numberOrBigIntType
68566 : bigintType;
68567 }
68568 // If it's not a bigint type, implicit coercion will result in a number
68569 return numberType;
68570 }
68571 // Return true if type might be of the given kind. A union or intersection type might be of a given
68572 // kind if at least one constituent type is of the given kind.
68573 function maybeTypeOfKind(type, kind) {
68574 if (type.flags & kind) {
68575 return true;
68576 }
68577 if (type.flags & 3145728 /* UnionOrIntersection */) {
68578 var types = type.types;
68579 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
68580 var t = types_19[_i];
68581 if (maybeTypeOfKind(t, kind)) {
68582 return true;
68583 }
68584 }
68585 }
68586 return false;
68587 }
68588 function isTypeAssignableToKind(source, kind, strict) {
68589 if (source.flags & kind) {
68590 return true;
68591 }
68592 if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
68593 return false;
68594 }
68595 return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
68596 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
68597 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
68598 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
68599 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
68600 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
68601 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
68602 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
68603 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
68604 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
68605 }
68606 function allTypesAssignableToKind(source, kind, strict) {
68607 return source.flags & 1048576 /* Union */ ?
68608 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
68609 isTypeAssignableToKind(source, kind, strict);
68610 }
68611 function isConstEnumObjectType(type) {
68612 return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
68613 }
68614 function isConstEnumSymbol(symbol) {
68615 return (symbol.flags & 128 /* ConstEnum */) !== 0;
68616 }
68617 function checkInstanceOfExpression(left, right, leftType, rightType) {
68618 if (leftType === silentNeverType || rightType === silentNeverType) {
68619 return silentNeverType;
68620 }
68621 // TypeScript 1.0 spec (April 2014): 4.15.4
68622 // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
68623 // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
68624 // The result is always of the Boolean primitive type.
68625 // NOTE: do not raise error if leftType is unknown as related error was already reported
68626 if (!isTypeAny(leftType) &&
68627 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
68628 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
68629 }
68630 // NOTE: do not raise error if right is unknown as related error was already reported
68631 if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
68632 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);
68633 }
68634 return booleanType;
68635 }
68636 function checkInExpression(left, right, leftType, rightType) {
68637 if (leftType === silentNeverType || rightType === silentNeverType) {
68638 return silentNeverType;
68639 }
68640 leftType = checkNonNullType(leftType, left);
68641 rightType = checkNonNullType(rightType, right);
68642 // TypeScript 1.0 spec (April 2014): 4.15.5
68643 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
68644 // and the right operand to be of type Any, an object type, or a type parameter type.
68645 // The result is always of the Boolean primitive type.
68646 if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
68647 isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) {
68648 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
68649 }
68650 if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
68651 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
68652 }
68653 return booleanType;
68654 }
68655 function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
68656 var properties = node.properties;
68657 if (strictNullChecks && properties.length === 0) {
68658 return checkNonNullType(sourceType, node);
68659 }
68660 for (var i = 0; i < properties.length; i++) {
68661 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
68662 }
68663 return sourceType;
68664 }
68665 /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
68666 function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
68667 if (rightIsThis === void 0) { rightIsThis = false; }
68668 var properties = node.properties;
68669 var property = properties[propertyIndex];
68670 if (property.kind === 285 /* PropertyAssignment */ || property.kind === 286 /* ShorthandPropertyAssignment */) {
68671 var name = property.name;
68672 var exprType = getLiteralTypeFromPropertyName(name);
68673 if (isTypeUsableAsPropertyName(exprType)) {
68674 var text = getPropertyNameFromType(exprType);
68675 var prop = getPropertyOfType(objectLiteralType, text);
68676 if (prop) {
68677 markPropertyAsReferenced(prop, property, rightIsThis);
68678 checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
68679 }
68680 }
68681 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
68682 var type = getFlowTypeOfDestructuring(property, elementType);
68683 return checkDestructuringAssignment(property.kind === 286 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
68684 }
68685 else if (property.kind === 287 /* SpreadAssignment */) {
68686 if (propertyIndex < properties.length - 1) {
68687 error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
68688 }
68689 else {
68690 if (languageVersion < 99 /* ESNext */) {
68691 checkExternalEmitHelpers(property, 4 /* Rest */);
68692 }
68693 var nonRestNames = [];
68694 if (allProperties) {
68695 for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
68696 var otherProperty = allProperties_1[_i];
68697 if (!ts.isSpreadAssignment(otherProperty)) {
68698 nonRestNames.push(otherProperty.name);
68699 }
68700 }
68701 }
68702 var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
68703 checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68704 return checkDestructuringAssignment(property.expression, type);
68705 }
68706 }
68707 else {
68708 error(property, ts.Diagnostics.Property_assignment_expected);
68709 }
68710 }
68711 function checkArrayLiteralAssignment(node, sourceType, checkMode) {
68712 var elements = node.elements;
68713 if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
68714 checkExternalEmitHelpers(node, 512 /* Read */);
68715 }
68716 // This elementType will be used if the specific property corresponding to this index is not
68717 // present (aka the tuple element property). This call also checks that the parentType is in
68718 // fact an iterable or array (depending on target language).
68719 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
68720 for (var i = 0; i < elements.length; i++) {
68721 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
68722 }
68723 return sourceType;
68724 }
68725 function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
68726 var elements = node.elements;
68727 var element = elements[elementIndex];
68728 if (element.kind !== 219 /* OmittedExpression */) {
68729 if (element.kind !== 217 /* SpreadElement */) {
68730 var indexType = getLiteralType(elementIndex);
68731 if (isArrayLikeType(sourceType)) {
68732 // We create a synthetic expression so that getIndexedAccessType doesn't get confused
68733 // when the element is a SyntaxKind.ElementAccessExpression.
68734 var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
68735 var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
68736 var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
68737 var type = getFlowTypeOfDestructuring(element, assignedType);
68738 return checkDestructuringAssignment(element, type, checkMode);
68739 }
68740 return checkDestructuringAssignment(element, elementType, checkMode);
68741 }
68742 if (elementIndex < elements.length - 1) {
68743 error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
68744 }
68745 else {
68746 var restExpression = element.expression;
68747 if (restExpression.kind === 213 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
68748 error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
68749 }
68750 else {
68751 checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68752 var type = everyType(sourceType, isTupleType) ?
68753 mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
68754 createArrayType(elementType);
68755 return checkDestructuringAssignment(restExpression, type, checkMode);
68756 }
68757 }
68758 }
68759 return undefined;
68760 }
68761 function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
68762 var target;
68763 if (exprOrAssignment.kind === 286 /* ShorthandPropertyAssignment */) {
68764 var prop = exprOrAssignment;
68765 if (prop.objectAssignmentInitializer) {
68766 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
68767 // undefined from the final type.
68768 if (strictNullChecks &&
68769 !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
68770 sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
68771 }
68772 checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
68773 }
68774 target = exprOrAssignment.name;
68775 }
68776 else {
68777 target = exprOrAssignment;
68778 }
68779 if (target.kind === 213 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
68780 checkBinaryExpression(target, checkMode);
68781 target = target.left;
68782 }
68783 if (target.kind === 197 /* ObjectLiteralExpression */) {
68784 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
68785 }
68786 if (target.kind === 196 /* ArrayLiteralExpression */) {
68787 return checkArrayLiteralAssignment(target, sourceType, checkMode);
68788 }
68789 return checkReferenceAssignment(target, sourceType, checkMode);
68790 }
68791 function checkReferenceAssignment(target, sourceType, checkMode) {
68792 var targetType = checkExpression(target, checkMode);
68793 var error = target.parent.kind === 287 /* SpreadAssignment */ ?
68794 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
68795 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
68796 var optionalError = target.parent.kind === 287 /* SpreadAssignment */ ?
68797 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
68798 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
68799 if (checkReferenceExpression(target, error, optionalError)) {
68800 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
68801 }
68802 if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
68803 checkExternalEmitHelpers(target.parent, 2097152 /* ClassPrivateFieldSet */);
68804 }
68805 return sourceType;
68806 }
68807 /**
68808 * This is a *shallow* check: An expression is side-effect-free if the
68809 * evaluation of the expression *itself* cannot produce side effects.
68810 * For example, x++ / 3 is side-effect free because the / operator
68811 * does not have side effects.
68812 * The intent is to "smell test" an expression for correctness in positions where
68813 * its value is discarded (e.g. the left side of the comma operator).
68814 */
68815 function isSideEffectFree(node) {
68816 node = ts.skipParentheses(node);
68817 switch (node.kind) {
68818 case 78 /* Identifier */:
68819 case 10 /* StringLiteral */:
68820 case 13 /* RegularExpressionLiteral */:
68821 case 202 /* TaggedTemplateExpression */:
68822 case 215 /* TemplateExpression */:
68823 case 14 /* NoSubstitutionTemplateLiteral */:
68824 case 8 /* NumericLiteral */:
68825 case 9 /* BigIntLiteral */:
68826 case 109 /* TrueKeyword */:
68827 case 94 /* FalseKeyword */:
68828 case 103 /* NullKeyword */:
68829 case 149 /* UndefinedKeyword */:
68830 case 205 /* FunctionExpression */:
68831 case 218 /* ClassExpression */:
68832 case 206 /* ArrowFunction */:
68833 case 196 /* ArrayLiteralExpression */:
68834 case 197 /* ObjectLiteralExpression */:
68835 case 208 /* TypeOfExpression */:
68836 case 222 /* NonNullExpression */:
68837 case 271 /* JsxSelfClosingElement */:
68838 case 270 /* JsxElement */:
68839 return true;
68840 case 214 /* ConditionalExpression */:
68841 return isSideEffectFree(node.whenTrue) &&
68842 isSideEffectFree(node.whenFalse);
68843 case 213 /* BinaryExpression */:
68844 if (ts.isAssignmentOperator(node.operatorToken.kind)) {
68845 return false;
68846 }
68847 return isSideEffectFree(node.left) &&
68848 isSideEffectFree(node.right);
68849 case 211 /* PrefixUnaryExpression */:
68850 case 212 /* PostfixUnaryExpression */:
68851 // Unary operators ~, !, +, and - have no side effects.
68852 // The rest do.
68853 switch (node.operator) {
68854 case 53 /* ExclamationToken */:
68855 case 39 /* PlusToken */:
68856 case 40 /* MinusToken */:
68857 case 54 /* TildeToken */:
68858 return true;
68859 }
68860 return false;
68861 // Some forms listed here for clarity
68862 case 209 /* VoidExpression */: // Explicit opt-out
68863 case 203 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
68864 case 221 /* AsExpression */: // Not SEF, but can produce useful type warnings
68865 default:
68866 return false;
68867 }
68868 }
68869 function isTypeEqualityComparableTo(source, target) {
68870 return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
68871 }
68872 var CheckBinaryExpressionState;
68873 (function (CheckBinaryExpressionState) {
68874 CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
68875 CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
68876 CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
68877 })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
68878 function checkBinaryExpression(node, checkMode) {
68879 var workStacks = {
68880 expr: [node],
68881 state: [0 /* MaybeCheckLeft */],
68882 leftType: [undefined]
68883 };
68884 var stackIndex = 0;
68885 var lastResult;
68886 while (stackIndex >= 0) {
68887 node = workStacks.expr[stackIndex];
68888 switch (workStacks.state[stackIndex]) {
68889 case 0 /* MaybeCheckLeft */: {
68890 if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
68891 finishInvocation(checkExpression(node.right, checkMode));
68892 break;
68893 }
68894 checkGrammarNullishCoalesceWithLogicalExpression(node);
68895 var operator = node.operatorToken.kind;
68896 if (operator === 62 /* EqualsToken */ && (node.left.kind === 197 /* ObjectLiteralExpression */ || node.left.kind === 196 /* ArrayLiteralExpression */)) {
68897 finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */));
68898 break;
68899 }
68900 advanceState(1 /* CheckRight */);
68901 maybeCheckExpression(node.left);
68902 break;
68903 }
68904 case 1 /* CheckRight */: {
68905 var leftType = lastResult;
68906 workStacks.leftType[stackIndex] = leftType;
68907 var operator = node.operatorToken.kind;
68908 if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
68909 checkTruthinessOfType(leftType, node.left);
68910 }
68911 advanceState(2 /* FinishCheck */);
68912 maybeCheckExpression(node.right);
68913 break;
68914 }
68915 case 2 /* FinishCheck */: {
68916 var leftType = workStacks.leftType[stackIndex];
68917 var rightType = lastResult;
68918 finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
68919 break;
68920 }
68921 default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
68922 }
68923 }
68924 return lastResult;
68925 function finishInvocation(result) {
68926 lastResult = result;
68927 stackIndex--;
68928 }
68929 /**
68930 * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
68931 * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
68932 */
68933 function advanceState(nextState) {
68934 workStacks.state[stackIndex] = nextState;
68935 }
68936 function maybeCheckExpression(node) {
68937 if (ts.isBinaryExpression(node)) {
68938 stackIndex++;
68939 workStacks.expr[stackIndex] = node;
68940 workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
68941 workStacks.leftType[stackIndex] = undefined;
68942 }
68943 else {
68944 lastResult = checkExpression(node, checkMode);
68945 }
68946 }
68947 }
68948 function checkGrammarNullishCoalesceWithLogicalExpression(node) {
68949 var left = node.left, operatorToken = node.operatorToken, right = node.right;
68950 if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
68951 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
68952 grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
68953 }
68954 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
68955 grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
68956 }
68957 }
68958 }
68959 // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
68960 // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
68961 function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
68962 var operator = operatorToken.kind;
68963 if (operator === 62 /* EqualsToken */ && (left.kind === 197 /* ObjectLiteralExpression */ || left.kind === 196 /* ArrayLiteralExpression */)) {
68964 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */);
68965 }
68966 var leftType;
68967 if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
68968 leftType = checkTruthinessExpression(left, checkMode);
68969 }
68970 else {
68971 leftType = checkExpression(left, checkMode);
68972 }
68973 var rightType = checkExpression(right, checkMode);
68974 return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
68975 }
68976 function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
68977 var operator = operatorToken.kind;
68978 switch (operator) {
68979 case 41 /* AsteriskToken */:
68980 case 42 /* AsteriskAsteriskToken */:
68981 case 65 /* AsteriskEqualsToken */:
68982 case 66 /* AsteriskAsteriskEqualsToken */:
68983 case 43 /* SlashToken */:
68984 case 67 /* SlashEqualsToken */:
68985 case 44 /* PercentToken */:
68986 case 68 /* PercentEqualsToken */:
68987 case 40 /* MinusToken */:
68988 case 64 /* MinusEqualsToken */:
68989 case 47 /* LessThanLessThanToken */:
68990 case 69 /* LessThanLessThanEqualsToken */:
68991 case 48 /* GreaterThanGreaterThanToken */:
68992 case 70 /* GreaterThanGreaterThanEqualsToken */:
68993 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
68994 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
68995 case 51 /* BarToken */:
68996 case 73 /* BarEqualsToken */:
68997 case 52 /* CaretToken */:
68998 case 77 /* CaretEqualsToken */:
68999 case 50 /* AmpersandToken */:
69000 case 72 /* AmpersandEqualsToken */:
69001 if (leftType === silentNeverType || rightType === silentNeverType) {
69002 return silentNeverType;
69003 }
69004 leftType = checkNonNullType(leftType, left);
69005 rightType = checkNonNullType(rightType, right);
69006 var suggestedOperator = void 0;
69007 // if a user tries to apply a bitwise operator to 2 boolean operands
69008 // try and return them a helpful suggestion
69009 if ((leftType.flags & 528 /* BooleanLike */) &&
69010 (rightType.flags & 528 /* BooleanLike */) &&
69011 (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
69012 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));
69013 return numberType;
69014 }
69015 else {
69016 // otherwise just check each operand separately and report errors as normal
69017 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);
69018 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);
69019 var resultType_1;
69020 // If both are any or unknown, allow operation; assume it will resolve to number
69021 if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
69022 // Or, if neither could be bigint, implicit coercion results in a number result
69023 !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
69024 resultType_1 = numberType;
69025 }
69026 // At least one is assignable to bigint, so check that both are
69027 else if (bothAreBigIntLike(leftType, rightType)) {
69028 switch (operator) {
69029 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
69030 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
69031 reportOperatorError();
69032 break;
69033 case 42 /* AsteriskAsteriskToken */:
69034 case 66 /* AsteriskAsteriskEqualsToken */:
69035 if (languageVersion < 3 /* ES2016 */) {
69036 error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
69037 }
69038 }
69039 resultType_1 = bigintType;
69040 }
69041 // Exactly one of leftType/rightType is assignable to bigint
69042 else {
69043 reportOperatorError(bothAreBigIntLike);
69044 resultType_1 = errorType;
69045 }
69046 if (leftOk && rightOk) {
69047 checkAssignmentOperator(resultType_1);
69048 }
69049 return resultType_1;
69050 }
69051 case 39 /* PlusToken */:
69052 case 63 /* PlusEqualsToken */:
69053 if (leftType === silentNeverType || rightType === silentNeverType) {
69054 return silentNeverType;
69055 }
69056 if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
69057 leftType = checkNonNullType(leftType, left);
69058 rightType = checkNonNullType(rightType, right);
69059 }
69060 var resultType = void 0;
69061 if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
69062 // Operands of an enum type are treated as having the primitive type Number.
69063 // If both operands are of the Number primitive type, the result is of the Number primitive type.
69064 resultType = numberType;
69065 }
69066 else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
69067 // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
69068 resultType = bigintType;
69069 }
69070 else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
69071 // If one or both operands are of the String primitive type, the result is of the String primitive type.
69072 resultType = stringType;
69073 }
69074 else if (isTypeAny(leftType) || isTypeAny(rightType)) {
69075 // Otherwise, the result is of type Any.
69076 // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
69077 resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
69078 }
69079 // Symbols are not allowed at all in arithmetic expressions
69080 if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
69081 return resultType;
69082 }
69083 if (!resultType) {
69084 // Types that have a reasonably good chance of being a valid operand type.
69085 // If both types have an awaited type of one of these, we'll assume the user
69086 // might be missing an await without doing an exhaustive check that inserting
69087 // await(s) will actually be a completely valid binary expression.
69088 var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
69089 reportOperatorError(function (left, right) {
69090 return isTypeAssignableToKind(left, closeEnoughKind_1) &&
69091 isTypeAssignableToKind(right, closeEnoughKind_1);
69092 });
69093 return anyType;
69094 }
69095 if (operator === 63 /* PlusEqualsToken */) {
69096 checkAssignmentOperator(resultType);
69097 }
69098 return resultType;
69099 case 29 /* LessThanToken */:
69100 case 31 /* GreaterThanToken */:
69101 case 32 /* LessThanEqualsToken */:
69102 case 33 /* GreaterThanEqualsToken */:
69103 if (checkForDisallowedESSymbolOperand(operator)) {
69104 leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
69105 rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
69106 reportOperatorErrorUnless(function (left, right) {
69107 return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
69108 });
69109 }
69110 return booleanType;
69111 case 34 /* EqualsEqualsToken */:
69112 case 35 /* ExclamationEqualsToken */:
69113 case 36 /* EqualsEqualsEqualsToken */:
69114 case 37 /* ExclamationEqualsEqualsToken */:
69115 reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
69116 return booleanType;
69117 case 101 /* InstanceOfKeyword */:
69118 return checkInstanceOfExpression(left, right, leftType, rightType);
69119 case 100 /* InKeyword */:
69120 return checkInExpression(left, right, leftType, rightType);
69121 case 55 /* AmpersandAmpersandToken */:
69122 case 75 /* AmpersandAmpersandEqualsToken */: {
69123 var resultType_2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ?
69124 getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
69125 leftType;
69126 if (operator === 75 /* AmpersandAmpersandEqualsToken */) {
69127 checkAssignmentOperator(rightType);
69128 }
69129 return resultType_2;
69130 }
69131 case 56 /* BarBarToken */:
69132 case 74 /* BarBarEqualsToken */: {
69133 var resultType_3 = getTypeFacts(leftType) & 8388608 /* Falsy */ ?
69134 getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
69135 leftType;
69136 if (operator === 74 /* BarBarEqualsToken */) {
69137 checkAssignmentOperator(rightType);
69138 }
69139 return resultType_3;
69140 }
69141 case 60 /* QuestionQuestionToken */:
69142 case 76 /* QuestionQuestionEqualsToken */: {
69143 var resultType_4 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
69144 getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
69145 leftType;
69146 if (operator === 76 /* QuestionQuestionEqualsToken */) {
69147 checkAssignmentOperator(rightType);
69148 }
69149 return resultType_4;
69150 }
69151 case 62 /* EqualsToken */:
69152 var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
69153 checkAssignmentDeclaration(declKind, rightType);
69154 if (isAssignmentDeclaration(declKind)) {
69155 if (!(rightType.flags & 524288 /* Object */) ||
69156 declKind !== 2 /* ModuleExports */ &&
69157 declKind !== 6 /* Prototype */ &&
69158 !isEmptyObjectType(rightType) &&
69159 !isFunctionObjectType(rightType) &&
69160 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
69161 // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
69162 checkAssignmentOperator(rightType);
69163 }
69164 return leftType;
69165 }
69166 else {
69167 checkAssignmentOperator(rightType);
69168 return getRegularTypeOfObjectLiteral(rightType);
69169 }
69170 case 27 /* CommaToken */:
69171 if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
69172 var sf = ts.getSourceFileOfNode(left);
69173 var sourceText = sf.text;
69174 var start_3 = ts.skipTrivia(sourceText, left.pos);
69175 var isInDiag2657 = sf.parseDiagnostics.some(function (diag) {
69176 if (diag.code !== ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code)
69177 return false;
69178 return ts.textSpanContainsPosition(diag, start_3);
69179 });
69180 if (!isInDiag2657)
69181 error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
69182 }
69183 return rightType;
69184 default:
69185 return ts.Debug.fail();
69186 }
69187 function bothAreBigIntLike(left, right) {
69188 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
69189 }
69190 function checkAssignmentDeclaration(kind, rightType) {
69191 if (kind === 2 /* ModuleExports */) {
69192 for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
69193 var prop = _a[_i];
69194 var propType = getTypeOfSymbol(prop);
69195 if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
69196 var name = prop.escapedName;
69197 var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
69198 if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
69199 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
69200 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
69201 }
69202 }
69203 }
69204 }
69205 }
69206 function isEvalNode(node) {
69207 return node.kind === 78 /* Identifier */ && node.escapedText === "eval";
69208 }
69209 // Return true if there was no error, false if there was an error.
69210 function checkForDisallowedESSymbolOperand(operator) {
69211 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
69212 maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
69213 undefined;
69214 if (offendingSymbolOperand) {
69215 error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
69216 return false;
69217 }
69218 return true;
69219 }
69220 function getSuggestedBooleanOperator(operator) {
69221 switch (operator) {
69222 case 51 /* BarToken */:
69223 case 73 /* BarEqualsToken */:
69224 return 56 /* BarBarToken */;
69225 case 52 /* CaretToken */:
69226 case 77 /* CaretEqualsToken */:
69227 return 37 /* ExclamationEqualsEqualsToken */;
69228 case 50 /* AmpersandToken */:
69229 case 72 /* AmpersandEqualsToken */:
69230 return 55 /* AmpersandAmpersandToken */;
69231 default:
69232 return undefined;
69233 }
69234 }
69235 function checkAssignmentOperator(valueType) {
69236 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
69237 // TypeScript 1.0 spec (April 2014): 4.17
69238 // An assignment of the form
69239 // VarExpr = ValueExpr
69240 // requires VarExpr to be classified as a reference
69241 // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
69242 // and the type of the non-compound operation to be assignable to the type of VarExpr.
69243 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)
69244 && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
69245 // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
69246 checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
69247 }
69248 }
69249 }
69250 function isAssignmentDeclaration(kind) {
69251 var _a;
69252 switch (kind) {
69253 case 2 /* ModuleExports */:
69254 return true;
69255 case 1 /* ExportsProperty */:
69256 case 5 /* Property */:
69257 case 6 /* Prototype */:
69258 case 3 /* PrototypeProperty */:
69259 case 4 /* ThisProperty */:
69260 var symbol = getSymbolOfNode(left);
69261 var init = ts.getAssignedExpandoInitializer(right);
69262 return !!init && ts.isObjectLiteralExpression(init) &&
69263 !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
69264 default:
69265 return false;
69266 }
69267 }
69268 /**
69269 * Returns true if an error is reported
69270 */
69271 function reportOperatorErrorUnless(typesAreCompatible) {
69272 if (!typesAreCompatible(leftType, rightType)) {
69273 reportOperatorError(typesAreCompatible);
69274 return true;
69275 }
69276 return false;
69277 }
69278 function reportOperatorError(isRelated) {
69279 var _a;
69280 var wouldWorkWithAwait = false;
69281 var errNode = errorNode || operatorToken;
69282 if (isRelated) {
69283 var awaitedLeftType = getAwaitedType(leftType);
69284 var awaitedRightType = getAwaitedType(rightType);
69285 wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
69286 && !!(awaitedLeftType && awaitedRightType)
69287 && isRelated(awaitedLeftType, awaitedRightType);
69288 }
69289 var effectiveLeft = leftType;
69290 var effectiveRight = rightType;
69291 if (!wouldWorkWithAwait && isRelated) {
69292 _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
69293 }
69294 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
69295 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
69296 errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
69297 }
69298 }
69299 function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
69300 var typeName;
69301 switch (operatorToken.kind) {
69302 case 36 /* EqualsEqualsEqualsToken */:
69303 case 34 /* EqualsEqualsToken */:
69304 typeName = "false";
69305 break;
69306 case 37 /* ExclamationEqualsEqualsToken */:
69307 case 35 /* ExclamationEqualsToken */:
69308 typeName = "true";
69309 }
69310 if (typeName) {
69311 return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
69312 }
69313 return undefined;
69314 }
69315 }
69316 function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
69317 var effectiveLeft = leftType;
69318 var effectiveRight = rightType;
69319 var leftBase = getBaseTypeOfLiteralType(leftType);
69320 var rightBase = getBaseTypeOfLiteralType(rightType);
69321 if (!isRelated(leftBase, rightBase)) {
69322 effectiveLeft = leftBase;
69323 effectiveRight = rightBase;
69324 }
69325 return [effectiveLeft, effectiveRight];
69326 }
69327 function checkYieldExpression(node) {
69328 // Grammar checking
69329 if (produceDiagnostics) {
69330 if (!(node.flags & 8192 /* YieldContext */)) {
69331 grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
69332 }
69333 if (isInParameterInitializerBeforeContainingFunction(node)) {
69334 error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
69335 }
69336 }
69337 var func = ts.getContainingFunction(node);
69338 if (!func)
69339 return anyType;
69340 var functionFlags = ts.getFunctionFlags(func);
69341 if (!(functionFlags & 1 /* Generator */)) {
69342 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
69343 return anyType;
69344 }
69345 var isAsync = (functionFlags & 2 /* Async */) !== 0;
69346 if (node.asteriskToken) {
69347 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
69348 // and __asyncValues helpers
69349 if (isAsync && languageVersion < 99 /* ESNext */) {
69350 checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
69351 }
69352 // Generator functions prior to ES2015 require the __values helper
69353 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
69354 checkExternalEmitHelpers(node, 256 /* Values */);
69355 }
69356 }
69357 // There is no point in doing an assignability check if the function
69358 // has no explicit return type because the return type is directly computed
69359 // from the yield expressions.
69360 var returnType = getReturnTypeFromAnnotation(func);
69361 var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
69362 var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
69363 var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
69364 var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
69365 var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
69366 var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
69367 if (returnType && yieldedType) {
69368 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
69369 }
69370 if (node.asteriskToken) {
69371 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
69372 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
69373 || anyType;
69374 }
69375 else if (returnType) {
69376 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
69377 || anyType;
69378 }
69379 return getContextualIterationType(2 /* Next */, func) || anyType;
69380 }
69381 function checkConditionalExpression(node, checkMode) {
69382 var type = checkTruthinessExpression(node.condition);
69383 checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
69384 var type1 = checkExpression(node.whenTrue, checkMode);
69385 var type2 = checkExpression(node.whenFalse, checkMode);
69386 return getUnionType([type1, type2], 2 /* Subtype */);
69387 }
69388 function checkTemplateExpression(node) {
69389 // We just want to check each expressions, but we are unconcerned with
69390 // the type of each expression, as any value may be coerced into a string.
69391 // It is worth asking whether this is what we really want though.
69392 // A place where we actually *are* concerned with the expressions' types are
69393 // in tagged templates.
69394 ts.forEach(node.templateSpans, function (templateSpan) {
69395 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
69396 error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
69397 }
69398 });
69399 return stringType;
69400 }
69401 function getContextNode(node) {
69402 if (node.kind === 278 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
69403 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)
69404 }
69405 return node;
69406 }
69407 function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
69408 var context = getContextNode(node);
69409 var saveContextualType = context.contextualType;
69410 var saveInferenceContext = context.inferenceContext;
69411 try {
69412 context.contextualType = contextualType;
69413 context.inferenceContext = inferenceContext;
69414 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
69415 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
69416 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
69417 // here would be to not mark contextually typed literals as fresh in the first place.
69418 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
69419 getRegularTypeOfLiteralType(type) : type;
69420 return result;
69421 }
69422 finally {
69423 // In the event our operation is canceled or some other exception occurs, reset the contextual type
69424 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
69425 // may hold onto the checker that created it.
69426 context.contextualType = saveContextualType;
69427 context.inferenceContext = saveInferenceContext;
69428 }
69429 }
69430 function checkExpressionCached(node, checkMode) {
69431 var links = getNodeLinks(node);
69432 if (!links.resolvedType) {
69433 if (checkMode && checkMode !== 0 /* Normal */) {
69434 return checkExpression(node, checkMode);
69435 }
69436 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
69437 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
69438 // to the top of the stack ensures all transient types are computed from a known point.
69439 var saveFlowLoopStart = flowLoopStart;
69440 var saveFlowTypeCache = flowTypeCache;
69441 flowLoopStart = flowLoopCount;
69442 flowTypeCache = undefined;
69443 links.resolvedType = checkExpression(node, checkMode);
69444 flowTypeCache = saveFlowTypeCache;
69445 flowLoopStart = saveFlowLoopStart;
69446 }
69447 return links.resolvedType;
69448 }
69449 function isTypeAssertion(node) {
69450 node = ts.skipParentheses(node);
69451 return node.kind === 203 /* TypeAssertionExpression */ || node.kind === 221 /* AsExpression */;
69452 }
69453 function checkDeclarationInitializer(declaration, contextualType) {
69454 var initializer = ts.getEffectiveInitializer(declaration);
69455 var type = getQuickTypeOfExpression(initializer) ||
69456 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
69457 return ts.isParameter(declaration) && declaration.name.kind === 194 /* ArrayBindingPattern */ &&
69458 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
69459 padTupleType(type, declaration.name) : type;
69460 }
69461 function padTupleType(type, pattern) {
69462 var patternElements = pattern.elements;
69463 var elementTypes = getTypeArguments(type).slice();
69464 var elementFlags = type.target.elementFlags.slice();
69465 for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) {
69466 var e = patternElements[i];
69467 if (i < patternElements.length - 1 || !(e.kind === 195 /* BindingElement */ && e.dotDotDotToken)) {
69468 elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
69469 elementFlags.push(2 /* Optional */);
69470 if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
69471 reportImplicitAny(e, anyType);
69472 }
69473 }
69474 }
69475 return createTupleType(elementTypes, elementFlags, type.target.readonly);
69476 }
69477 function widenTypeInferredFromInitializer(declaration, type) {
69478 var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
69479 if (ts.isInJSFile(declaration)) {
69480 if (widened.flags & 98304 /* Nullable */) {
69481 reportImplicitAny(declaration, anyType);
69482 return anyType;
69483 }
69484 else if (isEmptyArrayLiteralType(widened)) {
69485 reportImplicitAny(declaration, anyArrayType);
69486 return anyArrayType;
69487 }
69488 }
69489 return widened;
69490 }
69491 function isLiteralOfContextualType(candidateType, contextualType) {
69492 if (contextualType) {
69493 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
69494 var types = contextualType.types;
69495 return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
69496 }
69497 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
69498 // If the contextual type is a type variable constrained to a primitive type, consider
69499 // this a literal context for literals of that primitive type. For example, given a
69500 // type parameter 'T extends string', infer string literal types for T.
69501 var constraint = getBaseConstraintOfType(contextualType) || unknownType;
69502 return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
69503 maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
69504 maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
69505 maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
69506 isLiteralOfContextualType(candidateType, constraint);
69507 }
69508 // If the contextual type is a literal of a particular primitive type, we consider this a
69509 // literal context for all literals of that primitive type.
69510 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
69511 contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
69512 contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
69513 contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
69514 contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
69515 }
69516 return false;
69517 }
69518 function isConstContext(node) {
69519 var parent = node.parent;
69520 return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
69521 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
69522 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
69523 }
69524 function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
69525 var type = checkExpression(node, checkMode, forceTuple);
69526 return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
69527 isTypeAssertion(node) ? type :
69528 getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
69529 }
69530 function checkPropertyAssignment(node, checkMode) {
69531 // Do not use hasDynamicName here, because that returns false for well known symbols.
69532 // We want to perform checkComputedPropertyName for all computed properties, including
69533 // well known symbols.
69534 if (node.name.kind === 157 /* ComputedPropertyName */) {
69535 checkComputedPropertyName(node.name);
69536 }
69537 return checkExpressionForMutableLocation(node.initializer, checkMode);
69538 }
69539 function checkObjectLiteralMethod(node, checkMode) {
69540 // Grammar checking
69541 checkGrammarMethod(node);
69542 // Do not use hasDynamicName here, because that returns false for well known symbols.
69543 // We want to perform checkComputedPropertyName for all computed properties, including
69544 // well known symbols.
69545 if (node.name.kind === 157 /* ComputedPropertyName */) {
69546 checkComputedPropertyName(node.name);
69547 }
69548 var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
69549 return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
69550 }
69551 function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
69552 if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
69553 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
69554 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
69555 var signature = callSignature || constructSignature;
69556 if (signature && signature.typeParameters) {
69557 var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
69558 if (contextualType) {
69559 var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
69560 if (contextualSignature && !contextualSignature.typeParameters) {
69561 if (checkMode & 8 /* SkipGenericFunctions */) {
69562 skippedGenericFunction(node, checkMode);
69563 return anyFunctionType;
69564 }
69565 var context = getInferenceContext(node);
69566 // We have an expression that is an argument of a generic function for which we are performing
69567 // type argument inference. The expression is of a function type with a single generic call
69568 // signature and a contextual function type with a single non-generic call signature. Now check
69569 // if the outer function returns a function type with a single non-generic call signature and
69570 // if some of the outer function type parameters have no inferences so far. If so, we can
69571 // potentially add inferred type parameters to the outer function return type.
69572 var returnType = context.signature && getReturnTypeOfSignature(context.signature);
69573 var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
69574 if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
69575 // Instantiate the signature with its own type parameters as type arguments, possibly
69576 // renaming the type parameters to ensure they have unique names.
69577 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
69578 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
69579 // Infer from the parameters of the instantiated signature to the parameters of the
69580 // contextual signature starting with an empty set of inference candidates.
69581 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
69582 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
69583 inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
69584 });
69585 if (ts.some(inferences_3, hasInferenceCandidates)) {
69586 // We have inference candidates, indicating that one or more type parameters are referenced
69587 // in the parameter types of the contextual signature. Now also infer from the return type.
69588 applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
69589 inferTypes(inferences_3, source, target);
69590 });
69591 // If the type parameters for which we produced candidates do not have any inferences yet,
69592 // we adopt the new inference candidates and add the type parameters of the expression type
69593 // to the set of inferred type parameters for the outer function return type.
69594 if (!hasOverlappingInferences(context.inferences, inferences_3)) {
69595 mergeInferences(context.inferences, inferences_3);
69596 context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
69597 return getOrCreateTypeFromSignature(instantiatedSignature);
69598 }
69599 }
69600 }
69601 return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
69602 }
69603 }
69604 }
69605 }
69606 return type;
69607 }
69608 function skippedGenericFunction(node, checkMode) {
69609 if (checkMode & 2 /* Inferential */) {
69610 // We have skipped a generic function during inferential typing. Obtain the inference context and
69611 // indicate this has occurred such that we know a second pass of inference is be needed.
69612 var context = getInferenceContext(node);
69613 context.flags |= 4 /* SkippedGenericFunction */;
69614 }
69615 }
69616 function hasInferenceCandidates(info) {
69617 return !!(info.candidates || info.contraCandidates);
69618 }
69619 function hasOverlappingInferences(a, b) {
69620 for (var i = 0; i < a.length; i++) {
69621 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
69622 return true;
69623 }
69624 }
69625 return false;
69626 }
69627 function mergeInferences(target, source) {
69628 for (var i = 0; i < target.length; i++) {
69629 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
69630 target[i] = source[i];
69631 }
69632 }
69633 }
69634 function getUniqueTypeParameters(context, typeParameters) {
69635 var result = [];
69636 var oldTypeParameters;
69637 var newTypeParameters;
69638 for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
69639 var tp = typeParameters_2[_i];
69640 var name = tp.symbol.escapedName;
69641 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
69642 var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
69643 var symbol = createSymbol(262144 /* TypeParameter */, newName);
69644 var newTypeParameter = createTypeParameter(symbol);
69645 newTypeParameter.target = tp;
69646 oldTypeParameters = ts.append(oldTypeParameters, tp);
69647 newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
69648 result.push(newTypeParameter);
69649 }
69650 else {
69651 result.push(tp);
69652 }
69653 }
69654 if (newTypeParameters) {
69655 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
69656 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
69657 var tp = newTypeParameters_1[_a];
69658 tp.mapper = mapper;
69659 }
69660 }
69661 return result;
69662 }
69663 function hasTypeParameterByName(typeParameters, name) {
69664 return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
69665 }
69666 function getUniqueTypeParameterName(typeParameters, baseName) {
69667 var len = baseName.length;
69668 while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
69669 len--;
69670 var s = baseName.slice(0, len);
69671 for (var index = 1; true; index++) {
69672 var augmentedName = (s + index);
69673 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
69674 return augmentedName;
69675 }
69676 }
69677 }
69678 function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
69679 var signature = getSingleCallSignature(funcType);
69680 if (signature && !signature.typeParameters) {
69681 return getReturnTypeOfSignature(signature);
69682 }
69683 }
69684 function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
69685 var funcType = checkExpression(expr.expression);
69686 var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
69687 var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
69688 return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
69689 }
69690 /**
69691 * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
69692 * with computing the type and may not fully check all contained sub-expressions for errors.
69693 */
69694 function getTypeOfExpression(node) {
69695 // Don't bother caching types that require no flow analysis and are quick to compute.
69696 var quickType = getQuickTypeOfExpression(node);
69697 if (quickType) {
69698 return quickType;
69699 }
69700 // If a type has been cached for the node, return it.
69701 if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
69702 var cachedType = flowTypeCache[getNodeId(node)];
69703 if (cachedType) {
69704 return cachedType;
69705 }
69706 }
69707 var startInvocationCount = flowInvocationCount;
69708 var type = checkExpression(node);
69709 // If control flow analysis was required to determine the type, it is worth caching.
69710 if (flowInvocationCount !== startInvocationCount) {
69711 var cache = flowTypeCache || (flowTypeCache = []);
69712 cache[getNodeId(node)] = type;
69713 ts.setNodeFlags(node, node.flags | 67108864 /* TypeCached */);
69714 }
69715 return type;
69716 }
69717 function getQuickTypeOfExpression(node) {
69718 var expr = ts.skipParentheses(node);
69719 // Optimize for the common case of a call to a function with a single non-generic call
69720 // signature where we can just fetch the return type without checking the arguments.
69721 if (ts.isCallExpression(expr) && expr.expression.kind !== 105 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
69722 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
69723 getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
69724 if (type) {
69725 return type;
69726 }
69727 }
69728 else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
69729 return getTypeFromTypeNode(expr.type);
69730 }
69731 else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
69732 node.kind === 109 /* TrueKeyword */ || node.kind === 94 /* FalseKeyword */) {
69733 return checkExpression(node);
69734 }
69735 return undefined;
69736 }
69737 /**
69738 * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
69739 * with computing the type and may not fully check all contained sub-expressions for errors.
69740 * It is intended for uses where you know there is no contextual type,
69741 * and requesting the contextual type might cause a circularity or other bad behaviour.
69742 * It sets the contextual type of the node to any before calling getTypeOfExpression.
69743 */
69744 function getContextFreeTypeOfExpression(node) {
69745 var links = getNodeLinks(node);
69746 if (links.contextFreeType) {
69747 return links.contextFreeType;
69748 }
69749 var saveContextualType = node.contextualType;
69750 node.contextualType = anyType;
69751 try {
69752 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
69753 return type;
69754 }
69755 finally {
69756 // In the event our operation is canceled or some other exception occurs, reset the contextual type
69757 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
69758 // may hold onto the checker that created it.
69759 node.contextualType = saveContextualType;
69760 }
69761 }
69762 function checkExpression(node, checkMode, forceTuple) {
69763 var saveCurrentNode = currentNode;
69764 currentNode = node;
69765 instantiationCount = 0;
69766 var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
69767 var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
69768 if (isConstEnumObjectType(type)) {
69769 checkConstEnumAccess(node, type);
69770 }
69771 currentNode = saveCurrentNode;
69772 return type;
69773 }
69774 function checkConstEnumAccess(node, type) {
69775 // enum object type for const enums are only permitted in:
69776 // - 'left' in property access
69777 // - 'object' in indexed access
69778 // - target in rhs of import statement
69779 var ok = (node.parent.kind === 198 /* PropertyAccessExpression */ && node.parent.expression === node) ||
69780 (node.parent.kind === 199 /* ElementAccessExpression */ && node.parent.expression === node) ||
69781 ((node.kind === 78 /* Identifier */ || node.kind === 156 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
69782 (node.parent.kind === 175 /* TypeQuery */ && node.parent.exprName === node)) ||
69783 (node.parent.kind === 267 /* ExportSpecifier */); // We allow reexporting const enums
69784 if (!ok) {
69785 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);
69786 }
69787 if (compilerOptions.isolatedModules) {
69788 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
69789 var constEnumDeclaration = type.symbol.valueDeclaration;
69790 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
69791 error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
69792 }
69793 }
69794 }
69795 function checkParenthesizedExpression(node, checkMode) {
69796 var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
69797 if (tag) {
69798 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
69799 }
69800 return checkExpression(node.expression, checkMode);
69801 }
69802 function checkExpressionWorker(node, checkMode, forceTuple) {
69803 var kind = node.kind;
69804 if (cancellationToken) {
69805 // Only bother checking on a few construct kinds. We don't want to be excessively
69806 // hitting the cancellation token on every node we check.
69807 switch (kind) {
69808 case 218 /* ClassExpression */:
69809 case 205 /* FunctionExpression */:
69810 case 206 /* ArrowFunction */:
69811 cancellationToken.throwIfCancellationRequested();
69812 }
69813 }
69814 switch (kind) {
69815 case 78 /* Identifier */:
69816 return checkIdentifier(node);
69817 case 107 /* ThisKeyword */:
69818 return checkThisExpression(node);
69819 case 105 /* SuperKeyword */:
69820 return checkSuperExpression(node);
69821 case 103 /* NullKeyword */:
69822 return nullWideningType;
69823 case 14 /* NoSubstitutionTemplateLiteral */:
69824 case 10 /* StringLiteral */:
69825 return getFreshTypeOfLiteralType(getLiteralType(node.text));
69826 case 8 /* NumericLiteral */:
69827 checkGrammarNumericLiteral(node);
69828 return getFreshTypeOfLiteralType(getLiteralType(+node.text));
69829 case 9 /* BigIntLiteral */:
69830 checkGrammarBigIntLiteral(node);
69831 return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
69832 case 109 /* TrueKeyword */:
69833 return trueType;
69834 case 94 /* FalseKeyword */:
69835 return falseType;
69836 case 215 /* TemplateExpression */:
69837 return checkTemplateExpression(node);
69838 case 13 /* RegularExpressionLiteral */:
69839 return globalRegExpType;
69840 case 196 /* ArrayLiteralExpression */:
69841 return checkArrayLiteral(node, checkMode, forceTuple);
69842 case 197 /* ObjectLiteralExpression */:
69843 return checkObjectLiteral(node, checkMode);
69844 case 198 /* PropertyAccessExpression */:
69845 return checkPropertyAccessExpression(node);
69846 case 156 /* QualifiedName */:
69847 return checkQualifiedName(node);
69848 case 199 /* ElementAccessExpression */:
69849 return checkIndexedAccess(node);
69850 case 200 /* CallExpression */:
69851 if (node.expression.kind === 99 /* ImportKeyword */) {
69852 return checkImportCallExpression(node);
69853 }
69854 // falls through
69855 case 201 /* NewExpression */:
69856 return checkCallExpression(node, checkMode);
69857 case 202 /* TaggedTemplateExpression */:
69858 return checkTaggedTemplateExpression(node);
69859 case 204 /* ParenthesizedExpression */:
69860 return checkParenthesizedExpression(node, checkMode);
69861 case 218 /* ClassExpression */:
69862 return checkClassExpression(node);
69863 case 205 /* FunctionExpression */:
69864 case 206 /* ArrowFunction */:
69865 return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
69866 case 208 /* TypeOfExpression */:
69867 return checkTypeOfExpression(node);
69868 case 203 /* TypeAssertionExpression */:
69869 case 221 /* AsExpression */:
69870 return checkAssertion(node);
69871 case 222 /* NonNullExpression */:
69872 return checkNonNullAssertion(node);
69873 case 223 /* MetaProperty */:
69874 return checkMetaProperty(node);
69875 case 207 /* DeleteExpression */:
69876 return checkDeleteExpression(node);
69877 case 209 /* VoidExpression */:
69878 return checkVoidExpression(node);
69879 case 210 /* AwaitExpression */:
69880 return checkAwaitExpression(node);
69881 case 211 /* PrefixUnaryExpression */:
69882 return checkPrefixUnaryExpression(node);
69883 case 212 /* PostfixUnaryExpression */:
69884 return checkPostfixUnaryExpression(node);
69885 case 213 /* BinaryExpression */:
69886 return checkBinaryExpression(node, checkMode);
69887 case 214 /* ConditionalExpression */:
69888 return checkConditionalExpression(node, checkMode);
69889 case 217 /* SpreadElement */:
69890 return checkSpreadExpression(node, checkMode);
69891 case 219 /* OmittedExpression */:
69892 return undefinedWideningType;
69893 case 216 /* YieldExpression */:
69894 return checkYieldExpression(node);
69895 case 224 /* SyntheticExpression */:
69896 return checkSyntheticExpression(node);
69897 case 280 /* JsxExpression */:
69898 return checkJsxExpression(node, checkMode);
69899 case 270 /* JsxElement */:
69900 return checkJsxElement(node, checkMode);
69901 case 271 /* JsxSelfClosingElement */:
69902 return checkJsxSelfClosingElement(node, checkMode);
69903 case 274 /* JsxFragment */:
69904 return checkJsxFragment(node);
69905 case 278 /* JsxAttributes */:
69906 return checkJsxAttributes(node, checkMode);
69907 case 272 /* JsxOpeningElement */:
69908 ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
69909 }
69910 return errorType;
69911 }
69912 // DECLARATION AND STATEMENT TYPE CHECKING
69913 function checkTypeParameter(node) {
69914 // Grammar Checking
69915 if (node.expression) {
69916 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
69917 }
69918 checkSourceElement(node.constraint);
69919 checkSourceElement(node.default);
69920 var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
69921 // Resolve base constraint to reveal circularity errors
69922 getBaseConstraintOfType(typeParameter);
69923 if (!hasNonCircularTypeParameterDefault(typeParameter)) {
69924 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
69925 }
69926 var constraintType = getConstraintOfTypeParameter(typeParameter);
69927 var defaultType = getDefaultFromTypeParameter(typeParameter);
69928 if (constraintType && defaultType) {
69929 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
69930 }
69931 if (produceDiagnostics) {
69932 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
69933 }
69934 }
69935 function checkParameter(node) {
69936 // Grammar checking
69937 // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
69938 // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
69939 // or if its FunctionBody is strict code(11.1.5).
69940 checkGrammarDecoratorsAndModifiers(node);
69941 checkVariableLikeDeclaration(node);
69942 var func = ts.getContainingFunction(node);
69943 if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) {
69944 if (!(func.kind === 165 /* Constructor */ && ts.nodeIsPresent(func.body))) {
69945 error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
69946 }
69947 if (func.kind === 165 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
69948 error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
69949 }
69950 }
69951 if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
69952 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
69953 }
69954 if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
69955 if (func.parameters.indexOf(node) !== 0) {
69956 error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
69957 }
69958 if (func.kind === 165 /* Constructor */ || func.kind === 169 /* ConstructSignature */ || func.kind === 174 /* ConstructorType */) {
69959 error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
69960 }
69961 if (func.kind === 206 /* ArrowFunction */) {
69962 error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
69963 }
69964 if (func.kind === 166 /* GetAccessor */ || func.kind === 167 /* SetAccessor */) {
69965 error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
69966 }
69967 }
69968 // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
69969 // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
69970 if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
69971 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
69972 }
69973 }
69974 function checkTypePredicate(node) {
69975 var parent = getTypePredicateParent(node);
69976 if (!parent) {
69977 // The parent must not be valid.
69978 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
69979 return;
69980 }
69981 var signature = getSignatureFromDeclaration(parent);
69982 var typePredicate = getTypePredicateOfSignature(signature);
69983 if (!typePredicate) {
69984 return;
69985 }
69986 checkSourceElement(node.type);
69987 var parameterName = node.parameterName;
69988 if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
69989 getTypeFromThisTypeNode(parameterName);
69990 }
69991 else {
69992 if (typePredicate.parameterIndex >= 0) {
69993 if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
69994 error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
69995 }
69996 else {
69997 if (typePredicate.type) {
69998 var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
69999 checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
70000 /*headMessage*/ undefined, leadingError);
70001 }
70002 }
70003 }
70004 else if (parameterName) {
70005 var hasReportedError = false;
70006 for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
70007 var name = _a[_i].name;
70008 if (ts.isBindingPattern(name) &&
70009 checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
70010 hasReportedError = true;
70011 break;
70012 }
70013 }
70014 if (!hasReportedError) {
70015 error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
70016 }
70017 }
70018 }
70019 }
70020 function getTypePredicateParent(node) {
70021 switch (node.parent.kind) {
70022 case 206 /* ArrowFunction */:
70023 case 168 /* CallSignature */:
70024 case 248 /* FunctionDeclaration */:
70025 case 205 /* FunctionExpression */:
70026 case 173 /* FunctionType */:
70027 case 164 /* MethodDeclaration */:
70028 case 163 /* MethodSignature */:
70029 var parent = node.parent;
70030 if (node === parent.type) {
70031 return parent;
70032 }
70033 }
70034 }
70035 function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
70036 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
70037 var element = _a[_i];
70038 if (ts.isOmittedExpression(element)) {
70039 continue;
70040 }
70041 var name = element.name;
70042 if (name.kind === 78 /* Identifier */ && name.escapedText === predicateVariableName) {
70043 error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
70044 return true;
70045 }
70046 else if (name.kind === 194 /* ArrayBindingPattern */ || name.kind === 193 /* ObjectBindingPattern */) {
70047 if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
70048 return true;
70049 }
70050 }
70051 }
70052 }
70053 function checkSignatureDeclaration(node) {
70054 // Grammar checking
70055 if (node.kind === 170 /* IndexSignature */) {
70056 checkGrammarIndexSignature(node);
70057 }
70058 // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
70059 else if (node.kind === 173 /* FunctionType */ || node.kind === 248 /* FunctionDeclaration */ || node.kind === 174 /* ConstructorType */ ||
70060 node.kind === 168 /* CallSignature */ || node.kind === 165 /* Constructor */ ||
70061 node.kind === 169 /* ConstructSignature */) {
70062 checkGrammarFunctionLikeDeclaration(node);
70063 }
70064 var functionFlags = ts.getFunctionFlags(node);
70065 if (!(functionFlags & 4 /* Invalid */)) {
70066 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
70067 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
70068 checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
70069 }
70070 // Async functions prior to ES2017 require the __awaiter helper
70071 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
70072 checkExternalEmitHelpers(node, 64 /* Awaiter */);
70073 }
70074 // Generator functions, Async functions, and Async Generator functions prior to
70075 // ES2015 require the __generator helper
70076 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
70077 checkExternalEmitHelpers(node, 128 /* Generator */);
70078 }
70079 }
70080 checkTypeParameters(node.typeParameters);
70081 ts.forEach(node.parameters, checkParameter);
70082 // TODO(rbuckton): Should we start checking JSDoc types?
70083 if (node.type) {
70084 checkSourceElement(node.type);
70085 }
70086 if (produceDiagnostics) {
70087 checkCollisionWithArgumentsInGeneratedCode(node);
70088 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
70089 if (noImplicitAny && !returnTypeNode) {
70090 switch (node.kind) {
70091 case 169 /* ConstructSignature */:
70092 error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
70093 break;
70094 case 168 /* CallSignature */:
70095 error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
70096 break;
70097 }
70098 }
70099 if (returnTypeNode) {
70100 var functionFlags_1 = ts.getFunctionFlags(node);
70101 if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
70102 var returnType = getTypeFromTypeNode(returnTypeNode);
70103 if (returnType === voidType) {
70104 error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
70105 }
70106 else {
70107 // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
70108 // However, that would not catch the error in the following case.
70109 //
70110 // interface BadGenerator extends Iterable<number>, Iterator<string> { }
70111 // function* g(): BadGenerator { } // Iterable and Iterator have different types!
70112 //
70113 var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
70114 var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
70115 var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
70116 var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
70117 checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
70118 }
70119 }
70120 else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
70121 checkAsyncFunctionReturnType(node, returnTypeNode);
70122 }
70123 }
70124 if (node.kind !== 170 /* IndexSignature */ && node.kind !== 304 /* JSDocFunctionType */) {
70125 registerForUnusedIdentifiersCheck(node);
70126 }
70127 }
70128 }
70129 function checkClassForDuplicateDeclarations(node) {
70130 var instanceNames = new ts.Map();
70131 var staticNames = new ts.Map();
70132 // instance and static private identifiers share the same scope
70133 var privateIdentifiers = new ts.Map();
70134 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
70135 var member = _a[_i];
70136 if (member.kind === 165 /* Constructor */) {
70137 for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
70138 var param = _c[_b];
70139 if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
70140 addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
70141 }
70142 }
70143 }
70144 else {
70145 var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
70146 var name = member.name;
70147 if (!name) {
70148 return;
70149 }
70150 var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
70151 isStatic ? staticNames :
70152 instanceNames;
70153 var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
70154 if (memberName) {
70155 switch (member.kind) {
70156 case 166 /* GetAccessor */:
70157 addName(names, name, memberName, 1 /* GetAccessor */);
70158 break;
70159 case 167 /* SetAccessor */:
70160 addName(names, name, memberName, 2 /* SetAccessor */);
70161 break;
70162 case 162 /* PropertyDeclaration */:
70163 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
70164 break;
70165 case 164 /* MethodDeclaration */:
70166 addName(names, name, memberName, 8 /* Method */);
70167 break;
70168 }
70169 }
70170 }
70171 }
70172 function addName(names, location, name, meaning) {
70173 var prev = names.get(name);
70174 if (prev) {
70175 if (prev & 8 /* Method */) {
70176 if (meaning !== 8 /* Method */) {
70177 error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
70178 }
70179 }
70180 else if (prev & meaning) {
70181 error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
70182 }
70183 else {
70184 names.set(name, prev | meaning);
70185 }
70186 }
70187 else {
70188 names.set(name, meaning);
70189 }
70190 }
70191 }
70192 /**
70193 * Static members being set on a constructor function may conflict with built-in properties
70194 * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
70195 * built-in properties. This check issues a transpile error when a class has a static
70196 * member with the same name as a non-writable built-in property.
70197 *
70198 * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
70199 * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
70200 * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
70201 * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
70202 */
70203 function checkClassForStaticPropertyNameConflicts(node) {
70204 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
70205 var member = _a[_i];
70206 var memberNameNode = member.name;
70207 var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
70208 if (isStatic && memberNameNode) {
70209 var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
70210 switch (memberName) {
70211 case "name":
70212 case "length":
70213 case "caller":
70214 case "arguments":
70215 case "prototype":
70216 var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
70217 var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
70218 error(memberNameNode, message, memberName, className);
70219 break;
70220 }
70221 }
70222 }
70223 }
70224 function checkObjectTypeForDuplicateDeclarations(node) {
70225 var names = new ts.Map();
70226 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
70227 var member = _a[_i];
70228 if (member.kind === 161 /* PropertySignature */) {
70229 var memberName = void 0;
70230 var name = member.name;
70231 switch (name.kind) {
70232 case 10 /* StringLiteral */:
70233 case 8 /* NumericLiteral */:
70234 memberName = name.text;
70235 break;
70236 case 78 /* Identifier */:
70237 memberName = ts.idText(name);
70238 break;
70239 default:
70240 continue;
70241 }
70242 if (names.get(memberName)) {
70243 error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
70244 error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
70245 }
70246 else {
70247 names.set(memberName, true);
70248 }
70249 }
70250 }
70251 }
70252 function checkTypeForDuplicateIndexSignatures(node) {
70253 if (node.kind === 250 /* InterfaceDeclaration */) {
70254 var nodeSymbol = getSymbolOfNode(node);
70255 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
70256 // to prevent this run check only for the first declaration of a given kind
70257 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
70258 return;
70259 }
70260 }
70261 // TypeScript 1.0 spec (April 2014)
70262 // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
70263 // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
70264 var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
70265 if (indexSymbol) {
70266 var seenNumericIndexer = false;
70267 var seenStringIndexer = false;
70268 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
70269 var decl = _a[_i];
70270 var declaration = decl;
70271 if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
70272 switch (declaration.parameters[0].type.kind) {
70273 case 146 /* StringKeyword */:
70274 if (!seenStringIndexer) {
70275 seenStringIndexer = true;
70276 }
70277 else {
70278 error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
70279 }
70280 break;
70281 case 143 /* NumberKeyword */:
70282 if (!seenNumericIndexer) {
70283 seenNumericIndexer = true;
70284 }
70285 else {
70286 error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
70287 }
70288 break;
70289 }
70290 }
70291 }
70292 }
70293 }
70294 function checkPropertyDeclaration(node) {
70295 // Grammar checking
70296 if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
70297 checkGrammarComputedPropertyName(node.name);
70298 checkVariableLikeDeclaration(node);
70299 // Private class fields transformation relies on WeakMaps.
70300 if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
70301 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
70302 getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
70303 }
70304 }
70305 }
70306 function checkPropertySignature(node) {
70307 if (ts.isPrivateIdentifier(node.name)) {
70308 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
70309 }
70310 return checkPropertyDeclaration(node);
70311 }
70312 function checkMethodDeclaration(node) {
70313 // Grammar checking
70314 if (!checkGrammarMethod(node))
70315 checkGrammarComputedPropertyName(node.name);
70316 if (ts.isPrivateIdentifier(node.name)) {
70317 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
70318 }
70319 // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
70320 checkFunctionOrMethodDeclaration(node);
70321 // Abstract methods cannot have an implementation.
70322 // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
70323 if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 164 /* MethodDeclaration */ && node.body) {
70324 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
70325 }
70326 }
70327 function checkConstructorDeclaration(node) {
70328 // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
70329 checkSignatureDeclaration(node);
70330 // Grammar check for checking only related to constructorDeclaration
70331 if (!checkGrammarConstructorTypeParameters(node))
70332 checkGrammarConstructorTypeAnnotation(node);
70333 checkSourceElement(node.body);
70334 var symbol = getSymbolOfNode(node);
70335 var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
70336 // Only type check the symbol once
70337 if (node === firstDeclaration) {
70338 checkFunctionOrConstructorSymbol(symbol);
70339 }
70340 // exit early in the case of signature - super checks are not relevant to them
70341 if (ts.nodeIsMissing(node.body)) {
70342 return;
70343 }
70344 if (!produceDiagnostics) {
70345 return;
70346 }
70347 function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
70348 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
70349 return true;
70350 }
70351 return n.kind === 162 /* PropertyDeclaration */ &&
70352 !ts.hasSyntacticModifier(n, 32 /* Static */) &&
70353 !!n.initializer;
70354 }
70355 // TS 1.0 spec (April 2014): 8.3.2
70356 // Constructors of classes with no extends clause may not contain super calls, whereas
70357 // constructors of derived classes must contain at least one super call somewhere in their function body.
70358 var containingClassDecl = node.parent;
70359 if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
70360 captureLexicalThis(node.parent, containingClassDecl);
70361 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
70362 var superCall = findFirstSuperCall(node.body);
70363 if (superCall) {
70364 if (classExtendsNull) {
70365 error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
70366 }
70367 // The first statement in the body of a constructor (excluding prologue directives) must be a super call
70368 // if both of the following are true:
70369 // - The containing class is a derived class.
70370 // - The constructor declares parameter properties
70371 // or the containing class declares instance member variables with initializers.
70372 var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
70373 (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
70374 ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); }));
70375 // Skip past any prologue directives to find the first statement
70376 // to ensure that it was a super call.
70377 if (superCallShouldBeFirst) {
70378 var statements = node.body.statements;
70379 var superCallStatement = void 0;
70380 for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
70381 var statement = statements_4[_i];
70382 if (statement.kind === 230 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
70383 superCallStatement = statement;
70384 break;
70385 }
70386 if (!ts.isPrologueDirective(statement)) {
70387 break;
70388 }
70389 }
70390 if (!superCallStatement) {
70391 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);
70392 }
70393 }
70394 }
70395 else if (!classExtendsNull) {
70396 error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
70397 }
70398 }
70399 }
70400 function checkAccessorDeclaration(node) {
70401 if (produceDiagnostics) {
70402 // Grammar checking accessors
70403 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
70404 checkGrammarComputedPropertyName(node.name);
70405 checkDecorators(node);
70406 checkSignatureDeclaration(node);
70407 if (node.kind === 166 /* GetAccessor */) {
70408 if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
70409 if (!(node.flags & 512 /* HasExplicitReturn */)) {
70410 error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
70411 }
70412 }
70413 }
70414 // Do not use hasDynamicName here, because that returns false for well known symbols.
70415 // We want to perform checkComputedPropertyName for all computed properties, including
70416 // well known symbols.
70417 if (node.name.kind === 157 /* ComputedPropertyName */) {
70418 checkComputedPropertyName(node.name);
70419 }
70420 if (ts.isPrivateIdentifier(node.name)) {
70421 error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
70422 }
70423 if (!hasNonBindableDynamicName(node)) {
70424 // TypeScript 1.0 spec (April 2014): 8.4.3
70425 // Accessors for the same member name must specify the same accessibility.
70426 var otherKind = node.kind === 166 /* GetAccessor */ ? 167 /* SetAccessor */ : 166 /* GetAccessor */;
70427 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
70428 if (otherAccessor) {
70429 var nodeFlags = ts.getEffectiveModifierFlags(node);
70430 var otherFlags = ts.getEffectiveModifierFlags(otherAccessor);
70431 if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
70432 error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
70433 }
70434 if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
70435 error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
70436 }
70437 // TypeScript 1.0 spec (April 2014): 4.5
70438 // If both accessors include type annotations, the specified types must be identical.
70439 checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
70440 checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
70441 }
70442 }
70443 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
70444 if (node.kind === 166 /* GetAccessor */) {
70445 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
70446 }
70447 }
70448 checkSourceElement(node.body);
70449 }
70450 function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
70451 var firstType = getAnnotatedType(first);
70452 var secondType = getAnnotatedType(second);
70453 if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
70454 error(first, message);
70455 }
70456 }
70457 function checkMissingDeclaration(node) {
70458 checkDecorators(node);
70459 }
70460 function getEffectiveTypeArguments(node, typeParameters) {
70461 return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
70462 }
70463 function checkTypeArgumentConstraints(node, typeParameters) {
70464 var typeArguments;
70465 var mapper;
70466 var result = true;
70467 for (var i = 0; i < typeParameters.length; i++) {
70468 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
70469 if (constraint) {
70470 if (!typeArguments) {
70471 typeArguments = getEffectiveTypeArguments(node, typeParameters);
70472 mapper = createTypeMapper(typeParameters, typeArguments);
70473 }
70474 result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
70475 }
70476 }
70477 return result;
70478 }
70479 function getTypeParametersForTypeReference(node) {
70480 var type = getTypeFromTypeReference(node);
70481 if (type !== errorType) {
70482 var symbol = getNodeLinks(node).resolvedSymbol;
70483 if (symbol) {
70484 return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
70485 (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
70486 }
70487 }
70488 return undefined;
70489 }
70490 function checkTypeReferenceNode(node) {
70491 checkGrammarTypeArguments(node, node.typeArguments);
70492 if (node.kind === 172 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
70493 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
70494 }
70495 ts.forEach(node.typeArguments, checkSourceElement);
70496 var type = getTypeFromTypeReference(node);
70497 if (type !== errorType) {
70498 if (node.typeArguments && produceDiagnostics) {
70499 var typeParameters = getTypeParametersForTypeReference(node);
70500 if (typeParameters) {
70501 checkTypeArgumentConstraints(node, typeParameters);
70502 }
70503 }
70504 var symbol = getNodeLinks(node).resolvedSymbol;
70505 if (symbol) {
70506 if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
70507 errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName);
70508 }
70509 if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
70510 error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
70511 }
70512 }
70513 }
70514 }
70515 function getTypeArgumentConstraint(node) {
70516 var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
70517 if (!typeReferenceNode)
70518 return undefined;
70519 var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
70520 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
70521 return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
70522 }
70523 function checkTypeQuery(node) {
70524 getTypeFromTypeQueryNode(node);
70525 }
70526 function checkTypeLiteral(node) {
70527 ts.forEach(node.members, checkSourceElement);
70528 if (produceDiagnostics) {
70529 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
70530 checkIndexConstraints(type);
70531 checkTypeForDuplicateIndexSignatures(node);
70532 checkObjectTypeForDuplicateDeclarations(node);
70533 }
70534 }
70535 function checkArrayType(node) {
70536 checkSourceElement(node.elementType);
70537 }
70538 function checkTupleType(node) {
70539 var elementTypes = node.elements;
70540 var seenOptionalElement = false;
70541 var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
70542 for (var i = 0; i < elementTypes.length; i++) {
70543 var e = elementTypes[i];
70544 if (e.kind !== 191 /* NamedTupleMember */ && hasNamedElement) {
70545 grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
70546 break;
70547 }
70548 var flags = getTupleElementFlags(e);
70549 if (flags & 8 /* Variadic */) {
70550 if (!isArrayLikeType(getTypeFromTypeNode(e.type))) {
70551 error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
70552 break;
70553 }
70554 }
70555 else if (flags & 4 /* Rest */) {
70556 if (i !== elementTypes.length - 1) {
70557 grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
70558 break;
70559 }
70560 }
70561 else if (flags & 2 /* Optional */) {
70562 seenOptionalElement = true;
70563 }
70564 else if (seenOptionalElement) {
70565 grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
70566 break;
70567 }
70568 }
70569 ts.forEach(node.elements, checkSourceElement);
70570 }
70571 function checkUnionOrIntersectionType(node) {
70572 ts.forEach(node.types, checkSourceElement);
70573 }
70574 function checkIndexedAccessIndexType(type, accessNode) {
70575 if (!(type.flags & 8388608 /* IndexedAccess */)) {
70576 return type;
70577 }
70578 // Check if the index type is assignable to 'keyof T' for the object type.
70579 var objectType = type.objectType;
70580 var indexType = type.indexType;
70581 if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
70582 if (accessNode.kind === 199 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
70583 ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
70584 error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
70585 }
70586 return type;
70587 }
70588 // Check if we're indexing with a numeric type and if either object or index types
70589 // is a generic type with a constraint that has a numeric index signature.
70590 var apparentObjectType = getApparentType(objectType);
70591 if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
70592 return type;
70593 }
70594 if (isGenericObjectType(objectType)) {
70595 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
70596 if (propertyName_1) {
70597 var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
70598 if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
70599 error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
70600 return errorType;
70601 }
70602 }
70603 }
70604 error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
70605 return errorType;
70606 }
70607 function checkIndexedAccessType(node) {
70608 checkSourceElement(node.objectType);
70609 checkSourceElement(node.indexType);
70610 checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
70611 }
70612 function checkMappedType(node) {
70613 checkSourceElement(node.typeParameter);
70614 checkSourceElement(node.type);
70615 if (!node.type) {
70616 reportImplicitAny(node, anyType);
70617 }
70618 var type = getTypeFromMappedTypeNode(node);
70619 var constraintType = getConstraintTypeFromMappedType(type);
70620 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
70621 }
70622 function checkThisType(node) {
70623 getTypeFromThisTypeNode(node);
70624 }
70625 function checkTypeOperator(node) {
70626 checkGrammarTypeOperatorNode(node);
70627 checkSourceElement(node.type);
70628 }
70629 function checkConditionalType(node) {
70630 ts.forEachChild(node, checkSourceElement);
70631 }
70632 function checkInferType(node) {
70633 if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 183 /* ConditionalType */ && n.parent.extendsType === n; })) {
70634 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
70635 }
70636 checkSourceElement(node.typeParameter);
70637 registerForUnusedIdentifiersCheck(node);
70638 }
70639 function checkImportType(node) {
70640 checkSourceElement(node.argument);
70641 getTypeFromTypeNode(node);
70642 }
70643 function checkNamedTupleMember(node) {
70644 if (node.dotDotDotToken && node.questionToken) {
70645 grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
70646 }
70647 if (node.type.kind === 179 /* OptionalType */) {
70648 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);
70649 }
70650 if (node.type.kind === 180 /* RestType */) {
70651 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
70652 }
70653 checkSourceElement(node.type);
70654 getTypeFromTypeNode(node);
70655 }
70656 function isPrivateWithinAmbient(node) {
70657 return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
70658 }
70659 function getEffectiveDeclarationFlags(n, flagsToCheck) {
70660 var flags = ts.getCombinedModifierFlags(n);
70661 // children of classes (even ambient classes) should not be marked as ambient or export
70662 // because those flags have no useful semantics there.
70663 if (n.parent.kind !== 250 /* InterfaceDeclaration */ &&
70664 n.parent.kind !== 249 /* ClassDeclaration */ &&
70665 n.parent.kind !== 218 /* ClassExpression */ &&
70666 n.flags & 8388608 /* Ambient */) {
70667 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
70668 // It is nested in an ambient context, which means it is automatically exported
70669 flags |= 1 /* Export */;
70670 }
70671 flags |= 2 /* Ambient */;
70672 }
70673 return flags & flagsToCheck;
70674 }
70675 function checkFunctionOrConstructorSymbol(symbol) {
70676 if (!produceDiagnostics) {
70677 return;
70678 }
70679 function getCanonicalOverload(overloads, implementation) {
70680 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
70681 // Error on all deviations from this canonical set of flags
70682 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
70683 // report the errors on those. To achieve this, we will say that the implementation is
70684 // the canonical signature only if it is in the same container as the first overload
70685 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
70686 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
70687 }
70688 function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
70689 // Error if some overloads have a flag that is not shared by all overloads. To find the
70690 // deviations, we XOR someOverloadFlags with allOverloadFlags
70691 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
70692 if (someButNotAllOverloadFlags !== 0) {
70693 var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
70694 ts.forEach(overloads, function (o) {
70695 var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
70696 if (deviation & 1 /* Export */) {
70697 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
70698 }
70699 else if (deviation & 2 /* Ambient */) {
70700 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
70701 }
70702 else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
70703 error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
70704 }
70705 else if (deviation & 128 /* Abstract */) {
70706 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
70707 }
70708 });
70709 }
70710 }
70711 function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
70712 if (someHaveQuestionToken !== allHaveQuestionToken) {
70713 var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
70714 ts.forEach(overloads, function (o) {
70715 var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
70716 if (deviation) {
70717 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
70718 }
70719 });
70720 }
70721 }
70722 var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
70723 var someNodeFlags = 0 /* None */;
70724 var allNodeFlags = flagsToCheck;
70725 var someHaveQuestionToken = false;
70726 var allHaveQuestionToken = true;
70727 var hasOverloads = false;
70728 var bodyDeclaration;
70729 var lastSeenNonAmbientDeclaration;
70730 var previousDeclaration;
70731 var declarations = symbol.declarations;
70732 var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
70733 function reportImplementationExpectedError(node) {
70734 if (node.name && ts.nodeIsMissing(node.name)) {
70735 return;
70736 }
70737 var seen = false;
70738 var subsequentNode = ts.forEachChild(node.parent, function (c) {
70739 if (seen) {
70740 return c;
70741 }
70742 else {
70743 seen = c === node;
70744 }
70745 });
70746 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
70747 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
70748 if (subsequentNode && subsequentNode.pos === node.end) {
70749 if (subsequentNode.kind === node.kind) {
70750 var errorNode_1 = subsequentNode.name || subsequentNode;
70751 var subsequentName = subsequentNode.name;
70752 if (node.name && subsequentName && (
70753 // both are private identifiers
70754 ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
70755 // Both are computed property names
70756 // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
70757 ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
70758 // Both are literal property names that are the same.
70759 ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
70760 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
70761 var reportError = (node.kind === 164 /* MethodDeclaration */ || node.kind === 163 /* MethodSignature */) &&
70762 ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */);
70763 // we can get here in two cases
70764 // 1. mixed static and instance class members
70765 // 2. something with the same name was defined before the set of overloads that prevents them from merging
70766 // here we'll report error only for the first case since for second we should already report error in binder
70767 if (reportError) {
70768 var diagnostic = ts.hasSyntacticModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
70769 error(errorNode_1, diagnostic);
70770 }
70771 return;
70772 }
70773 if (ts.nodeIsPresent(subsequentNode.body)) {
70774 error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
70775 return;
70776 }
70777 }
70778 }
70779 var errorNode = node.name || node;
70780 if (isConstructor) {
70781 error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
70782 }
70783 else {
70784 // Report different errors regarding non-consecutive blocks of declarations depending on whether
70785 // the node in question is abstract.
70786 if (ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
70787 error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
70788 }
70789 else {
70790 error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
70791 }
70792 }
70793 }
70794 var duplicateFunctionDeclaration = false;
70795 var multipleConstructorImplementation = false;
70796 var hasNonAmbientClass = false;
70797 var functionDeclarations = [];
70798 for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
70799 var current = declarations_4[_i];
70800 var node = current;
70801 var inAmbientContext = node.flags & 8388608 /* Ambient */;
70802 var inAmbientContextOrInterface = node.parent.kind === 250 /* InterfaceDeclaration */ || node.parent.kind === 176 /* TypeLiteral */ || inAmbientContext;
70803 if (inAmbientContextOrInterface) {
70804 // check if declarations are consecutive only if they are non-ambient
70805 // 1. ambient declarations can be interleaved
70806 // i.e. this is legal
70807 // declare function foo();
70808 // declare function bar();
70809 // declare function foo();
70810 // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
70811 previousDeclaration = undefined;
70812 }
70813 if ((node.kind === 249 /* ClassDeclaration */ || node.kind === 218 /* ClassExpression */) && !inAmbientContext) {
70814 hasNonAmbientClass = true;
70815 }
70816 if (node.kind === 248 /* FunctionDeclaration */ || node.kind === 164 /* MethodDeclaration */ || node.kind === 163 /* MethodSignature */ || node.kind === 165 /* Constructor */) {
70817 functionDeclarations.push(node);
70818 var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
70819 someNodeFlags |= currentNodeFlags;
70820 allNodeFlags &= currentNodeFlags;
70821 someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
70822 allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
70823 var bodyIsPresent = ts.nodeIsPresent(node.body);
70824 if (bodyIsPresent && bodyDeclaration) {
70825 if (isConstructor) {
70826 multipleConstructorImplementation = true;
70827 }
70828 else {
70829 duplicateFunctionDeclaration = true;
70830 }
70831 }
70832 else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
70833 reportImplementationExpectedError(previousDeclaration);
70834 }
70835 if (bodyIsPresent) {
70836 if (!bodyDeclaration) {
70837 bodyDeclaration = node;
70838 }
70839 }
70840 else {
70841 hasOverloads = true;
70842 }
70843 previousDeclaration = node;
70844 if (!inAmbientContextOrInterface) {
70845 lastSeenNonAmbientDeclaration = node;
70846 }
70847 }
70848 }
70849 if (multipleConstructorImplementation) {
70850 ts.forEach(functionDeclarations, function (declaration) {
70851 error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
70852 });
70853 }
70854 if (duplicateFunctionDeclaration) {
70855 ts.forEach(functionDeclarations, function (declaration) {
70856 error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_function_implementation);
70857 });
70858 }
70859 if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
70860 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
70861 // TODO: The below just replicates our older error from when classes and functions were
70862 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
70863 // might be warranted. :shrug:
70864 ts.forEach(declarations, function (declaration) {
70865 addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
70866 });
70867 }
70868 // Abstract methods can't have an implementation -- in particular, they don't need one.
70869 if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
70870 !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
70871 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
70872 }
70873 if (hasOverloads) {
70874 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
70875 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
70876 if (bodyDeclaration) {
70877 var signatures = getSignaturesOfSymbol(symbol);
70878 var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
70879 for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
70880 var signature = signatures_10[_a];
70881 if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
70882 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));
70883 break;
70884 }
70885 }
70886 }
70887 }
70888 }
70889 function checkExportsOnMergedDeclarations(node) {
70890 if (!produceDiagnostics) {
70891 return;
70892 }
70893 // if localSymbol is defined on node then node itself is exported - check is required
70894 var symbol = node.localSymbol;
70895 if (!symbol) {
70896 // local symbol is undefined => this declaration is non-exported.
70897 // however symbol might contain other declarations that are exported
70898 symbol = getSymbolOfNode(node);
70899 if (!symbol.exportSymbol) {
70900 // this is a pure local symbol (all declarations are non-exported) - no need to check anything
70901 return;
70902 }
70903 }
70904 // run the check only for the first declaration in the list
70905 if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
70906 return;
70907 }
70908 var exportedDeclarationSpaces = 0 /* None */;
70909 var nonExportedDeclarationSpaces = 0 /* None */;
70910 var defaultExportedDeclarationSpaces = 0 /* None */;
70911 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
70912 var d = _a[_i];
70913 var declarationSpaces = getDeclarationSpaces(d);
70914 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
70915 if (effectiveDeclarationFlags & 1 /* Export */) {
70916 if (effectiveDeclarationFlags & 512 /* Default */) {
70917 defaultExportedDeclarationSpaces |= declarationSpaces;
70918 }
70919 else {
70920 exportedDeclarationSpaces |= declarationSpaces;
70921 }
70922 }
70923 else {
70924 nonExportedDeclarationSpaces |= declarationSpaces;
70925 }
70926 }
70927 // Spaces for anything not declared a 'default export'.
70928 var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
70929 var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
70930 var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
70931 if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
70932 // declaration spaces for exported and non-exported declarations intersect
70933 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
70934 var d = _c[_b];
70935 var declarationSpaces = getDeclarationSpaces(d);
70936 var name = ts.getNameOfDeclaration(d);
70937 // Only error on the declarations that contributed to the intersecting spaces.
70938 if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
70939 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));
70940 }
70941 else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
70942 error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
70943 }
70944 }
70945 }
70946 function getDeclarationSpaces(decl) {
70947 var d = decl;
70948 switch (d.kind) {
70949 case 250 /* InterfaceDeclaration */:
70950 case 251 /* TypeAliasDeclaration */:
70951 // A jsdoc typedef and callback are, by definition, type aliases.
70952 // falls through
70953 case 327 /* JSDocTypedefTag */:
70954 case 320 /* JSDocCallbackTag */:
70955 case 321 /* JSDocEnumTag */:
70956 return 2 /* ExportType */;
70957 case 253 /* ModuleDeclaration */:
70958 return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
70959 ? 4 /* ExportNamespace */ | 1 /* ExportValue */
70960 : 4 /* ExportNamespace */;
70961 case 249 /* ClassDeclaration */:
70962 case 252 /* EnumDeclaration */:
70963 case 288 /* EnumMember */:
70964 return 2 /* ExportType */ | 1 /* ExportValue */;
70965 case 294 /* SourceFile */:
70966 return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
70967 case 263 /* ExportAssignment */:
70968 // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
70969 if (!ts.isEntityNameExpression(d.expression)) {
70970 return 1 /* ExportValue */;
70971 }
70972 d = d.expression;
70973 // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
70974 // falls through
70975 case 257 /* ImportEqualsDeclaration */:
70976 case 260 /* NamespaceImport */:
70977 case 259 /* ImportClause */:
70978 var result_11 = 0 /* None */;
70979 var target = resolveAlias(getSymbolOfNode(d));
70980 ts.forEach(target.declarations, function (d) { result_11 |= getDeclarationSpaces(d); });
70981 return result_11;
70982 case 246 /* VariableDeclaration */:
70983 case 195 /* BindingElement */:
70984 case 248 /* FunctionDeclaration */:
70985 case 262 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
70986 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
70987 // Identifiers are used as declarations of assignment declarations whose parents may be
70988 // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
70989 // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
70990 // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
70991 // all of which are pretty much always values, or at least imply a value meaning.
70992 // It may be apprpriate to treat these as aliases in the future.
70993 return 1 /* ExportValue */;
70994 default:
70995 return ts.Debug.failBadSyntaxKind(d);
70996 }
70997 }
70998 }
70999 function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
71000 var promisedType = getPromisedTypeOfPromise(type, errorNode);
71001 return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
71002 }
71003 /**
71004 * Gets the "promised type" of a promise.
71005 * @param type The type of the promise.
71006 * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
71007 */
71008 function getPromisedTypeOfPromise(type, errorNode) {
71009 //
71010 // { // type
71011 // then( // thenFunction
71012 // onfulfilled: ( // onfulfilledParameterType
71013 // value: T // valueParameterType
71014 // ) => any
71015 // ): any;
71016 // }
71017 //
71018 if (isTypeAny(type)) {
71019 return undefined;
71020 }
71021 var typeAsPromise = type;
71022 if (typeAsPromise.promisedTypeOfPromise) {
71023 return typeAsPromise.promisedTypeOfPromise;
71024 }
71025 if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
71026 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
71027 }
71028 var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
71029 if (isTypeAny(thenFunction)) {
71030 return undefined;
71031 }
71032 var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
71033 if (thenSignatures.length === 0) {
71034 if (errorNode) {
71035 error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
71036 }
71037 return undefined;
71038 }
71039 var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
71040 if (isTypeAny(onfulfilledParameterType)) {
71041 return undefined;
71042 }
71043 var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
71044 if (onfulfilledParameterSignatures.length === 0) {
71045 if (errorNode) {
71046 error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
71047 }
71048 return undefined;
71049 }
71050 return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
71051 }
71052 /**
71053 * Gets the "awaited type" of a type.
71054 * @param type The type to await.
71055 * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
71056 * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
71057 * The runtime behavior of the `await` keyword.
71058 */
71059 function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
71060 var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
71061 return awaitedType || errorType;
71062 }
71063 /**
71064 * Determines whether a type has a callable `then` member.
71065 */
71066 function isThenableType(type) {
71067 var thenFunction = getTypeOfPropertyOfType(type, "then");
71068 return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
71069 }
71070 /**
71071 * Gets the "awaited type" of a type.
71072 *
71073 * The "awaited type" of an expression is its "promised type" if the expression is a
71074 * Promise-like type; otherwise, it is the type of the expression. If the "promised
71075 * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
71076 * non-promise type is found.
71077 *
71078 * This is used to reflect the runtime behavior of the `await` keyword.
71079 */
71080 function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
71081 if (isTypeAny(type)) {
71082 return type;
71083 }
71084 var typeAsAwaitable = type;
71085 if (typeAsAwaitable.awaitedTypeOfType) {
71086 return typeAsAwaitable.awaitedTypeOfType;
71087 }
71088 // For a union, get a union of the awaited types of each constituent.
71089 //
71090 return typeAsAwaitable.awaitedTypeOfType =
71091 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
71092 }
71093 function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
71094 var typeAsAwaitable = type;
71095 if (typeAsAwaitable.awaitedTypeOfType) {
71096 return typeAsAwaitable.awaitedTypeOfType;
71097 }
71098 var promisedType = getPromisedTypeOfPromise(type);
71099 if (promisedType) {
71100 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
71101 // Verify that we don't have a bad actor in the form of a promise whose
71102 // promised type is the same as the promise type, or a mutually recursive
71103 // promise. If so, we return undefined as we cannot guess the shape. If this
71104 // were the actual case in the JavaScript, this Promise would never resolve.
71105 //
71106 // An example of a bad actor with a singly-recursive promise type might
71107 // be:
71108 //
71109 // interface BadPromise {
71110 // then(
71111 // onfulfilled: (value: BadPromise) => any,
71112 // onrejected: (error: any) => any): BadPromise;
71113 // }
71114 //
71115 // The above interface will pass the PromiseLike check, and return a
71116 // promised type of `BadPromise`. Since this is a self reference, we
71117 // don't want to keep recursing ad infinitum.
71118 //
71119 // An example of a bad actor in the form of a mutually-recursive
71120 // promise type might be:
71121 //
71122 // interface BadPromiseA {
71123 // then(
71124 // onfulfilled: (value: BadPromiseB) => any,
71125 // onrejected: (error: any) => any): BadPromiseB;
71126 // }
71127 //
71128 // interface BadPromiseB {
71129 // then(
71130 // onfulfilled: (value: BadPromiseA) => any,
71131 // onrejected: (error: any) => any): BadPromiseA;
71132 // }
71133 //
71134 if (errorNode) {
71135 error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
71136 }
71137 return undefined;
71138 }
71139 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
71140 // See the comments above for more information.
71141 awaitedTypeStack.push(type.id);
71142 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
71143 awaitedTypeStack.pop();
71144 if (!awaitedType) {
71145 return undefined;
71146 }
71147 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
71148 }
71149 // The type was not a promise, so it could not be unwrapped any further.
71150 // As long as the type does not have a callable "then" property, it is
71151 // safe to return the type; otherwise, an error is reported and we return
71152 // undefined.
71153 //
71154 // An example of a non-promise "thenable" might be:
71155 //
71156 // await { then(): void {} }
71157 //
71158 // The "thenable" does not match the minimal definition for a promise. When
71159 // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
71160 // will never settle. We treat this as an error to help flag an early indicator
71161 // of a runtime problem. If the user wants to return this value from an async
71162 // function, they would need to wrap it in some other value. If they want it to
71163 // be treated as a promise, they can cast to <any>.
71164 if (isThenableType(type)) {
71165 if (errorNode) {
71166 if (!diagnosticMessage)
71167 return ts.Debug.fail();
71168 error(errorNode, diagnosticMessage, arg0);
71169 }
71170 return undefined;
71171 }
71172 return typeAsAwaitable.awaitedTypeOfType = type;
71173 }
71174 /**
71175 * Checks the return type of an async function to ensure it is a compatible
71176 * Promise implementation.
71177 *
71178 * This checks that an async function has a valid Promise-compatible return type.
71179 * An async function has a valid Promise-compatible return type if the resolved value
71180 * of the return type has a construct signature that takes in an `initializer` function
71181 * that in turn supplies a `resolve` function as one of its arguments and results in an
71182 * object with a callable `then` signature.
71183 *
71184 * @param node The signature to check
71185 */
71186 function checkAsyncFunctionReturnType(node, returnTypeNode) {
71187 // As part of our emit for an async function, we will need to emit the entity name of
71188 // the return type annotation as an expression. To meet the necessary runtime semantics
71189 // for __awaiter, we must also check that the type of the declaration (e.g. the static
71190 // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
71191 //
71192 // An example might be (from lib.es6.d.ts):
71193 //
71194 // interface Promise<T> { ... }
71195 // interface PromiseConstructor {
71196 // new <T>(...): Promise<T>;
71197 // }
71198 // declare var Promise: PromiseConstructor;
71199 //
71200 // When an async function declares a return type annotation of `Promise<T>`, we
71201 // need to get the type of the `Promise` variable declaration above, which would
71202 // be `PromiseConstructor`.
71203 //
71204 // The same case applies to a class:
71205 //
71206 // declare class Promise<T> {
71207 // constructor(...);
71208 // then<U>(...): Promise<U>;
71209 // }
71210 //
71211 var returnType = getTypeFromTypeNode(returnTypeNode);
71212 if (languageVersion >= 2 /* ES2015 */) {
71213 if (returnType === errorType) {
71214 return;
71215 }
71216 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
71217 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
71218 // The promise type was not a valid type reference to the global promise type, so we
71219 // report an error and return the unknown type.
71220 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));
71221 return;
71222 }
71223 }
71224 else {
71225 // Always mark the type node as referenced if it points to a value
71226 markTypeNodeAsReferenced(returnTypeNode);
71227 if (returnType === errorType) {
71228 return;
71229 }
71230 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
71231 if (promiseConstructorName === undefined) {
71232 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));
71233 return;
71234 }
71235 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
71236 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
71237 if (promiseConstructorType === errorType) {
71238 if (promiseConstructorName.kind === 78 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
71239 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);
71240 }
71241 else {
71242 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));
71243 }
71244 return;
71245 }
71246 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
71247 if (globalPromiseConstructorLikeType === emptyObjectType) {
71248 // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
71249 // compatibility with __awaiter.
71250 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));
71251 return;
71252 }
71253 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)) {
71254 return;
71255 }
71256 // Verify there is no local declaration that could collide with the promise constructor.
71257 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
71258 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
71259 if (collidingSymbol) {
71260 error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
71261 return;
71262 }
71263 }
71264 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);
71265 }
71266 /** Check a decorator */
71267 function checkDecorator(node) {
71268 var signature = getResolvedSignature(node);
71269 checkDeprecatedSignature(signature, node);
71270 var returnType = getReturnTypeOfSignature(signature);
71271 if (returnType.flags & 1 /* Any */) {
71272 return;
71273 }
71274 var expectedReturnType;
71275 var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
71276 var errorInfo;
71277 switch (node.parent.kind) {
71278 case 249 /* ClassDeclaration */:
71279 var classSymbol = getSymbolOfNode(node.parent);
71280 var classConstructorType = getTypeOfSymbol(classSymbol);
71281 expectedReturnType = getUnionType([classConstructorType, voidType]);
71282 break;
71283 case 159 /* Parameter */:
71284 expectedReturnType = voidType;
71285 errorInfo = ts.chainDiagnosticMessages(
71286 /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
71287 break;
71288 case 162 /* PropertyDeclaration */:
71289 expectedReturnType = voidType;
71290 errorInfo = ts.chainDiagnosticMessages(
71291 /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
71292 break;
71293 case 164 /* MethodDeclaration */:
71294 case 166 /* GetAccessor */:
71295 case 167 /* SetAccessor */:
71296 var methodType = getTypeOfNode(node.parent);
71297 var descriptorType = createTypedPropertyDescriptorType(methodType);
71298 expectedReturnType = getUnionType([descriptorType, voidType]);
71299 break;
71300 default:
71301 return ts.Debug.fail();
71302 }
71303 checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
71304 }
71305 /**
71306 * If a TypeNode can be resolved to a value symbol imported from an external module, it is
71307 * marked as referenced to prevent import elision.
71308 */
71309 function markTypeNodeAsReferenced(node) {
71310 markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
71311 }
71312 function markEntityNameOrEntityExpressionAsReference(typeName) {
71313 if (!typeName)
71314 return;
71315 var rootName = ts.getFirstIdentifier(typeName);
71316 var meaning = (typeName.kind === 78 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
71317 var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
71318 if (rootSymbol
71319 && rootSymbol.flags & 2097152 /* Alias */
71320 && symbolIsValue(rootSymbol)
71321 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
71322 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
71323 markAliasSymbolAsReferenced(rootSymbol);
71324 }
71325 }
71326 /**
71327 * This function marks the type used for metadata decorator as referenced if it is import
71328 * from external module.
71329 * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
71330 * union and intersection type
71331 * @param node
71332 */
71333 function markDecoratorMedataDataTypeNodeAsReferenced(node) {
71334 var entityName = getEntityNameForDecoratorMetadata(node);
71335 if (entityName && ts.isEntityName(entityName)) {
71336 markEntityNameOrEntityExpressionAsReference(entityName);
71337 }
71338 }
71339 function getEntityNameForDecoratorMetadata(node) {
71340 if (node) {
71341 switch (node.kind) {
71342 case 182 /* IntersectionType */:
71343 case 181 /* UnionType */:
71344 return getEntityNameForDecoratorMetadataFromTypeList(node.types);
71345 case 183 /* ConditionalType */:
71346 return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
71347 case 185 /* ParenthesizedType */:
71348 case 191 /* NamedTupleMember */:
71349 return getEntityNameForDecoratorMetadata(node.type);
71350 case 172 /* TypeReference */:
71351 return node.typeName;
71352 }
71353 }
71354 }
71355 function getEntityNameForDecoratorMetadataFromTypeList(types) {
71356 var commonEntityName;
71357 for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
71358 var typeNode = types_20[_i];
71359 while (typeNode.kind === 185 /* ParenthesizedType */ || typeNode.kind === 191 /* NamedTupleMember */) {
71360 typeNode = typeNode.type; // Skip parens if need be
71361 }
71362 if (typeNode.kind === 140 /* NeverKeyword */) {
71363 continue; // Always elide `never` from the union/intersection if possible
71364 }
71365 if (!strictNullChecks && (typeNode.kind === 190 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 149 /* UndefinedKeyword */)) {
71366 continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
71367 }
71368 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
71369 if (!individualEntityName) {
71370 // Individual is something like string number
71371 // So it would be serialized to either that type or object
71372 // Safe to return here
71373 return undefined;
71374 }
71375 if (commonEntityName) {
71376 // Note this is in sync with the transformation that happens for type node.
71377 // Keep this in sync with serializeUnionOrIntersectionType
71378 // Verify if they refer to same entity and is identifier
71379 // return undefined if they dont match because we would emit object
71380 if (!ts.isIdentifier(commonEntityName) ||
71381 !ts.isIdentifier(individualEntityName) ||
71382 commonEntityName.escapedText !== individualEntityName.escapedText) {
71383 return undefined;
71384 }
71385 }
71386 else {
71387 commonEntityName = individualEntityName;
71388 }
71389 }
71390 return commonEntityName;
71391 }
71392 function getParameterTypeNodeForDecoratorCheck(node) {
71393 var typeNode = ts.getEffectiveTypeAnnotationNode(node);
71394 return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
71395 }
71396 /** Check the decorators of a node */
71397 function checkDecorators(node) {
71398 if (!node.decorators) {
71399 return;
71400 }
71401 // skip this check for nodes that cannot have decorators. These should have already had an error reported by
71402 // checkGrammarDecorators.
71403 if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
71404 return;
71405 }
71406 if (!compilerOptions.experimentalDecorators) {
71407 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);
71408 }
71409 var firstDecorator = node.decorators[0];
71410 checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
71411 if (node.kind === 159 /* Parameter */) {
71412 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
71413 }
71414 if (compilerOptions.emitDecoratorMetadata) {
71415 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
71416 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
71417 switch (node.kind) {
71418 case 249 /* ClassDeclaration */:
71419 var constructor = ts.getFirstConstructorWithBody(node);
71420 if (constructor) {
71421 for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
71422 var parameter = _a[_i];
71423 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
71424 }
71425 }
71426 break;
71427 case 166 /* GetAccessor */:
71428 case 167 /* SetAccessor */:
71429 var otherKind = node.kind === 166 /* GetAccessor */ ? 167 /* SetAccessor */ : 166 /* GetAccessor */;
71430 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
71431 markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
71432 break;
71433 case 164 /* MethodDeclaration */:
71434 for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
71435 var parameter = _c[_b];
71436 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
71437 }
71438 markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
71439 break;
71440 case 162 /* PropertyDeclaration */:
71441 markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
71442 break;
71443 case 159 /* Parameter */:
71444 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
71445 var containingSignature = node.parent;
71446 for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
71447 var parameter = _e[_d];
71448 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
71449 }
71450 break;
71451 }
71452 }
71453 ts.forEach(node.decorators, checkDecorator);
71454 }
71455 function checkFunctionDeclaration(node) {
71456 if (produceDiagnostics) {
71457 checkFunctionOrMethodDeclaration(node);
71458 checkGrammarForGenerator(node);
71459 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
71460 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
71461 }
71462 }
71463 function checkJSDocTypeAliasTag(node) {
71464 if (!node.typeExpression) {
71465 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
71466 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
71467 }
71468 if (node.name) {
71469 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
71470 }
71471 checkSourceElement(node.typeExpression);
71472 }
71473 function checkJSDocTemplateTag(node) {
71474 checkSourceElement(node.constraint);
71475 for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
71476 var tp = _a[_i];
71477 checkSourceElement(tp);
71478 }
71479 }
71480 function checkJSDocTypeTag(node) {
71481 checkSourceElement(node.typeExpression);
71482 }
71483 function checkJSDocParameterTag(node) {
71484 checkSourceElement(node.typeExpression);
71485 if (!ts.getParameterSymbolFromJSDoc(node)) {
71486 var decl = ts.getHostSignatureFromJSDoc(node);
71487 // don't issue an error for invalid hosts -- just functions --
71488 // and give a better error message when the host function mentions `arguments`
71489 // but the tag doesn't have an array type
71490 if (decl) {
71491 var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
71492 if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
71493 return;
71494 }
71495 if (!containsArgumentsReference(decl)) {
71496 if (ts.isQualifiedName(node.name)) {
71497 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));
71498 }
71499 else {
71500 error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
71501 }
71502 }
71503 else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
71504 node.typeExpression && node.typeExpression.type &&
71505 !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
71506 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 === 156 /* QualifiedName */ ? node.name.right : node.name));
71507 }
71508 }
71509 }
71510 }
71511 function checkJSDocPropertyTag(node) {
71512 checkSourceElement(node.typeExpression);
71513 }
71514 function checkJSDocFunctionType(node) {
71515 if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
71516 reportImplicitAny(node, anyType);
71517 }
71518 checkSignatureDeclaration(node);
71519 }
71520 function checkJSDocImplementsTag(node) {
71521 var classLike = ts.getEffectiveJSDocHost(node);
71522 if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
71523 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
71524 }
71525 }
71526 function checkJSDocAugmentsTag(node) {
71527 var classLike = ts.getEffectiveJSDocHost(node);
71528 if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
71529 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
71530 return;
71531 }
71532 var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
71533 ts.Debug.assert(augmentsTags.length > 0);
71534 if (augmentsTags.length > 1) {
71535 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
71536 }
71537 var name = getIdentifierFromEntityNameExpression(node.class.expression);
71538 var extend = ts.getClassExtendsHeritageElement(classLike);
71539 if (extend) {
71540 var className = getIdentifierFromEntityNameExpression(extend.expression);
71541 if (className && name.escapedText !== className.escapedText) {
71542 error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
71543 }
71544 }
71545 }
71546 function getIdentifierFromEntityNameExpression(node) {
71547 switch (node.kind) {
71548 case 78 /* Identifier */:
71549 return node;
71550 case 198 /* PropertyAccessExpression */:
71551 return node.name;
71552 default:
71553 return undefined;
71554 }
71555 }
71556 function checkFunctionOrMethodDeclaration(node) {
71557 checkDecorators(node);
71558 checkSignatureDeclaration(node);
71559 var functionFlags = ts.getFunctionFlags(node);
71560 // Do not use hasDynamicName here, because that returns false for well known symbols.
71561 // We want to perform checkComputedPropertyName for all computed properties, including
71562 // well known symbols.
71563 if (node.name && node.name.kind === 157 /* ComputedPropertyName */) {
71564 // This check will account for methods in class/interface declarations,
71565 // as well as accessors in classes/object literals
71566 checkComputedPropertyName(node.name);
71567 }
71568 if (!hasNonBindableDynamicName(node)) {
71569 // first we want to check the local symbol that contain this declaration
71570 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
71571 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
71572 var symbol = getSymbolOfNode(node);
71573 var localSymbol = node.localSymbol || symbol;
71574 // Since the javascript won't do semantic analysis like typescript,
71575 // if the javascript file comes before the typescript file and both contain same name functions,
71576 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
71577 var firstDeclaration = ts.find(localSymbol.declarations,
71578 // Get first non javascript function declaration
71579 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
71580 // Only type check the symbol once
71581 if (node === firstDeclaration) {
71582 checkFunctionOrConstructorSymbol(localSymbol);
71583 }
71584 if (symbol.parent) {
71585 // run check once for the first declaration
71586 if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
71587 // run check on export symbol to check that modifiers agree across all exported declarations
71588 checkFunctionOrConstructorSymbol(symbol);
71589 }
71590 }
71591 }
71592 var body = node.kind === 163 /* MethodSignature */ ? undefined : node.body;
71593 checkSourceElement(body);
71594 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
71595 if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
71596 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
71597 // in an ambient context
71598 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
71599 reportImplicitAny(node, anyType);
71600 }
71601 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
71602 // A generator with a body and no type annotation can still cause errors. It can error if the
71603 // yielded values have no common supertype, or it can give an implicit any error if it has no
71604 // yielded values. The only way to trigger these errors is to try checking its return type.
71605 getReturnTypeOfSignature(getSignatureFromDeclaration(node));
71606 }
71607 }
71608 // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
71609 if (ts.isInJSFile(node)) {
71610 var typeTag = ts.getJSDocTypeTag(node);
71611 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
71612 error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
71613 }
71614 }
71615 }
71616 function registerForUnusedIdentifiersCheck(node) {
71617 // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
71618 if (produceDiagnostics) {
71619 var sourceFile = ts.getSourceFileOfNode(node);
71620 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
71621 if (!potentiallyUnusedIdentifiers) {
71622 potentiallyUnusedIdentifiers = [];
71623 allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
71624 }
71625 // TODO: GH#22580
71626 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
71627 potentiallyUnusedIdentifiers.push(node);
71628 }
71629 }
71630 function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
71631 for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
71632 var node = potentiallyUnusedIdentifiers_1[_i];
71633 switch (node.kind) {
71634 case 249 /* ClassDeclaration */:
71635 case 218 /* ClassExpression */:
71636 checkUnusedClassMembers(node, addDiagnostic);
71637 checkUnusedTypeParameters(node, addDiagnostic);
71638 break;
71639 case 294 /* SourceFile */:
71640 case 253 /* ModuleDeclaration */:
71641 case 227 /* Block */:
71642 case 255 /* CaseBlock */:
71643 case 234 /* ForStatement */:
71644 case 235 /* ForInStatement */:
71645 case 236 /* ForOfStatement */:
71646 checkUnusedLocalsAndParameters(node, addDiagnostic);
71647 break;
71648 case 165 /* Constructor */:
71649 case 205 /* FunctionExpression */:
71650 case 248 /* FunctionDeclaration */:
71651 case 206 /* ArrowFunction */:
71652 case 164 /* MethodDeclaration */:
71653 case 166 /* GetAccessor */:
71654 case 167 /* SetAccessor */:
71655 if (node.body) { // Don't report unused parameters in overloads
71656 checkUnusedLocalsAndParameters(node, addDiagnostic);
71657 }
71658 checkUnusedTypeParameters(node, addDiagnostic);
71659 break;
71660 case 163 /* MethodSignature */:
71661 case 168 /* CallSignature */:
71662 case 169 /* ConstructSignature */:
71663 case 173 /* FunctionType */:
71664 case 174 /* ConstructorType */:
71665 case 251 /* TypeAliasDeclaration */:
71666 case 250 /* InterfaceDeclaration */:
71667 checkUnusedTypeParameters(node, addDiagnostic);
71668 break;
71669 case 184 /* InferType */:
71670 checkUnusedInferTypeParameter(node, addDiagnostic);
71671 break;
71672 default:
71673 ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
71674 }
71675 }
71676 }
71677 function errorUnusedLocal(declaration, name, addDiagnostic) {
71678 var node = ts.getNameOfDeclaration(declaration) || declaration;
71679 var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
71680 addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
71681 }
71682 function isIdentifierThatStartsWithUnderscore(node) {
71683 return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
71684 }
71685 function checkUnusedClassMembers(node, addDiagnostic) {
71686 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
71687 var member = _a[_i];
71688 switch (member.kind) {
71689 case 164 /* MethodDeclaration */:
71690 case 162 /* PropertyDeclaration */:
71691 case 166 /* GetAccessor */:
71692 case 167 /* SetAccessor */:
71693 if (member.kind === 167 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
71694 // Already would have reported an error on the getter.
71695 break;
71696 }
71697 var symbol = getSymbolOfNode(member);
71698 if (!symbol.isReferenced
71699 && (ts.hasEffectiveModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
71700 && !(member.flags & 8388608 /* Ambient */)) {
71701 addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
71702 }
71703 break;
71704 case 165 /* Constructor */:
71705 for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
71706 var parameter = _c[_b];
71707 if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) {
71708 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
71709 }
71710 }
71711 break;
71712 case 170 /* IndexSignature */:
71713 case 226 /* SemicolonClassElement */:
71714 // Can't be private
71715 break;
71716 default:
71717 ts.Debug.fail();
71718 }
71719 }
71720 }
71721 function checkUnusedInferTypeParameter(node, addDiagnostic) {
71722 var typeParameter = node.typeParameter;
71723 if (isTypeParameterUnused(typeParameter)) {
71724 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
71725 }
71726 }
71727 function checkUnusedTypeParameters(node, addDiagnostic) {
71728 // Only report errors on the last declaration for the type parameter container;
71729 // this ensures that all uses have been accounted for.
71730 if (ts.last(getSymbolOfNode(node).declarations) !== node)
71731 return;
71732 var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
71733 var seenParentsWithEveryUnused = new ts.Set();
71734 for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
71735 var typeParameter = typeParameters_3[_i];
71736 if (!isTypeParameterUnused(typeParameter))
71737 continue;
71738 var name = ts.idText(typeParameter.name);
71739 var parent = typeParameter.parent;
71740 if (parent.kind !== 184 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
71741 if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
71742 var range = ts.isJSDocTemplateTag(parent)
71743 // Whole @template tag
71744 ? ts.rangeOfNode(parent)
71745 // Include the `<>` in the error message
71746 : ts.rangeOfTypeParameters(parent.typeParameters);
71747 var only = parent.typeParameters.length === 1;
71748 var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
71749 var arg0 = only ? name : undefined;
71750 addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
71751 }
71752 }
71753 else {
71754 addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
71755 }
71756 }
71757 }
71758 function isTypeParameterUnused(typeParameter) {
71759 return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
71760 }
71761 function addToGroup(map, key, value, getKey) {
71762 var keyString = String(getKey(key));
71763 var group = map.get(keyString);
71764 if (group) {
71765 group[1].push(value);
71766 }
71767 else {
71768 map.set(keyString, [key, [value]]);
71769 }
71770 }
71771 function tryGetRootParameterDeclaration(node) {
71772 return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
71773 }
71774 function isValidUnusedLocalDeclaration(declaration) {
71775 if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
71776 return !!ts.findAncestor(declaration.parent, function (ancestor) {
71777 return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
71778 ts.isForOfStatement(ancestor) ? true : "quit";
71779 });
71780 }
71781 return ts.isAmbientModule(declaration) ||
71782 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
71783 }
71784 function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
71785 // 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.
71786 var unusedImports = new ts.Map();
71787 var unusedDestructures = new ts.Map();
71788 var unusedVariables = new ts.Map();
71789 nodeWithLocals.locals.forEach(function (local) {
71790 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
71791 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
71792 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
71793 return;
71794 }
71795 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
71796 var declaration = _a[_i];
71797 if (isValidUnusedLocalDeclaration(declaration)) {
71798 continue;
71799 }
71800 if (isImportedDeclaration(declaration)) {
71801 addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
71802 }
71803 else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
71804 // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
71805 var lastElement = ts.last(declaration.parent.elements);
71806 if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
71807 addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
71808 }
71809 }
71810 else if (ts.isVariableDeclaration(declaration)) {
71811 addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
71812 }
71813 else {
71814 var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
71815 var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
71816 if (parameter && name) {
71817 if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
71818 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
71819 }
71820 }
71821 else {
71822 errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
71823 }
71824 }
71825 }
71826 });
71827 unusedImports.forEach(function (_a) {
71828 var importClause = _a[0], unuseds = _a[1];
71829 var importDecl = importClause.parent;
71830 var nDeclarations = (importClause.name ? 1 : 0) +
71831 (importClause.namedBindings ?
71832 (importClause.namedBindings.kind === 260 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
71833 : 0);
71834 if (nDeclarations === unuseds.length) {
71835 addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
71836 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
71837 : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
71838 }
71839 else {
71840 for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
71841 var unused = unuseds_1[_i];
71842 errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
71843 }
71844 }
71845 });
71846 unusedDestructures.forEach(function (_a) {
71847 var bindingPattern = _a[0], bindingElements = _a[1];
71848 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
71849 if (bindingPattern.elements.length === bindingElements.length) {
71850 if (bindingElements.length === 1 && bindingPattern.parent.kind === 246 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 247 /* VariableDeclarationList */) {
71851 addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
71852 }
71853 else {
71854 addDiagnostic(bindingPattern, kind, bindingElements.length === 1
71855 ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
71856 : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
71857 }
71858 }
71859 else {
71860 for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
71861 var e = bindingElements_1[_i];
71862 addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
71863 }
71864 }
71865 });
71866 unusedVariables.forEach(function (_a) {
71867 var declarationList = _a[0], declarations = _a[1];
71868 if (declarationList.declarations.length === declarations.length) {
71869 addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
71870 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
71871 : ts.createDiagnosticForNode(declarationList.parent.kind === 229 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
71872 }
71873 else {
71874 for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
71875 var decl = declarations_5[_i];
71876 addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
71877 }
71878 }
71879 });
71880 }
71881 function bindingNameText(name) {
71882 switch (name.kind) {
71883 case 78 /* Identifier */:
71884 return ts.idText(name);
71885 case 194 /* ArrayBindingPattern */:
71886 case 193 /* ObjectBindingPattern */:
71887 return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
71888 default:
71889 return ts.Debug.assertNever(name);
71890 }
71891 }
71892 function isImportedDeclaration(node) {
71893 return node.kind === 259 /* ImportClause */ || node.kind === 262 /* ImportSpecifier */ || node.kind === 260 /* NamespaceImport */;
71894 }
71895 function importClauseFromImported(decl) {
71896 return decl.kind === 259 /* ImportClause */ ? decl : decl.kind === 260 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
71897 }
71898 function checkBlock(node) {
71899 // Grammar checking for SyntaxKind.Block
71900 if (node.kind === 227 /* Block */) {
71901 checkGrammarStatementInAmbientContext(node);
71902 }
71903 if (ts.isFunctionOrModuleBlock(node)) {
71904 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
71905 ts.forEach(node.statements, checkSourceElement);
71906 flowAnalysisDisabled = saveFlowAnalysisDisabled;
71907 }
71908 else {
71909 ts.forEach(node.statements, checkSourceElement);
71910 }
71911 if (node.locals) {
71912 registerForUnusedIdentifiersCheck(node);
71913 }
71914 }
71915 function checkCollisionWithArgumentsInGeneratedCode(node) {
71916 // no rest parameters \ declaration context \ overload - no codegen impact
71917 if (languageVersion >= 2 /* ES2015 */ || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
71918 return;
71919 }
71920 ts.forEach(node.parameters, function (p) {
71921 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
71922 errorSkippedOn("noEmit", p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
71923 }
71924 });
71925 }
71926 function needCollisionCheckForIdentifier(node, identifier, name) {
71927 if (!(identifier && identifier.escapedText === name)) {
71928 return false;
71929 }
71930 if (node.kind === 162 /* PropertyDeclaration */ ||
71931 node.kind === 161 /* PropertySignature */ ||
71932 node.kind === 164 /* MethodDeclaration */ ||
71933 node.kind === 163 /* MethodSignature */ ||
71934 node.kind === 166 /* GetAccessor */ ||
71935 node.kind === 167 /* SetAccessor */) {
71936 // it is ok to have member named '_super' or '_this' - member access is always qualified
71937 return false;
71938 }
71939 if (node.flags & 8388608 /* Ambient */) {
71940 // ambient context - no codegen impact
71941 return false;
71942 }
71943 var root = ts.getRootDeclaration(node);
71944 if (root.kind === 159 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
71945 // just an overload - no codegen impact
71946 return false;
71947 }
71948 return true;
71949 }
71950 // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
71951 function checkIfThisIsCapturedInEnclosingScope(node) {
71952 ts.findAncestor(node, function (current) {
71953 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
71954 var isDeclaration_1 = node.kind !== 78 /* Identifier */;
71955 if (isDeclaration_1) {
71956 error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
71957 }
71958 else {
71959 error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
71960 }
71961 return true;
71962 }
71963 return false;
71964 });
71965 }
71966 function checkIfNewTargetIsCapturedInEnclosingScope(node) {
71967 ts.findAncestor(node, function (current) {
71968 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
71969 var isDeclaration_2 = node.kind !== 78 /* Identifier */;
71970 if (isDeclaration_2) {
71971 error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
71972 }
71973 else {
71974 error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
71975 }
71976 return true;
71977 }
71978 return false;
71979 });
71980 }
71981 function checkWeakMapCollision(node) {
71982 var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
71983 if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
71984 errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
71985 }
71986 }
71987 function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
71988 // No need to check for require or exports for ES6 modules and later
71989 if (moduleKind >= ts.ModuleKind.ES2015) {
71990 return;
71991 }
71992 if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
71993 return;
71994 }
71995 // Uninstantiated modules shouldnt do this check
71996 if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
71997 return;
71998 }
71999 // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
72000 var parent = getDeclarationContainer(node);
72001 if (parent.kind === 294 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
72002 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
72003 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));
72004 }
72005 }
72006 function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
72007 if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
72008 return;
72009 }
72010 // Uninstantiated modules shouldnt do this check
72011 if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
72012 return;
72013 }
72014 // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
72015 var parent = getDeclarationContainer(node);
72016 if (parent.kind === 294 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
72017 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
72018 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));
72019 }
72020 }
72021 function checkVarDeclaredNamesNotShadowed(node) {
72022 // - ScriptBody : StatementList
72023 // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
72024 // also occurs in the VarDeclaredNames of StatementList.
72025 // - Block : { StatementList }
72026 // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
72027 // also occurs in the VarDeclaredNames of StatementList.
72028 // Variable declarations are hoisted to the top of their function scope. They can shadow
72029 // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
72030 // by the binder as the declaration scope is different.
72031 // A non-initialized declaration is a no-op as the block declaration will resolve before the var
72032 // declaration. the problem is if the declaration has an initializer. this will act as a write to the
72033 // block declared value. this is fine for let, but not const.
72034 // Only consider declarations with initializers, uninitialized const declarations will not
72035 // step on a let/const variable.
72036 // Do not consider const and const declarations, as duplicate block-scoped declarations
72037 // are handled by the binder.
72038 // We are only looking for const declarations that step on let\const declarations from a
72039 // different scope. e.g.:
72040 // {
72041 // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
72042 // const x = 0; // symbol for this declaration will be 'symbol'
72043 // }
72044 // skip block-scoped variables and parameters
72045 if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
72046 return;
72047 }
72048 // skip variable declarations that don't have initializers
72049 // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
72050 // so we'll always treat binding elements as initialized
72051 if (node.kind === 246 /* VariableDeclaration */ && !node.initializer) {
72052 return;
72053 }
72054 var symbol = getSymbolOfNode(node);
72055 if (symbol.flags & 1 /* FunctionScopedVariable */) {
72056 if (!ts.isIdentifier(node.name))
72057 return ts.Debug.fail();
72058 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
72059 if (localDeclarationSymbol &&
72060 localDeclarationSymbol !== symbol &&
72061 localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
72062 if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
72063 var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 247 /* VariableDeclarationList */);
72064 var container = varDeclList.parent.kind === 229 /* VariableStatement */ && varDeclList.parent.parent
72065 ? varDeclList.parent.parent
72066 : undefined;
72067 // names of block-scoped and function scoped variables can collide only
72068 // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
72069 var namesShareScope = container &&
72070 (container.kind === 227 /* Block */ && ts.isFunctionLike(container.parent) ||
72071 container.kind === 254 /* ModuleBlock */ ||
72072 container.kind === 253 /* ModuleDeclaration */ ||
72073 container.kind === 294 /* SourceFile */);
72074 // here we know that function scoped variable is shadowed by block scoped one
72075 // if they are defined in the same scope - binder has already reported redeclaration error
72076 // otherwise if variable has an initializer - show error that initialization will fail
72077 // since LHS will be block scoped name instead of function scoped
72078 if (!namesShareScope) {
72079 var name = symbolToString(localDeclarationSymbol);
72080 error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
72081 }
72082 }
72083 }
72084 }
72085 }
72086 function convertAutoToAny(type) {
72087 return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
72088 }
72089 // Check variable, parameter, or property declaration
72090 function checkVariableLikeDeclaration(node) {
72091 var _a;
72092 checkDecorators(node);
72093 if (!ts.isBindingElement(node)) {
72094 checkSourceElement(node.type);
72095 }
72096 // JSDoc `function(string, string): string` syntax results in parameters with no name
72097 if (!node.name) {
72098 return;
72099 }
72100 // For a computed property, just check the initializer and exit
72101 // Do not use hasDynamicName here, because that returns false for well known symbols.
72102 // We want to perform checkComputedPropertyName for all computed properties, including
72103 // well known symbols.
72104 if (node.name.kind === 157 /* ComputedPropertyName */) {
72105 checkComputedPropertyName(node.name);
72106 if (node.initializer) {
72107 checkExpressionCached(node.initializer);
72108 }
72109 }
72110 if (node.kind === 195 /* BindingElement */) {
72111 if (node.parent.kind === 193 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
72112 checkExternalEmitHelpers(node, 4 /* Rest */);
72113 }
72114 // check computed properties inside property names of binding elements
72115 if (node.propertyName && node.propertyName.kind === 157 /* ComputedPropertyName */) {
72116 checkComputedPropertyName(node.propertyName);
72117 }
72118 // check private/protected variable access
72119 var parent = node.parent.parent;
72120 var parentType = getTypeForBindingElementParent(parent);
72121 var name = node.propertyName || node.name;
72122 if (parentType && !ts.isBindingPattern(name)) {
72123 var exprType = getLiteralTypeFromPropertyName(name);
72124 if (isTypeUsableAsPropertyName(exprType)) {
72125 var nameText = getPropertyNameFromType(exprType);
72126 var property = getPropertyOfType(parentType, nameText);
72127 if (property) {
72128 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
72129 checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property);
72130 }
72131 }
72132 }
72133 }
72134 // For a binding pattern, check contained binding elements
72135 if (ts.isBindingPattern(node.name)) {
72136 if (node.name.kind === 194 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
72137 checkExternalEmitHelpers(node, 512 /* Read */);
72138 }
72139 ts.forEach(node.name.elements, checkSourceElement);
72140 }
72141 // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
72142 if (node.initializer && ts.getRootDeclaration(node).kind === 159 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
72143 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
72144 return;
72145 }
72146 // For a binding pattern, validate the initializer and exit
72147 if (ts.isBindingPattern(node.name)) {
72148 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 235 /* ForInStatement */;
72149 var needCheckWidenedType = node.name.elements.length === 0;
72150 if (needCheckInitializer || needCheckWidenedType) {
72151 // Don't validate for-in initializer as it is already an error
72152 var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
72153 if (needCheckInitializer) {
72154 var initializerType = checkExpressionCached(node.initializer);
72155 if (strictNullChecks && needCheckWidenedType) {
72156 checkNonNullNonVoidType(initializerType, node);
72157 }
72158 else {
72159 checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
72160 }
72161 }
72162 // check the binding pattern with empty elements
72163 if (needCheckWidenedType) {
72164 if (ts.isArrayBindingPattern(node.name)) {
72165 checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
72166 }
72167 else if (strictNullChecks) {
72168 checkNonNullNonVoidType(widenedType, node);
72169 }
72170 }
72171 }
72172 return;
72173 }
72174 var symbol = getSymbolOfNode(node);
72175 var type = convertAutoToAny(getTypeOfSymbol(symbol));
72176 if (node === symbol.valueDeclaration) {
72177 // Node is the primary declaration of the symbol, just validate the initializer
72178 // Don't validate for-in initializer as it is already an error
72179 var initializer = ts.getEffectiveInitializer(node);
72180 if (initializer) {
72181 var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
72182 ts.isObjectLiteralExpression(initializer) &&
72183 (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
72184 !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
72185 if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 235 /* ForInStatement */) {
72186 checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
72187 }
72188 }
72189 if (symbol.declarations.length > 1) {
72190 if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
72191 error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
72192 }
72193 }
72194 }
72195 else {
72196 // Node is a secondary declaration, check that type is identical to primary declaration and check that
72197 // initializer is consistent with type associated with the node
72198 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
72199 if (type !== errorType && declarationType !== errorType &&
72200 !isTypeIdenticalTo(type, declarationType) &&
72201 !(symbol.flags & 67108864 /* Assignment */)) {
72202 errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
72203 }
72204 if (node.initializer) {
72205 checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
72206 }
72207 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
72208 error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
72209 }
72210 }
72211 if (node.kind !== 162 /* PropertyDeclaration */ && node.kind !== 161 /* PropertySignature */) {
72212 // We know we don't have a binding pattern or computed name here
72213 checkExportsOnMergedDeclarations(node);
72214 if (node.kind === 246 /* VariableDeclaration */ || node.kind === 195 /* BindingElement */) {
72215 checkVarDeclaredNamesNotShadowed(node);
72216 }
72217 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
72218 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
72219 if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
72220 potentialWeakMapCollisions.push(node);
72221 }
72222 }
72223 }
72224 function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
72225 var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
72226 var message = nextDeclaration.kind === 162 /* PropertyDeclaration */ || nextDeclaration.kind === 161 /* PropertySignature */
72227 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
72228 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
72229 var declName = ts.declarationNameToString(nextDeclarationName);
72230 var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
72231 if (firstDeclaration) {
72232 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
72233 }
72234 }
72235 function areDeclarationFlagsIdentical(left, right) {
72236 if ((left.kind === 159 /* Parameter */ && right.kind === 246 /* VariableDeclaration */) ||
72237 (left.kind === 246 /* VariableDeclaration */ && right.kind === 159 /* Parameter */)) {
72238 // Differences in optionality between parameters and variables are allowed.
72239 return true;
72240 }
72241 if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
72242 return false;
72243 }
72244 var interestingFlags = 8 /* Private */ |
72245 16 /* Protected */ |
72246 256 /* Async */ |
72247 128 /* Abstract */ |
72248 64 /* Readonly */ |
72249 32 /* Static */;
72250 return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
72251 }
72252 function checkVariableDeclaration(node) {
72253 checkGrammarVariableDeclaration(node);
72254 return checkVariableLikeDeclaration(node);
72255 }
72256 function checkBindingElement(node) {
72257 checkGrammarBindingElement(node);
72258 return checkVariableLikeDeclaration(node);
72259 }
72260 function checkVariableStatement(node) {
72261 // Grammar checking
72262 if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
72263 checkGrammarForDisallowedLetOrConstStatement(node);
72264 ts.forEach(node.declarationList.declarations, checkSourceElement);
72265 }
72266 function checkExpressionStatement(node) {
72267 // Grammar checking
72268 checkGrammarStatementInAmbientContext(node);
72269 checkExpression(node.expression);
72270 }
72271 function checkIfStatement(node) {
72272 // Grammar checking
72273 checkGrammarStatementInAmbientContext(node);
72274 var type = checkTruthinessExpression(node.expression);
72275 checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
72276 checkSourceElement(node.thenStatement);
72277 if (node.thenStatement.kind === 228 /* EmptyStatement */) {
72278 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
72279 }
72280 checkSourceElement(node.elseStatement);
72281 }
72282 function checkTestingKnownTruthyCallableType(condExpr, body, type) {
72283 if (!strictNullChecks) {
72284 return;
72285 }
72286 var testedNode = ts.isIdentifier(condExpr)
72287 ? condExpr
72288 : ts.isPropertyAccessExpression(condExpr)
72289 ? condExpr.name
72290 : undefined;
72291 if (!testedNode) {
72292 return;
72293 }
72294 var possiblyFalsy = getFalsyFlags(type);
72295 if (possiblyFalsy) {
72296 return;
72297 }
72298 // While it technically should be invalid for any known-truthy value
72299 // to be tested, we de-scope to functions unrefenced in the block as a
72300 // heuristic to identify the most common bugs. There are too many
72301 // false positives for values sourced from type definitions without
72302 // strictNullChecks otherwise.
72303 var callSignatures = getSignaturesOfType(type, 0 /* Call */);
72304 if (callSignatures.length === 0) {
72305 return;
72306 }
72307 var testedFunctionSymbol = getSymbolAtLocation(testedNode);
72308 if (!testedFunctionSymbol) {
72309 return;
72310 }
72311 var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
72312 if (ts.isIdentifier(childNode)) {
72313 var childSymbol = getSymbolAtLocation(childNode);
72314 if (childSymbol && childSymbol === testedFunctionSymbol) {
72315 // If the test was a simple identifier, the above check is sufficient
72316 if (ts.isIdentifier(condExpr)) {
72317 return true;
72318 }
72319 // Otherwise we need to ensure the symbol is called on the same target
72320 var testedExpression = testedNode.parent;
72321 var childExpression = childNode.parent;
72322 while (testedExpression && childExpression) {
72323 if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
72324 testedExpression.kind === 107 /* ThisKeyword */ && childExpression.kind === 107 /* ThisKeyword */) {
72325 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
72326 }
72327 if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
72328 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
72329 return false;
72330 }
72331 childExpression = childExpression.expression;
72332 testedExpression = testedExpression.expression;
72333 }
72334 else {
72335 return false;
72336 }
72337 }
72338 }
72339 }
72340 return ts.forEachChild(childNode, check);
72341 });
72342 if (!functionIsUsedInBody) {
72343 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
72344 }
72345 }
72346 function checkDoStatement(node) {
72347 // Grammar checking
72348 checkGrammarStatementInAmbientContext(node);
72349 checkSourceElement(node.statement);
72350 checkTruthinessExpression(node.expression);
72351 }
72352 function checkWhileStatement(node) {
72353 // Grammar checking
72354 checkGrammarStatementInAmbientContext(node);
72355 checkTruthinessExpression(node.expression);
72356 checkSourceElement(node.statement);
72357 }
72358 function checkTruthinessOfType(type, node) {
72359 if (type.flags & 16384 /* Void */) {
72360 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
72361 }
72362 return type;
72363 }
72364 function checkTruthinessExpression(node, checkMode) {
72365 return checkTruthinessOfType(checkExpression(node, checkMode), node);
72366 }
72367 function checkForStatement(node) {
72368 // Grammar checking
72369 if (!checkGrammarStatementInAmbientContext(node)) {
72370 if (node.initializer && node.initializer.kind === 247 /* VariableDeclarationList */) {
72371 checkGrammarVariableDeclarationList(node.initializer);
72372 }
72373 }
72374 if (node.initializer) {
72375 if (node.initializer.kind === 247 /* VariableDeclarationList */) {
72376 ts.forEach(node.initializer.declarations, checkVariableDeclaration);
72377 }
72378 else {
72379 checkExpression(node.initializer);
72380 }
72381 }
72382 if (node.condition)
72383 checkTruthinessExpression(node.condition);
72384 if (node.incrementor)
72385 checkExpression(node.incrementor);
72386 checkSourceElement(node.statement);
72387 if (node.locals) {
72388 registerForUnusedIdentifiersCheck(node);
72389 }
72390 }
72391 function checkForOfStatement(node) {
72392 checkGrammarForInOrForOfStatement(node);
72393 if (node.awaitModifier) {
72394 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
72395 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
72396 // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
72397 checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
72398 }
72399 }
72400 else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
72401 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
72402 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
72403 }
72404 // Check the LHS and RHS
72405 // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
72406 // via checkRightHandSideOfForOf.
72407 // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
72408 // Then check that the RHS is assignable to it.
72409 if (node.initializer.kind === 247 /* VariableDeclarationList */) {
72410 checkForInOrForOfVariableDeclaration(node);
72411 }
72412 else {
72413 var varExpr = node.initializer;
72414 var iteratedType = checkRightHandSideOfForOf(node);
72415 // There may be a destructuring assignment on the left side
72416 if (varExpr.kind === 196 /* ArrayLiteralExpression */ || varExpr.kind === 197 /* ObjectLiteralExpression */) {
72417 // iteratedType may be undefined. In this case, we still want to check the structure of
72418 // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
72419 // to short circuit the type relation checking as much as possible, so we pass the unknownType.
72420 checkDestructuringAssignment(varExpr, iteratedType || errorType);
72421 }
72422 else {
72423 var leftType = checkExpression(varExpr);
72424 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);
72425 // iteratedType will be undefined if the rightType was missing properties/signatures
72426 // required to get its iteratedType (like [Symbol.iterator] or next). This may be
72427 // because we accessed properties from anyType, or it may have led to an error inside
72428 // getElementTypeOfIterable.
72429 if (iteratedType) {
72430 checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
72431 }
72432 }
72433 }
72434 checkSourceElement(node.statement);
72435 if (node.locals) {
72436 registerForUnusedIdentifiersCheck(node);
72437 }
72438 }
72439 function checkForInStatement(node) {
72440 // Grammar checking
72441 checkGrammarForInOrForOfStatement(node);
72442 var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
72443 // TypeScript 1.0 spec (April 2014): 5.4
72444 // In a 'for-in' statement of the form
72445 // for (let VarDecl in Expr) Statement
72446 // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
72447 // and Expr must be an expression of type Any, an object type, or a type parameter type.
72448 if (node.initializer.kind === 247 /* VariableDeclarationList */) {
72449 var variable = node.initializer.declarations[0];
72450 if (variable && ts.isBindingPattern(variable.name)) {
72451 error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
72452 }
72453 checkForInOrForOfVariableDeclaration(node);
72454 }
72455 else {
72456 // In a 'for-in' statement of the form
72457 // for (Var in Expr) Statement
72458 // Var must be an expression classified as a reference of type Any or the String primitive type,
72459 // and Expr must be an expression of type Any, an object type, or a type parameter type.
72460 var varExpr = node.initializer;
72461 var leftType = checkExpression(varExpr);
72462 if (varExpr.kind === 196 /* ArrayLiteralExpression */ || varExpr.kind === 197 /* ObjectLiteralExpression */) {
72463 error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
72464 }
72465 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
72466 error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
72467 }
72468 else {
72469 // run check only former check succeeded to avoid cascading errors
72470 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);
72471 }
72472 }
72473 // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
72474 // in this case error about missing name is already reported - do not report extra one
72475 if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
72476 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));
72477 }
72478 checkSourceElement(node.statement);
72479 if (node.locals) {
72480 registerForUnusedIdentifiersCheck(node);
72481 }
72482 }
72483 function checkForInOrForOfVariableDeclaration(iterationStatement) {
72484 var variableDeclarationList = iterationStatement.initializer;
72485 // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
72486 if (variableDeclarationList.declarations.length >= 1) {
72487 var decl = variableDeclarationList.declarations[0];
72488 checkVariableDeclaration(decl);
72489 }
72490 }
72491 function checkRightHandSideOfForOf(statement) {
72492 var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
72493 return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
72494 }
72495 function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
72496 if (isTypeAny(inputType)) {
72497 return inputType;
72498 }
72499 return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
72500 }
72501 /**
72502 * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
72503 * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
72504 * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
72505 */
72506 function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
72507 var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
72508 if (inputType === neverType) {
72509 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
72510 return undefined;
72511 }
72512 var uplevelIteration = languageVersion >= 2 /* ES2015 */;
72513 var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
72514 // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
72515 // or higher, when inside of an async generator or for-await-if, or when
72516 // downlevelIteration is requested.
72517 if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
72518 // We only report errors for an invalid iterable type in ES2015 or higher.
72519 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
72520 if (checkAssignability) {
72521 if (iterationTypes) {
72522 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 :
72523 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 :
72524 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 :
72525 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 :
72526 undefined;
72527 if (diagnostic) {
72528 checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
72529 }
72530 }
72531 }
72532 if (iterationTypes || uplevelIteration) {
72533 return iterationTypes && iterationTypes.yieldType;
72534 }
72535 }
72536 var arrayType = inputType;
72537 var reportedError = false;
72538 var hasStringConstituent = false;
72539 // If strings are permitted, remove any string-like constituents from the array type.
72540 // This allows us to find other non-string element types from an array unioned with
72541 // a string.
72542 if (use & 4 /* AllowsStringInputFlag */) {
72543 if (arrayType.flags & 1048576 /* Union */) {
72544 // After we remove all types that are StringLike, we will know if there was a string constituent
72545 // based on whether the result of filter is a new array.
72546 var arrayTypes = inputType.types;
72547 var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
72548 if (filteredTypes !== arrayTypes) {
72549 arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
72550 }
72551 }
72552 else if (arrayType.flags & 132 /* StringLike */) {
72553 arrayType = neverType;
72554 }
72555 hasStringConstituent = arrayType !== inputType;
72556 if (hasStringConstituent) {
72557 if (languageVersion < 1 /* ES5 */) {
72558 if (errorNode) {
72559 error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
72560 reportedError = true;
72561 }
72562 }
72563 // Now that we've removed all the StringLike types, if no constituents remain, then the entire
72564 // arrayOrStringType was a string.
72565 if (arrayType.flags & 131072 /* Never */) {
72566 return stringType;
72567 }
72568 }
72569 }
72570 if (!isArrayLikeType(arrayType)) {
72571 if (errorNode && !reportedError) {
72572 // Which error we report depends on whether we allow strings or if there was a
72573 // string constituent. For example, if the input type is number | string, we
72574 // want to say that number is not an array type. But if the input was just
72575 // number and string input is allowed, we want to say that number is not an
72576 // array type or a string type.
72577 var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
72578 var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
72579 ? downlevelIteration
72580 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
72581 : yieldType
72582 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
72583 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
72584 : downlevelIteration
72585 ? [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]
72586 : yieldType
72587 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
72588 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
72589 errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
72590 }
72591 return hasStringConstituent ? stringType : undefined;
72592 }
72593 var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
72594 if (hasStringConstituent && arrayElementType) {
72595 // This is just an optimization for the case where arrayOrStringType is string | string[]
72596 if (arrayElementType.flags & 132 /* StringLike */) {
72597 return stringType;
72598 }
72599 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
72600 }
72601 return arrayElementType;
72602 }
72603 /**
72604 * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
72605 */
72606 function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
72607 if (isTypeAny(inputType)) {
72608 return undefined;
72609 }
72610 var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
72611 return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
72612 }
72613 function createIterationTypes(yieldType, returnType, nextType) {
72614 // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
72615 // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
72616 // as it is combined via `getIntersectionType` when merging iteration types.
72617 if (yieldType === void 0) { yieldType = neverType; }
72618 if (returnType === void 0) { returnType = neverType; }
72619 if (nextType === void 0) { nextType = unknownType; }
72620 // Use the cache only for intrinsic types to keep it small as they are likely to be
72621 // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
72622 // are also cached on the type they are requested for, so we shouldn't need to maintain
72623 // the cache for less-frequently used types.
72624 if (yieldType.flags & 67359327 /* Intrinsic */ &&
72625 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
72626 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
72627 var id = getTypeListId([yieldType, returnType, nextType]);
72628 var iterationTypes = iterationTypesCache.get(id);
72629 if (!iterationTypes) {
72630 iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
72631 iterationTypesCache.set(id, iterationTypes);
72632 }
72633 return iterationTypes;
72634 }
72635 return { yieldType: yieldType, returnType: returnType, nextType: nextType };
72636 }
72637 /**
72638 * Combines multiple `IterationTypes` records.
72639 *
72640 * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
72641 * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
72642 * for the combined iteration types.
72643 */
72644 function combineIterationTypes(array) {
72645 var yieldTypes;
72646 var returnTypes;
72647 var nextTypes;
72648 for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
72649 var iterationTypes = array_10[_i];
72650 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
72651 continue;
72652 }
72653 if (iterationTypes === anyIterationTypes) {
72654 return anyIterationTypes;
72655 }
72656 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
72657 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
72658 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
72659 }
72660 if (yieldTypes || returnTypes || nextTypes) {
72661 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
72662 }
72663 return noIterationTypes;
72664 }
72665 function getCachedIterationTypes(type, cacheKey) {
72666 return type[cacheKey];
72667 }
72668 function setCachedIterationTypes(type, cacheKey, cachedTypes) {
72669 return type[cacheKey] = cachedTypes;
72670 }
72671 /**
72672 * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
72673 *
72674 * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
72675 *
72676 * Another thing to note is that at any step of this process, we could run into a dead end,
72677 * meaning either the property is missing, or we run into the anyType. If either of these things
72678 * happens, we return `undefined` to signal that we could not find the iteration type. If a property
72679 * is missing, and the previous step did not result in `any`, then we also give an error if the
72680 * caller requested it. Then the caller can decide what to do in the case where there is no iterated
72681 * type.
72682 *
72683 * For a **for-of** statement, `yield*` (in a normal generator), spread, array
72684 * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
72685 * method.
72686 *
72687 * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
72688 *
72689 * For a **for-await-of** statement or a `yield*` in an async generator we will look for
72690 * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
72691 */
72692 function getIterationTypesOfIterable(type, use, errorNode) {
72693 if (isTypeAny(type)) {
72694 return anyIterationTypes;
72695 }
72696 if (!(type.flags & 1048576 /* Union */)) {
72697 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
72698 if (iterationTypes_1 === noIterationTypes) {
72699 if (errorNode) {
72700 reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
72701 }
72702 return undefined;
72703 }
72704 return iterationTypes_1;
72705 }
72706 var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
72707 var cachedTypes = getCachedIterationTypes(type, cacheKey);
72708 if (cachedTypes)
72709 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
72710 var allIterationTypes;
72711 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
72712 var constituent = _a[_i];
72713 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
72714 if (iterationTypes_2 === noIterationTypes) {
72715 if (errorNode) {
72716 reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
72717 errorNode = undefined;
72718 }
72719 }
72720 else {
72721 allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
72722 }
72723 }
72724 var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
72725 setCachedIterationTypes(type, cacheKey, iterationTypes);
72726 return iterationTypes === noIterationTypes ? undefined : iterationTypes;
72727 }
72728 function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
72729 if (iterationTypes === noIterationTypes)
72730 return noIterationTypes;
72731 if (iterationTypes === anyIterationTypes)
72732 return anyIterationTypes;
72733 var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
72734 return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
72735 }
72736 /**
72737 * Gets the *yield*, *return*, and *next* types from a non-union type.
72738 *
72739 * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
72740 * returned to indicate to the caller that it should report an error. Otherwise, an
72741 * `IterationTypes` record is returned.
72742 *
72743 * NOTE: You probably don't want to call this directly and should be calling
72744 * `getIterationTypesOfIterable` instead.
72745 */
72746 function getIterationTypesOfIterableWorker(type, use, errorNode) {
72747 if (isTypeAny(type)) {
72748 return anyIterationTypes;
72749 }
72750 if (use & 2 /* AllowsAsyncIterablesFlag */) {
72751 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
72752 getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
72753 if (iterationTypes) {
72754 return iterationTypes;
72755 }
72756 }
72757 if (use & 1 /* AllowsSyncIterablesFlag */) {
72758 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
72759 getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
72760 if (iterationTypes) {
72761 if (use & 2 /* AllowsAsyncIterablesFlag */) {
72762 // for a sync iterable in an async context, only use the cached types if they are valid.
72763 if (iterationTypes !== noIterationTypes) {
72764 return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
72765 }
72766 }
72767 else {
72768 return iterationTypes;
72769 }
72770 }
72771 }
72772 if (use & 2 /* AllowsAsyncIterablesFlag */) {
72773 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
72774 if (iterationTypes !== noIterationTypes) {
72775 return iterationTypes;
72776 }
72777 }
72778 if (use & 1 /* AllowsSyncIterablesFlag */) {
72779 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
72780 if (iterationTypes !== noIterationTypes) {
72781 if (use & 2 /* AllowsAsyncIterablesFlag */) {
72782 return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
72783 ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
72784 : noIterationTypes);
72785 }
72786 else {
72787 return iterationTypes;
72788 }
72789 }
72790 }
72791 return noIterationTypes;
72792 }
72793 /**
72794 * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
72795 * `AsyncIterable`-like type from the cache.
72796 *
72797 * NOTE: You probably don't want to call this directly and should be calling
72798 * `getIterationTypesOfIterable` instead.
72799 */
72800 function getIterationTypesOfIterableCached(type, resolver) {
72801 return getCachedIterationTypes(type, resolver.iterableCacheKey);
72802 }
72803 function getIterationTypesOfGlobalIterableType(globalType, resolver) {
72804 var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
72805 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
72806 return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
72807 }
72808 /**
72809 * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
72810 * type from from common heuristics.
72811 *
72812 * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
72813 * returned. If we found iteration types, an `IterationTypes` record is returned.
72814 * Otherwise, we return `undefined` to indicate to the caller it should perform a more
72815 * exhaustive analysis.
72816 *
72817 * NOTE: You probably don't want to call this directly and should be calling
72818 * `getIterationTypesOfIterable` instead.
72819 */
72820 function getIterationTypesOfIterableFast(type, resolver) {
72821 // As an optimization, if the type is an instantiation of one of the following global types, then
72822 // just grab its related type argument:
72823 // - `Iterable<T>` or `AsyncIterable<T>`
72824 // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
72825 var globalType;
72826 if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
72827 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
72828 var yieldType = getTypeArguments(type)[0];
72829 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
72830 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
72831 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
72832 // different definitions.
72833 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
72834 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
72835 }
72836 // As an optimization, if the type is an instantiation of the following global type, then
72837 // just grab its related type arguments:
72838 // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
72839 if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
72840 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
72841 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
72842 }
72843 }
72844 /**
72845 * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
72846 * type from its members.
72847 *
72848 * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
72849 * record is returned. Otherwise, `noIterationTypes` is returned.
72850 *
72851 * NOTE: You probably don't want to call this directly and should be calling
72852 * `getIterationTypesOfIterable` instead.
72853 */
72854 function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
72855 var _a;
72856 var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
72857 var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
72858 if (isTypeAny(methodType)) {
72859 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
72860 }
72861 var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
72862 if (!ts.some(signatures)) {
72863 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
72864 }
72865 var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature));
72866 var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
72867 return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
72868 }
72869 function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
72870 var message = allowAsyncIterables
72871 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
72872 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
72873 errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
72874 }
72875 /**
72876 * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
72877 *
72878 * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
72879 * record is returned. Otherwise, `undefined` is returned.
72880 */
72881 function getIterationTypesOfIterator(type, resolver, errorNode) {
72882 if (isTypeAny(type)) {
72883 return anyIterationTypes;
72884 }
72885 var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
72886 getIterationTypesOfIteratorFast(type, resolver) ||
72887 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
72888 return iterationTypes === noIterationTypes ? undefined : iterationTypes;
72889 }
72890 /**
72891 * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
72892 * cache.
72893 *
72894 * NOTE: You probably don't want to call this directly and should be calling
72895 * `getIterationTypesOfIterator` instead.
72896 */
72897 function getIterationTypesOfIteratorCached(type, resolver) {
72898 return getCachedIterationTypes(type, resolver.iteratorCacheKey);
72899 }
72900 /**
72901 * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
72902 * cache or from common heuristics.
72903 *
72904 * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
72905 * returned. If we found iteration types, an `IterationTypes` record is returned.
72906 * Otherwise, we return `undefined` to indicate to the caller it should perform a more
72907 * exhaustive analysis.
72908 *
72909 * NOTE: You probably don't want to call this directly and should be calling
72910 * `getIterationTypesOfIterator` instead.
72911 */
72912 function getIterationTypesOfIteratorFast(type, resolver) {
72913 // As an optimization, if the type is an instantiation of one of the following global types,
72914 // then just grab its related type argument:
72915 // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
72916 // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
72917 // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
72918 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
72919 if (isReferenceToType(type, globalType)) {
72920 var yieldType = getTypeArguments(type)[0];
72921 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
72922 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
72923 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
72924 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
72925 getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
72926 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
72927 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
72928 }
72929 if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
72930 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
72931 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
72932 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
72933 }
72934 }
72935 function isIteratorResult(type, kind) {
72936 // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
72937 // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
72938 // > If the end was not reached `done` is `false` and a value is available.
72939 // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
72940 var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
72941 return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
72942 }
72943 function isYieldIteratorResult(type) {
72944 return isIteratorResult(type, 0 /* Yield */);
72945 }
72946 function isReturnIteratorResult(type) {
72947 return isIteratorResult(type, 1 /* Return */);
72948 }
72949 /**
72950 * Gets the *yield* and *return* types of an `IteratorResult`-like type.
72951 *
72952 * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
72953 * returned to indicate to the caller that it should handle the error. Otherwise, an
72954 * `IterationTypes` record is returned.
72955 */
72956 function getIterationTypesOfIteratorResult(type) {
72957 if (isTypeAny(type)) {
72958 return anyIterationTypes;
72959 }
72960 var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
72961 if (cachedTypes) {
72962 return cachedTypes;
72963 }
72964 // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
72965 // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
72966 if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
72967 var yieldType_1 = getTypeArguments(type)[0];
72968 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
72969 }
72970 if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
72971 var returnType_1 = getTypeArguments(type)[0];
72972 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
72973 }
72974 // Choose any constituents that can produce the requested iteration type.
72975 var yieldIteratorResult = filterType(type, isYieldIteratorResult);
72976 var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
72977 var returnIteratorResult = filterType(type, isReturnIteratorResult);
72978 var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
72979 if (!yieldType && !returnType) {
72980 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
72981 }
72982 // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
72983 // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
72984 // > `value` property may be absent from the conforming object if it does not inherit an explicit
72985 // > `value` property.
72986 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
72987 }
72988 /**
72989 * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
72990 * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
72991 *
72992 * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
72993 * record is returned. Otherwise, we return `undefined`.
72994 */
72995 function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
72996 var method = getPropertyOfType(type, methodName);
72997 // Ignore 'return' or 'throw' if they are missing.
72998 if (!method && methodName !== "next") {
72999 return undefined;
73000 }
73001 var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
73002 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
73003 : undefined;
73004 if (isTypeAny(methodType)) {
73005 // `return()` and `throw()` don't provide a *next* type.
73006 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
73007 }
73008 // Both async and non-async iterators *must* have a `next` method.
73009 var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
73010 if (methodSignatures.length === 0) {
73011 if (errorNode) {
73012 var diagnostic = methodName === "next"
73013 ? resolver.mustHaveANextMethodDiagnostic
73014 : resolver.mustBeAMethodDiagnostic;
73015 error(errorNode, diagnostic, methodName);
73016 }
73017 return methodName === "next" ? anyIterationTypes : undefined;
73018 }
73019 // Extract the first parameter and return type of each signature.
73020 var methodParameterTypes;
73021 var methodReturnTypes;
73022 for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
73023 var signature = methodSignatures_1[_i];
73024 if (methodName !== "throw" && ts.some(signature.parameters)) {
73025 methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
73026 }
73027 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
73028 }
73029 // Resolve the *next* or *return* type from the first parameter of a `next()` or
73030 // `return()` method, respectively.
73031 var returnTypes;
73032 var nextType;
73033 if (methodName !== "throw") {
73034 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
73035 if (methodName === "next") {
73036 // The value of `next(value)` is *not* awaited by async generators
73037 nextType = methodParameterType;
73038 }
73039 else if (methodName === "return") {
73040 // The value of `return(value)` *is* awaited by async generators
73041 var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
73042 returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
73043 }
73044 }
73045 // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
73046 var yieldType;
73047 var methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
73048 var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
73049 var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
73050 if (iterationTypes === noIterationTypes) {
73051 if (errorNode) {
73052 error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
73053 }
73054 yieldType = anyType;
73055 returnTypes = ts.append(returnTypes, anyType);
73056 }
73057 else {
73058 yieldType = iterationTypes.yieldType;
73059 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
73060 }
73061 return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
73062 }
73063 /**
73064 * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
73065 * type from its members.
73066 *
73067 * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
73068 * record is returned. Otherwise, `noIterationTypes` is returned.
73069 *
73070 * NOTE: You probably don't want to call this directly and should be calling
73071 * `getIterationTypesOfIterator` instead.
73072 */
73073 function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
73074 var iterationTypes = combineIterationTypes([
73075 getIterationTypesOfMethod(type, resolver, "next", errorNode),
73076 getIterationTypesOfMethod(type, resolver, "return", errorNode),
73077 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
73078 ]);
73079 return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
73080 }
73081 /**
73082 * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
73083 * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
73084 * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
73085 */
73086 function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
73087 if (isTypeAny(returnType)) {
73088 return undefined;
73089 }
73090 var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
73091 return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
73092 }
73093 function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
73094 if (isTypeAny(type)) {
73095 return anyIterationTypes;
73096 }
73097 var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
73098 var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
73099 return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
73100 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
73101 }
73102 function checkBreakOrContinueStatement(node) {
73103 // Grammar checking
73104 if (!checkGrammarStatementInAmbientContext(node))
73105 checkGrammarBreakOrContinueStatement(node);
73106 // TODO: Check that target label is valid
73107 }
73108 function unwrapReturnType(returnType, functionFlags) {
73109 var _a, _b;
73110 var isGenerator = !!(functionFlags & 1 /* Generator */);
73111 var isAsync = !!(functionFlags & 2 /* Async */);
73112 return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
73113 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
73114 returnType;
73115 }
73116 function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
73117 var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
73118 return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
73119 }
73120 function checkReturnStatement(node) {
73121 var _a;
73122 // Grammar checking
73123 if (checkGrammarStatementInAmbientContext(node)) {
73124 return;
73125 }
73126 var func = ts.getContainingFunction(node);
73127 if (!func) {
73128 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
73129 return;
73130 }
73131 var signature = getSignatureFromDeclaration(func);
73132 var returnType = getReturnTypeOfSignature(signature);
73133 var functionFlags = ts.getFunctionFlags(func);
73134 if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
73135 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
73136 if (func.kind === 167 /* SetAccessor */) {
73137 if (node.expression) {
73138 error(node, ts.Diagnostics.Setters_cannot_return_a_value);
73139 }
73140 }
73141 else if (func.kind === 165 /* Constructor */) {
73142 if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
73143 error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
73144 }
73145 }
73146 else if (getReturnTypeFromAnnotation(func)) {
73147 var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
73148 var unwrappedExprType = functionFlags & 2 /* Async */
73149 ? 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)
73150 : exprType;
73151 if (unwrappedReturnType) {
73152 // If the function has a return type, but promisedType is
73153 // undefined, an error will be reported in checkAsyncFunctionReturnType
73154 // so we don't need to report one here.
73155 checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
73156 }
73157 }
73158 }
73159 else if (func.kind !== 165 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
73160 // The function has a return type, but the return statement doesn't have an expression.
73161 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
73162 }
73163 }
73164 function checkWithStatement(node) {
73165 // Grammar checking for withStatement
73166 if (!checkGrammarStatementInAmbientContext(node)) {
73167 if (node.flags & 32768 /* AwaitContext */) {
73168 grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
73169 }
73170 }
73171 checkExpression(node.expression);
73172 var sourceFile = ts.getSourceFileOfNode(node);
73173 if (!hasParseDiagnostics(sourceFile)) {
73174 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
73175 var end = node.statement.pos;
73176 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
73177 }
73178 }
73179 function checkSwitchStatement(node) {
73180 // Grammar checking
73181 checkGrammarStatementInAmbientContext(node);
73182 var firstDefaultClause;
73183 var hasDuplicateDefaultClause = false;
73184 var expressionType = checkExpression(node.expression);
73185 var expressionIsLiteral = isLiteralType(expressionType);
73186 ts.forEach(node.caseBlock.clauses, function (clause) {
73187 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
73188 if (clause.kind === 282 /* DefaultClause */ && !hasDuplicateDefaultClause) {
73189 if (firstDefaultClause === undefined) {
73190 firstDefaultClause = clause;
73191 }
73192 else {
73193 grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
73194 hasDuplicateDefaultClause = true;
73195 }
73196 }
73197 if (produceDiagnostics && clause.kind === 281 /* CaseClause */) {
73198 // TypeScript 1.0 spec (April 2014): 5.9
73199 // In a 'switch' statement, each 'case' expression must be of a type that is comparable
73200 // to or from the type of the 'switch' expression.
73201 var caseType = checkExpression(clause.expression);
73202 var caseIsLiteral = isLiteralType(caseType);
73203 var comparedExpressionType = expressionType;
73204 if (!caseIsLiteral || !expressionIsLiteral) {
73205 caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
73206 comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
73207 }
73208 if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
73209 // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
73210 checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
73211 }
73212 }
73213 ts.forEach(clause.statements, checkSourceElement);
73214 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
73215 error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
73216 }
73217 });
73218 if (node.caseBlock.locals) {
73219 registerForUnusedIdentifiersCheck(node.caseBlock);
73220 }
73221 }
73222 function checkLabeledStatement(node) {
73223 // Grammar checking
73224 if (!checkGrammarStatementInAmbientContext(node)) {
73225 ts.findAncestor(node.parent, function (current) {
73226 if (ts.isFunctionLike(current)) {
73227 return "quit";
73228 }
73229 if (current.kind === 242 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
73230 grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
73231 return true;
73232 }
73233 return false;
73234 });
73235 }
73236 // ensure that label is unique
73237 checkSourceElement(node.statement);
73238 }
73239 function checkThrowStatement(node) {
73240 // Grammar checking
73241 if (!checkGrammarStatementInAmbientContext(node)) {
73242 if (ts.isIdentifier(node.expression) && !node.expression.escapedText) {
73243 grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
73244 }
73245 }
73246 if (node.expression) {
73247 checkExpression(node.expression);
73248 }
73249 }
73250 function checkTryStatement(node) {
73251 // Grammar checking
73252 checkGrammarStatementInAmbientContext(node);
73253 checkBlock(node.tryBlock);
73254 var catchClause = node.catchClause;
73255 if (catchClause) {
73256 // Grammar checking
73257 if (catchClause.variableDeclaration) {
73258 if (catchClause.variableDeclaration.type && getTypeOfNode(catchClause.variableDeclaration) === errorType) {
73259 grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
73260 }
73261 else if (catchClause.variableDeclaration.initializer) {
73262 grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
73263 }
73264 else {
73265 var blockLocals_1 = catchClause.block.locals;
73266 if (blockLocals_1) {
73267 ts.forEachKey(catchClause.locals, function (caughtName) {
73268 var blockLocal = blockLocals_1.get(caughtName);
73269 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
73270 grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
73271 }
73272 });
73273 }
73274 }
73275 }
73276 checkBlock(catchClause.block);
73277 }
73278 if (node.finallyBlock) {
73279 checkBlock(node.finallyBlock);
73280 }
73281 }
73282 function checkIndexConstraints(type) {
73283 var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
73284 var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
73285 var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
73286 var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
73287 if (stringIndexType || numberIndexType) {
73288 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
73289 var propType = getTypeOfSymbol(prop);
73290 checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
73291 checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
73292 });
73293 var classDeclaration = type.symbol.valueDeclaration;
73294 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
73295 for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
73296 var member = _a[_i];
73297 // Only process instance properties with computed names here.
73298 // Static properties cannot be in conflict with indexers,
73299 // and properties with literal names were already checked.
73300 if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
73301 var symbol = getSymbolOfNode(member);
73302 var propType = getTypeOfSymbol(symbol);
73303 checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
73304 checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
73305 }
73306 }
73307 }
73308 }
73309 var errorNode;
73310 if (stringIndexType && numberIndexType) {
73311 errorNode = declaredNumberIndexer || declaredStringIndexer;
73312 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
73313 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
73314 var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
73315 errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
73316 }
73317 }
73318 if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
73319 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
73320 }
73321 function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
73322 // ESSymbol properties apply to neither string nor numeric indexers.
73323 if (!indexType || ts.isKnownSymbol(prop)) {
73324 return;
73325 }
73326 var propDeclaration = prop.valueDeclaration;
73327 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
73328 if (name && ts.isPrivateIdentifier(name)) {
73329 return;
73330 }
73331 // index is numeric and property name is not valid numeric literal
73332 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
73333 return;
73334 }
73335 // perform property check if property or indexer is declared in 'type'
73336 // this allows us to rule out cases when both property and indexer are inherited from the base class
73337 var errorNode;
73338 if (propDeclaration && name &&
73339 (propDeclaration.kind === 213 /* BinaryExpression */ ||
73340 name.kind === 157 /* ComputedPropertyName */ ||
73341 prop.parent === containingType.symbol)) {
73342 errorNode = propDeclaration;
73343 }
73344 else if (indexDeclaration) {
73345 errorNode = indexDeclaration;
73346 }
73347 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
73348 // for interfaces property and indexer might be inherited from different bases
73349 // check if any base class already has both property and indexer.
73350 // check should be performed only if 'type' is the first type that brings property\indexer together
73351 var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
73352 errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
73353 }
73354 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
73355 var errorMessage = indexKind === 0 /* String */
73356 ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
73357 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
73358 error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
73359 }
73360 }
73361 }
73362 function checkTypeNameIsReserved(name, message) {
73363 // TS 1.0 spec (April 2014): 3.6.1
73364 // The predefined type keywords are reserved and cannot be used as names of user defined types.
73365 switch (name.escapedText) {
73366 case "any":
73367 case "unknown":
73368 case "number":
73369 case "bigint":
73370 case "boolean":
73371 case "string":
73372 case "symbol":
73373 case "void":
73374 case "object":
73375 error(name, message, name.escapedText);
73376 }
73377 }
73378 /**
73379 * The name cannot be used as 'Object' of user defined types with special target.
73380 */
73381 function checkClassNameCollisionWithObject(name) {
73382 if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
73383 && moduleKind < ts.ModuleKind.ES2015) {
73384 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
73385 }
73386 }
73387 /**
73388 * Check each type parameter and check that type parameters have no duplicate type parameter declarations
73389 */
73390 function checkTypeParameters(typeParameterDeclarations) {
73391 if (typeParameterDeclarations) {
73392 var seenDefault = false;
73393 for (var i = 0; i < typeParameterDeclarations.length; i++) {
73394 var node = typeParameterDeclarations[i];
73395 checkTypeParameter(node);
73396 if (produceDiagnostics) {
73397 if (node.default) {
73398 seenDefault = true;
73399 checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
73400 }
73401 else if (seenDefault) {
73402 error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
73403 }
73404 for (var j = 0; j < i; j++) {
73405 if (typeParameterDeclarations[j].symbol === node.symbol) {
73406 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
73407 }
73408 }
73409 }
73410 }
73411 }
73412 }
73413 /** Check that type parameter defaults only reference previously declared type parameters */
73414 function checkTypeParametersNotReferenced(root, typeParameters, index) {
73415 visit(root);
73416 function visit(node) {
73417 if (node.kind === 172 /* TypeReference */) {
73418 var type = getTypeFromTypeReference(node);
73419 if (type.flags & 262144 /* TypeParameter */) {
73420 for (var i = index; i < typeParameters.length; i++) {
73421 if (type.symbol === getSymbolOfNode(typeParameters[i])) {
73422 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
73423 }
73424 }
73425 }
73426 }
73427 ts.forEachChild(node, visit);
73428 }
73429 }
73430 /** Check that type parameter lists are identical across multiple declarations */
73431 function checkTypeParameterListsIdentical(symbol) {
73432 if (symbol.declarations.length === 1) {
73433 return;
73434 }
73435 var links = getSymbolLinks(symbol);
73436 if (!links.typeParametersChecked) {
73437 links.typeParametersChecked = true;
73438 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
73439 if (declarations.length <= 1) {
73440 return;
73441 }
73442 var type = getDeclaredTypeOfSymbol(symbol);
73443 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
73444 // Report an error on every conflicting declaration.
73445 var name = symbolToString(symbol);
73446 for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
73447 var declaration = declarations_6[_i];
73448 error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
73449 }
73450 }
73451 }
73452 }
73453 function areTypeParametersIdentical(declarations, targetParameters) {
73454 var maxTypeArgumentCount = ts.length(targetParameters);
73455 var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
73456 for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
73457 var declaration = declarations_7[_i];
73458 // If this declaration has too few or too many type parameters, we report an error
73459 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
73460 var numTypeParameters = sourceParameters.length;
73461 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
73462 return false;
73463 }
73464 for (var i = 0; i < numTypeParameters; i++) {
73465 var source = sourceParameters[i];
73466 var target = targetParameters[i];
73467 // If the type parameter node does not have the same as the resolved type
73468 // parameter at this position, we report an error.
73469 if (source.name.escapedText !== target.symbol.escapedName) {
73470 return false;
73471 }
73472 // If the type parameter node does not have an identical constraint as the resolved
73473 // type parameter at this position, we report an error.
73474 var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
73475 var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
73476 var targetConstraint = getConstraintOfTypeParameter(target);
73477 // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
73478 // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
73479 if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
73480 return false;
73481 }
73482 // If the type parameter node has a default and it is not identical to the default
73483 // for the type parameter at this position, we report an error.
73484 var sourceDefault = source.default && getTypeFromTypeNode(source.default);
73485 var targetDefault = getDefaultFromTypeParameter(target);
73486 if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
73487 return false;
73488 }
73489 }
73490 }
73491 return true;
73492 }
73493 function checkClassExpression(node) {
73494 checkClassLikeDeclaration(node);
73495 checkNodeDeferred(node);
73496 return getTypeOfSymbol(getSymbolOfNode(node));
73497 }
73498 function checkClassExpressionDeferred(node) {
73499 ts.forEach(node.members, checkSourceElement);
73500 registerForUnusedIdentifiersCheck(node);
73501 }
73502 function checkClassDeclaration(node) {
73503 if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) {
73504 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
73505 }
73506 checkClassLikeDeclaration(node);
73507 ts.forEach(node.members, checkSourceElement);
73508 registerForUnusedIdentifiersCheck(node);
73509 }
73510 function checkClassLikeDeclaration(node) {
73511 checkGrammarClassLikeDeclaration(node);
73512 checkDecorators(node);
73513 if (node.name) {
73514 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
73515 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
73516 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
73517 if (!(node.flags & 8388608 /* Ambient */)) {
73518 checkClassNameCollisionWithObject(node.name);
73519 }
73520 }
73521 checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
73522 checkExportsOnMergedDeclarations(node);
73523 var symbol = getSymbolOfNode(node);
73524 var type = getDeclaredTypeOfSymbol(symbol);
73525 var typeWithThis = getTypeWithThisArgument(type);
73526 var staticType = getTypeOfSymbol(symbol);
73527 checkTypeParameterListsIdentical(symbol);
73528 checkClassForDuplicateDeclarations(node);
73529 // Only check for reserved static identifiers on non-ambient context.
73530 if (!(node.flags & 8388608 /* Ambient */)) {
73531 checkClassForStaticPropertyNameConflicts(node);
73532 }
73533 var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
73534 if (baseTypeNode) {
73535 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
73536 if (languageVersion < 2 /* ES2015 */) {
73537 checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
73538 }
73539 // check both @extends and extends if both are specified.
73540 var extendsNode = ts.getClassExtendsHeritageElement(node);
73541 if (extendsNode && extendsNode !== baseTypeNode) {
73542 checkExpression(extendsNode.expression);
73543 }
73544 var baseTypes = getBaseTypes(type);
73545 if (baseTypes.length && produceDiagnostics) {
73546 var baseType_1 = baseTypes[0];
73547 var baseConstructorType = getBaseConstructorTypeOfClass(type);
73548 var staticBaseType = getApparentType(baseConstructorType);
73549 checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
73550 checkSourceElement(baseTypeNode.expression);
73551 if (ts.some(baseTypeNode.typeArguments)) {
73552 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
73553 for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
73554 var constructor = _a[_i];
73555 if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
73556 break;
73557 }
73558 }
73559 }
73560 var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
73561 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
73562 issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
73563 }
73564 else {
73565 // Report static side error only when instance type is assignable
73566 checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
73567 }
73568 if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
73569 error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
73570 }
73571 if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
73572 // When the static base type is a "class-like" constructor function (but not actually a class), we verify
73573 // that all instantiated base constructor signatures return the same type.
73574 var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
73575 if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
73576 error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
73577 }
73578 }
73579 checkKindsOfPropertyMemberOverrides(type, baseType_1);
73580 }
73581 }
73582 var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
73583 if (implementedTypeNodes) {
73584 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
73585 var typeRefNode = implementedTypeNodes_1[_b];
73586 if (!ts.isEntityNameExpression(typeRefNode.expression)) {
73587 error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
73588 }
73589 checkTypeReferenceNode(typeRefNode);
73590 if (produceDiagnostics) {
73591 var t = getReducedType(getTypeFromTypeNode(typeRefNode));
73592 if (t !== errorType) {
73593 if (isValidBaseType(t)) {
73594 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
73595 ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
73596 ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
73597 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
73598 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
73599 issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
73600 }
73601 }
73602 else {
73603 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
73604 }
73605 }
73606 }
73607 }
73608 }
73609 if (produceDiagnostics) {
73610 checkIndexConstraints(type);
73611 checkTypeForDuplicateIndexSignatures(node);
73612 checkPropertyInitialization(node);
73613 }
73614 }
73615 function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
73616 // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
73617 var issuedMemberError = false;
73618 var _loop_22 = function (member) {
73619 if (ts.hasStaticModifier(member)) {
73620 return "continue";
73621 }
73622 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
73623 if (declaredProp) {
73624 var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
73625 var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
73626 if (prop && baseProp) {
73627 var rootChain = function () { return ts.chainDiagnosticMessages(
73628 /*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)); };
73629 if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
73630 issuedMemberError = true;
73631 }
73632 }
73633 }
73634 };
73635 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73636 var member = _a[_i];
73637 _loop_22(member);
73638 }
73639 if (!issuedMemberError) {
73640 // check again with diagnostics to generate a less-specific error
73641 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
73642 }
73643 }
73644 function checkBaseTypeAccessibility(type, node) {
73645 var signatures = getSignaturesOfType(type, 1 /* Construct */);
73646 if (signatures.length) {
73647 var declaration = signatures[0].declaration;
73648 if (declaration && ts.hasEffectiveModifier(declaration, 8 /* Private */)) {
73649 var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
73650 if (!isNodeWithinClass(node, typeClassDeclaration)) {
73651 error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
73652 }
73653 }
73654 }
73655 }
73656 function getTargetSymbol(s) {
73657 // if symbol is instantiated its flags are not copied from the 'target'
73658 // so we'll need to get back original 'target' symbol to work with correct set of flags
73659 return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
73660 }
73661 function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
73662 return ts.filter(symbol.declarations, function (d) {
73663 return d.kind === 249 /* ClassDeclaration */ || d.kind === 250 /* InterfaceDeclaration */;
73664 });
73665 }
73666 function checkKindsOfPropertyMemberOverrides(type, baseType) {
73667 // TypeScript 1.0 spec (April 2014): 8.2.3
73668 // A derived class inherits all members from its base class it doesn't override.
73669 // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
73670 // Both public and private property members are inherited, but only public property members can be overridden.
73671 // A property member in a derived class is said to override a property member in a base class
73672 // when the derived class property member has the same name and kind(instance or static)
73673 // as the base class property member.
73674 // The type of an overriding property member must be assignable(section 3.8.4)
73675 // to the type of the overridden property member, or otherwise a compile - time error occurs.
73676 // Base class instance member functions can be overridden by derived class instance member functions,
73677 // but not by other kinds of members.
73678 // Base class instance member variables and accessors can be overridden by
73679 // derived class instance member variables and accessors, but not by other kinds of members.
73680 // NOTE: assignability is checked in checkClassDeclaration
73681 var baseProperties = getPropertiesOfType(baseType);
73682 basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
73683 var baseProperty = baseProperties_1[_i];
73684 var base = getTargetSymbol(baseProperty);
73685 if (base.flags & 4194304 /* Prototype */) {
73686 continue;
73687 }
73688 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
73689 if (!baseSymbol) {
73690 continue;
73691 }
73692 var derived = getTargetSymbol(baseSymbol);
73693 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
73694 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
73695 // In order to resolve whether the inherited method was overridden in the base class or not,
73696 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
73697 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
73698 if (derived === base) {
73699 // derived class inherits base without override/redeclaration
73700 var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
73701 // It is an error to inherit an abstract member without implementing it or being declared abstract.
73702 // If there is no declaration for the derived class (as in the case of class expressions),
73703 // then the class cannot be declared abstract.
73704 if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* Abstract */))) {
73705 // Searches other base types for a declaration that would satisfy the inherited abstract member.
73706 // (The class may have more than one base type via declaration merging with an interface with the
73707 // same name.)
73708 for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
73709 var otherBaseType = _b[_a];
73710 if (otherBaseType === baseType)
73711 continue;
73712 var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
73713 var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
73714 if (derivedElsewhere && derivedElsewhere !== base) {
73715 continue basePropertyCheck;
73716 }
73717 }
73718 if (derivedClassDecl.kind === 218 /* ClassExpression */) {
73719 error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
73720 }
73721 else {
73722 error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
73723 }
73724 }
73725 }
73726 else {
73727 // derived overrides base.
73728 var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
73729 if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
73730 // either base or derived property is private - not override, skip it
73731 continue;
73732 }
73733 var errorMessage = void 0;
73734 var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
73735 var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
73736 if (basePropertyFlags && derivedPropertyFlags) {
73737 // property/accessor is overridden with property/accessor
73738 if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
73739 || base.valueDeclaration && base.valueDeclaration.parent.kind === 250 /* InterfaceDeclaration */
73740 || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
73741 // when the base property is abstract or from an interface, base/derived flags don't need to match
73742 // same when the derived property is from an assignment
73743 continue;
73744 }
73745 var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
73746 var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
73747 if (overriddenInstanceProperty || overriddenInstanceAccessor) {
73748 var errorMessage_1 = overriddenInstanceProperty ?
73749 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
73750 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
73751 error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
73752 }
73753 else if (compilerOptions.useDefineForClassFields) {
73754 var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 162 /* PropertyDeclaration */ && !d.initializer; });
73755 if (uninitialized
73756 && !(derived.flags & 33554432 /* Transient */)
73757 && !(baseDeclarationFlags & 128 /* Abstract */)
73758 && !(derivedDeclarationFlags & 128 /* Abstract */)
73759 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
73760 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
73761 var propName = uninitialized.name;
73762 if (uninitialized.exclamationToken
73763 || !constructor
73764 || !ts.isIdentifier(propName)
73765 || !strictNullChecks
73766 || !isPropertyInitializedInConstructor(propName, type, constructor)) {
73767 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;
73768 error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
73769 }
73770 }
73771 }
73772 // correct case
73773 continue;
73774 }
73775 else if (isPrototypeProperty(base)) {
73776 if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
73777 // method is overridden with method or property -- correct case
73778 continue;
73779 }
73780 else {
73781 ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
73782 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
73783 }
73784 }
73785 else if (base.flags & 98304 /* Accessor */) {
73786 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
73787 }
73788 else {
73789 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
73790 }
73791 error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
73792 }
73793 }
73794 }
73795 function getNonInterhitedProperties(type, baseTypes, properties) {
73796 if (!ts.length(baseTypes)) {
73797 return properties;
73798 }
73799 var seen = new ts.Map();
73800 ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
73801 for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
73802 var base = baseTypes_2[_i];
73803 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
73804 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
73805 var prop = properties_4[_a];
73806 var existing = seen.get(prop.escapedName);
73807 if (existing && !isPropertyIdenticalTo(existing, prop)) {
73808 seen.delete(prop.escapedName);
73809 }
73810 }
73811 }
73812 return ts.arrayFrom(seen.values());
73813 }
73814 function checkInheritedPropertiesAreIdentical(type, typeNode) {
73815 var baseTypes = getBaseTypes(type);
73816 if (baseTypes.length < 2) {
73817 return true;
73818 }
73819 var seen = new ts.Map();
73820 ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
73821 var ok = true;
73822 for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
73823 var base = baseTypes_3[_i];
73824 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
73825 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
73826 var prop = properties_6[_a];
73827 var existing = seen.get(prop.escapedName);
73828 if (!existing) {
73829 seen.set(prop.escapedName, { prop: prop, containingType: base });
73830 }
73831 else {
73832 var isInheritedProperty = existing.containingType !== type;
73833 if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
73834 ok = false;
73835 var typeName1 = typeToString(existing.containingType);
73836 var typeName2 = typeToString(base);
73837 var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
73838 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
73839 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
73840 }
73841 }
73842 }
73843 }
73844 return ok;
73845 }
73846 function checkPropertyInitialization(node) {
73847 if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
73848 return;
73849 }
73850 var constructor = findConstructorDeclaration(node);
73851 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73852 var member = _a[_i];
73853 if (ts.getEffectiveModifierFlags(member) & 2 /* Ambient */) {
73854 continue;
73855 }
73856 if (isInstancePropertyWithoutInitializer(member)) {
73857 var propName = member.name;
73858 if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
73859 var type = getTypeOfSymbol(getSymbolOfNode(member));
73860 if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
73861 if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
73862 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
73863 }
73864 }
73865 }
73866 }
73867 }
73868 }
73869 function isInstancePropertyWithoutInitializer(node) {
73870 return node.kind === 162 /* PropertyDeclaration */ &&
73871 !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
73872 !node.exclamationToken &&
73873 !node.initializer;
73874 }
73875 function isPropertyInitializedInConstructor(propName, propType, constructor) {
73876 var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
73877 ts.setParent(reference.expression, reference);
73878 ts.setParent(reference, constructor);
73879 reference.flowNode = constructor.returnFlowNode;
73880 var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
73881 return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
73882 }
73883 function checkInterfaceDeclaration(node) {
73884 // Grammar checking
73885 if (!checkGrammarDecoratorsAndModifiers(node))
73886 checkGrammarInterfaceDeclaration(node);
73887 checkTypeParameters(node.typeParameters);
73888 if (produceDiagnostics) {
73889 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
73890 checkExportsOnMergedDeclarations(node);
73891 var symbol = getSymbolOfNode(node);
73892 checkTypeParameterListsIdentical(symbol);
73893 // Only check this symbol once
73894 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 250 /* InterfaceDeclaration */);
73895 if (node === firstInterfaceDecl) {
73896 var type = getDeclaredTypeOfSymbol(symbol);
73897 var typeWithThis = getTypeWithThisArgument(type);
73898 // run subsequent checks only if first set succeeded
73899 if (checkInheritedPropertiesAreIdentical(type, node.name)) {
73900 for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
73901 var baseType = _a[_i];
73902 checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
73903 }
73904 checkIndexConstraints(type);
73905 }
73906 }
73907 checkObjectTypeForDuplicateDeclarations(node);
73908 }
73909 ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
73910 if (!ts.isEntityNameExpression(heritageElement.expression)) {
73911 error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
73912 }
73913 checkTypeReferenceNode(heritageElement);
73914 });
73915 ts.forEach(node.members, checkSourceElement);
73916 if (produceDiagnostics) {
73917 checkTypeForDuplicateIndexSignatures(node);
73918 registerForUnusedIdentifiersCheck(node);
73919 }
73920 }
73921 function checkTypeAliasDeclaration(node) {
73922 // Grammar checking
73923 checkGrammarDecoratorsAndModifiers(node);
73924 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
73925 checkExportsOnMergedDeclarations(node);
73926 checkTypeParameters(node.typeParameters);
73927 checkSourceElement(node.type);
73928 registerForUnusedIdentifiersCheck(node);
73929 }
73930 function computeEnumMemberValues(node) {
73931 var nodeLinks = getNodeLinks(node);
73932 if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
73933 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
73934 var autoValue = 0;
73935 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73936 var member = _a[_i];
73937 var value = computeMemberValue(member, autoValue);
73938 getNodeLinks(member).enumMemberValue = value;
73939 autoValue = typeof value === "number" ? value + 1 : undefined;
73940 }
73941 }
73942 }
73943 function computeMemberValue(member, autoValue) {
73944 if (ts.isComputedNonLiteralName(member.name)) {
73945 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
73946 }
73947 else {
73948 var text = ts.getTextOfPropertyName(member.name);
73949 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
73950 error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
73951 }
73952 }
73953 if (member.initializer) {
73954 return computeConstantValue(member);
73955 }
73956 // In ambient non-const numeric enum declarations, enum members without initializers are
73957 // considered computed members (as opposed to having auto-incremented values).
73958 if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
73959 return undefined;
73960 }
73961 // If the member declaration specifies no value, the member is considered a constant enum member.
73962 // If the member is the first member in the enum declaration, it is assigned the value zero.
73963 // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
73964 // occurs if the immediately preceding member is not a constant enum member.
73965 if (autoValue !== undefined) {
73966 return autoValue;
73967 }
73968 error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
73969 return undefined;
73970 }
73971 function computeConstantValue(member) {
73972 var enumKind = getEnumKind(getSymbolOfNode(member.parent));
73973 var isConstEnum = ts.isEnumConst(member.parent);
73974 var initializer = member.initializer;
73975 var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
73976 if (value !== undefined) {
73977 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
73978 error(initializer, isNaN(value) ?
73979 ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
73980 ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
73981 }
73982 }
73983 else if (enumKind === 1 /* Literal */) {
73984 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
73985 return 0;
73986 }
73987 else if (isConstEnum) {
73988 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
73989 }
73990 else if (member.parent.flags & 8388608 /* Ambient */) {
73991 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
73992 }
73993 else {
73994 // Only here do we need to check that the initializer is assignable to the enum type.
73995 var source = checkExpression(initializer);
73996 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
73997 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));
73998 }
73999 else {
74000 checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
74001 }
74002 }
74003 return value;
74004 function evaluate(expr) {
74005 switch (expr.kind) {
74006 case 211 /* PrefixUnaryExpression */:
74007 var value_2 = evaluate(expr.operand);
74008 if (typeof value_2 === "number") {
74009 switch (expr.operator) {
74010 case 39 /* PlusToken */: return value_2;
74011 case 40 /* MinusToken */: return -value_2;
74012 case 54 /* TildeToken */: return ~value_2;
74013 }
74014 }
74015 break;
74016 case 213 /* BinaryExpression */:
74017 var left = evaluate(expr.left);
74018 var right = evaluate(expr.right);
74019 if (typeof left === "number" && typeof right === "number") {
74020 switch (expr.operatorToken.kind) {
74021 case 51 /* BarToken */: return left | right;
74022 case 50 /* AmpersandToken */: return left & right;
74023 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
74024 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
74025 case 47 /* LessThanLessThanToken */: return left << right;
74026 case 52 /* CaretToken */: return left ^ right;
74027 case 41 /* AsteriskToken */: return left * right;
74028 case 43 /* SlashToken */: return left / right;
74029 case 39 /* PlusToken */: return left + right;
74030 case 40 /* MinusToken */: return left - right;
74031 case 44 /* PercentToken */: return left % right;
74032 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
74033 }
74034 }
74035 else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
74036 return left + right;
74037 }
74038 break;
74039 case 10 /* StringLiteral */:
74040 case 14 /* NoSubstitutionTemplateLiteral */:
74041 return expr.text;
74042 case 8 /* NumericLiteral */:
74043 checkGrammarNumericLiteral(expr);
74044 return +expr.text;
74045 case 204 /* ParenthesizedExpression */:
74046 return evaluate(expr.expression);
74047 case 78 /* Identifier */:
74048 var identifier = expr;
74049 if (isInfinityOrNaNString(identifier.escapedText)) {
74050 return +(identifier.escapedText);
74051 }
74052 return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
74053 case 199 /* ElementAccessExpression */:
74054 case 198 /* PropertyAccessExpression */:
74055 var ex = expr;
74056 if (isConstantMemberAccess(ex)) {
74057 var type = getTypeOfExpression(ex.expression);
74058 if (type.symbol && type.symbol.flags & 384 /* Enum */) {
74059 var name = void 0;
74060 if (ex.kind === 198 /* PropertyAccessExpression */) {
74061 name = ex.name.escapedText;
74062 }
74063 else {
74064 name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
74065 }
74066 return evaluateEnumMember(expr, type.symbol, name);
74067 }
74068 }
74069 break;
74070 }
74071 return undefined;
74072 }
74073 function evaluateEnumMember(expr, enumSymbol, name) {
74074 var memberSymbol = enumSymbol.exports.get(name);
74075 if (memberSymbol) {
74076 var declaration = memberSymbol.valueDeclaration;
74077 if (declaration !== member) {
74078 if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
74079 return getEnumMemberValue(declaration);
74080 }
74081 error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
74082 return 0;
74083 }
74084 else {
74085 error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
74086 }
74087 }
74088 return undefined;
74089 }
74090 }
74091 function isConstantMemberAccess(node) {
74092 return node.kind === 78 /* Identifier */ ||
74093 node.kind === 198 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
74094 node.kind === 199 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
74095 ts.isStringLiteralLike(node.argumentExpression);
74096 }
74097 function checkEnumDeclaration(node) {
74098 if (!produceDiagnostics) {
74099 return;
74100 }
74101 // Grammar checking
74102 checkGrammarDecoratorsAndModifiers(node);
74103 checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
74104 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74105 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74106 checkExportsOnMergedDeclarations(node);
74107 node.members.forEach(checkEnumMember);
74108 computeEnumMemberValues(node);
74109 // Spec 2014 - Section 9.3:
74110 // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
74111 // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
74112 // for the first member.
74113 //
74114 // Only perform this check once per symbol
74115 var enumSymbol = getSymbolOfNode(node);
74116 var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
74117 if (node === firstDeclaration) {
74118 if (enumSymbol.declarations.length > 1) {
74119 var enumIsConst_1 = ts.isEnumConst(node);
74120 // check that const is placed\omitted on all enum declarations
74121 ts.forEach(enumSymbol.declarations, function (decl) {
74122 if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
74123 error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
74124 }
74125 });
74126 }
74127 var seenEnumMissingInitialInitializer_1 = false;
74128 ts.forEach(enumSymbol.declarations, function (declaration) {
74129 // return true if we hit a violation of the rule, false otherwise
74130 if (declaration.kind !== 252 /* EnumDeclaration */) {
74131 return false;
74132 }
74133 var enumDeclaration = declaration;
74134 if (!enumDeclaration.members.length) {
74135 return false;
74136 }
74137 var firstEnumMember = enumDeclaration.members[0];
74138 if (!firstEnumMember.initializer) {
74139 if (seenEnumMissingInitialInitializer_1) {
74140 error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
74141 }
74142 else {
74143 seenEnumMissingInitialInitializer_1 = true;
74144 }
74145 }
74146 });
74147 }
74148 }
74149 function checkEnumMember(node) {
74150 if (ts.isPrivateIdentifier(node.name)) {
74151 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
74152 }
74153 }
74154 function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
74155 var declarations = symbol.declarations;
74156 for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
74157 var declaration = declarations_8[_i];
74158 if ((declaration.kind === 249 /* ClassDeclaration */ ||
74159 (declaration.kind === 248 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
74160 !(declaration.flags & 8388608 /* Ambient */)) {
74161 return declaration;
74162 }
74163 }
74164 return undefined;
74165 }
74166 function inSameLexicalScope(node1, node2) {
74167 var container1 = ts.getEnclosingBlockScopeContainer(node1);
74168 var container2 = ts.getEnclosingBlockScopeContainer(node2);
74169 if (isGlobalSourceFile(container1)) {
74170 return isGlobalSourceFile(container2);
74171 }
74172 else if (isGlobalSourceFile(container2)) {
74173 return false;
74174 }
74175 else {
74176 return container1 === container2;
74177 }
74178 }
74179 function checkModuleDeclaration(node) {
74180 if (produceDiagnostics) {
74181 // Grammar checking
74182 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
74183 var inAmbientContext = node.flags & 8388608 /* Ambient */;
74184 if (isGlobalAugmentation && !inAmbientContext) {
74185 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
74186 }
74187 var isAmbientExternalModule = ts.isAmbientModule(node);
74188 var contextErrorMessage = isAmbientExternalModule
74189 ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
74190 : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
74191 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
74192 // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
74193 return;
74194 }
74195 if (!checkGrammarDecoratorsAndModifiers(node)) {
74196 if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
74197 grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
74198 }
74199 }
74200 if (ts.isIdentifier(node.name)) {
74201 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74202 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74203 }
74204 checkExportsOnMergedDeclarations(node);
74205 var symbol = getSymbolOfNode(node);
74206 // The following checks only apply on a non-ambient instantiated module declaration.
74207 if (symbol.flags & 512 /* ValueModule */
74208 && !inAmbientContext
74209 && symbol.declarations.length > 1
74210 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
74211 var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
74212 if (firstNonAmbientClassOrFunc) {
74213 if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
74214 error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
74215 }
74216 else if (node.pos < firstNonAmbientClassOrFunc.pos) {
74217 error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
74218 }
74219 }
74220 // if the module merges with a class declaration in the same lexical scope,
74221 // we need to track this to ensure the correct emit.
74222 var mergedClass = ts.getDeclarationOfKind(symbol, 249 /* ClassDeclaration */);
74223 if (mergedClass &&
74224 inSameLexicalScope(node, mergedClass)) {
74225 getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
74226 }
74227 }
74228 if (isAmbientExternalModule) {
74229 if (ts.isExternalModuleAugmentation(node)) {
74230 // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
74231 // otherwise we'll be swamped in cascading errors.
74232 // We can detect if augmentation was applied using following rules:
74233 // - augmentation for a global scope is always applied
74234 // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
74235 var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
74236 if (checkBody && node.body) {
74237 for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
74238 var statement = _a[_i];
74239 checkModuleAugmentationElement(statement, isGlobalAugmentation);
74240 }
74241 }
74242 }
74243 else if (isGlobalSourceFile(node.parent)) {
74244 if (isGlobalAugmentation) {
74245 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
74246 }
74247 else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
74248 error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
74249 }
74250 }
74251 else {
74252 if (isGlobalAugmentation) {
74253 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
74254 }
74255 else {
74256 // Node is not an augmentation and is not located on the script level.
74257 // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
74258 error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
74259 }
74260 }
74261 }
74262 }
74263 if (node.body) {
74264 checkSourceElement(node.body);
74265 if (!ts.isGlobalScopeAugmentation(node)) {
74266 registerForUnusedIdentifiersCheck(node);
74267 }
74268 }
74269 }
74270 function checkModuleAugmentationElement(node, isGlobalAugmentation) {
74271 switch (node.kind) {
74272 case 229 /* VariableStatement */:
74273 // error each individual name in variable statement instead of marking the entire variable statement
74274 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
74275 var decl = _a[_i];
74276 checkModuleAugmentationElement(decl, isGlobalAugmentation);
74277 }
74278 break;
74279 case 263 /* ExportAssignment */:
74280 case 264 /* ExportDeclaration */:
74281 grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
74282 break;
74283 case 257 /* ImportEqualsDeclaration */:
74284 case 258 /* ImportDeclaration */:
74285 grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
74286 break;
74287 case 195 /* BindingElement */:
74288 case 246 /* VariableDeclaration */:
74289 var name = node.name;
74290 if (ts.isBindingPattern(name)) {
74291 for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
74292 var el = _c[_b];
74293 // mark individual names in binding pattern
74294 checkModuleAugmentationElement(el, isGlobalAugmentation);
74295 }
74296 break;
74297 }
74298 // falls through
74299 case 249 /* ClassDeclaration */:
74300 case 252 /* EnumDeclaration */:
74301 case 248 /* FunctionDeclaration */:
74302 case 250 /* InterfaceDeclaration */:
74303 case 253 /* ModuleDeclaration */:
74304 case 251 /* TypeAliasDeclaration */:
74305 if (isGlobalAugmentation) {
74306 return;
74307 }
74308 var symbol = getSymbolOfNode(node);
74309 if (symbol) {
74310 // module augmentations cannot introduce new names on the top level scope of the module
74311 // this is done it two steps
74312 // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
74313 // 2. main check - report error if value declaration of the parent symbol is module augmentation)
74314 var reportError = !(symbol.flags & 33554432 /* Transient */);
74315 if (!reportError) {
74316 // symbol should not originate in augmentation
74317 reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
74318 }
74319 }
74320 break;
74321 }
74322 }
74323 function getFirstNonModuleExportsIdentifier(node) {
74324 switch (node.kind) {
74325 case 78 /* Identifier */:
74326 return node;
74327 case 156 /* QualifiedName */:
74328 do {
74329 node = node.left;
74330 } while (node.kind !== 78 /* Identifier */);
74331 return node;
74332 case 198 /* PropertyAccessExpression */:
74333 do {
74334 if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
74335 return node.name;
74336 }
74337 node = node.expression;
74338 } while (node.kind !== 78 /* Identifier */);
74339 return node;
74340 }
74341 }
74342 function checkExternalImportOrExportDeclaration(node) {
74343 var moduleName = ts.getExternalModuleName(node);
74344 if (!moduleName || ts.nodeIsMissing(moduleName)) {
74345 // Should be a parse error.
74346 return false;
74347 }
74348 if (!ts.isStringLiteral(moduleName)) {
74349 error(moduleName, ts.Diagnostics.String_literal_expected);
74350 return false;
74351 }
74352 var inAmbientExternalModule = node.parent.kind === 254 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
74353 if (node.parent.kind !== 294 /* SourceFile */ && !inAmbientExternalModule) {
74354 error(moduleName, node.kind === 264 /* ExportDeclaration */ ?
74355 ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
74356 ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
74357 return false;
74358 }
74359 if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
74360 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
74361 // no need to do this again.
74362 if (!isTopLevelInExternalModuleAugmentation(node)) {
74363 // TypeScript 1.0 spec (April 2013): 12.1.6
74364 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
74365 // other external modules only through top - level external module names.
74366 // Relative external module names are not permitted.
74367 error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
74368 return false;
74369 }
74370 }
74371 return true;
74372 }
74373 function checkAliasSymbol(node) {
74374 var symbol = getSymbolOfNode(node);
74375 var target = resolveAlias(symbol);
74376 if (target !== unknownSymbol) {
74377 // For external modules, `symbol` represents the local symbol for an alias.
74378 // This local symbol will merge any other local declarations (excluding other aliases)
74379 // and symbol.flags will contains combined representation for all merged declaration.
74380 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
74381 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
74382 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
74383 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
74384 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
74385 (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
74386 (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
74387 if (target.flags & excludedMeanings) {
74388 var message = node.kind === 267 /* ExportSpecifier */ ?
74389 ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
74390 ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
74391 error(node, message, symbolToString(symbol));
74392 }
74393 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
74394 if (compilerOptions.isolatedModules
74395 && node.kind === 267 /* ExportSpecifier */
74396 && !node.parent.parent.isTypeOnly
74397 && !(target.flags & 111551 /* Value */)
74398 && !(node.flags & 8388608 /* Ambient */)) {
74399 error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
74400 }
74401 if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) {
74402 errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName);
74403 }
74404 }
74405 }
74406 function checkImportBinding(node) {
74407 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74408 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74409 checkAliasSymbol(node);
74410 if (node.kind === 262 /* ImportSpecifier */ &&
74411 ts.idText(node.propertyName || node.name) === "default" &&
74412 compilerOptions.esModuleInterop &&
74413 moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
74414 checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
74415 }
74416 }
74417 function checkImportDeclaration(node) {
74418 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
74419 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
74420 return;
74421 }
74422 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
74423 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
74424 }
74425 if (checkExternalImportOrExportDeclaration(node)) {
74426 var importClause = node.importClause;
74427 if (importClause && !checkGrammarImportClause(importClause)) {
74428 if (importClause.name) {
74429 checkImportBinding(importClause);
74430 }
74431 if (importClause.namedBindings) {
74432 if (importClause.namedBindings.kind === 260 /* NamespaceImport */) {
74433 checkImportBinding(importClause.namedBindings);
74434 if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) {
74435 // import * as ns from "foo";
74436 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
74437 }
74438 }
74439 else {
74440 var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
74441 if (moduleExisted) {
74442 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
74443 }
74444 }
74445 }
74446 }
74447 }
74448 }
74449 function checkImportEqualsDeclaration(node) {
74450 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
74451 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
74452 return;
74453 }
74454 checkGrammarDecoratorsAndModifiers(node);
74455 if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
74456 checkImportBinding(node);
74457 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
74458 markExportAsReferenced(node);
74459 }
74460 if (node.moduleReference.kind !== 269 /* ExternalModuleReference */) {
74461 var target = resolveAlias(getSymbolOfNode(node));
74462 if (target !== unknownSymbol) {
74463 if (target.flags & 111551 /* Value */) {
74464 // Target is a value symbol, check that it is not hidden by a local declaration with the same name
74465 var moduleName = ts.getFirstIdentifier(node.moduleReference);
74466 if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
74467 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
74468 }
74469 }
74470 if (target.flags & 788968 /* Type */) {
74471 checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
74472 }
74473 }
74474 }
74475 else {
74476 if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
74477 // Import equals declaration is deprecated in es6 or above
74478 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);
74479 }
74480 }
74481 }
74482 }
74483 function checkExportDeclaration(node) {
74484 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
74485 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
74486 return;
74487 }
74488 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
74489 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
74490 }
74491 if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
74492 checkExternalEmitHelpers(node, 4194304 /* CreateBinding */);
74493 }
74494 checkGrammarExportDeclaration(node);
74495 if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
74496 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
74497 // export { x, y }
74498 // export { x, y } from "foo"
74499 ts.forEach(node.exportClause.elements, checkExportSpecifier);
74500 var inAmbientExternalModule = node.parent.kind === 254 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
74501 var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 254 /* ModuleBlock */ &&
74502 !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
74503 if (node.parent.kind !== 294 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
74504 error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
74505 }
74506 }
74507 else {
74508 // export * from "foo"
74509 // export * as ns from "foo";
74510 var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
74511 if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
74512 error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
74513 }
74514 else if (node.exportClause) {
74515 checkAliasSymbol(node.exportClause);
74516 }
74517 if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
74518 if (node.exportClause) {
74519 // export * as ns from "foo";
74520 // 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.
74521 // We only use the helper here when in esModuleInterop
74522 if (compilerOptions.esModuleInterop) {
74523 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
74524 }
74525 }
74526 else {
74527 // export * from "foo"
74528 checkExternalEmitHelpers(node, 65536 /* ExportStar */);
74529 }
74530 }
74531 }
74532 }
74533 }
74534 function checkGrammarExportDeclaration(node) {
74535 var _a;
74536 var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 265 /* NamedExports */;
74537 if (isTypeOnlyExportStar) {
74538 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
74539 }
74540 return !isTypeOnlyExportStar;
74541 }
74542 function checkGrammarModuleElementContext(node, errorMessage) {
74543 var isInAppropriateContext = node.parent.kind === 294 /* SourceFile */ || node.parent.kind === 254 /* ModuleBlock */ || node.parent.kind === 253 /* ModuleDeclaration */;
74544 if (!isInAppropriateContext) {
74545 grammarErrorOnFirstToken(node, errorMessage);
74546 }
74547 return !isInAppropriateContext;
74548 }
74549 function importClauseContainsReferencedImport(importClause) {
74550 return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
74551 return !!getSymbolOfNode(declaration).isReferenced;
74552 });
74553 }
74554 function importClauseContainsConstEnumUsedAsValue(importClause) {
74555 return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
74556 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
74557 });
74558 }
74559 function checkImportsForTypeOnlyConversion(sourceFile) {
74560 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
74561 var statement = _a[_i];
74562 if (ts.isImportDeclaration(statement) &&
74563 statement.importClause &&
74564 !statement.importClause.isTypeOnly &&
74565 importClauseContainsReferencedImport(statement.importClause) &&
74566 !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
74567 !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
74568 error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
74569 }
74570 }
74571 }
74572 function checkExportSpecifier(node) {
74573 checkAliasSymbol(node);
74574 if (ts.getEmitDeclarations(compilerOptions)) {
74575 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
74576 }
74577 if (!node.parent.parent.moduleSpecifier) {
74578 var exportedName = node.propertyName || node.name;
74579 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
74580 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
74581 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
74582 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
74583 error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
74584 }
74585 else {
74586 markExportAsReferenced(node);
74587 var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
74588 if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
74589 checkExpressionCached(node.propertyName || node.name);
74590 }
74591 }
74592 }
74593 else {
74594 if (compilerOptions.esModuleInterop &&
74595 moduleKind !== ts.ModuleKind.System &&
74596 moduleKind < ts.ModuleKind.ES2015 &&
74597 ts.idText(node.propertyName || node.name) === "default") {
74598 checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
74599 }
74600 }
74601 }
74602 function checkExportAssignment(node) {
74603 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
74604 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
74605 return;
74606 }
74607 var container = node.parent.kind === 294 /* SourceFile */ ? node.parent : node.parent.parent;
74608 if (container.kind === 253 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
74609 if (node.isExportEquals) {
74610 error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
74611 }
74612 else {
74613 error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
74614 }
74615 return;
74616 }
74617 // Grammar checking
74618 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
74619 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
74620 }
74621 if (node.expression.kind === 78 /* Identifier */) {
74622 var id = node.expression;
74623 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
74624 if (sym) {
74625 markAliasReferenced(sym, id);
74626 // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
74627 var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
74628 if (target === unknownSymbol || target.flags & 111551 /* Value */) {
74629 // However if it is a value, we need to check it's being used correctly
74630 checkExpressionCached(node.expression);
74631 }
74632 }
74633 if (ts.getEmitDeclarations(compilerOptions)) {
74634 collectLinkedAliases(node.expression, /*setVisibility*/ true);
74635 }
74636 }
74637 else {
74638 checkExpressionCached(node.expression);
74639 }
74640 checkExternalModuleExports(container);
74641 if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
74642 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
74643 }
74644 if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
74645 if (moduleKind >= ts.ModuleKind.ES2015) {
74646 // export assignment is not supported in es6 modules
74647 grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
74648 }
74649 else if (moduleKind === ts.ModuleKind.System) {
74650 // system modules does not support export assignment
74651 grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
74652 }
74653 }
74654 }
74655 function hasExportedMembers(moduleSymbol) {
74656 return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
74657 }
74658 function checkExternalModuleExports(node) {
74659 var moduleSymbol = getSymbolOfNode(node);
74660 var links = getSymbolLinks(moduleSymbol);
74661 if (!links.exportsChecked) {
74662 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
74663 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
74664 var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
74665 if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
74666 error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
74667 }
74668 }
74669 // Checks for export * conflicts
74670 var exports_2 = getExportsOfModule(moduleSymbol);
74671 if (exports_2) {
74672 exports_2.forEach(function (_a, id) {
74673 var declarations = _a.declarations, flags = _a.flags;
74674 if (id === "__export") {
74675 return;
74676 }
74677 // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
74678 // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
74679 if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
74680 return;
74681 }
74682 var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
74683 if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
74684 // it is legal to merge type alias with other values
74685 // so count should be either 1 (just type alias) or 2 (type alias + merged value)
74686 return;
74687 }
74688 if (exportedDeclarationsCount > 1) {
74689 for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
74690 var declaration = declarations_9[_i];
74691 if (isNotOverload(declaration)) {
74692 diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
74693 }
74694 }
74695 }
74696 });
74697 }
74698 links.exportsChecked = true;
74699 }
74700 }
74701 function checkSourceElement(node) {
74702 if (node) {
74703 var saveCurrentNode = currentNode;
74704 currentNode = node;
74705 instantiationCount = 0;
74706 checkSourceElementWorker(node);
74707 currentNode = saveCurrentNode;
74708 }
74709 }
74710 function checkSourceElementWorker(node) {
74711 if (ts.isInJSFile(node)) {
74712 ts.forEach(node.jsDoc, function (_a) {
74713 var tags = _a.tags;
74714 return ts.forEach(tags, checkSourceElement);
74715 });
74716 }
74717 var kind = node.kind;
74718 if (cancellationToken) {
74719 // Only bother checking on a few construct kinds. We don't want to be excessively
74720 // hitting the cancellation token on every node we check.
74721 switch (kind) {
74722 case 253 /* ModuleDeclaration */:
74723 case 249 /* ClassDeclaration */:
74724 case 250 /* InterfaceDeclaration */:
74725 case 248 /* FunctionDeclaration */:
74726 cancellationToken.throwIfCancellationRequested();
74727 }
74728 }
74729 if (kind >= 229 /* FirstStatement */ && kind <= 245 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
74730 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
74731 }
74732 switch (kind) {
74733 case 158 /* TypeParameter */:
74734 return checkTypeParameter(node);
74735 case 159 /* Parameter */:
74736 return checkParameter(node);
74737 case 162 /* PropertyDeclaration */:
74738 return checkPropertyDeclaration(node);
74739 case 161 /* PropertySignature */:
74740 return checkPropertySignature(node);
74741 case 173 /* FunctionType */:
74742 case 174 /* ConstructorType */:
74743 case 168 /* CallSignature */:
74744 case 169 /* ConstructSignature */:
74745 case 170 /* IndexSignature */:
74746 return checkSignatureDeclaration(node);
74747 case 164 /* MethodDeclaration */:
74748 case 163 /* MethodSignature */:
74749 return checkMethodDeclaration(node);
74750 case 165 /* Constructor */:
74751 return checkConstructorDeclaration(node);
74752 case 166 /* GetAccessor */:
74753 case 167 /* SetAccessor */:
74754 return checkAccessorDeclaration(node);
74755 case 172 /* TypeReference */:
74756 return checkTypeReferenceNode(node);
74757 case 171 /* TypePredicate */:
74758 return checkTypePredicate(node);
74759 case 175 /* TypeQuery */:
74760 return checkTypeQuery(node);
74761 case 176 /* TypeLiteral */:
74762 return checkTypeLiteral(node);
74763 case 177 /* ArrayType */:
74764 return checkArrayType(node);
74765 case 178 /* TupleType */:
74766 return checkTupleType(node);
74767 case 181 /* UnionType */:
74768 case 182 /* IntersectionType */:
74769 return checkUnionOrIntersectionType(node);
74770 case 185 /* ParenthesizedType */:
74771 case 179 /* OptionalType */:
74772 case 180 /* RestType */:
74773 return checkSourceElement(node.type);
74774 case 186 /* ThisType */:
74775 return checkThisType(node);
74776 case 187 /* TypeOperator */:
74777 return checkTypeOperator(node);
74778 case 183 /* ConditionalType */:
74779 return checkConditionalType(node);
74780 case 184 /* InferType */:
74781 return checkInferType(node);
74782 case 192 /* ImportType */:
74783 return checkImportType(node);
74784 case 191 /* NamedTupleMember */:
74785 return checkNamedTupleMember(node);
74786 case 311 /* JSDocAugmentsTag */:
74787 return checkJSDocAugmentsTag(node);
74788 case 312 /* JSDocImplementsTag */:
74789 return checkJSDocImplementsTag(node);
74790 case 327 /* JSDocTypedefTag */:
74791 case 320 /* JSDocCallbackTag */:
74792 case 321 /* JSDocEnumTag */:
74793 return checkJSDocTypeAliasTag(node);
74794 case 326 /* JSDocTemplateTag */:
74795 return checkJSDocTemplateTag(node);
74796 case 325 /* JSDocTypeTag */:
74797 return checkJSDocTypeTag(node);
74798 case 322 /* JSDocParameterTag */:
74799 return checkJSDocParameterTag(node);
74800 case 328 /* JSDocPropertyTag */:
74801 return checkJSDocPropertyTag(node);
74802 case 304 /* JSDocFunctionType */:
74803 checkJSDocFunctionType(node);
74804 // falls through
74805 case 302 /* JSDocNonNullableType */:
74806 case 301 /* JSDocNullableType */:
74807 case 299 /* JSDocAllType */:
74808 case 300 /* JSDocUnknownType */:
74809 case 308 /* JSDocTypeLiteral */:
74810 checkJSDocTypeIsInJsFile(node);
74811 ts.forEachChild(node, checkSourceElement);
74812 return;
74813 case 305 /* JSDocVariadicType */:
74814 checkJSDocVariadicType(node);
74815 return;
74816 case 298 /* JSDocTypeExpression */:
74817 return checkSourceElement(node.type);
74818 case 188 /* IndexedAccessType */:
74819 return checkIndexedAccessType(node);
74820 case 189 /* MappedType */:
74821 return checkMappedType(node);
74822 case 248 /* FunctionDeclaration */:
74823 return checkFunctionDeclaration(node);
74824 case 227 /* Block */:
74825 case 254 /* ModuleBlock */:
74826 return checkBlock(node);
74827 case 229 /* VariableStatement */:
74828 return checkVariableStatement(node);
74829 case 230 /* ExpressionStatement */:
74830 return checkExpressionStatement(node);
74831 case 231 /* IfStatement */:
74832 return checkIfStatement(node);
74833 case 232 /* DoStatement */:
74834 return checkDoStatement(node);
74835 case 233 /* WhileStatement */:
74836 return checkWhileStatement(node);
74837 case 234 /* ForStatement */:
74838 return checkForStatement(node);
74839 case 235 /* ForInStatement */:
74840 return checkForInStatement(node);
74841 case 236 /* ForOfStatement */:
74842 return checkForOfStatement(node);
74843 case 237 /* ContinueStatement */:
74844 case 238 /* BreakStatement */:
74845 return checkBreakOrContinueStatement(node);
74846 case 239 /* ReturnStatement */:
74847 return checkReturnStatement(node);
74848 case 240 /* WithStatement */:
74849 return checkWithStatement(node);
74850 case 241 /* SwitchStatement */:
74851 return checkSwitchStatement(node);
74852 case 242 /* LabeledStatement */:
74853 return checkLabeledStatement(node);
74854 case 243 /* ThrowStatement */:
74855 return checkThrowStatement(node);
74856 case 244 /* TryStatement */:
74857 return checkTryStatement(node);
74858 case 246 /* VariableDeclaration */:
74859 return checkVariableDeclaration(node);
74860 case 195 /* BindingElement */:
74861 return checkBindingElement(node);
74862 case 249 /* ClassDeclaration */:
74863 return checkClassDeclaration(node);
74864 case 250 /* InterfaceDeclaration */:
74865 return checkInterfaceDeclaration(node);
74866 case 251 /* TypeAliasDeclaration */:
74867 return checkTypeAliasDeclaration(node);
74868 case 252 /* EnumDeclaration */:
74869 return checkEnumDeclaration(node);
74870 case 253 /* ModuleDeclaration */:
74871 return checkModuleDeclaration(node);
74872 case 258 /* ImportDeclaration */:
74873 return checkImportDeclaration(node);
74874 case 257 /* ImportEqualsDeclaration */:
74875 return checkImportEqualsDeclaration(node);
74876 case 264 /* ExportDeclaration */:
74877 return checkExportDeclaration(node);
74878 case 263 /* ExportAssignment */:
74879 return checkExportAssignment(node);
74880 case 228 /* EmptyStatement */:
74881 case 245 /* DebuggerStatement */:
74882 checkGrammarStatementInAmbientContext(node);
74883 return;
74884 case 268 /* MissingDeclaration */:
74885 return checkMissingDeclaration(node);
74886 }
74887 }
74888 function checkJSDocTypeIsInJsFile(node) {
74889 if (!ts.isInJSFile(node)) {
74890 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
74891 }
74892 }
74893 function checkJSDocVariadicType(node) {
74894 checkJSDocTypeIsInJsFile(node);
74895 checkSourceElement(node.type);
74896 // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
74897 var parent = node.parent;
74898 if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
74899 if (ts.last(parent.parent.parameters) !== parent) {
74900 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
74901 }
74902 return;
74903 }
74904 if (!ts.isJSDocTypeExpression(parent)) {
74905 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
74906 }
74907 var paramTag = node.parent.parent;
74908 if (!ts.isJSDocParameterTag(paramTag)) {
74909 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
74910 return;
74911 }
74912 var param = ts.getParameterSymbolFromJSDoc(paramTag);
74913 if (!param) {
74914 // We will error in `checkJSDocParameterTag`.
74915 return;
74916 }
74917 var host = ts.getHostSignatureFromJSDoc(paramTag);
74918 if (!host || ts.last(host.parameters).symbol !== param) {
74919 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
74920 }
74921 }
74922 function getTypeFromJSDocVariadicType(node) {
74923 var type = getTypeFromTypeNode(node.type);
74924 var parent = node.parent;
74925 var paramTag = node.parent.parent;
74926 if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
74927 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
74928 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
74929 if (host_1) {
74930 /*
74931 Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
74932 So in the following situation we will not create an array type:
74933 /** @param {...number} a * /
74934 function f(a) {}
74935 Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
74936 */
74937 var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
74938 var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
74939 if (!lastParamDeclaration ||
74940 symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
74941 return createArrayType(type);
74942 }
74943 }
74944 }
74945 if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
74946 return createArrayType(type);
74947 }
74948 return addOptionality(type);
74949 }
74950 // Function and class expression bodies are checked after all statements in the enclosing body. This is
74951 // to ensure constructs like the following are permitted:
74952 // const foo = function () {
74953 // const s = foo();
74954 // return "hello";
74955 // }
74956 // Here, performing a full type check of the body of the function expression whilst in the process of
74957 // determining the type of foo would cause foo to be given type any because of the recursive reference.
74958 // Delaying the type check of the body ensures foo has been assigned a type.
74959 function checkNodeDeferred(node) {
74960 var enclosingFile = ts.getSourceFileOfNode(node);
74961 var links = getNodeLinks(enclosingFile);
74962 if (!(links.flags & 1 /* TypeChecked */)) {
74963 links.deferredNodes = links.deferredNodes || new ts.Map();
74964 var id = getNodeId(node);
74965 links.deferredNodes.set(id, node);
74966 }
74967 }
74968 function checkDeferredNodes(context) {
74969 var links = getNodeLinks(context);
74970 if (links.deferredNodes) {
74971 links.deferredNodes.forEach(checkDeferredNode);
74972 }
74973 }
74974 function checkDeferredNode(node) {
74975 var saveCurrentNode = currentNode;
74976 currentNode = node;
74977 instantiationCount = 0;
74978 switch (node.kind) {
74979 case 200 /* CallExpression */:
74980 case 201 /* NewExpression */:
74981 case 202 /* TaggedTemplateExpression */:
74982 case 160 /* Decorator */:
74983 case 272 /* JsxOpeningElement */:
74984 // These node kinds are deferred checked when overload resolution fails
74985 // To save on work, we ensure the arguments are checked just once, in
74986 // a deferred way
74987 resolveUntypedCall(node);
74988 break;
74989 case 205 /* FunctionExpression */:
74990 case 206 /* ArrowFunction */:
74991 case 164 /* MethodDeclaration */:
74992 case 163 /* MethodSignature */:
74993 checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
74994 break;
74995 case 166 /* GetAccessor */:
74996 case 167 /* SetAccessor */:
74997 checkAccessorDeclaration(node);
74998 break;
74999 case 218 /* ClassExpression */:
75000 checkClassExpressionDeferred(node);
75001 break;
75002 case 271 /* JsxSelfClosingElement */:
75003 checkJsxSelfClosingElementDeferred(node);
75004 break;
75005 case 270 /* JsxElement */:
75006 checkJsxElementDeferred(node);
75007 break;
75008 }
75009 currentNode = saveCurrentNode;
75010 }
75011 function checkSourceFile(node) {
75012 ts.performance.mark("beforeCheck");
75013 checkSourceFileWorker(node);
75014 ts.performance.mark("afterCheck");
75015 ts.performance.measure("Check", "beforeCheck", "afterCheck");
75016 }
75017 function unusedIsError(kind, isAmbient) {
75018 if (isAmbient) {
75019 return false;
75020 }
75021 switch (kind) {
75022 case 0 /* Local */:
75023 return !!compilerOptions.noUnusedLocals;
75024 case 1 /* Parameter */:
75025 return !!compilerOptions.noUnusedParameters;
75026 default:
75027 return ts.Debug.assertNever(kind);
75028 }
75029 }
75030 function getPotentiallyUnusedIdentifiers(sourceFile) {
75031 return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
75032 }
75033 // Fully type check a source file and collect the relevant diagnostics.
75034 function checkSourceFileWorker(node) {
75035 var links = getNodeLinks(node);
75036 if (!(links.flags & 1 /* TypeChecked */)) {
75037 if (ts.skipTypeChecking(node, compilerOptions, host)) {
75038 return;
75039 }
75040 // Grammar checking
75041 checkGrammarSourceFile(node);
75042 ts.clear(potentialThisCollisions);
75043 ts.clear(potentialNewTargetCollisions);
75044 ts.clear(potentialWeakMapCollisions);
75045 ts.forEach(node.statements, checkSourceElement);
75046 checkSourceElement(node.endOfFileToken);
75047 checkDeferredNodes(node);
75048 if (ts.isExternalOrCommonJsModule(node)) {
75049 registerForUnusedIdentifiersCheck(node);
75050 }
75051 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
75052 checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
75053 if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
75054 diagnostics.add(diag);
75055 }
75056 });
75057 }
75058 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
75059 !node.isDeclarationFile &&
75060 ts.isExternalModule(node)) {
75061 checkImportsForTypeOnlyConversion(node);
75062 }
75063 if (ts.isExternalOrCommonJsModule(node)) {
75064 checkExternalModuleExports(node);
75065 }
75066 if (potentialThisCollisions.length) {
75067 ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
75068 ts.clear(potentialThisCollisions);
75069 }
75070 if (potentialNewTargetCollisions.length) {
75071 ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
75072 ts.clear(potentialNewTargetCollisions);
75073 }
75074 if (potentialWeakMapCollisions.length) {
75075 ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
75076 ts.clear(potentialWeakMapCollisions);
75077 }
75078 links.flags |= 1 /* TypeChecked */;
75079 }
75080 }
75081 function getDiagnostics(sourceFile, ct) {
75082 try {
75083 // Record the cancellation token so it can be checked later on during checkSourceElement.
75084 // Do this in a finally block so we can ensure that it gets reset back to nothing after
75085 // this call is done.
75086 cancellationToken = ct;
75087 return getDiagnosticsWorker(sourceFile);
75088 }
75089 finally {
75090 cancellationToken = undefined;
75091 }
75092 }
75093 function getDiagnosticsWorker(sourceFile) {
75094 throwIfNonDiagnosticsProducing();
75095 if (sourceFile) {
75096 // Some global diagnostics are deferred until they are needed and
75097 // may not be reported in the first call to getGlobalDiagnostics.
75098 // We should catch these changes and report them.
75099 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
75100 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
75101 checkSourceFile(sourceFile);
75102 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
75103 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
75104 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
75105 // If the arrays are not the same reference, new diagnostics were added.
75106 var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
75107 return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
75108 }
75109 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
75110 // If the arrays are the same reference, but the length has changed, a single
75111 // new diagnostic was added as DiagnosticCollection attempts to reuse the
75112 // same array.
75113 return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
75114 }
75115 return semanticDiagnostics;
75116 }
75117 // Global diagnostics are always added when a file is not provided to
75118 // getDiagnostics
75119 ts.forEach(host.getSourceFiles(), checkSourceFile);
75120 return diagnostics.getDiagnostics();
75121 }
75122 function getGlobalDiagnostics() {
75123 throwIfNonDiagnosticsProducing();
75124 return diagnostics.getGlobalDiagnostics();
75125 }
75126 function throwIfNonDiagnosticsProducing() {
75127 if (!produceDiagnostics) {
75128 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
75129 }
75130 }
75131 // Language service support
75132 function getSymbolsInScope(location, meaning) {
75133 if (location.flags & 16777216 /* InWithStatement */) {
75134 // We cannot answer semantic questions within a with block, do not proceed any further
75135 return [];
75136 }
75137 var symbols = ts.createSymbolTable();
75138 var isStatic = false;
75139 populateSymbols();
75140 symbols.delete("this" /* This */); // Not a symbol, a keyword
75141 return symbolsToArray(symbols);
75142 function populateSymbols() {
75143 while (location) {
75144 if (location.locals && !isGlobalSourceFile(location)) {
75145 copySymbols(location.locals, meaning);
75146 }
75147 switch (location.kind) {
75148 case 294 /* SourceFile */:
75149 if (!ts.isExternalOrCommonJsModule(location))
75150 break;
75151 // falls through
75152 case 253 /* ModuleDeclaration */:
75153 copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
75154 break;
75155 case 252 /* EnumDeclaration */:
75156 copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
75157 break;
75158 case 218 /* ClassExpression */:
75159 var className = location.name;
75160 if (className) {
75161 copySymbol(location.symbol, meaning);
75162 }
75163 // this fall-through is necessary because we would like to handle
75164 // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
75165 // falls through
75166 case 249 /* ClassDeclaration */:
75167 case 250 /* InterfaceDeclaration */:
75168 // If we didn't come from static member of class or interface,
75169 // add the type parameters into the symbol table
75170 // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
75171 // Note: that the memberFlags come from previous iteration.
75172 if (!isStatic) {
75173 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
75174 }
75175 break;
75176 case 205 /* FunctionExpression */:
75177 var funcName = location.name;
75178 if (funcName) {
75179 copySymbol(location.symbol, meaning);
75180 }
75181 break;
75182 }
75183 if (ts.introducesArgumentsExoticObject(location)) {
75184 copySymbol(argumentsSymbol, meaning);
75185 }
75186 isStatic = ts.hasSyntacticModifier(location, 32 /* Static */);
75187 location = location.parent;
75188 }
75189 copySymbols(globals, meaning);
75190 }
75191 /**
75192 * Copy the given symbol into symbol tables if the symbol has the given meaning
75193 * and it doesn't already existed in the symbol table
75194 * @param key a key for storing in symbol table; if undefined, use symbol.name
75195 * @param symbol the symbol to be added into symbol table
75196 * @param meaning meaning of symbol to filter by before adding to symbol table
75197 */
75198 function copySymbol(symbol, meaning) {
75199 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
75200 var id = symbol.escapedName;
75201 // We will copy all symbol regardless of its reserved name because
75202 // symbolsToArray will check whether the key is a reserved name and
75203 // it will not copy symbol with reserved name to the array
75204 if (!symbols.has(id)) {
75205 symbols.set(id, symbol);
75206 }
75207 }
75208 }
75209 function copySymbols(source, meaning) {
75210 if (meaning) {
75211 source.forEach(function (symbol) {
75212 copySymbol(symbol, meaning);
75213 });
75214 }
75215 }
75216 }
75217 function isTypeDeclarationName(name) {
75218 return name.kind === 78 /* Identifier */ &&
75219 isTypeDeclaration(name.parent) &&
75220 ts.getNameOfDeclaration(name.parent) === name;
75221 }
75222 function isTypeDeclaration(node) {
75223 switch (node.kind) {
75224 case 158 /* TypeParameter */:
75225 case 249 /* ClassDeclaration */:
75226 case 250 /* InterfaceDeclaration */:
75227 case 251 /* TypeAliasDeclaration */:
75228 case 252 /* EnumDeclaration */:
75229 case 327 /* JSDocTypedefTag */:
75230 case 320 /* JSDocCallbackTag */:
75231 case 321 /* JSDocEnumTag */:
75232 return true;
75233 case 259 /* ImportClause */:
75234 return node.isTypeOnly;
75235 case 262 /* ImportSpecifier */:
75236 case 267 /* ExportSpecifier */:
75237 return node.parent.parent.isTypeOnly;
75238 default:
75239 return false;
75240 }
75241 }
75242 // True if the given identifier is part of a type reference
75243 function isTypeReferenceIdentifier(node) {
75244 while (node.parent.kind === 156 /* QualifiedName */) {
75245 node = node.parent;
75246 }
75247 return node.parent.kind === 172 /* TypeReference */;
75248 }
75249 function isHeritageClauseElementIdentifier(node) {
75250 while (node.parent.kind === 198 /* PropertyAccessExpression */) {
75251 node = node.parent;
75252 }
75253 return node.parent.kind === 220 /* ExpressionWithTypeArguments */;
75254 }
75255 function forEachEnclosingClass(node, callback) {
75256 var result;
75257 while (true) {
75258 node = ts.getContainingClass(node);
75259 if (!node)
75260 break;
75261 if (result = callback(node))
75262 break;
75263 }
75264 return result;
75265 }
75266 function isNodeUsedDuringClassInitialization(node) {
75267 return !!ts.findAncestor(node, function (element) {
75268 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
75269 return true;
75270 }
75271 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
75272 return "quit";
75273 }
75274 return false;
75275 });
75276 }
75277 function isNodeWithinClass(node, classDeclaration) {
75278 return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
75279 }
75280 function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
75281 while (nodeOnRightSide.parent.kind === 156 /* QualifiedName */) {
75282 nodeOnRightSide = nodeOnRightSide.parent;
75283 }
75284 if (nodeOnRightSide.parent.kind === 257 /* ImportEqualsDeclaration */) {
75285 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
75286 }
75287 if (nodeOnRightSide.parent.kind === 263 /* ExportAssignment */) {
75288 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
75289 }
75290 return undefined;
75291 }
75292 function isInRightSideOfImportOrExportAssignment(node) {
75293 return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
75294 }
75295 function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
75296 var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
75297 switch (specialPropertyAssignmentKind) {
75298 case 1 /* ExportsProperty */:
75299 case 3 /* PrototypeProperty */:
75300 return getSymbolOfNode(entityName.parent);
75301 case 4 /* ThisProperty */:
75302 case 2 /* ModuleExports */:
75303 case 5 /* Property */:
75304 return getSymbolOfNode(entityName.parent.parent);
75305 }
75306 }
75307 function isImportTypeQualifierPart(node) {
75308 var parent = node.parent;
75309 while (ts.isQualifiedName(parent)) {
75310 node = parent;
75311 parent = parent.parent;
75312 }
75313 if (parent && parent.kind === 192 /* ImportType */ && parent.qualifier === node) {
75314 return parent;
75315 }
75316 return undefined;
75317 }
75318 function getSymbolOfNameOrPropertyAccessExpression(name) {
75319 if (ts.isDeclarationName(name)) {
75320 return getSymbolOfNode(name.parent);
75321 }
75322 if (ts.isInJSFile(name) &&
75323 name.parent.kind === 198 /* PropertyAccessExpression */ &&
75324 name.parent === name.parent.parent.left) {
75325 // Check if this is a special property assignment
75326 if (!ts.isPrivateIdentifier(name)) {
75327 var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
75328 if (specialPropertyAssignmentSymbol) {
75329 return specialPropertyAssignmentSymbol;
75330 }
75331 }
75332 }
75333 if (name.parent.kind === 263 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
75334 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
75335 var success = resolveEntityName(name,
75336 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
75337 if (success && success !== unknownSymbol) {
75338 return success;
75339 }
75340 }
75341 else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
75342 // Since we already checked for ExportAssignment, this really could only be an Import
75343 var importEqualsDeclaration = ts.getAncestor(name, 257 /* ImportEqualsDeclaration */);
75344 ts.Debug.assert(importEqualsDeclaration !== undefined);
75345 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
75346 }
75347 if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
75348 var possibleImportNode = isImportTypeQualifierPart(name);
75349 if (possibleImportNode) {
75350 getTypeFromTypeNode(possibleImportNode);
75351 var sym = getNodeLinks(name).resolvedSymbol;
75352 return sym === unknownSymbol ? undefined : sym;
75353 }
75354 }
75355 while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
75356 name = name.parent;
75357 }
75358 if (isHeritageClauseElementIdentifier(name)) {
75359 var meaning = 0 /* None */;
75360 // In an interface or class, we're definitely interested in a type.
75361 if (name.parent.kind === 220 /* ExpressionWithTypeArguments */) {
75362 meaning = 788968 /* Type */;
75363 // In a class 'extends' clause we are also looking for a value.
75364 if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
75365 meaning |= 111551 /* Value */;
75366 }
75367 }
75368 else {
75369 meaning = 1920 /* Namespace */;
75370 }
75371 meaning |= 2097152 /* Alias */;
75372 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
75373 if (entityNameSymbol) {
75374 return entityNameSymbol;
75375 }
75376 }
75377 if (name.parent.kind === 322 /* JSDocParameterTag */) {
75378 return ts.getParameterSymbolFromJSDoc(name.parent);
75379 }
75380 if (name.parent.kind === 158 /* TypeParameter */ && name.parent.parent.kind === 326 /* JSDocTemplateTag */) {
75381 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
75382 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
75383 return typeParameter && typeParameter.symbol;
75384 }
75385 if (ts.isExpressionNode(name)) {
75386 if (ts.nodeIsMissing(name)) {
75387 // Missing entity name.
75388 return undefined;
75389 }
75390 if (name.kind === 78 /* Identifier */) {
75391 if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
75392 var symbol = getIntrinsicTagSymbol(name.parent);
75393 return symbol === unknownSymbol ? undefined : symbol;
75394 }
75395 return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
75396 }
75397 else if (name.kind === 198 /* PropertyAccessExpression */ || name.kind === 156 /* QualifiedName */) {
75398 var links = getNodeLinks(name);
75399 if (links.resolvedSymbol) {
75400 return links.resolvedSymbol;
75401 }
75402 if (name.kind === 198 /* PropertyAccessExpression */) {
75403 checkPropertyAccessExpression(name);
75404 }
75405 else {
75406 checkQualifiedName(name);
75407 }
75408 return links.resolvedSymbol;
75409 }
75410 }
75411 else if (isTypeReferenceIdentifier(name)) {
75412 var meaning = name.parent.kind === 172 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
75413 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
75414 }
75415 if (name.parent.kind === 171 /* TypePredicate */) {
75416 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
75417 }
75418 // Do we want to return undefined here?
75419 return undefined;
75420 }
75421 function getSymbolAtLocation(node, ignoreErrors) {
75422 if (node.kind === 294 /* SourceFile */) {
75423 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
75424 }
75425 var parent = node.parent;
75426 var grandParent = parent.parent;
75427 if (node.flags & 16777216 /* InWithStatement */) {
75428 // We cannot answer semantic questions within a with block, do not proceed any further
75429 return undefined;
75430 }
75431 if (isDeclarationNameOrImportPropertyName(node)) {
75432 // This is a declaration, call getSymbolOfNode
75433 var parentSymbol = getSymbolOfNode(parent);
75434 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
75435 ? getImmediateAliasedSymbol(parentSymbol)
75436 : parentSymbol;
75437 }
75438 else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
75439 return getSymbolOfNode(parent.parent);
75440 }
75441 if (node.kind === 78 /* Identifier */) {
75442 if (isInRightSideOfImportOrExportAssignment(node)) {
75443 return getSymbolOfNameOrPropertyAccessExpression(node);
75444 }
75445 else if (parent.kind === 195 /* BindingElement */ &&
75446 grandParent.kind === 193 /* ObjectBindingPattern */ &&
75447 node === parent.propertyName) {
75448 var typeOfPattern = getTypeOfNode(grandParent);
75449 var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
75450 if (propertyDeclaration) {
75451 return propertyDeclaration;
75452 }
75453 }
75454 }
75455 switch (node.kind) {
75456 case 78 /* Identifier */:
75457 case 79 /* PrivateIdentifier */:
75458 case 198 /* PropertyAccessExpression */:
75459 case 156 /* QualifiedName */:
75460 return getSymbolOfNameOrPropertyAccessExpression(node);
75461 case 107 /* ThisKeyword */:
75462 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
75463 if (ts.isFunctionLike(container)) {
75464 var sig = getSignatureFromDeclaration(container);
75465 if (sig.thisParameter) {
75466 return sig.thisParameter;
75467 }
75468 }
75469 if (ts.isInExpressionContext(node)) {
75470 return checkExpression(node).symbol;
75471 }
75472 // falls through
75473 case 186 /* ThisType */:
75474 return getTypeFromThisTypeNode(node).symbol;
75475 case 105 /* SuperKeyword */:
75476 return checkExpression(node).symbol;
75477 case 132 /* ConstructorKeyword */:
75478 // constructor keyword for an overload, should take us to the definition if it exist
75479 var constructorDeclaration = node.parent;
75480 if (constructorDeclaration && constructorDeclaration.kind === 165 /* Constructor */) {
75481 return constructorDeclaration.parent.symbol;
75482 }
75483 return undefined;
75484 case 10 /* StringLiteral */:
75485 case 14 /* NoSubstitutionTemplateLiteral */:
75486 // 1). import x = require("./mo/*gotToDefinitionHere*/d")
75487 // 2). External module name in an import declaration
75488 // 3). Dynamic import call or require in javascript
75489 // 4). type A = import("./f/*gotToDefinitionHere*/oo")
75490 if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
75491 ((node.parent.kind === 258 /* ImportDeclaration */ || node.parent.kind === 264 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
75492 ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
75493 (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
75494 return resolveExternalModuleName(node, node, ignoreErrors);
75495 }
75496 if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
75497 return getSymbolOfNode(parent);
75498 }
75499 // falls through
75500 case 8 /* NumericLiteral */:
75501 // index access
75502 var objectType = ts.isElementAccessExpression(parent)
75503 ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
75504 : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
75505 ? getTypeFromTypeNode(grandParent.objectType)
75506 : undefined;
75507 return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
75508 case 87 /* DefaultKeyword */:
75509 case 97 /* FunctionKeyword */:
75510 case 38 /* EqualsGreaterThanToken */:
75511 case 83 /* ClassKeyword */:
75512 return getSymbolOfNode(node.parent);
75513 case 192 /* ImportType */:
75514 return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
75515 case 92 /* ExportKeyword */:
75516 return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
75517 default:
75518 return undefined;
75519 }
75520 }
75521 function getShorthandAssignmentValueSymbol(location) {
75522 if (location && location.kind === 286 /* ShorthandPropertyAssignment */) {
75523 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
75524 }
75525 return undefined;
75526 }
75527 /** Returns the target of an export specifier without following aliases */
75528 function getExportSpecifierLocalTargetSymbol(node) {
75529 return node.parent.parent.moduleSpecifier ?
75530 getExternalModuleMember(node.parent.parent, node) :
75531 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
75532 }
75533 function getTypeOfNode(node) {
75534 if (node.flags & 16777216 /* InWithStatement */) {
75535 // We cannot answer semantic questions within a with block, do not proceed any further
75536 return errorType;
75537 }
75538 var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
75539 var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
75540 if (ts.isPartOfTypeNode(node)) {
75541 var typeFromTypeNode = getTypeFromTypeNode(node);
75542 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
75543 }
75544 if (ts.isExpressionNode(node)) {
75545 return getRegularTypeOfExpression(node);
75546 }
75547 if (classType && !classDecl.isImplements) {
75548 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
75549 // extends clause of a class. We handle that case here.
75550 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
75551 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
75552 }
75553 if (isTypeDeclaration(node)) {
75554 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
75555 var symbol = getSymbolOfNode(node);
75556 return getDeclaredTypeOfSymbol(symbol);
75557 }
75558 if (isTypeDeclarationName(node)) {
75559 var symbol = getSymbolAtLocation(node);
75560 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
75561 }
75562 if (ts.isDeclaration(node)) {
75563 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
75564 var symbol = getSymbolOfNode(node);
75565 return getTypeOfSymbol(symbol);
75566 }
75567 if (isDeclarationNameOrImportPropertyName(node)) {
75568 var symbol = getSymbolAtLocation(node);
75569 if (symbol) {
75570 return getTypeOfSymbol(symbol);
75571 }
75572 return errorType;
75573 }
75574 if (ts.isBindingPattern(node)) {
75575 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
75576 }
75577 if (isInRightSideOfImportOrExportAssignment(node)) {
75578 var symbol = getSymbolAtLocation(node);
75579 if (symbol) {
75580 var declaredType = getDeclaredTypeOfSymbol(symbol);
75581 return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
75582 }
75583 }
75584 return errorType;
75585 }
75586 // Gets the type of object literal or array literal of destructuring assignment.
75587 // { a } from
75588 // for ( { a } of elems) {
75589 // }
75590 // [ a ] from
75591 // [a] = [ some array ...]
75592 function getTypeOfAssignmentPattern(expr) {
75593 ts.Debug.assert(expr.kind === 197 /* ObjectLiteralExpression */ || expr.kind === 196 /* ArrayLiteralExpression */);
75594 // If this is from "for of"
75595 // for ( { a } of elems) {
75596 // }
75597 if (expr.parent.kind === 236 /* ForOfStatement */) {
75598 var iteratedType = checkRightHandSideOfForOf(expr.parent);
75599 return checkDestructuringAssignment(expr, iteratedType || errorType);
75600 }
75601 // If this is from "for" initializer
75602 // for ({a } = elems[0];.....) { }
75603 if (expr.parent.kind === 213 /* BinaryExpression */) {
75604 var iteratedType = getTypeOfExpression(expr.parent.right);
75605 return checkDestructuringAssignment(expr, iteratedType || errorType);
75606 }
75607 // If this is from nested object binding pattern
75608 // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
75609 if (expr.parent.kind === 285 /* PropertyAssignment */) {
75610 var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
75611 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType;
75612 var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent);
75613 return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex);
75614 }
75615 // Array literal assignment - array destructuring pattern
75616 var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
75617 // [{ property1: p1, property2 }] = elems;
75618 var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
75619 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
75620 return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
75621 }
75622 // Gets the property symbol corresponding to the property in destructuring assignment
75623 // 'property1' from
75624 // for ( { property1: a } of elems) {
75625 // }
75626 // 'property1' at location 'a' from:
75627 // [a] = [ property1, property2 ]
75628 function getPropertySymbolOfDestructuringAssignment(location) {
75629 // Get the type of the object or array literal and then look for property of given name in the type
75630 var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
75631 return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
75632 }
75633 function getRegularTypeOfExpression(expr) {
75634 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
75635 expr = expr.parent;
75636 }
75637 return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
75638 }
75639 /**
75640 * Gets either the static or instance type of a class element, based on
75641 * whether the element is declared as "static".
75642 */
75643 function getParentTypeOfClassElement(node) {
75644 var classSymbol = getSymbolOfNode(node.parent);
75645 return ts.hasSyntacticModifier(node, 32 /* Static */)
75646 ? getTypeOfSymbol(classSymbol)
75647 : getDeclaredTypeOfSymbol(classSymbol);
75648 }
75649 function getClassElementPropertyKeyType(element) {
75650 var name = element.name;
75651 switch (name.kind) {
75652 case 78 /* Identifier */:
75653 return getLiteralType(ts.idText(name));
75654 case 8 /* NumericLiteral */:
75655 case 10 /* StringLiteral */:
75656 return getLiteralType(name.text);
75657 case 157 /* ComputedPropertyName */:
75658 var nameType = checkComputedPropertyName(name);
75659 return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
75660 default:
75661 return ts.Debug.fail("Unsupported property name.");
75662 }
75663 }
75664 // Return the list of properties of the given type, augmented with properties from Function
75665 // if the type has call or construct signatures
75666 function getAugmentedPropertiesOfType(type) {
75667 type = getApparentType(type);
75668 var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
75669 var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
75670 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
75671 undefined;
75672 if (functionType) {
75673 ts.forEach(getPropertiesOfType(functionType), function (p) {
75674 if (!propsByName.has(p.escapedName)) {
75675 propsByName.set(p.escapedName, p);
75676 }
75677 });
75678 }
75679 return getNamedMembers(propsByName);
75680 }
75681 function typeHasCallOrConstructSignatures(type) {
75682 return ts.typeHasCallOrConstructSignatures(type, checker);
75683 }
75684 function getRootSymbols(symbol) {
75685 var roots = getImmediateRootSymbols(symbol);
75686 return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
75687 }
75688 function getImmediateRootSymbols(symbol) {
75689 if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
75690 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
75691 }
75692 else if (symbol.flags & 33554432 /* Transient */) {
75693 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
75694 return leftSpread ? [leftSpread, rightSpread]
75695 : syntheticOrigin ? [syntheticOrigin]
75696 : ts.singleElementArray(tryGetAliasTarget(symbol));
75697 }
75698 return undefined;
75699 }
75700 function tryGetAliasTarget(symbol) {
75701 var target;
75702 var next = symbol;
75703 while (next = getSymbolLinks(next).target) {
75704 target = next;
75705 }
75706 return target;
75707 }
75708 // Emitter support
75709 function isArgumentsLocalBinding(nodeIn) {
75710 // Note: does not handle isShorthandPropertyAssignment (and probably a few more)
75711 if (ts.isGeneratedIdentifier(nodeIn))
75712 return false;
75713 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
75714 if (!node)
75715 return false;
75716 var parent = node.parent;
75717 if (!parent)
75718 return false;
75719 var isPropertyName = ((ts.isPropertyAccessExpression(parent)
75720 || ts.isPropertyAssignment(parent))
75721 && parent.name === node);
75722 return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol;
75723 }
75724 function moduleExportsSomeValue(moduleReferenceExpression) {
75725 var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
75726 if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
75727 // If the module is not found or is shorthand, assume that it may export a value.
75728 return true;
75729 }
75730 var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
75731 // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
75732 // otherwise it will return moduleSymbol itself
75733 moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
75734 var symbolLinks = getSymbolLinks(moduleSymbol);
75735 if (symbolLinks.exportsSomeValue === undefined) {
75736 // for export assignments - check if resolved symbol for RHS is itself a value
75737 // otherwise - check if at least one export is value
75738 symbolLinks.exportsSomeValue = hasExportAssignment
75739 ? !!(moduleSymbol.flags & 111551 /* Value */)
75740 : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
75741 }
75742 return symbolLinks.exportsSomeValue;
75743 function isValue(s) {
75744 s = resolveSymbol(s);
75745 return s && !!(s.flags & 111551 /* Value */);
75746 }
75747 }
75748 function isNameOfModuleOrEnumDeclaration(node) {
75749 return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
75750 }
75751 // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
75752 // node of the exported entity's container. Otherwise, return undefined.
75753 function getReferencedExportContainer(nodeIn, prefixLocals) {
75754 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
75755 if (node) {
75756 // When resolving the export container for the name of a module or enum
75757 // declaration, we need to start resolution at the declaration's container.
75758 // Otherwise, we could incorrectly resolve the export container as the
75759 // declaration if it contains an exported member with the same name.
75760 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
75761 if (symbol) {
75762 if (symbol.flags & 1048576 /* ExportValue */) {
75763 // If we reference an exported entity within the same module declaration, then whether
75764 // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
75765 // kinds that we do NOT prefix.
75766 var exportSymbol = getMergedSymbol(symbol.exportSymbol);
75767 if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
75768 return undefined;
75769 }
75770 symbol = exportSymbol;
75771 }
75772 var parentSymbol_1 = getParentOfSymbol(symbol);
75773 if (parentSymbol_1) {
75774 if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 294 /* SourceFile */) {
75775 var symbolFile = parentSymbol_1.valueDeclaration;
75776 var referenceFile = ts.getSourceFileOfNode(node);
75777 // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
75778 var symbolIsUmdExport = symbolFile !== referenceFile;
75779 return symbolIsUmdExport ? undefined : symbolFile;
75780 }
75781 return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
75782 }
75783 }
75784 }
75785 }
75786 // When resolved as an expression identifier, if the given node references an import, return the declaration of
75787 // that import. Otherwise, return undefined.
75788 function getReferencedImportDeclaration(nodeIn) {
75789 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
75790 if (node) {
75791 var symbol = getReferencedValueSymbol(node);
75792 // We should only get the declaration of an alias if there isn't a local value
75793 // declaration for the symbol
75794 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
75795 return getDeclarationOfAliasSymbol(symbol);
75796 }
75797 }
75798 return undefined;
75799 }
75800 function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
75801 return ts.isBindingElement(symbol.valueDeclaration)
75802 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 284 /* CatchClause */;
75803 }
75804 function isSymbolOfDeclarationWithCollidingName(symbol) {
75805 if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
75806 var links = getSymbolLinks(symbol);
75807 if (links.isDeclarationWithCollidingName === undefined) {
75808 var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
75809 if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
75810 var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
75811 if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
75812 // redeclaration - always should be renamed
75813 links.isDeclarationWithCollidingName = true;
75814 }
75815 else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
75816 // binding is captured in the function
75817 // should be renamed if:
75818 // - binding is not top level - top level bindings never collide with anything
75819 // AND
75820 // - binding is not declared in loop, should be renamed to avoid name reuse across siblings
75821 // let a, b
75822 // { let x = 1; a = () => x; }
75823 // { let x = 100; b = () => x; }
75824 // console.log(a()); // should print '1'
75825 // console.log(b()); // should print '100'
75826 // OR
75827 // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
75828 // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
75829 // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
75830 // they will not collide with anything
75831 var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
75832 var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
75833 var inLoopBodyBlock = container.kind === 227 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
75834 links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
75835 }
75836 else {
75837 links.isDeclarationWithCollidingName = false;
75838 }
75839 }
75840 }
75841 return links.isDeclarationWithCollidingName;
75842 }
75843 return false;
75844 }
75845 // When resolved as an expression identifier, if the given node references a nested block scoped entity with
75846 // a name that either hides an existing name or might hide it when compiled downlevel,
75847 // return the declaration of that entity. Otherwise, return undefined.
75848 function getReferencedDeclarationWithCollidingName(nodeIn) {
75849 if (!ts.isGeneratedIdentifier(nodeIn)) {
75850 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
75851 if (node) {
75852 var symbol = getReferencedValueSymbol(node);
75853 if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
75854 return symbol.valueDeclaration;
75855 }
75856 }
75857 }
75858 return undefined;
75859 }
75860 // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
75861 // existing name or might hide a name when compiled downlevel
75862 function isDeclarationWithCollidingName(nodeIn) {
75863 var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
75864 if (node) {
75865 var symbol = getSymbolOfNode(node);
75866 if (symbol) {
75867 return isSymbolOfDeclarationWithCollidingName(symbol);
75868 }
75869 }
75870 return false;
75871 }
75872 function isValueAliasDeclaration(node) {
75873 switch (node.kind) {
75874 case 257 /* ImportEqualsDeclaration */:
75875 return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
75876 case 259 /* ImportClause */:
75877 case 260 /* NamespaceImport */:
75878 case 262 /* ImportSpecifier */:
75879 case 267 /* ExportSpecifier */:
75880 var symbol = getSymbolOfNode(node) || unknownSymbol;
75881 return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
75882 case 264 /* ExportDeclaration */:
75883 var exportClause = node.exportClause;
75884 return !!exportClause && (ts.isNamespaceExport(exportClause) ||
75885 ts.some(exportClause.elements, isValueAliasDeclaration));
75886 case 263 /* ExportAssignment */:
75887 return node.expression && node.expression.kind === 78 /* Identifier */ ?
75888 isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
75889 true;
75890 }
75891 return false;
75892 }
75893 function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
75894 var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
75895 if (node === undefined || node.parent.kind !== 294 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
75896 // parent is not source file or it is not reference to internal module
75897 return false;
75898 }
75899 var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
75900 return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
75901 }
75902 function isAliasResolvedToValue(symbol) {
75903 var target = resolveAlias(symbol);
75904 if (target === unknownSymbol) {
75905 return true;
75906 }
75907 // const enums and modules that contain only const enums are not considered values from the emit perspective
75908 // unless 'preserveConstEnums' option is set to true
75909 return !!(target.flags & 111551 /* Value */) &&
75910 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
75911 }
75912 function isConstEnumOrConstEnumOnlyModule(s) {
75913 return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
75914 }
75915 function isReferencedAliasDeclaration(node, checkChildren) {
75916 if (isAliasSymbolDeclaration(node)) {
75917 var symbol = getSymbolOfNode(node);
75918 if (symbol && getSymbolLinks(symbol).referenced) {
75919 return true;
75920 }
75921 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
75922 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
75923 target.flags & 111551 /* Value */ &&
75924 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
75925 // An `export import ... =` of a value symbol is always considered referenced
75926 return true;
75927 }
75928 }
75929 if (checkChildren) {
75930 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
75931 }
75932 return false;
75933 }
75934 function isImplementationOfOverload(node) {
75935 if (ts.nodeIsPresent(node.body)) {
75936 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
75937 return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
75938 var symbol = getSymbolOfNode(node);
75939 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
75940 // If this function body corresponds to function with multiple signature, it is implementation of overload
75941 // e.g.: function foo(a: string): string;
75942 // function foo(a: number): number;
75943 // function foo(a: any) { // This is implementation of the overloads
75944 // return a;
75945 // }
75946 return signaturesOfSymbol.length > 1 ||
75947 // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
75948 // e.g.: function foo(a: string): string;
75949 // function foo(a: any) { // This is implementation of the overloads
75950 // return a;
75951 // }
75952 (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
75953 }
75954 return false;
75955 }
75956 function isRequiredInitializedParameter(parameter) {
75957 return !!strictNullChecks &&
75958 !isOptionalParameter(parameter) &&
75959 !ts.isJSDocParameterTag(parameter) &&
75960 !!parameter.initializer &&
75961 !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
75962 }
75963 function isOptionalUninitializedParameterProperty(parameter) {
75964 return strictNullChecks &&
75965 isOptionalParameter(parameter) &&
75966 !parameter.initializer &&
75967 ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
75968 }
75969 function isOptionalUninitializedParameter(parameter) {
75970 return !!strictNullChecks &&
75971 isOptionalParameter(parameter) &&
75972 !parameter.initializer;
75973 }
75974 function isExpandoFunctionDeclaration(node) {
75975 var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
75976 if (!declaration) {
75977 return false;
75978 }
75979 var symbol = getSymbolOfNode(declaration);
75980 if (!symbol || !(symbol.flags & 16 /* Function */)) {
75981 return false;
75982 }
75983 return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
75984 }
75985 function getPropertiesOfContainerFunction(node) {
75986 var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
75987 if (!declaration) {
75988 return ts.emptyArray;
75989 }
75990 var symbol = getSymbolOfNode(declaration);
75991 return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
75992 }
75993 function getNodeCheckFlags(node) {
75994 return getNodeLinks(node).flags || 0;
75995 }
75996 function getEnumMemberValue(node) {
75997 computeEnumMemberValues(node.parent);
75998 return getNodeLinks(node).enumMemberValue;
75999 }
76000 function canHaveConstantValue(node) {
76001 switch (node.kind) {
76002 case 288 /* EnumMember */:
76003 case 198 /* PropertyAccessExpression */:
76004 case 199 /* ElementAccessExpression */:
76005 return true;
76006 }
76007 return false;
76008 }
76009 function getConstantValue(node) {
76010 if (node.kind === 288 /* EnumMember */) {
76011 return getEnumMemberValue(node);
76012 }
76013 var symbol = getNodeLinks(node).resolvedSymbol;
76014 if (symbol && (symbol.flags & 8 /* EnumMember */)) {
76015 // inline property\index accesses only for const enums
76016 var member = symbol.valueDeclaration;
76017 if (ts.isEnumConst(member.parent)) {
76018 return getEnumMemberValue(member);
76019 }
76020 }
76021 return undefined;
76022 }
76023 function isFunctionType(type) {
76024 return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
76025 }
76026 function getTypeReferenceSerializationKind(typeNameIn, location) {
76027 var _a;
76028 // ensure both `typeName` and `location` are parse tree nodes.
76029 var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
76030 if (!typeName)
76031 return ts.TypeReferenceSerializationKind.Unknown;
76032 if (location) {
76033 location = ts.getParseTreeNode(location);
76034 if (!location)
76035 return ts.TypeReferenceSerializationKind.Unknown;
76036 }
76037 // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
76038 var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
76039 var isTypeOnly = ((_a = valueSymbol === null || valueSymbol === void 0 ? void 0 : valueSymbol.declarations) === null || _a === void 0 ? void 0 : _a.every(ts.isTypeOnlyImportOrExportDeclaration)) || false;
76040 var resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
76041 // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
76042 var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
76043 if (resolvedSymbol && resolvedSymbol === typeSymbol) {
76044 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
76045 if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) {
76046 return ts.TypeReferenceSerializationKind.Promise;
76047 }
76048 var constructorType = getTypeOfSymbol(resolvedSymbol);
76049 if (constructorType && isConstructorType(constructorType)) {
76050 return isTypeOnly ? ts.TypeReferenceSerializationKind.TypeWithCallSignature : ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
76051 }
76052 }
76053 // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
76054 if (!typeSymbol) {
76055 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
76056 }
76057 var type = getDeclaredTypeOfSymbol(typeSymbol);
76058 if (type === errorType) {
76059 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
76060 }
76061 else if (type.flags & 3 /* AnyOrUnknown */) {
76062 return ts.TypeReferenceSerializationKind.ObjectType;
76063 }
76064 else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
76065 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
76066 }
76067 else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
76068 return ts.TypeReferenceSerializationKind.BooleanType;
76069 }
76070 else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
76071 return ts.TypeReferenceSerializationKind.NumberLikeType;
76072 }
76073 else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
76074 return ts.TypeReferenceSerializationKind.BigIntLikeType;
76075 }
76076 else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
76077 return ts.TypeReferenceSerializationKind.StringLikeType;
76078 }
76079 else if (isTupleType(type)) {
76080 return ts.TypeReferenceSerializationKind.ArrayLikeType;
76081 }
76082 else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
76083 return ts.TypeReferenceSerializationKind.ESSymbolType;
76084 }
76085 else if (isFunctionType(type)) {
76086 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
76087 }
76088 else if (isArrayType(type)) {
76089 return ts.TypeReferenceSerializationKind.ArrayLikeType;
76090 }
76091 else {
76092 return ts.TypeReferenceSerializationKind.ObjectType;
76093 }
76094 }
76095 function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
76096 var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
76097 if (!declaration) {
76098 return ts.factory.createToken(128 /* AnyKeyword */);
76099 }
76100 // Get type of the symbol if this is the valid symbol otherwise get type at location
76101 var symbol = getSymbolOfNode(declaration);
76102 var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
76103 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
76104 : errorType;
76105 if (type.flags & 8192 /* UniqueESSymbol */ &&
76106 type.symbol === symbol) {
76107 flags |= 1048576 /* AllowUniqueESSymbolType */;
76108 }
76109 if (addUndefined) {
76110 type = getOptionalType(type);
76111 }
76112 return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
76113 }
76114 function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
76115 var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
76116 if (!signatureDeclaration) {
76117 return ts.factory.createToken(128 /* AnyKeyword */);
76118 }
76119 var signature = getSignatureFromDeclaration(signatureDeclaration);
76120 return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
76121 }
76122 function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
76123 var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
76124 if (!expr) {
76125 return ts.factory.createToken(128 /* AnyKeyword */);
76126 }
76127 var type = getWidenedType(getRegularTypeOfExpression(expr));
76128 return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
76129 }
76130 function hasGlobalName(name) {
76131 return globals.has(ts.escapeLeadingUnderscores(name));
76132 }
76133 function getReferencedValueSymbol(reference, startInDeclarationContainer) {
76134 var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
76135 if (resolvedSymbol) {
76136 return resolvedSymbol;
76137 }
76138 var location = reference;
76139 if (startInDeclarationContainer) {
76140 // When resolving the name of a declaration as a value, we need to start resolution
76141 // at a point outside of the declaration.
76142 var parent = reference.parent;
76143 if (ts.isDeclaration(parent) && reference === parent.name) {
76144 location = getDeclarationContainer(parent);
76145 }
76146 }
76147 return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
76148 }
76149 function getReferencedValueDeclaration(referenceIn) {
76150 if (!ts.isGeneratedIdentifier(referenceIn)) {
76151 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
76152 if (reference) {
76153 var symbol = getReferencedValueSymbol(reference);
76154 if (symbol) {
76155 return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
76156 }
76157 }
76158 }
76159 return undefined;
76160 }
76161 function isLiteralConstDeclaration(node) {
76162 if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
76163 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
76164 }
76165 return false;
76166 }
76167 function literalTypeToNode(type, enclosing, tracker) {
76168 var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
76169 : type === trueType ? ts.factory.createTrue() : type === falseType && ts.factory.createFalse();
76170 if (enumResult)
76171 return enumResult;
76172 var literalValue = type.value;
76173 return typeof literalValue === "object" ? ts.factory.createBigIntLiteral(literalValue) :
76174 typeof literalValue === "number" ? ts.factory.createNumericLiteral(literalValue) :
76175 ts.factory.createStringLiteral(literalValue);
76176 }
76177 function createLiteralConstValue(node, tracker) {
76178 var type = getTypeOfSymbol(getSymbolOfNode(node));
76179 return literalTypeToNode(type, node, tracker);
76180 }
76181 function getJsxFactoryEntity(location) {
76182 return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
76183 }
76184 function getJsxFragmentFactoryEntity(location) {
76185 if (location) {
76186 var file = ts.getSourceFileOfNode(location);
76187 if (file) {
76188 if (file.localJsxFragmentFactory) {
76189 return file.localJsxFragmentFactory;
76190 }
76191 var jsxFragPragmas = file.pragmas.get("jsxfrag");
76192 var jsxFragPragma = ts.isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
76193 if (jsxFragPragma) {
76194 file.localJsxFragmentFactory = ts.parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
76195 return file.localJsxFragmentFactory;
76196 }
76197 }
76198 }
76199 if (compilerOptions.jsxFragmentFactory) {
76200 return ts.parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
76201 }
76202 }
76203 function createResolver() {
76204 // this variable and functions that use it are deliberately moved here from the outer scope
76205 // to avoid scope pollution
76206 var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
76207 var fileToDirective;
76208 if (resolvedTypeReferenceDirectives) {
76209 // populate reverse mapping: file path -> type reference directive that was resolved to this file
76210 fileToDirective = new ts.Map();
76211 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
76212 if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
76213 return;
76214 }
76215 var file = host.getSourceFile(resolvedDirective.resolvedFileName);
76216 if (file) {
76217 // Add the transitive closure of path references loaded by this file (as long as they are not)
76218 // part of an existing type reference.
76219 addReferencedFilesToTypeDirective(file, key);
76220 }
76221 });
76222 }
76223 return {
76224 getReferencedExportContainer: getReferencedExportContainer,
76225 getReferencedImportDeclaration: getReferencedImportDeclaration,
76226 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
76227 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
76228 isValueAliasDeclaration: function (nodeIn) {
76229 var node = ts.getParseTreeNode(nodeIn);
76230 // Synthesized nodes are always treated like values.
76231 return node ? isValueAliasDeclaration(node) : true;
76232 },
76233 hasGlobalName: hasGlobalName,
76234 isReferencedAliasDeclaration: function (nodeIn, checkChildren) {
76235 var node = ts.getParseTreeNode(nodeIn);
76236 // Synthesized nodes are always treated as referenced.
76237 return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
76238 },
76239 getNodeCheckFlags: function (nodeIn) {
76240 var node = ts.getParseTreeNode(nodeIn);
76241 return node ? getNodeCheckFlags(node) : 0;
76242 },
76243 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
76244 isDeclarationVisible: isDeclarationVisible,
76245 isImplementationOfOverload: isImplementationOfOverload,
76246 isRequiredInitializedParameter: isRequiredInitializedParameter,
76247 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
76248 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
76249 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
76250 createTypeOfDeclaration: createTypeOfDeclaration,
76251 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
76252 createTypeOfExpression: createTypeOfExpression,
76253 createLiteralConstValue: createLiteralConstValue,
76254 isSymbolAccessible: isSymbolAccessible,
76255 isEntityNameVisible: isEntityNameVisible,
76256 getConstantValue: function (nodeIn) {
76257 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
76258 return node ? getConstantValue(node) : undefined;
76259 },
76260 collectLinkedAliases: collectLinkedAliases,
76261 getReferencedValueDeclaration: getReferencedValueDeclaration,
76262 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
76263 isOptionalParameter: isOptionalParameter,
76264 moduleExportsSomeValue: moduleExportsSomeValue,
76265 isArgumentsLocalBinding: isArgumentsLocalBinding,
76266 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
76267 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
76268 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
76269 isLiteralConstDeclaration: isLiteralConstDeclaration,
76270 isLateBound: function (nodeIn) {
76271 var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
76272 var symbol = node && getSymbolOfNode(node);
76273 return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
76274 },
76275 getJsxFactoryEntity: getJsxFactoryEntity,
76276 getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity,
76277 getAllAccessorDeclarations: function (accessor) {
76278 accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
76279 var otherKind = accessor.kind === 167 /* SetAccessor */ ? 166 /* GetAccessor */ : 167 /* SetAccessor */;
76280 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
76281 var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
76282 var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
76283 var setAccessor = accessor.kind === 167 /* SetAccessor */ ? accessor : otherAccessor;
76284 var getAccessor = accessor.kind === 166 /* GetAccessor */ ? accessor : otherAccessor;
76285 return {
76286 firstAccessor: firstAccessor,
76287 secondAccessor: secondAccessor,
76288 setAccessor: setAccessor,
76289 getAccessor: getAccessor
76290 };
76291 },
76292 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
76293 isBindingCapturedByNode: function (node, decl) {
76294 var parseNode = ts.getParseTreeNode(node);
76295 var parseDecl = ts.getParseTreeNode(decl);
76296 return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
76297 },
76298 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
76299 var n = ts.getParseTreeNode(node);
76300 ts.Debug.assert(n && n.kind === 294 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
76301 var sym = getSymbolOfNode(node);
76302 if (!sym) {
76303 return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
76304 }
76305 return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
76306 },
76307 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
76308 };
76309 function isImportRequiredByAugmentation(node) {
76310 var file = ts.getSourceFileOfNode(node);
76311 if (!file.symbol)
76312 return false;
76313 var importTarget = getExternalModuleFileFromDeclaration(node);
76314 if (!importTarget)
76315 return false;
76316 if (importTarget === file)
76317 return false;
76318 var exports = getExportsOfModule(file.symbol);
76319 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
76320 var s = _a[_i];
76321 if (s.mergeId) {
76322 var merged = getMergedSymbol(s);
76323 for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
76324 var d = _c[_b];
76325 var declFile = ts.getSourceFileOfNode(d);
76326 if (declFile === importTarget) {
76327 return true;
76328 }
76329 }
76330 }
76331 }
76332 return false;
76333 }
76334 function isInHeritageClause(node) {
76335 return node.parent && node.parent.kind === 220 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 283 /* HeritageClause */;
76336 }
76337 // defined here to avoid outer scope pollution
76338 function getTypeReferenceDirectivesForEntityName(node) {
76339 // program does not have any files with type reference directives - bail out
76340 if (!fileToDirective) {
76341 return undefined;
76342 }
76343 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
76344 // qualified names can only be used as types\namespaces
76345 // identifiers are treated as values only if they appear in type queries
76346 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
76347 if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 198 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
76348 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
76349 }
76350 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
76351 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
76352 }
76353 // defined here to avoid outer scope pollution
76354 function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
76355 // program does not have any files with type reference directives - bail out
76356 if (!fileToDirective) {
76357 return undefined;
76358 }
76359 if (!isSymbolFromTypeDeclarationFile(symbol)) {
76360 return undefined;
76361 }
76362 // check what declarations in the symbol can contribute to the target meaning
76363 var typeReferenceDirectives;
76364 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
76365 var decl = _a[_i];
76366 // check meaning of the local symbol to see if declaration needs to be analyzed further
76367 if (decl.symbol && decl.symbol.flags & meaning) {
76368 var file = ts.getSourceFileOfNode(decl);
76369 var typeReferenceDirective = fileToDirective.get(file.path);
76370 if (typeReferenceDirective) {
76371 (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
76372 }
76373 else {
76374 // found at least one entry that does not originate from type reference directive
76375 return undefined;
76376 }
76377 }
76378 }
76379 return typeReferenceDirectives;
76380 }
76381 function isSymbolFromTypeDeclarationFile(symbol) {
76382 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
76383 if (!symbol.declarations) {
76384 return false;
76385 }
76386 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
76387 // external modules cannot define or contribute to type declaration files
76388 var current = symbol;
76389 while (true) {
76390 var parent = getParentOfSymbol(current);
76391 if (parent) {
76392 current = parent;
76393 }
76394 else {
76395 break;
76396 }
76397 }
76398 if (current.valueDeclaration && current.valueDeclaration.kind === 294 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
76399 return false;
76400 }
76401 // check that at least one declaration of top level symbol originates from type declaration file
76402 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
76403 var decl = _a[_i];
76404 var file = ts.getSourceFileOfNode(decl);
76405 if (fileToDirective.has(file.path)) {
76406 return true;
76407 }
76408 }
76409 return false;
76410 }
76411 function addReferencedFilesToTypeDirective(file, key) {
76412 if (fileToDirective.has(file.path))
76413 return;
76414 fileToDirective.set(file.path, key);
76415 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
76416 var fileName = _a[_i].fileName;
76417 var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
76418 var referencedFile = host.getSourceFile(resolvedFile);
76419 if (referencedFile) {
76420 addReferencedFilesToTypeDirective(referencedFile, key);
76421 }
76422 }
76423 }
76424 }
76425 function getExternalModuleFileFromDeclaration(declaration) {
76426 var specifier = declaration.kind === 253 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
76427 var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
76428 if (!moduleSymbol) {
76429 return undefined;
76430 }
76431 return ts.getDeclarationOfKind(moduleSymbol, 294 /* SourceFile */);
76432 }
76433 function initializeTypeChecker() {
76434 // Bind all source files and propagate errors
76435 for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
76436 var file = _a[_i];
76437 ts.bindSourceFile(file, compilerOptions);
76438 }
76439 amalgamatedDuplicates = new ts.Map();
76440 // Initialize global symbol table
76441 var augmentations;
76442 for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
76443 var file = _c[_b];
76444 if (file.redirectInfo) {
76445 continue;
76446 }
76447 if (!ts.isExternalOrCommonJsModule(file)) {
76448 // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
76449 // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
76450 var fileGlobalThisSymbol = file.locals.get("globalThis");
76451 if (fileGlobalThisSymbol) {
76452 for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
76453 var declaration = _e[_d];
76454 diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
76455 }
76456 }
76457 mergeSymbolTable(globals, file.locals);
76458 }
76459 if (file.jsGlobalAugmentations) {
76460 mergeSymbolTable(globals, file.jsGlobalAugmentations);
76461 }
76462 if (file.patternAmbientModules && file.patternAmbientModules.length) {
76463 patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
76464 }
76465 if (file.moduleAugmentations.length) {
76466 (augmentations || (augmentations = [])).push(file.moduleAugmentations);
76467 }
76468 if (file.symbol && file.symbol.globalExports) {
76469 // Merge in UMD exports with first-in-wins semantics (see #9771)
76470 var source = file.symbol.globalExports;
76471 source.forEach(function (sourceSymbol, id) {
76472 if (!globals.has(id)) {
76473 globals.set(id, sourceSymbol);
76474 }
76475 });
76476 }
76477 }
76478 // We do global augmentations separately from module augmentations (and before creating global types) because they
76479 // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
76480 // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
76481 // checking for an export or property on the module (if export=) which, in turn, can fall back to the
76482 // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
76483 // did module augmentations prior to finalizing the global types.
76484 if (augmentations) {
76485 // merge _global_ module augmentations.
76486 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
76487 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
76488 var list = augmentations_1[_f];
76489 for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
76490 var augmentation = list_1[_g];
76491 if (!ts.isGlobalScopeAugmentation(augmentation.parent))
76492 continue;
76493 mergeModuleAugmentation(augmentation);
76494 }
76495 }
76496 }
76497 // Setup global builtins
76498 addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
76499 getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
76500 getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
76501 getSymbolLinks(unknownSymbol).type = errorType;
76502 getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
76503 // Initialize special types
76504 globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
76505 globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
76506 globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
76507 globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
76508 globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
76509 globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
76510 globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
76511 globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
76512 globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
76513 anyArrayType = createArrayType(anyType);
76514 autoArrayType = createArrayType(autoType);
76515 if (autoArrayType === emptyObjectType) {
76516 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
76517 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
76518 }
76519 globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
76520 anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
76521 globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
76522 if (augmentations) {
76523 // merge _nonglobal_ module augmentations.
76524 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
76525 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
76526 var list = augmentations_2[_h];
76527 for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
76528 var augmentation = list_2[_j];
76529 if (ts.isGlobalScopeAugmentation(augmentation.parent))
76530 continue;
76531 mergeModuleAugmentation(augmentation);
76532 }
76533 }
76534 }
76535 amalgamatedDuplicates.forEach(function (_a) {
76536 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
76537 // If not many things conflict, issue individual errors
76538 if (conflictingSymbols.size < 8) {
76539 conflictingSymbols.forEach(function (_a, symbolName) {
76540 var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
76541 var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
76542 for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
76543 var node = firstFileLocations_1[_i];
76544 addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
76545 }
76546 for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
76547 var node = secondFileLocations_1[_b];
76548 addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
76549 }
76550 });
76551 }
76552 else {
76553 // Otherwise issue top-level error since the files appear very identical in terms of what they contain
76554 var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
76555 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)));
76556 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)));
76557 }
76558 });
76559 amalgamatedDuplicates = undefined;
76560 }
76561 function checkExternalEmitHelpers(location, helpers) {
76562 if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
76563 var sourceFile = ts.getSourceFileOfNode(location);
76564 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
76565 var helpersModule = resolveHelpersModule(sourceFile, location);
76566 if (helpersModule !== unknownSymbol) {
76567 var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
76568 for (var helper = 1 /* FirstEmitHelper */; helper <= 4194304 /* LastEmitHelper */; helper <<= 1) {
76569 if (uncheckedHelpers & helper) {
76570 var name = getHelperName(helper);
76571 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
76572 if (!symbol) {
76573 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);
76574 }
76575 }
76576 }
76577 }
76578 requestedExternalEmitHelpers |= helpers;
76579 }
76580 }
76581 }
76582 function getHelperName(helper) {
76583 switch (helper) {
76584 case 1 /* Extends */: return "__extends";
76585 case 2 /* Assign */: return "__assign";
76586 case 4 /* Rest */: return "__rest";
76587 case 8 /* Decorate */: return "__decorate";
76588 case 16 /* Metadata */: return "__metadata";
76589 case 32 /* Param */: return "__param";
76590 case 64 /* Awaiter */: return "__awaiter";
76591 case 128 /* Generator */: return "__generator";
76592 case 256 /* Values */: return "__values";
76593 case 512 /* Read */: return "__read";
76594 case 1024 /* Spread */: return "__spread";
76595 case 2048 /* SpreadArrays */: return "__spreadArrays";
76596 case 4096 /* Await */: return "__await";
76597 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
76598 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
76599 case 32768 /* AsyncValues */: return "__asyncValues";
76600 case 65536 /* ExportStar */: return "__exportStar";
76601 case 131072 /* ImportStar */: return "__importStar";
76602 case 262144 /* ImportDefault */: return "__importDefault";
76603 case 524288 /* MakeTemplateObject */: return "__makeTemplateObject";
76604 case 1048576 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
76605 case 2097152 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
76606 case 4194304 /* CreateBinding */: return "__createBinding";
76607 default: return ts.Debug.fail("Unrecognized helper");
76608 }
76609 }
76610 function resolveHelpersModule(node, errorNode) {
76611 if (!externalHelpersModule) {
76612 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
76613 }
76614 return externalHelpersModule;
76615 }
76616 // GRAMMAR CHECKING
76617 function checkGrammarDecoratorsAndModifiers(node) {
76618 return checkGrammarDecorators(node) || checkGrammarModifiers(node);
76619 }
76620 function checkGrammarDecorators(node) {
76621 if (!node.decorators) {
76622 return false;
76623 }
76624 if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
76625 if (node.kind === 164 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
76626 return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
76627 }
76628 else {
76629 return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
76630 }
76631 }
76632 else if (node.kind === 166 /* GetAccessor */ || node.kind === 167 /* SetAccessor */) {
76633 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
76634 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
76635 return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
76636 }
76637 }
76638 return false;
76639 }
76640 function checkGrammarModifiers(node) {
76641 var quickResult = reportObviousModifierErrors(node);
76642 if (quickResult !== undefined) {
76643 return quickResult;
76644 }
76645 var lastStatic, lastDeclare, lastAsync, lastReadonly;
76646 var flags = 0 /* None */;
76647 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
76648 var modifier = _a[_i];
76649 if (modifier.kind !== 141 /* ReadonlyKeyword */) {
76650 if (node.kind === 161 /* PropertySignature */ || node.kind === 163 /* MethodSignature */) {
76651 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
76652 }
76653 if (node.kind === 170 /* IndexSignature */) {
76654 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
76655 }
76656 }
76657 switch (modifier.kind) {
76658 case 84 /* ConstKeyword */:
76659 if (node.kind !== 252 /* EnumDeclaration */) {
76660 return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */));
76661 }
76662 break;
76663 case 122 /* PublicKeyword */:
76664 case 121 /* ProtectedKeyword */:
76665 case 120 /* PrivateKeyword */:
76666 var text = visibilityToString(ts.modifierToFlag(modifier.kind));
76667 if (flags & 28 /* AccessibilityModifier */) {
76668 return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
76669 }
76670 else if (flags & 32 /* Static */) {
76671 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
76672 }
76673 else if (flags & 64 /* Readonly */) {
76674 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
76675 }
76676 else if (flags & 256 /* Async */) {
76677 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
76678 }
76679 else if (node.parent.kind === 254 /* ModuleBlock */ || node.parent.kind === 294 /* SourceFile */) {
76680 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
76681 }
76682 else if (flags & 128 /* Abstract */) {
76683 if (modifier.kind === 120 /* PrivateKeyword */) {
76684 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
76685 }
76686 else {
76687 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
76688 }
76689 }
76690 else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
76691 return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
76692 }
76693 flags |= ts.modifierToFlag(modifier.kind);
76694 break;
76695 case 123 /* StaticKeyword */:
76696 if (flags & 32 /* Static */) {
76697 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
76698 }
76699 else if (flags & 64 /* Readonly */) {
76700 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
76701 }
76702 else if (flags & 256 /* Async */) {
76703 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
76704 }
76705 else if (node.parent.kind === 254 /* ModuleBlock */ || node.parent.kind === 294 /* SourceFile */) {
76706 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
76707 }
76708 else if (node.kind === 159 /* Parameter */) {
76709 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
76710 }
76711 else if (flags & 128 /* Abstract */) {
76712 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
76713 }
76714 else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
76715 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
76716 }
76717 flags |= 32 /* Static */;
76718 lastStatic = modifier;
76719 break;
76720 case 141 /* ReadonlyKeyword */:
76721 if (flags & 64 /* Readonly */) {
76722 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
76723 }
76724 else if (node.kind !== 162 /* PropertyDeclaration */ && node.kind !== 161 /* PropertySignature */ && node.kind !== 170 /* IndexSignature */ && node.kind !== 159 /* Parameter */) {
76725 // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
76726 return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
76727 }
76728 flags |= 64 /* Readonly */;
76729 lastReadonly = modifier;
76730 break;
76731 case 92 /* ExportKeyword */:
76732 if (flags & 1 /* Export */) {
76733 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
76734 }
76735 else if (flags & 2 /* Ambient */) {
76736 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
76737 }
76738 else if (flags & 128 /* Abstract */) {
76739 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
76740 }
76741 else if (flags & 256 /* Async */) {
76742 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
76743 }
76744 else if (ts.isClassLike(node.parent)) {
76745 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
76746 }
76747 else if (node.kind === 159 /* Parameter */) {
76748 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
76749 }
76750 flags |= 1 /* Export */;
76751 break;
76752 case 87 /* DefaultKeyword */:
76753 var container = node.parent.kind === 294 /* SourceFile */ ? node.parent : node.parent.parent;
76754 if (container.kind === 253 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
76755 return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
76756 }
76757 flags |= 512 /* Default */;
76758 break;
76759 case 133 /* DeclareKeyword */:
76760 if (flags & 2 /* Ambient */) {
76761 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
76762 }
76763 else if (flags & 256 /* Async */) {
76764 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
76765 }
76766 else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
76767 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
76768 }
76769 else if (node.kind === 159 /* Parameter */) {
76770 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
76771 }
76772 else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 254 /* ModuleBlock */) {
76773 return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
76774 }
76775 else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
76776 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
76777 }
76778 flags |= 2 /* Ambient */;
76779 lastDeclare = modifier;
76780 break;
76781 case 125 /* AbstractKeyword */:
76782 if (flags & 128 /* Abstract */) {
76783 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
76784 }
76785 if (node.kind !== 249 /* ClassDeclaration */) {
76786 if (node.kind !== 164 /* MethodDeclaration */ &&
76787 node.kind !== 162 /* PropertyDeclaration */ &&
76788 node.kind !== 166 /* GetAccessor */ &&
76789 node.kind !== 167 /* SetAccessor */) {
76790 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
76791 }
76792 if (!(node.parent.kind === 249 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) {
76793 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
76794 }
76795 if (flags & 32 /* Static */) {
76796 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
76797 }
76798 if (flags & 8 /* Private */) {
76799 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
76800 }
76801 }
76802 if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) {
76803 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
76804 }
76805 flags |= 128 /* Abstract */;
76806 break;
76807 case 129 /* AsyncKeyword */:
76808 if (flags & 256 /* Async */) {
76809 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
76810 }
76811 else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
76812 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
76813 }
76814 else if (node.kind === 159 /* Parameter */) {
76815 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
76816 }
76817 flags |= 256 /* Async */;
76818 lastAsync = modifier;
76819 break;
76820 }
76821 }
76822 if (node.kind === 165 /* Constructor */) {
76823 if (flags & 32 /* Static */) {
76824 return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
76825 }
76826 if (flags & 128 /* Abstract */) {
76827 return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
76828 }
76829 else if (flags & 256 /* Async */) {
76830 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
76831 }
76832 else if (flags & 64 /* Readonly */) {
76833 return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
76834 }
76835 return false;
76836 }
76837 else if ((node.kind === 258 /* ImportDeclaration */ || node.kind === 257 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
76838 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
76839 }
76840 else if (node.kind === 159 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
76841 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
76842 }
76843 else if (node.kind === 159 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
76844 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
76845 }
76846 if (flags & 256 /* Async */) {
76847 return checkGrammarAsyncModifier(node, lastAsync);
76848 }
76849 return false;
76850 }
76851 /**
76852 * true | false: Early return this value from checkGrammarModifiers.
76853 * undefined: Need to do full checking on the modifiers.
76854 */
76855 function reportObviousModifierErrors(node) {
76856 return !node.modifiers
76857 ? false
76858 : shouldReportBadModifier(node)
76859 ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
76860 : undefined;
76861 }
76862 function shouldReportBadModifier(node) {
76863 switch (node.kind) {
76864 case 166 /* GetAccessor */:
76865 case 167 /* SetAccessor */:
76866 case 165 /* Constructor */:
76867 case 162 /* PropertyDeclaration */:
76868 case 161 /* PropertySignature */:
76869 case 164 /* MethodDeclaration */:
76870 case 163 /* MethodSignature */:
76871 case 170 /* IndexSignature */:
76872 case 253 /* ModuleDeclaration */:
76873 case 258 /* ImportDeclaration */:
76874 case 257 /* ImportEqualsDeclaration */:
76875 case 264 /* ExportDeclaration */:
76876 case 263 /* ExportAssignment */:
76877 case 205 /* FunctionExpression */:
76878 case 206 /* ArrowFunction */:
76879 case 159 /* Parameter */:
76880 return false;
76881 default:
76882 if (node.parent.kind === 254 /* ModuleBlock */ || node.parent.kind === 294 /* SourceFile */) {
76883 return false;
76884 }
76885 switch (node.kind) {
76886 case 248 /* FunctionDeclaration */:
76887 return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */);
76888 case 249 /* ClassDeclaration */:
76889 return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */);
76890 case 250 /* InterfaceDeclaration */:
76891 case 229 /* VariableStatement */:
76892 case 251 /* TypeAliasDeclaration */:
76893 return true;
76894 case 252 /* EnumDeclaration */:
76895 return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */);
76896 default:
76897 ts.Debug.fail();
76898 return false;
76899 }
76900 }
76901 }
76902 function nodeHasAnyModifiersExcept(node, allowedModifier) {
76903 return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
76904 }
76905 function checkGrammarAsyncModifier(node, asyncModifier) {
76906 switch (node.kind) {
76907 case 164 /* MethodDeclaration */:
76908 case 248 /* FunctionDeclaration */:
76909 case 205 /* FunctionExpression */:
76910 case 206 /* ArrowFunction */:
76911 return false;
76912 }
76913 return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
76914 }
76915 function checkGrammarForDisallowedTrailingComma(list, diag) {
76916 if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
76917 if (list && list.hasTrailingComma) {
76918 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
76919 }
76920 return false;
76921 }
76922 function checkGrammarTypeParameterList(typeParameters, file) {
76923 if (typeParameters && typeParameters.length === 0) {
76924 var start = typeParameters.pos - "<".length;
76925 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
76926 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
76927 }
76928 return false;
76929 }
76930 function checkGrammarParameterList(parameters) {
76931 var seenOptionalParameter = false;
76932 var parameterCount = parameters.length;
76933 for (var i = 0; i < parameterCount; i++) {
76934 var parameter = parameters[i];
76935 if (parameter.dotDotDotToken) {
76936 if (i !== (parameterCount - 1)) {
76937 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
76938 }
76939 if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
76940 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
76941 }
76942 if (parameter.questionToken) {
76943 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
76944 }
76945 if (parameter.initializer) {
76946 return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
76947 }
76948 }
76949 else if (isOptionalParameter(parameter)) {
76950 seenOptionalParameter = true;
76951 if (parameter.questionToken && parameter.initializer) {
76952 return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
76953 }
76954 }
76955 else if (seenOptionalParameter && !parameter.initializer) {
76956 return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
76957 }
76958 }
76959 }
76960 function getNonSimpleParameters(parameters) {
76961 return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
76962 }
76963 function checkGrammarForUseStrictSimpleParameterList(node) {
76964 if (languageVersion >= 3 /* ES2016 */) {
76965 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
76966 if (useStrictDirective_1) {
76967 var nonSimpleParameters = getNonSimpleParameters(node.parameters);
76968 if (ts.length(nonSimpleParameters)) {
76969 ts.forEach(nonSimpleParameters, function (parameter) {
76970 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));
76971 });
76972 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)); });
76973 ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
76974 return true;
76975 }
76976 }
76977 }
76978 return false;
76979 }
76980 function checkGrammarFunctionLikeDeclaration(node) {
76981 // Prevent cascading error by short-circuit
76982 var file = ts.getSourceFileOfNode(node);
76983 return checkGrammarDecoratorsAndModifiers(node) ||
76984 checkGrammarTypeParameterList(node.typeParameters, file) ||
76985 checkGrammarParameterList(node.parameters) ||
76986 checkGrammarArrowFunction(node, file) ||
76987 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
76988 }
76989 function checkGrammarClassLikeDeclaration(node) {
76990 var file = ts.getSourceFileOfNode(node);
76991 return checkGrammarClassDeclarationHeritageClauses(node) ||
76992 checkGrammarTypeParameterList(node.typeParameters, file);
76993 }
76994 function checkGrammarArrowFunction(node, file) {
76995 if (!ts.isArrowFunction(node)) {
76996 return false;
76997 }
76998 var equalsGreaterThanToken = node.equalsGreaterThanToken;
76999 var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
77000 var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
77001 return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
77002 }
77003 function checkGrammarIndexSignatureParameters(node) {
77004 var parameter = node.parameters[0];
77005 if (node.parameters.length !== 1) {
77006 if (parameter) {
77007 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
77008 }
77009 else {
77010 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
77011 }
77012 }
77013 checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
77014 if (parameter.dotDotDotToken) {
77015 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
77016 }
77017 if (ts.hasEffectiveModifiers(parameter)) {
77018 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
77019 }
77020 if (parameter.questionToken) {
77021 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
77022 }
77023 if (parameter.initializer) {
77024 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
77025 }
77026 if (!parameter.type) {
77027 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
77028 }
77029 if (parameter.type.kind !== 146 /* StringKeyword */ && parameter.type.kind !== 143 /* NumberKeyword */) {
77030 var type = getTypeFromTypeNode(parameter.type);
77031 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
77032 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));
77033 }
77034 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
77035 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
77036 }
77037 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
77038 }
77039 if (!node.type) {
77040 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
77041 }
77042 return false;
77043 }
77044 function checkGrammarIndexSignature(node) {
77045 // Prevent cascading error by short-circuit
77046 return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
77047 }
77048 function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
77049 if (typeArguments && typeArguments.length === 0) {
77050 var sourceFile = ts.getSourceFileOfNode(node);
77051 var start = typeArguments.pos - "<".length;
77052 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
77053 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
77054 }
77055 return false;
77056 }
77057 function checkGrammarTypeArguments(node, typeArguments) {
77058 return checkGrammarForDisallowedTrailingComma(typeArguments) ||
77059 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
77060 }
77061 function checkGrammarTaggedTemplateChain(node) {
77062 if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
77063 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
77064 }
77065 return false;
77066 }
77067 function checkGrammarForOmittedArgument(args) {
77068 if (args) {
77069 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
77070 var arg = args_4[_i];
77071 if (arg.kind === 219 /* OmittedExpression */) {
77072 return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
77073 }
77074 }
77075 }
77076 return false;
77077 }
77078 function checkGrammarArguments(args) {
77079 return checkGrammarForOmittedArgument(args);
77080 }
77081 function checkGrammarHeritageClause(node) {
77082 var types = node.types;
77083 if (checkGrammarForDisallowedTrailingComma(types)) {
77084 return true;
77085 }
77086 if (types && types.length === 0) {
77087 var listType = ts.tokenToString(node.token);
77088 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
77089 }
77090 return ts.some(types, checkGrammarExpressionWithTypeArguments);
77091 }
77092 function checkGrammarExpressionWithTypeArguments(node) {
77093 return checkGrammarTypeArguments(node, node.typeArguments);
77094 }
77095 function checkGrammarClassDeclarationHeritageClauses(node) {
77096 var seenExtendsClause = false;
77097 var seenImplementsClause = false;
77098 if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
77099 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
77100 var heritageClause = _a[_i];
77101 if (heritageClause.token === 93 /* ExtendsKeyword */) {
77102 if (seenExtendsClause) {
77103 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
77104 }
77105 if (seenImplementsClause) {
77106 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
77107 }
77108 if (heritageClause.types.length > 1) {
77109 return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
77110 }
77111 seenExtendsClause = true;
77112 }
77113 else {
77114 ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
77115 if (seenImplementsClause) {
77116 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
77117 }
77118 seenImplementsClause = true;
77119 }
77120 // Grammar checking heritageClause inside class declaration
77121 checkGrammarHeritageClause(heritageClause);
77122 }
77123 }
77124 }
77125 function checkGrammarInterfaceDeclaration(node) {
77126 var seenExtendsClause = false;
77127 if (node.heritageClauses) {
77128 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
77129 var heritageClause = _a[_i];
77130 if (heritageClause.token === 93 /* ExtendsKeyword */) {
77131 if (seenExtendsClause) {
77132 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
77133 }
77134 seenExtendsClause = true;
77135 }
77136 else {
77137 ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
77138 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
77139 }
77140 // Grammar checking heritageClause inside class declaration
77141 checkGrammarHeritageClause(heritageClause);
77142 }
77143 }
77144 return false;
77145 }
77146 function checkGrammarComputedPropertyName(node) {
77147 // If node is not a computedPropertyName, just skip the grammar checking
77148 if (node.kind !== 157 /* ComputedPropertyName */) {
77149 return false;
77150 }
77151 var computedPropertyName = node;
77152 if (computedPropertyName.expression.kind === 213 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
77153 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
77154 }
77155 return false;
77156 }
77157 function checkGrammarForGenerator(node) {
77158 if (node.asteriskToken) {
77159 ts.Debug.assert(node.kind === 248 /* FunctionDeclaration */ ||
77160 node.kind === 205 /* FunctionExpression */ ||
77161 node.kind === 164 /* MethodDeclaration */);
77162 if (node.flags & 8388608 /* Ambient */) {
77163 return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
77164 }
77165 if (!node.body) {
77166 return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
77167 }
77168 }
77169 }
77170 function checkGrammarForInvalidQuestionMark(questionToken, message) {
77171 return !!questionToken && grammarErrorOnNode(questionToken, message);
77172 }
77173 function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
77174 return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
77175 }
77176 function checkGrammarObjectLiteralExpression(node, inDestructuring) {
77177 var seen = new ts.Map();
77178 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
77179 var prop = _a[_i];
77180 if (prop.kind === 287 /* SpreadAssignment */) {
77181 if (inDestructuring) {
77182 // a rest property cannot be destructured any further
77183 var expression = ts.skipParentheses(prop.expression);
77184 if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
77185 return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
77186 }
77187 }
77188 continue;
77189 }
77190 var name = prop.name;
77191 if (name.kind === 157 /* ComputedPropertyName */) {
77192 // If the name is not a ComputedPropertyName, the grammar checking will skip it
77193 checkGrammarComputedPropertyName(name);
77194 }
77195 if (prop.kind === 286 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
77196 // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
77197 // outside of destructuring it is a syntax error
77198 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);
77199 }
77200 if (name.kind === 79 /* PrivateIdentifier */) {
77201 return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
77202 }
77203 // Modifiers are never allowed on properties except for 'async' on a method declaration
77204 if (prop.modifiers) {
77205 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
77206 for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
77207 var mod = _c[_b];
77208 if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 164 /* MethodDeclaration */) {
77209 grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
77210 }
77211 }
77212 }
77213 // ECMA-262 11.1.5 Object Initializer
77214 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
77215 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
77216 // IsDataDescriptor(propId.descriptor) is true.
77217 // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
77218 // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
77219 // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
77220 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
77221 var currentKind = void 0;
77222 switch (prop.kind) {
77223 case 286 /* ShorthandPropertyAssignment */:
77224 checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
77225 // falls through
77226 case 285 /* PropertyAssignment */:
77227 // Grammar checking for computedPropertyName and shorthandPropertyAssignment
77228 checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
77229 if (name.kind === 8 /* NumericLiteral */) {
77230 checkGrammarNumericLiteral(name);
77231 }
77232 currentKind = 4 /* PropertyAssignment */;
77233 break;
77234 case 164 /* MethodDeclaration */:
77235 currentKind = 8 /* Method */;
77236 break;
77237 case 166 /* GetAccessor */:
77238 currentKind = 1 /* GetAccessor */;
77239 break;
77240 case 167 /* SetAccessor */:
77241 currentKind = 2 /* SetAccessor */;
77242 break;
77243 default:
77244 throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
77245 }
77246 if (!inDestructuring) {
77247 var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
77248 if (effectiveName === undefined) {
77249 continue;
77250 }
77251 var existingKind = seen.get(effectiveName);
77252 if (!existingKind) {
77253 seen.set(effectiveName, currentKind);
77254 }
77255 else {
77256 if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
77257 grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
77258 }
77259 else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
77260 if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
77261 seen.set(effectiveName, currentKind | existingKind);
77262 }
77263 else {
77264 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
77265 }
77266 }
77267 else {
77268 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
77269 }
77270 }
77271 }
77272 }
77273 }
77274 function checkGrammarJsxElement(node) {
77275 checkGrammarTypeArguments(node, node.typeArguments);
77276 var seen = new ts.Map();
77277 for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
77278 var attr = _a[_i];
77279 if (attr.kind === 279 /* JsxSpreadAttribute */) {
77280 continue;
77281 }
77282 var name = attr.name, initializer = attr.initializer;
77283 if (!seen.get(name.escapedText)) {
77284 seen.set(name.escapedText, true);
77285 }
77286 else {
77287 return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
77288 }
77289 if (initializer && initializer.kind === 280 /* JsxExpression */ && !initializer.expression) {
77290 return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
77291 }
77292 }
77293 }
77294 function checkGrammarJsxExpression(node) {
77295 if (node.expression && ts.isCommaSequence(node.expression)) {
77296 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
77297 }
77298 }
77299 function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
77300 if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
77301 return true;
77302 }
77303 if (forInOrOfStatement.kind === 236 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
77304 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
77305 // use of 'for-await-of' in non-async function
77306 var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
77307 if (!hasParseDiagnostics(sourceFile)) {
77308 var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
77309 var func = ts.getContainingFunction(forInOrOfStatement);
77310 if (func && func.kind !== 165 /* Constructor */) {
77311 ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
77312 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
77313 ts.addRelatedInfo(diagnostic, relatedInfo);
77314 }
77315 diagnostics.add(diagnostic);
77316 return true;
77317 }
77318 return false;
77319 }
77320 }
77321 if (forInOrOfStatement.initializer.kind === 247 /* VariableDeclarationList */) {
77322 var variableList = forInOrOfStatement.initializer;
77323 if (!checkGrammarVariableDeclarationList(variableList)) {
77324 var declarations = variableList.declarations;
77325 // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
77326 // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
77327 // For example:
77328 // var let = 10;
77329 // for (let of [1,2,3]) {} // this is invalid ES6 syntax
77330 // for (let in [1,2,3]) {} // this is invalid ES6 syntax
77331 // We will then want to skip on grammar checking on variableList declaration
77332 if (!declarations.length) {
77333 return false;
77334 }
77335 if (declarations.length > 1) {
77336 var diagnostic = forInOrOfStatement.kind === 235 /* ForInStatement */
77337 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
77338 : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
77339 return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
77340 }
77341 var firstDeclaration = declarations[0];
77342 if (firstDeclaration.initializer) {
77343 var diagnostic = forInOrOfStatement.kind === 235 /* ForInStatement */
77344 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
77345 : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
77346 return grammarErrorOnNode(firstDeclaration.name, diagnostic);
77347 }
77348 if (firstDeclaration.type) {
77349 var diagnostic = forInOrOfStatement.kind === 235 /* ForInStatement */
77350 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
77351 : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
77352 return grammarErrorOnNode(firstDeclaration, diagnostic);
77353 }
77354 }
77355 }
77356 return false;
77357 }
77358 function checkGrammarAccessor(accessor) {
77359 if (!(accessor.flags & 8388608 /* Ambient */)) {
77360 if (languageVersion < 1 /* ES5 */) {
77361 return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
77362 }
77363 if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
77364 return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
77365 }
77366 }
77367 if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
77368 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
77369 }
77370 if (accessor.typeParameters) {
77371 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
77372 }
77373 if (!doesAccessorHaveCorrectParameterCount(accessor)) {
77374 return grammarErrorOnNode(accessor.name, accessor.kind === 166 /* GetAccessor */ ?
77375 ts.Diagnostics.A_get_accessor_cannot_have_parameters :
77376 ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
77377 }
77378 if (accessor.kind === 167 /* SetAccessor */) {
77379 if (accessor.type) {
77380 return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
77381 }
77382 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
77383 if (parameter.dotDotDotToken) {
77384 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
77385 }
77386 if (parameter.questionToken) {
77387 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
77388 }
77389 if (parameter.initializer) {
77390 return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
77391 }
77392 }
77393 return false;
77394 }
77395 /** Does the accessor have the right number of parameters?
77396 * A get accessor has no parameters or a single `this` parameter.
77397 * A set accessor has one parameter or a `this` parameter and one more parameter.
77398 */
77399 function doesAccessorHaveCorrectParameterCount(accessor) {
77400 return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 166 /* GetAccessor */ ? 0 : 1);
77401 }
77402 function getAccessorThisParameter(accessor) {
77403 if (accessor.parameters.length === (accessor.kind === 166 /* GetAccessor */ ? 1 : 2)) {
77404 return ts.getThisParameter(accessor);
77405 }
77406 }
77407 function checkGrammarTypeOperatorNode(node) {
77408 if (node.operator === 150 /* UniqueKeyword */) {
77409 if (node.type.kind !== 147 /* SymbolKeyword */) {
77410 return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(147 /* SymbolKeyword */));
77411 }
77412 var parent = ts.walkUpParenthesizedTypes(node.parent);
77413 if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) {
77414 parent = parent.parent;
77415 if (ts.isJSDocTypeTag(parent)) {
77416 // walk up past JSDoc comment node
77417 parent = parent.parent.parent;
77418 }
77419 }
77420 switch (parent.kind) {
77421 case 246 /* VariableDeclaration */:
77422 var decl = parent;
77423 if (decl.name.kind !== 78 /* Identifier */) {
77424 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
77425 }
77426 if (!ts.isVariableDeclarationInVariableStatement(decl)) {
77427 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
77428 }
77429 if (!(decl.parent.flags & 2 /* Const */)) {
77430 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
77431 }
77432 break;
77433 case 162 /* PropertyDeclaration */:
77434 if (!ts.hasSyntacticModifier(parent, 32 /* Static */) ||
77435 !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) {
77436 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
77437 }
77438 break;
77439 case 161 /* PropertySignature */:
77440 if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) {
77441 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
77442 }
77443 break;
77444 default:
77445 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
77446 }
77447 }
77448 else if (node.operator === 141 /* ReadonlyKeyword */) {
77449 if (node.type.kind !== 177 /* ArrayType */ && node.type.kind !== 178 /* TupleType */) {
77450 return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(147 /* SymbolKeyword */));
77451 }
77452 }
77453 }
77454 function checkGrammarForInvalidDynamicName(node, message) {
77455 if (isNonBindableDynamicName(node)) {
77456 return grammarErrorOnNode(node, message);
77457 }
77458 }
77459 function checkGrammarMethod(node) {
77460 if (checkGrammarFunctionLikeDeclaration(node)) {
77461 return true;
77462 }
77463 if (node.kind === 164 /* MethodDeclaration */) {
77464 if (node.parent.kind === 197 /* ObjectLiteralExpression */) {
77465 // We only disallow modifier on a method declaration if it is a property of object-literal-expression
77466 if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) {
77467 return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
77468 }
77469 else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
77470 return true;
77471 }
77472 else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
77473 return true;
77474 }
77475 else if (node.body === undefined) {
77476 return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
77477 }
77478 }
77479 if (checkGrammarForGenerator(node)) {
77480 return true;
77481 }
77482 }
77483 if (ts.isClassLike(node.parent)) {
77484 // Technically, computed properties in ambient contexts is disallowed
77485 // for property declarations and accessors too, not just methods.
77486 // However, property declarations disallow computed names in general,
77487 // and accessors are not allowed in ambient contexts in general,
77488 // so this error only really matters for methods.
77489 if (node.flags & 8388608 /* Ambient */) {
77490 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);
77491 }
77492 else if (node.kind === 164 /* MethodDeclaration */ && !node.body) {
77493 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);
77494 }
77495 }
77496 else if (node.parent.kind === 250 /* InterfaceDeclaration */) {
77497 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);
77498 }
77499 else if (node.parent.kind === 176 /* TypeLiteral */) {
77500 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);
77501 }
77502 }
77503 function checkGrammarBreakOrContinueStatement(node) {
77504 var current = node;
77505 while (current) {
77506 if (ts.isFunctionLike(current)) {
77507 return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
77508 }
77509 switch (current.kind) {
77510 case 242 /* LabeledStatement */:
77511 if (node.label && current.label.escapedText === node.label.escapedText) {
77512 // found matching label - verify that label usage is correct
77513 // continue can only target labels that are on iteration statements
77514 var isMisplacedContinueLabel = node.kind === 237 /* ContinueStatement */
77515 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
77516 if (isMisplacedContinueLabel) {
77517 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
77518 }
77519 return false;
77520 }
77521 break;
77522 case 241 /* SwitchStatement */:
77523 if (node.kind === 238 /* BreakStatement */ && !node.label) {
77524 // unlabeled break within switch statement - ok
77525 return false;
77526 }
77527 break;
77528 default:
77529 if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
77530 // unlabeled break or continue within iteration statement - ok
77531 return false;
77532 }
77533 break;
77534 }
77535 current = current.parent;
77536 }
77537 if (node.label) {
77538 var message = node.kind === 238 /* BreakStatement */
77539 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
77540 : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
77541 return grammarErrorOnNode(node, message);
77542 }
77543 else {
77544 var message = node.kind === 238 /* BreakStatement */
77545 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
77546 : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
77547 return grammarErrorOnNode(node, message);
77548 }
77549 }
77550 function checkGrammarBindingElement(node) {
77551 if (node.dotDotDotToken) {
77552 var elements = node.parent.elements;
77553 if (node !== ts.last(elements)) {
77554 return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
77555 }
77556 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
77557 if (node.propertyName) {
77558 return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
77559 }
77560 }
77561 if (node.dotDotDotToken && node.initializer) {
77562 // Error on equals token which immediately precedes the initializer
77563 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
77564 }
77565 }
77566 function isStringOrNumberLiteralExpression(expr) {
77567 return ts.isStringOrNumericLiteralLike(expr) ||
77568 expr.kind === 211 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
77569 expr.operand.kind === 8 /* NumericLiteral */;
77570 }
77571 function isBigIntLiteralExpression(expr) {
77572 return expr.kind === 9 /* BigIntLiteral */ ||
77573 expr.kind === 211 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
77574 expr.operand.kind === 9 /* BigIntLiteral */;
77575 }
77576 function isSimpleLiteralEnumReference(expr) {
77577 if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
77578 ts.isEntityNameExpression(expr.expression)) {
77579 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
77580 }
77581 }
77582 function checkAmbientInitializer(node) {
77583 var initializer = node.initializer;
77584 if (initializer) {
77585 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
77586 isSimpleLiteralEnumReference(initializer) ||
77587 initializer.kind === 109 /* TrueKeyword */ || initializer.kind === 94 /* FalseKeyword */ ||
77588 isBigIntLiteralExpression(initializer));
77589 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
77590 if (isConstOrReadonly && !node.type) {
77591 if (isInvalidInitializer) {
77592 return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
77593 }
77594 }
77595 else {
77596 return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
77597 }
77598 if (!isConstOrReadonly || isInvalidInitializer) {
77599 return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
77600 }
77601 }
77602 }
77603 function checkGrammarVariableDeclaration(node) {
77604 if (node.parent.parent.kind !== 235 /* ForInStatement */ && node.parent.parent.kind !== 236 /* ForOfStatement */) {
77605 if (node.flags & 8388608 /* Ambient */) {
77606 checkAmbientInitializer(node);
77607 }
77608 else if (!node.initializer) {
77609 if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
77610 return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
77611 }
77612 if (ts.isVarConst(node)) {
77613 return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
77614 }
77615 }
77616 }
77617 if (node.exclamationToken && (node.parent.parent.kind !== 229 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
77618 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
77619 }
77620 var moduleKind = ts.getEmitModuleKind(compilerOptions);
77621 if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System &&
77622 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
77623 checkESModuleMarker(node.name);
77624 }
77625 var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
77626 // 1. LexicalDeclaration : LetOrConst BindingList ;
77627 // It is a Syntax Error if the BoundNames of BindingList contains "let".
77628 // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
77629 // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
77630 // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
77631 // and its Identifier is eval or arguments
77632 return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
77633 }
77634 function checkESModuleMarker(name) {
77635 if (name.kind === 78 /* Identifier */) {
77636 if (ts.idText(name) === "__esModule") {
77637 return grammarErrorOnNodeSkippedOn("noEmit", name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
77638 }
77639 }
77640 else {
77641 var elements = name.elements;
77642 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
77643 var element = elements_1[_i];
77644 if (!ts.isOmittedExpression(element)) {
77645 return checkESModuleMarker(element.name);
77646 }
77647 }
77648 }
77649 return false;
77650 }
77651 function checkGrammarNameInLetOrConstDeclarations(name) {
77652 if (name.kind === 78 /* Identifier */) {
77653 if (name.originalKeywordKind === 118 /* LetKeyword */) {
77654 return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
77655 }
77656 }
77657 else {
77658 var elements = name.elements;
77659 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
77660 var element = elements_2[_i];
77661 if (!ts.isOmittedExpression(element)) {
77662 checkGrammarNameInLetOrConstDeclarations(element.name);
77663 }
77664 }
77665 }
77666 return false;
77667 }
77668 function checkGrammarVariableDeclarationList(declarationList) {
77669 var declarations = declarationList.declarations;
77670 if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
77671 return true;
77672 }
77673 if (!declarationList.declarations.length) {
77674 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
77675 }
77676 return false;
77677 }
77678 function allowLetAndConstDeclarations(parent) {
77679 switch (parent.kind) {
77680 case 231 /* IfStatement */:
77681 case 232 /* DoStatement */:
77682 case 233 /* WhileStatement */:
77683 case 240 /* WithStatement */:
77684 case 234 /* ForStatement */:
77685 case 235 /* ForInStatement */:
77686 case 236 /* ForOfStatement */:
77687 return false;
77688 case 242 /* LabeledStatement */:
77689 return allowLetAndConstDeclarations(parent.parent);
77690 }
77691 return true;
77692 }
77693 function checkGrammarForDisallowedLetOrConstStatement(node) {
77694 if (!allowLetAndConstDeclarations(node.parent)) {
77695 if (ts.isLet(node.declarationList)) {
77696 return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
77697 }
77698 else if (ts.isVarConst(node.declarationList)) {
77699 return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
77700 }
77701 }
77702 }
77703 function checkGrammarMetaProperty(node) {
77704 var escapedText = node.name.escapedText;
77705 switch (node.keywordToken) {
77706 case 102 /* NewKeyword */:
77707 if (escapedText !== "target") {
77708 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");
77709 }
77710 break;
77711 case 99 /* ImportKeyword */:
77712 if (escapedText !== "meta") {
77713 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");
77714 }
77715 break;
77716 }
77717 }
77718 function hasParseDiagnostics(sourceFile) {
77719 return sourceFile.parseDiagnostics.length > 0;
77720 }
77721 function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
77722 var sourceFile = ts.getSourceFileOfNode(node);
77723 if (!hasParseDiagnostics(sourceFile)) {
77724 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
77725 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
77726 return true;
77727 }
77728 return false;
77729 }
77730 function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
77731 var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
77732 if (!hasParseDiagnostics(sourceFile)) {
77733 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
77734 return true;
77735 }
77736 return false;
77737 }
77738 function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) {
77739 var sourceFile = ts.getSourceFileOfNode(node);
77740 if (!hasParseDiagnostics(sourceFile)) {
77741 errorSkippedOn(key, node, message, arg0, arg1, arg2);
77742 return true;
77743 }
77744 return false;
77745 }
77746 function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
77747 var sourceFile = ts.getSourceFileOfNode(node);
77748 if (!hasParseDiagnostics(sourceFile)) {
77749 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
77750 return true;
77751 }
77752 return false;
77753 }
77754 function checkGrammarConstructorTypeParameters(node) {
77755 var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
77756 var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
77757 if (range) {
77758 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
77759 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
77760 }
77761 }
77762 function checkGrammarConstructorTypeAnnotation(node) {
77763 var type = ts.getEffectiveReturnTypeNode(node);
77764 if (type) {
77765 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
77766 }
77767 }
77768 function checkGrammarProperty(node) {
77769 if (ts.isClassLike(node.parent)) {
77770 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
77771 return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
77772 }
77773 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)) {
77774 return true;
77775 }
77776 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
77777 return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
77778 }
77779 }
77780 else if (node.parent.kind === 250 /* InterfaceDeclaration */) {
77781 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)) {
77782 return true;
77783 }
77784 if (node.initializer) {
77785 return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
77786 }
77787 }
77788 else if (node.parent.kind === 176 /* TypeLiteral */) {
77789 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)) {
77790 return true;
77791 }
77792 if (node.initializer) {
77793 return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
77794 }
77795 }
77796 if (node.flags & 8388608 /* Ambient */) {
77797 checkAmbientInitializer(node);
77798 }
77799 if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
77800 node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
77801 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
77802 }
77803 }
77804 function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
77805 // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
77806 // interfaces and imports categories:
77807 //
77808 // DeclarationElement:
77809 // ExportAssignment
77810 // export_opt InterfaceDeclaration
77811 // export_opt TypeAliasDeclaration
77812 // export_opt ImportDeclaration
77813 // export_opt ExternalImportDeclaration
77814 // export_opt AmbientDeclaration
77815 //
77816 // TODO: The spec needs to be amended to reflect this grammar.
77817 if (node.kind === 250 /* InterfaceDeclaration */ ||
77818 node.kind === 251 /* TypeAliasDeclaration */ ||
77819 node.kind === 258 /* ImportDeclaration */ ||
77820 node.kind === 257 /* ImportEqualsDeclaration */ ||
77821 node.kind === 264 /* ExportDeclaration */ ||
77822 node.kind === 263 /* ExportAssignment */ ||
77823 node.kind === 256 /* NamespaceExportDeclaration */ ||
77824 ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
77825 return false;
77826 }
77827 return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
77828 }
77829 function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
77830 for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
77831 var decl = _a[_i];
77832 if (ts.isDeclaration(decl) || decl.kind === 229 /* VariableStatement */) {
77833 if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
77834 return true;
77835 }
77836 }
77837 }
77838 return false;
77839 }
77840 function checkGrammarSourceFile(node) {
77841 return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
77842 }
77843 function checkGrammarStatementInAmbientContext(node) {
77844 if (node.flags & 8388608 /* Ambient */) {
77845 // Find containing block which is either Block, ModuleBlock, SourceFile
77846 var links = getNodeLinks(node);
77847 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
77848 return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
77849 }
77850 // We are either parented by another statement, or some sort of block.
77851 // If we're in a block, we only want to really report an error once
77852 // to prevent noisiness. So use a bit on the block to indicate if
77853 // this has already been reported, and don't report if it has.
77854 //
77855 if (node.parent.kind === 227 /* Block */ || node.parent.kind === 254 /* ModuleBlock */ || node.parent.kind === 294 /* SourceFile */) {
77856 var links_2 = getNodeLinks(node.parent);
77857 // Check if the containing block ever report this error
77858 if (!links_2.hasReportedStatementInAmbientContext) {
77859 return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
77860 }
77861 }
77862 else {
77863 // We must be parented by a statement. If so, there's no need
77864 // to report the error as our parent will have already done it.
77865 // Debug.assert(isStatement(node.parent));
77866 }
77867 }
77868 return false;
77869 }
77870 function checkGrammarNumericLiteral(node) {
77871 // Grammar checking
77872 if (node.numericLiteralFlags & 32 /* Octal */) {
77873 var diagnosticMessage = void 0;
77874 if (languageVersion >= 1 /* ES5 */) {
77875 diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
77876 }
77877 else if (ts.isChildOfNodeWithKind(node, 190 /* LiteralType */)) {
77878 diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
77879 }
77880 else if (ts.isChildOfNodeWithKind(node, 288 /* EnumMember */)) {
77881 diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
77882 }
77883 if (diagnosticMessage) {
77884 var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
77885 var literal = (withMinus ? "-" : "") + "0o" + node.text;
77886 return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
77887 }
77888 }
77889 // Realism (size) checking
77890 checkNumericLiteralValueSize(node);
77891 return false;
77892 }
77893 function checkNumericLiteralValueSize(node) {
77894 // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
77895 // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
77896 // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
77897 if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
77898 return;
77899 }
77900 // We can't rely on the runtime to accurately store and compare extremely large numeric values
77901 // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
77902 // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
77903 // it's likely addition operations on it will fail too
77904 var apparentValue = +ts.getTextOfNode(node);
77905 if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
77906 return;
77907 }
77908 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));
77909 }
77910 function checkGrammarBigIntLiteral(node) {
77911 var literalType = ts.isLiteralTypeNode(node.parent) ||
77912 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
77913 if (!literalType) {
77914 if (languageVersion < 7 /* ES2020 */) {
77915 if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
77916 return true;
77917 }
77918 }
77919 }
77920 return false;
77921 }
77922 function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
77923 var sourceFile = ts.getSourceFileOfNode(node);
77924 if (!hasParseDiagnostics(sourceFile)) {
77925 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
77926 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
77927 return true;
77928 }
77929 return false;
77930 }
77931 function getAmbientModules() {
77932 if (!ambientModulesCache) {
77933 ambientModulesCache = [];
77934 globals.forEach(function (global, sym) {
77935 // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
77936 if (ambientModuleSymbolRegex.test(sym)) {
77937 ambientModulesCache.push(global);
77938 }
77939 });
77940 }
77941 return ambientModulesCache;
77942 }
77943 function checkGrammarImportClause(node) {
77944 if (node.isTypeOnly && node.name && node.namedBindings) {
77945 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
77946 }
77947 return false;
77948 }
77949 function checkGrammarImportCallExpression(node) {
77950 if (moduleKind === ts.ModuleKind.ES2015) {
77951 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
77952 }
77953 if (node.typeArguments) {
77954 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
77955 }
77956 var nodeArguments = node.arguments;
77957 if (nodeArguments.length !== 1) {
77958 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
77959 }
77960 checkGrammarForDisallowedTrailingComma(nodeArguments);
77961 // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
77962 // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
77963 if (ts.isSpreadElement(nodeArguments[0])) {
77964 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
77965 }
77966 return false;
77967 }
77968 function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
77969 var sourceObjectFlags = ts.getObjectFlags(source);
77970 if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
77971 return ts.find(unionTarget.types, function (target) {
77972 if (target.flags & 524288 /* Object */) {
77973 var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
77974 if (overlapObjFlags & 4 /* Reference */) {
77975 return source.target === target.target;
77976 }
77977 if (overlapObjFlags & 16 /* Anonymous */) {
77978 return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
77979 }
77980 }
77981 return false;
77982 });
77983 }
77984 }
77985 function findBestTypeForObjectLiteral(source, unionTarget) {
77986 if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
77987 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
77988 }
77989 }
77990 function findBestTypeForInvokable(source, unionTarget) {
77991 var signatureKind = 0 /* Call */;
77992 var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
77993 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
77994 if (hasSignatures) {
77995 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
77996 }
77997 }
77998 function findMostOverlappyType(source, unionTarget) {
77999 var bestMatch;
78000 var matchingCount = 0;
78001 for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
78002 var target = _a[_i];
78003 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
78004 if (overlap.flags & 4194304 /* Index */) {
78005 // perfect overlap of keys
78006 bestMatch = target;
78007 matchingCount = Infinity;
78008 }
78009 else if (overlap.flags & 1048576 /* Union */) {
78010 // We only want to account for literal types otherwise.
78011 // If we have a union of index types, it seems likely that we
78012 // needed to elaborate between two generic mapped types anyway.
78013 var len = ts.length(ts.filter(overlap.types, isUnitType));
78014 if (len >= matchingCount) {
78015 bestMatch = target;
78016 matchingCount = len;
78017 }
78018 }
78019 else if (isUnitType(overlap) && 1 >= matchingCount) {
78020 bestMatch = target;
78021 matchingCount = 1;
78022 }
78023 }
78024 return bestMatch;
78025 }
78026 function filterPrimitivesIfContainsNonPrimitive(type) {
78027 if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
78028 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
78029 if (!(result.flags & 131072 /* Never */)) {
78030 return result;
78031 }
78032 }
78033 return type;
78034 }
78035 // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
78036 function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
78037 if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
78038 var sourceProperties = getPropertiesOfType(source);
78039 if (sourceProperties) {
78040 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
78041 if (sourcePropertiesFiltered) {
78042 return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
78043 }
78044 }
78045 }
78046 return undefined;
78047 }
78048 }
78049 ts.createTypeChecker = createTypeChecker;
78050 function isNotAccessor(declaration) {
78051 // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
78052 return !ts.isAccessor(declaration);
78053 }
78054 function isNotOverload(declaration) {
78055 return (declaration.kind !== 248 /* FunctionDeclaration */ && declaration.kind !== 164 /* MethodDeclaration */) ||
78056 !!declaration.body;
78057 }
78058 /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
78059 function isDeclarationNameOrImportPropertyName(name) {
78060 switch (name.parent.kind) {
78061 case 262 /* ImportSpecifier */:
78062 case 267 /* ExportSpecifier */:
78063 return ts.isIdentifier(name);
78064 default:
78065 return ts.isDeclarationName(name);
78066 }
78067 }
78068 function isSomeImportDeclaration(decl) {
78069 switch (decl.kind) {
78070 case 259 /* ImportClause */: // For default import
78071 case 257 /* ImportEqualsDeclaration */:
78072 case 260 /* NamespaceImport */:
78073 case 262 /* ImportSpecifier */: // For rename import `x as y`
78074 return true;
78075 case 78 /* Identifier */:
78076 // For regular import, `decl` is an Identifier under the ImportSpecifier.
78077 return decl.parent.kind === 262 /* ImportSpecifier */;
78078 default:
78079 return false;
78080 }
78081 }
78082 var JsxNames;
78083 (function (JsxNames) {
78084 JsxNames.JSX = "JSX";
78085 JsxNames.IntrinsicElements = "IntrinsicElements";
78086 JsxNames.ElementClass = "ElementClass";
78087 JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
78088 JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
78089 JsxNames.Element = "Element";
78090 JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
78091 JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
78092 JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
78093 })(JsxNames || (JsxNames = {}));
78094 function getIterationTypesKeyFromIterationTypeKind(typeKind) {
78095 switch (typeKind) {
78096 case 0 /* Yield */: return "yieldType";
78097 case 1 /* Return */: return "returnType";
78098 case 2 /* Next */: return "nextType";
78099 }
78100 }
78101 function signatureHasRestParameter(s) {
78102 return !!(s.flags & 1 /* HasRestParameter */);
78103 }
78104 ts.signatureHasRestParameter = signatureHasRestParameter;
78105 function signatureHasLiteralTypes(s) {
78106 return !!(s.flags & 2 /* HasLiteralTypes */);
78107 }
78108 ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
78109})(ts || (ts = {}));
78110var ts;
78111(function (ts) {
78112 var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
78113 function visitNode(node, visitor, test, lift) {
78114 if (node === undefined || visitor === undefined) {
78115 return node;
78116 }
78117 var visited = visitor(node);
78118 if (visited === node) {
78119 return node;
78120 }
78121 var visitedNode;
78122 if (visited === undefined) {
78123 return undefined;
78124 }
78125 else if (ts.isArray(visited)) {
78126 visitedNode = (lift || extractSingleNode)(visited);
78127 }
78128 else {
78129 visitedNode = visited;
78130 }
78131 ts.Debug.assertNode(visitedNode, test);
78132 return visitedNode;
78133 }
78134 ts.visitNode = visitNode;
78135 /**
78136 * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
78137 *
78138 * @param nodes The NodeArray to visit.
78139 * @param visitor The callback used to visit a Node.
78140 * @param test A node test to execute for each node.
78141 * @param start An optional value indicating the starting offset at which to start visiting.
78142 * @param count An optional value indicating the maximum number of nodes to visit.
78143 */
78144 function visitNodes(nodes, visitor, test, start, count) {
78145 if (nodes === undefined || visitor === undefined) {
78146 return nodes;
78147 }
78148 var updated;
78149 // Ensure start and count have valid values
78150 var length = nodes.length;
78151 if (start === undefined || start < 0) {
78152 start = 0;
78153 }
78154 if (count === undefined || count > length - start) {
78155 count = length - start;
78156 }
78157 var hasTrailingComma;
78158 var pos = -1;
78159 var end = -1;
78160 if (start > 0 || count < length) {
78161 // If we are not visiting all of the original nodes, we must always create a new array.
78162 // Since this is a fragment of a node array, we do not copy over the previous location
78163 // and will only copy over `hasTrailingComma` if we are including the last element.
78164 updated = [];
78165 hasTrailingComma = nodes.hasTrailingComma && start + count === length;
78166 }
78167 // Visit each original node.
78168 for (var i = 0; i < count; i++) {
78169 var node = nodes[i + start];
78170 var visited = node !== undefined ? visitor(node) : undefined;
78171 if (updated !== undefined || visited === undefined || visited !== node) {
78172 if (updated === undefined) {
78173 // Ensure we have a copy of `nodes`, up to the current index.
78174 updated = nodes.slice(0, i);
78175 hasTrailingComma = nodes.hasTrailingComma;
78176 pos = nodes.pos;
78177 end = nodes.end;
78178 }
78179 if (visited) {
78180 if (ts.isArray(visited)) {
78181 for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
78182 var visitedNode = visited_1[_i];
78183 void ts.Debug.assertNode(visitedNode, test);
78184 updated.push(visitedNode);
78185 }
78186 }
78187 else {
78188 void ts.Debug.assertNode(visited, test);
78189 updated.push(visited);
78190 }
78191 }
78192 }
78193 }
78194 if (updated) {
78195 // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory.
78196 var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma);
78197 ts.setTextRangePosEnd(updatedArray, pos, end);
78198 return updatedArray;
78199 }
78200 return nodes;
78201 }
78202 ts.visitNodes = visitNodes;
78203 /**
78204 * Starts a new lexical environment and visits a statement list, ending the lexical environment
78205 * and merging hoisted declarations upon completion.
78206 */
78207 function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) {
78208 if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
78209 context.startLexicalEnvironment();
78210 statements = nodesVisitor(statements, visitor, ts.isStatement, start);
78211 if (ensureUseStrict)
78212 statements = context.factory.ensureUseStrict(statements);
78213 return ts.factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
78214 }
78215 ts.visitLexicalEnvironment = visitLexicalEnvironment;
78216 function visitParameterList(nodes, visitor, context, nodesVisitor) {
78217 if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
78218 var updated;
78219 context.startLexicalEnvironment();
78220 if (nodes) {
78221 context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
78222 updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
78223 // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
78224 // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
78225 // that we might transform that introduces a temporary variable would fail as the temporary variable
78226 // exists in a different lexical scope. To address this, we move any binding patterns and initializers
78227 // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
78228 // when the emit target is greater than ES2015.
78229 if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
78230 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
78231 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
78232 }
78233 context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
78234 }
78235 context.suspendLexicalEnvironment();
78236 return updated;
78237 }
78238 ts.visitParameterList = visitParameterList;
78239 function addDefaultValueAssignmentsIfNeeded(parameters, context) {
78240 var result;
78241 for (var i = 0; i < parameters.length; i++) {
78242 var parameter = parameters[i];
78243 var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
78244 if (result || updated !== parameter) {
78245 if (!result)
78246 result = parameters.slice(0, i);
78247 result[i] = updated;
78248 }
78249 }
78250 if (result) {
78251 return ts.setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
78252 }
78253 return parameters;
78254 }
78255 function addDefaultValueAssignmentIfNeeded(parameter, context) {
78256 // A rest parameter cannot have a binding pattern or an initializer,
78257 // so let's just ignore it.
78258 return parameter.dotDotDotToken ? parameter :
78259 ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
78260 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
78261 parameter;
78262 }
78263 function addDefaultValueAssignmentForBindingPattern(parameter, context) {
78264 var factory = context.factory;
78265 context.addInitializationStatement(factory.createVariableStatement(
78266 /*modifiers*/ undefined, factory.createVariableDeclarationList([
78267 factory.createVariableDeclaration(parameter.name,
78268 /*exclamationToken*/ undefined, parameter.type, parameter.initializer ?
78269 factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()),
78270 /*questionToken*/ undefined, parameter.initializer,
78271 /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) :
78272 factory.getGeneratedNameForNode(parameter)),
78273 ])));
78274 return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type,
78275 /*initializer*/ undefined);
78276 }
78277 function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
78278 var factory = context.factory;
78279 context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
78280 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 */))
78281 ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
78282 return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type,
78283 /*initializer*/ undefined);
78284 }
78285 function visitFunctionBody(node, visitor, context, nodeVisitor) {
78286 if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
78287 context.resumeLexicalEnvironment();
78288 var updated = nodeVisitor(node, visitor, ts.isConciseBody);
78289 var declarations = context.endLexicalEnvironment();
78290 if (ts.some(declarations)) {
78291 if (!updated) {
78292 return context.factory.createBlock(declarations);
78293 }
78294 var block = context.factory.converters.convertToFunctionBlock(updated);
78295 var statements = ts.factory.mergeLexicalEnvironment(block.statements, declarations);
78296 return context.factory.updateBlock(block, statements);
78297 }
78298 return updated;
78299 }
78300 ts.visitFunctionBody = visitFunctionBody;
78301 function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) {
78302 if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
78303 if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
78304 if (node === undefined) {
78305 return undefined;
78306 }
78307 var kind = node.kind;
78308 // No need to visit nodes with no children.
78309 if ((kind > 0 /* FirstToken */ && kind <= 155 /* LastToken */) || kind === 186 /* ThisType */) {
78310 return node;
78311 }
78312 var factory = context.factory;
78313 switch (kind) {
78314 // Names
78315 case 78 /* Identifier */:
78316 return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
78317 case 156 /* QualifiedName */:
78318 return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier));
78319 case 157 /* ComputedPropertyName */:
78320 return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78321 // Signature elements
78322 case 158 /* TypeParameter */:
78323 return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode));
78324 case 159 /* Parameter */:
78325 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));
78326 case 160 /* Decorator */:
78327 return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78328 // Type elements
78329 case 161 /* PropertySignature */:
78330 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));
78331 case 162 /* PropertyDeclaration */:
78332 return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName),
78333 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
78334 nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
78335 case 163 /* MethodSignature */:
78336 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));
78337 case 164 /* MethodDeclaration */:
78338 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));
78339 case 165 /* Constructor */:
78340 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));
78341 case 166 /* GetAccessor */:
78342 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));
78343 case 167 /* SetAccessor */:
78344 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));
78345 case 168 /* CallSignature */:
78346 return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
78347 case 169 /* ConstructSignature */:
78348 return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
78349 case 170 /* IndexSignature */:
78350 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));
78351 // Types
78352 case 171 /* TypePredicate */:
78353 return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode));
78354 case 172 /* TypeReference */:
78355 return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
78356 case 173 /* FunctionType */:
78357 return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
78358 case 174 /* ConstructorType */:
78359 return factory.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
78360 case 175 /* TypeQuery */:
78361 return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
78362 case 176 /* TypeLiteral */:
78363 return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
78364 case 177 /* ArrayType */:
78365 return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode));
78366 case 178 /* TupleType */:
78367 return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode));
78368 case 179 /* OptionalType */:
78369 return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
78370 case 180 /* RestType */:
78371 return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
78372 case 181 /* UnionType */:
78373 return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
78374 case 182 /* IntersectionType */:
78375 return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
78376 case 183 /* ConditionalType */:
78377 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));
78378 case 184 /* InferType */:
78379 return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
78380 case 192 /* ImportType */:
78381 return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
78382 case 191 /* NamedTupleMember */:
78383 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));
78384 case 185 /* ParenthesizedType */:
78385 return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
78386 case 187 /* TypeOperator */:
78387 return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
78388 case 188 /* IndexedAccessType */:
78389 return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode));
78390 case 189 /* MappedType */:
78391 return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
78392 case 190 /* LiteralType */:
78393 return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression));
78394 // Binding patterns
78395 case 193 /* ObjectBindingPattern */:
78396 return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
78397 case 194 /* ArrayBindingPattern */:
78398 return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
78399 case 195 /* BindingElement */:
78400 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));
78401 // Expression
78402 case 196 /* ArrayLiteralExpression */:
78403 return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
78404 case 197 /* ObjectLiteralExpression */:
78405 return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
78406 case 198 /* PropertyAccessExpression */:
78407 if (node.flags & 32 /* OptionalChain */) {
78408 return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier));
78409 }
78410 return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
78411 case 199 /* ElementAccessExpression */:
78412 if (node.flags & 32 /* OptionalChain */) {
78413 return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
78414 }
78415 return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
78416 case 200 /* CallExpression */:
78417 if (node.flags & 32 /* OptionalChain */) {
78418 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));
78419 }
78420 return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
78421 case 201 /* NewExpression */:
78422 return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
78423 case 202 /* TaggedTemplateExpression */:
78424 return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral));
78425 case 203 /* TypeAssertionExpression */:
78426 return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression));
78427 case 204 /* ParenthesizedExpression */:
78428 return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78429 case 205 /* FunctionExpression */:
78430 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));
78431 case 206 /* ArrowFunction */:
78432 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));
78433 case 207 /* DeleteExpression */:
78434 return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78435 case 208 /* TypeOfExpression */:
78436 return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78437 case 209 /* VoidExpression */:
78438 return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78439 case 210 /* AwaitExpression */:
78440 return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78441 case 211 /* PrefixUnaryExpression */:
78442 return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
78443 case 212 /* PostfixUnaryExpression */:
78444 return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
78445 case 213 /* BinaryExpression */:
78446 return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression));
78447 case 214 /* ConditionalExpression */:
78448 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));
78449 case 215 /* TemplateExpression */:
78450 return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
78451 case 216 /* YieldExpression */:
78452 return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression));
78453 case 217 /* SpreadElement */:
78454 return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78455 case 218 /* ClassExpression */:
78456 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));
78457 case 220 /* ExpressionWithTypeArguments */:
78458 return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
78459 case 221 /* AsExpression */:
78460 return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode));
78461 case 222 /* NonNullExpression */:
78462 if (node.flags & 32 /* OptionalChain */) {
78463 return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78464 }
78465 return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78466 case 223 /* MetaProperty */:
78467 return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
78468 // Misc
78469 case 225 /* TemplateSpan */:
78470 return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
78471 // Element
78472 case 227 /* Block */:
78473 return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
78474 case 229 /* VariableStatement */:
78475 return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList));
78476 case 230 /* ExpressionStatement */:
78477 return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78478 case 231 /* IfStatement */:
78479 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));
78480 case 232 /* DoStatement */:
78481 return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression));
78482 case 233 /* WhileStatement */:
78483 return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
78484 case 234 /* ForStatement */:
78485 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));
78486 case 235 /* ForInStatement */:
78487 return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
78488 case 236 /* ForOfStatement */:
78489 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));
78490 case 237 /* ContinueStatement */:
78491 return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
78492 case 238 /* BreakStatement */:
78493 return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
78494 case 239 /* ReturnStatement */:
78495 return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78496 case 240 /* WithStatement */:
78497 return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
78498 case 241 /* SwitchStatement */:
78499 return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock));
78500 case 242 /* LabeledStatement */:
78501 return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
78502 case 243 /* ThrowStatement */:
78503 return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78504 case 244 /* TryStatement */:
78505 return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock));
78506 case 246 /* VariableDeclaration */:
78507 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));
78508 case 247 /* VariableDeclarationList */:
78509 return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
78510 case 248 /* FunctionDeclaration */:
78511 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));
78512 case 249 /* ClassDeclaration */:
78513 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));
78514 case 250 /* InterfaceDeclaration */:
78515 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));
78516 case 251 /* TypeAliasDeclaration */:
78517 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));
78518 case 252 /* EnumDeclaration */:
78519 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));
78520 case 253 /* ModuleDeclaration */:
78521 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));
78522 case 254 /* ModuleBlock */:
78523 return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
78524 case 255 /* CaseBlock */:
78525 return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
78526 case 256 /* NamespaceExportDeclaration */:
78527 return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
78528 case 257 /* ImportEqualsDeclaration */:
78529 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));
78530 case 258 /* ImportDeclaration */:
78531 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));
78532 case 259 /* ImportClause */:
78533 return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings));
78534 case 260 /* NamespaceImport */:
78535 return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
78536 case 266 /* NamespaceExport */:
78537 return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
78538 case 261 /* NamedImports */:
78539 return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
78540 case 262 /* ImportSpecifier */:
78541 return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
78542 case 263 /* ExportAssignment */:
78543 return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression));
78544 case 264 /* ExportDeclaration */:
78545 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));
78546 case 265 /* NamedExports */:
78547 return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
78548 case 267 /* ExportSpecifier */:
78549 return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
78550 // Module references
78551 case 269 /* ExternalModuleReference */:
78552 return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78553 // JSX
78554 case 270 /* JsxElement */:
78555 return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement));
78556 case 271 /* JsxSelfClosingElement */:
78557 return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
78558 case 272 /* JsxOpeningElement */:
78559 return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
78560 case 273 /* JsxClosingElement */:
78561 return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression));
78562 case 274 /* JsxFragment */:
78563 return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment));
78564 case 277 /* JsxAttribute */:
78565 return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
78566 case 278 /* JsxAttributes */:
78567 return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
78568 case 279 /* JsxSpreadAttribute */:
78569 return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78570 case 280 /* JsxExpression */:
78571 return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78572 // Clauses
78573 case 281 /* CaseClause */:
78574 return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
78575 case 282 /* DefaultClause */:
78576 return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
78577 case 283 /* HeritageClause */:
78578 return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
78579 case 284 /* CatchClause */:
78580 return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock));
78581 // Property assignments
78582 case 285 /* PropertyAssignment */:
78583 return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
78584 case 286 /* ShorthandPropertyAssignment */:
78585 return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression));
78586 case 287 /* SpreadAssignment */:
78587 return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78588 // Enum
78589 case 288 /* EnumMember */:
78590 return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
78591 // Top-level nodes
78592 case 294 /* SourceFile */:
78593 return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context));
78594 // Transformation nodes
78595 case 331 /* PartiallyEmittedExpression */:
78596 return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
78597 case 332 /* CommaListExpression */:
78598 return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
78599 default:
78600 // No need to visit nodes with no children.
78601 return node;
78602 }
78603 }
78604 ts.visitEachChild = visitEachChild;
78605 /**
78606 * Extracts the single node from a NodeArray.
78607 *
78608 * @param nodes The NodeArray.
78609 */
78610 function extractSingleNode(nodes) {
78611 ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
78612 return ts.singleOrUndefined(nodes);
78613 }
78614})(ts || (ts = {}));
78615/* @internal */
78616var ts;
78617(function (ts) {
78618 function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
78619 var _a = generatorOptions.extendedDiagnostics
78620 ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
78621 : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
78622 // Current source map file and its index in the sources list
78623 var rawSources = [];
78624 var sources = [];
78625 var sourceToSourceIndexMap = new ts.Map();
78626 var sourcesContent;
78627 var names = [];
78628 var nameToNameIndexMap;
78629 var mappings = "";
78630 // Last recorded and encoded mappings
78631 var lastGeneratedLine = 0;
78632 var lastGeneratedCharacter = 0;
78633 var lastSourceIndex = 0;
78634 var lastSourceLine = 0;
78635 var lastSourceCharacter = 0;
78636 var lastNameIndex = 0;
78637 var hasLast = false;
78638 var pendingGeneratedLine = 0;
78639 var pendingGeneratedCharacter = 0;
78640 var pendingSourceIndex = 0;
78641 var pendingSourceLine = 0;
78642 var pendingSourceCharacter = 0;
78643 var pendingNameIndex = 0;
78644 var hasPending = false;
78645 var hasPendingSource = false;
78646 var hasPendingName = false;
78647 return {
78648 getSources: function () { return rawSources; },
78649 addSource: addSource,
78650 setSourceContent: setSourceContent,
78651 addName: addName,
78652 addMapping: addMapping,
78653 appendSourceMap: appendSourceMap,
78654 toJSON: toJSON,
78655 toString: function () { return JSON.stringify(toJSON()); }
78656 };
78657 function addSource(fileName) {
78658 enter();
78659 var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName,
78660 /*isAbsolutePathAnUrl*/ true);
78661 var sourceIndex = sourceToSourceIndexMap.get(source);
78662 if (sourceIndex === undefined) {
78663 sourceIndex = sources.length;
78664 sources.push(source);
78665 rawSources.push(fileName);
78666 sourceToSourceIndexMap.set(source, sourceIndex);
78667 }
78668 exit();
78669 return sourceIndex;
78670 }
78671 /* eslint-disable boolean-trivia, no-null/no-null */
78672 function setSourceContent(sourceIndex, content) {
78673 enter();
78674 if (content !== null) {
78675 if (!sourcesContent)
78676 sourcesContent = [];
78677 while (sourcesContent.length < sourceIndex) {
78678 sourcesContent.push(null);
78679 }
78680 sourcesContent[sourceIndex] = content;
78681 }
78682 exit();
78683 }
78684 /* eslint-enable boolean-trivia, no-null/no-null */
78685 function addName(name) {
78686 enter();
78687 if (!nameToNameIndexMap)
78688 nameToNameIndexMap = new ts.Map();
78689 var nameIndex = nameToNameIndexMap.get(name);
78690 if (nameIndex === undefined) {
78691 nameIndex = names.length;
78692 names.push(name);
78693 nameToNameIndexMap.set(name, nameIndex);
78694 }
78695 exit();
78696 return nameIndex;
78697 }
78698 function isNewGeneratedPosition(generatedLine, generatedCharacter) {
78699 return !hasPending
78700 || pendingGeneratedLine !== generatedLine
78701 || pendingGeneratedCharacter !== generatedCharacter;
78702 }
78703 function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
78704 return sourceIndex !== undefined
78705 && sourceLine !== undefined
78706 && sourceCharacter !== undefined
78707 && pendingSourceIndex === sourceIndex
78708 && (pendingSourceLine > sourceLine
78709 || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
78710 }
78711 function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
78712 ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
78713 ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
78714 ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
78715 ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
78716 ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
78717 enter();
78718 // If this location wasn't recorded or the location in source is going backwards, record the mapping
78719 if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
78720 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
78721 commitPendingMapping();
78722 pendingGeneratedLine = generatedLine;
78723 pendingGeneratedCharacter = generatedCharacter;
78724 hasPendingSource = false;
78725 hasPendingName = false;
78726 hasPending = true;
78727 }
78728 if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
78729 pendingSourceIndex = sourceIndex;
78730 pendingSourceLine = sourceLine;
78731 pendingSourceCharacter = sourceCharacter;
78732 hasPendingSource = true;
78733 if (nameIndex !== undefined) {
78734 pendingNameIndex = nameIndex;
78735 hasPendingName = true;
78736 }
78737 }
78738 exit();
78739 }
78740 function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
78741 ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
78742 ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
78743 enter();
78744 // First, decode the old component sourcemap
78745 var sourceIndexToNewSourceIndexMap = [];
78746 var nameIndexToNewNameIndexMap;
78747 var mappingIterator = decodeMappings(map.mappings);
78748 for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
78749 var raw = iterResult.value;
78750 if (end && (raw.generatedLine > end.line ||
78751 (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
78752 break;
78753 }
78754 if (start && (raw.generatedLine < start.line ||
78755 (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
78756 continue;
78757 }
78758 // Then reencode all the updated mappings into the overall map
78759 var newSourceIndex = void 0;
78760 var newSourceLine = void 0;
78761 var newSourceCharacter = void 0;
78762 var newNameIndex = void 0;
78763 if (raw.sourceIndex !== undefined) {
78764 newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
78765 if (newSourceIndex === undefined) {
78766 // Apply offsets to each position and fixup source entries
78767 var rawPath = map.sources[raw.sourceIndex];
78768 var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
78769 var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
78770 sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
78771 if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
78772 setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
78773 }
78774 }
78775 newSourceLine = raw.sourceLine;
78776 newSourceCharacter = raw.sourceCharacter;
78777 if (map.names && raw.nameIndex !== undefined) {
78778 if (!nameIndexToNewNameIndexMap)
78779 nameIndexToNewNameIndexMap = [];
78780 newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
78781 if (newNameIndex === undefined) {
78782 nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
78783 }
78784 }
78785 }
78786 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
78787 var newGeneratedLine = rawGeneratedLine + generatedLine;
78788 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
78789 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
78790 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
78791 }
78792 exit();
78793 }
78794 function shouldCommitMapping() {
78795 return !hasLast
78796 || lastGeneratedLine !== pendingGeneratedLine
78797 || lastGeneratedCharacter !== pendingGeneratedCharacter
78798 || lastSourceIndex !== pendingSourceIndex
78799 || lastSourceLine !== pendingSourceLine
78800 || lastSourceCharacter !== pendingSourceCharacter
78801 || lastNameIndex !== pendingNameIndex;
78802 }
78803 function commitPendingMapping() {
78804 if (!hasPending || !shouldCommitMapping()) {
78805 return;
78806 }
78807 enter();
78808 // Line/Comma delimiters
78809 if (lastGeneratedLine < pendingGeneratedLine) {
78810 // Emit line delimiters
78811 do {
78812 mappings += ";";
78813 lastGeneratedLine++;
78814 lastGeneratedCharacter = 0;
78815 } while (lastGeneratedLine < pendingGeneratedLine);
78816 }
78817 else {
78818 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
78819 // Emit comma to separate the entry
78820 if (hasLast) {
78821 mappings += ",";
78822 }
78823 }
78824 // 1. Relative generated character
78825 mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
78826 lastGeneratedCharacter = pendingGeneratedCharacter;
78827 if (hasPendingSource) {
78828 // 2. Relative sourceIndex
78829 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
78830 lastSourceIndex = pendingSourceIndex;
78831 // 3. Relative source line
78832 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
78833 lastSourceLine = pendingSourceLine;
78834 // 4. Relative source character
78835 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
78836 lastSourceCharacter = pendingSourceCharacter;
78837 if (hasPendingName) {
78838 // 5. Relative nameIndex
78839 mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
78840 lastNameIndex = pendingNameIndex;
78841 }
78842 }
78843 hasLast = true;
78844 exit();
78845 }
78846 function toJSON() {
78847 commitPendingMapping();
78848 return {
78849 version: 3,
78850 file: file,
78851 sourceRoot: sourceRoot,
78852 sources: sources,
78853 names: names,
78854 mappings: mappings,
78855 sourcesContent: sourcesContent,
78856 };
78857 }
78858 }
78859 ts.createSourceMapGenerator = createSourceMapGenerator;
78860 // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
78861 var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
78862 var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
78863 function getLineInfo(text, lineStarts) {
78864 return {
78865 getLineCount: function () { return lineStarts.length; },
78866 getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
78867 };
78868 }
78869 ts.getLineInfo = getLineInfo;
78870 /**
78871 * Tries to find the sourceMappingURL comment at the end of a file.
78872 */
78873 function tryGetSourceMappingURL(lineInfo) {
78874 for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
78875 var line = lineInfo.getLineText(index);
78876 var comment = sourceMapCommentRegExp.exec(line);
78877 if (comment) {
78878 return comment[1];
78879 }
78880 // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
78881 else if (!line.match(whitespaceOrMapCommentRegExp)) {
78882 break;
78883 }
78884 }
78885 }
78886 ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
78887 /* eslint-disable no-null/no-null */
78888 function isStringOrNull(x) {
78889 return typeof x === "string" || x === null;
78890 }
78891 function isRawSourceMap(x) {
78892 return x !== null
78893 && typeof x === "object"
78894 && x.version === 3
78895 && typeof x.file === "string"
78896 && typeof x.mappings === "string"
78897 && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
78898 && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
78899 && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
78900 && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
78901 }
78902 ts.isRawSourceMap = isRawSourceMap;
78903 /* eslint-enable no-null/no-null */
78904 function tryParseRawSourceMap(text) {
78905 try {
78906 var parsed = JSON.parse(text);
78907 if (isRawSourceMap(parsed)) {
78908 return parsed;
78909 }
78910 }
78911 catch (_a) {
78912 // empty
78913 }
78914 return undefined;
78915 }
78916 ts.tryParseRawSourceMap = tryParseRawSourceMap;
78917 function decodeMappings(mappings) {
78918 var done = false;
78919 var pos = 0;
78920 var generatedLine = 0;
78921 var generatedCharacter = 0;
78922 var sourceIndex = 0;
78923 var sourceLine = 0;
78924 var sourceCharacter = 0;
78925 var nameIndex = 0;
78926 var error;
78927 return {
78928 get pos() { return pos; },
78929 get error() { return error; },
78930 get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
78931 next: function () {
78932 while (!done && pos < mappings.length) {
78933 var ch = mappings.charCodeAt(pos);
78934 if (ch === 59 /* semicolon */) {
78935 // new line
78936 generatedLine++;
78937 generatedCharacter = 0;
78938 pos++;
78939 continue;
78940 }
78941 if (ch === 44 /* comma */) {
78942 // Next entry is on same line - no action needed
78943 pos++;
78944 continue;
78945 }
78946 var hasSource = false;
78947 var hasName = false;
78948 generatedCharacter += base64VLQFormatDecode();
78949 if (hasReportedError())
78950 return stopIterating();
78951 if (generatedCharacter < 0)
78952 return setErrorAndStopIterating("Invalid generatedCharacter found");
78953 if (!isSourceMappingSegmentEnd()) {
78954 hasSource = true;
78955 sourceIndex += base64VLQFormatDecode();
78956 if (hasReportedError())
78957 return stopIterating();
78958 if (sourceIndex < 0)
78959 return setErrorAndStopIterating("Invalid sourceIndex found");
78960 if (isSourceMappingSegmentEnd())
78961 return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
78962 sourceLine += base64VLQFormatDecode();
78963 if (hasReportedError())
78964 return stopIterating();
78965 if (sourceLine < 0)
78966 return setErrorAndStopIterating("Invalid sourceLine found");
78967 if (isSourceMappingSegmentEnd())
78968 return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
78969 sourceCharacter += base64VLQFormatDecode();
78970 if (hasReportedError())
78971 return stopIterating();
78972 if (sourceCharacter < 0)
78973 return setErrorAndStopIterating("Invalid sourceCharacter found");
78974 if (!isSourceMappingSegmentEnd()) {
78975 hasName = true;
78976 nameIndex += base64VLQFormatDecode();
78977 if (hasReportedError())
78978 return stopIterating();
78979 if (nameIndex < 0)
78980 return setErrorAndStopIterating("Invalid nameIndex found");
78981 if (!isSourceMappingSegmentEnd())
78982 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
78983 }
78984 }
78985 return { value: captureMapping(hasSource, hasName), done: done };
78986 }
78987 return stopIterating();
78988 }
78989 };
78990 function captureMapping(hasSource, hasName) {
78991 return {
78992 generatedLine: generatedLine,
78993 generatedCharacter: generatedCharacter,
78994 sourceIndex: hasSource ? sourceIndex : undefined,
78995 sourceLine: hasSource ? sourceLine : undefined,
78996 sourceCharacter: hasSource ? sourceCharacter : undefined,
78997 nameIndex: hasName ? nameIndex : undefined
78998 };
78999 }
79000 function stopIterating() {
79001 done = true;
79002 return { value: undefined, done: true };
79003 }
79004 function setError(message) {
79005 if (error === undefined) {
79006 error = message;
79007 }
79008 }
79009 function setErrorAndStopIterating(message) {
79010 setError(message);
79011 return stopIterating();
79012 }
79013 function hasReportedError() {
79014 return error !== undefined;
79015 }
79016 function isSourceMappingSegmentEnd() {
79017 return (pos === mappings.length ||
79018 mappings.charCodeAt(pos) === 44 /* comma */ ||
79019 mappings.charCodeAt(pos) === 59 /* semicolon */);
79020 }
79021 function base64VLQFormatDecode() {
79022 var moreDigits = true;
79023 var shiftCount = 0;
79024 var value = 0;
79025 for (; moreDigits; pos++) {
79026 if (pos >= mappings.length)
79027 return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
79028 // 6 digit number
79029 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
79030 if (currentByte === -1)
79031 return setError("Invalid character in VLQ"), -1;
79032 // If msb is set, we still have more bits to continue
79033 moreDigits = (currentByte & 32) !== 0;
79034 // least significant 5 bits are the next msbs in the final value.
79035 value = value | ((currentByte & 31) << shiftCount);
79036 shiftCount += 5;
79037 }
79038 // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
79039 if ((value & 1) === 0) {
79040 // + number
79041 value = value >> 1;
79042 }
79043 else {
79044 // - number
79045 value = value >> 1;
79046 value = -value;
79047 }
79048 return value;
79049 }
79050 }
79051 ts.decodeMappings = decodeMappings;
79052 function sameMapping(left, right) {
79053 return left === right
79054 || left.generatedLine === right.generatedLine
79055 && left.generatedCharacter === right.generatedCharacter
79056 && left.sourceIndex === right.sourceIndex
79057 && left.sourceLine === right.sourceLine
79058 && left.sourceCharacter === right.sourceCharacter
79059 && left.nameIndex === right.nameIndex;
79060 }
79061 ts.sameMapping = sameMapping;
79062 function isSourceMapping(mapping) {
79063 return mapping.sourceIndex !== undefined
79064 && mapping.sourceLine !== undefined
79065 && mapping.sourceCharacter !== undefined;
79066 }
79067 ts.isSourceMapping = isSourceMapping;
79068 function base64FormatEncode(value) {
79069 return value >= 0 && value < 26 ? 65 /* A */ + value :
79070 value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
79071 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
79072 value === 62 ? 43 /* plus */ :
79073 value === 63 ? 47 /* slash */ :
79074 ts.Debug.fail(value + ": not a base64 value");
79075 }
79076 function base64FormatDecode(ch) {
79077 return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
79078 ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
79079 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
79080 ch === 43 /* plus */ ? 62 :
79081 ch === 47 /* slash */ ? 63 :
79082 -1;
79083 }
79084 function base64VLQFormatEncode(inValue) {
79085 // Add a new least significant bit that has the sign of the value.
79086 // if negative number the least significant bit that gets added to the number has value 1
79087 // else least significant bit value that gets added is 0
79088 // eg. -1 changes to binary : 01 [1] => 3
79089 // +1 changes to binary : 01 [0] => 2
79090 if (inValue < 0) {
79091 inValue = ((-inValue) << 1) + 1;
79092 }
79093 else {
79094 inValue = inValue << 1;
79095 }
79096 // Encode 5 bits at a time starting from least significant bits
79097 var encodedStr = "";
79098 do {
79099 var currentDigit = inValue & 31; // 11111
79100 inValue = inValue >> 5;
79101 if (inValue > 0) {
79102 // There are still more digits to decode, set the msb (6th bit)
79103 currentDigit = currentDigit | 32;
79104 }
79105 encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
79106 } while (inValue > 0);
79107 return encodedStr;
79108 }
79109 function isSourceMappedPosition(value) {
79110 return value.sourceIndex !== undefined
79111 && value.sourcePosition !== undefined;
79112 }
79113 function sameMappedPosition(left, right) {
79114 return left.generatedPosition === right.generatedPosition
79115 && left.sourceIndex === right.sourceIndex
79116 && left.sourcePosition === right.sourcePosition;
79117 }
79118 function compareSourcePositions(left, right) {
79119 // Compares sourcePosition without comparing sourceIndex
79120 // since the mappings are grouped by sourceIndex
79121 ts.Debug.assert(left.sourceIndex === right.sourceIndex);
79122 return ts.compareValues(left.sourcePosition, right.sourcePosition);
79123 }
79124 function compareGeneratedPositions(left, right) {
79125 return ts.compareValues(left.generatedPosition, right.generatedPosition);
79126 }
79127 function getSourcePositionOfMapping(value) {
79128 return value.sourcePosition;
79129 }
79130 function getGeneratedPositionOfMapping(value) {
79131 return value.generatedPosition;
79132 }
79133 function createDocumentPositionMapper(host, map, mapPath) {
79134 var mapDirectory = ts.getDirectoryPath(mapPath);
79135 var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
79136 var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
79137 var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
79138 var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
79139 var sourceToSourceIndexMap = new ts.Map(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
79140 var decodedMappings;
79141 var generatedMappings;
79142 var sourceMappings;
79143 return {
79144 getSourcePosition: getSourcePosition,
79145 getGeneratedPosition: getGeneratedPosition
79146 };
79147 function processMapping(mapping) {
79148 var generatedPosition = generatedFile !== undefined
79149 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
79150 : -1;
79151 var source;
79152 var sourcePosition;
79153 if (isSourceMapping(mapping)) {
79154 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
79155 source = map.sources[mapping.sourceIndex];
79156 sourcePosition = sourceFile !== undefined
79157 ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
79158 : -1;
79159 }
79160 return {
79161 generatedPosition: generatedPosition,
79162 source: source,
79163 sourceIndex: mapping.sourceIndex,
79164 sourcePosition: sourcePosition,
79165 nameIndex: mapping.nameIndex
79166 };
79167 }
79168 function getDecodedMappings() {
79169 if (decodedMappings === undefined) {
79170 var decoder = decodeMappings(map.mappings);
79171 var mappings = ts.arrayFrom(decoder, processMapping);
79172 if (decoder.error !== undefined) {
79173 if (host.log) {
79174 host.log("Encountered error while decoding sourcemap: " + decoder.error);
79175 }
79176 decodedMappings = ts.emptyArray;
79177 }
79178 else {
79179 decodedMappings = mappings;
79180 }
79181 }
79182 return decodedMappings;
79183 }
79184 function getSourceMappings(sourceIndex) {
79185 if (sourceMappings === undefined) {
79186 var lists = [];
79187 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
79188 var mapping = _a[_i];
79189 if (!isSourceMappedPosition(mapping))
79190 continue;
79191 var list = lists[mapping.sourceIndex];
79192 if (!list)
79193 lists[mapping.sourceIndex] = list = [];
79194 list.push(mapping);
79195 }
79196 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
79197 }
79198 return sourceMappings[sourceIndex];
79199 }
79200 function getGeneratedMappings() {
79201 if (generatedMappings === undefined) {
79202 var list = [];
79203 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
79204 var mapping = _a[_i];
79205 list.push(mapping);
79206 }
79207 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
79208 }
79209 return generatedMappings;
79210 }
79211 function getGeneratedPosition(loc) {
79212 var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
79213 if (sourceIndex === undefined)
79214 return loc;
79215 var sourceMappings = getSourceMappings(sourceIndex);
79216 if (!ts.some(sourceMappings))
79217 return loc;
79218 var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
79219 if (targetIndex < 0) {
79220 // if no exact match, closest is 2's complement of result
79221 targetIndex = ~targetIndex;
79222 }
79223 var mapping = sourceMappings[targetIndex];
79224 if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
79225 return loc;
79226 }
79227 return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
79228 }
79229 function getSourcePosition(loc) {
79230 var generatedMappings = getGeneratedMappings();
79231 if (!ts.some(generatedMappings))
79232 return loc;
79233 var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
79234 if (targetIndex < 0) {
79235 // if no exact match, closest is 2's complement of result
79236 targetIndex = ~targetIndex;
79237 }
79238 var mapping = generatedMappings[targetIndex];
79239 if (mapping === undefined || !isSourceMappedPosition(mapping)) {
79240 return loc;
79241 }
79242 return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
79243 }
79244 }
79245 ts.createDocumentPositionMapper = createDocumentPositionMapper;
79246 ts.identitySourceMapConsumer = {
79247 getSourcePosition: ts.identity,
79248 getGeneratedPosition: ts.identity
79249 };
79250})(ts || (ts = {}));
79251/* @internal */
79252var ts;
79253(function (ts) {
79254 function getOriginalNodeId(node) {
79255 node = ts.getOriginalNode(node);
79256 return node ? ts.getNodeId(node) : 0;
79257 }
79258 ts.getOriginalNodeId = getOriginalNodeId;
79259 function containsDefaultReference(node) {
79260 if (!node)
79261 return false;
79262 if (!ts.isNamedImports(node))
79263 return false;
79264 return ts.some(node.elements, isNamedDefaultReference);
79265 }
79266 function isNamedDefaultReference(e) {
79267 return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
79268 }
79269 function chainBundle(context, transformSourceFile) {
79270 return transformSourceFileOrBundle;
79271 function transformSourceFileOrBundle(node) {
79272 return node.kind === 294 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
79273 }
79274 function transformBundle(node) {
79275 return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
79276 }
79277 }
79278 ts.chainBundle = chainBundle;
79279 function getExportNeedsImportStarHelper(node) {
79280 return !!ts.getNamespaceDeclarationNode(node);
79281 }
79282 ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
79283 function getImportNeedsImportStarHelper(node) {
79284 if (!!ts.getNamespaceDeclarationNode(node)) {
79285 return true;
79286 }
79287 var bindings = node.importClause && node.importClause.namedBindings;
79288 if (!bindings) {
79289 return false;
79290 }
79291 if (!ts.isNamedImports(bindings))
79292 return false;
79293 var defaultRefCount = 0;
79294 for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
79295 var binding = _a[_i];
79296 if (isNamedDefaultReference(binding)) {
79297 defaultRefCount++;
79298 }
79299 }
79300 // 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
79301 return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
79302 }
79303 ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
79304 function getImportNeedsImportDefaultHelper(node) {
79305 // 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)
79306 return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
79307 }
79308 ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
79309 function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
79310 var externalImports = [];
79311 var exportSpecifiers = ts.createMultiMap();
79312 var exportedBindings = [];
79313 var uniqueExports = new ts.Map();
79314 var exportedNames;
79315 var hasExportDefault = false;
79316 var exportEquals;
79317 var hasExportStarsToExportValues = false;
79318 var hasImportStar = false;
79319 var hasImportDefault = false;
79320 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
79321 var node = _a[_i];
79322 switch (node.kind) {
79323 case 258 /* ImportDeclaration */:
79324 // import "mod"
79325 // import x from "mod"
79326 // import * as x from "mod"
79327 // import { x, y } from "mod"
79328 externalImports.push(node);
79329 if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
79330 hasImportStar = true;
79331 }
79332 if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
79333 hasImportDefault = true;
79334 }
79335 break;
79336 case 257 /* ImportEqualsDeclaration */:
79337 if (node.moduleReference.kind === 269 /* ExternalModuleReference */) {
79338 // import x = require("mod")
79339 externalImports.push(node);
79340 }
79341 break;
79342 case 264 /* ExportDeclaration */:
79343 if (node.moduleSpecifier) {
79344 if (!node.exportClause) {
79345 // export * from "mod"
79346 externalImports.push(node);
79347 hasExportStarsToExportValues = true;
79348 }
79349 else {
79350 // export * as ns from "mod"
79351 // export { x, y } from "mod"
79352 externalImports.push(node);
79353 if (ts.isNamedExports(node.exportClause)) {
79354 addExportedNamesForExportDeclaration(node);
79355 }
79356 else {
79357 var name = node.exportClause.name;
79358 if (!uniqueExports.get(ts.idText(name))) {
79359 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
79360 uniqueExports.set(ts.idText(name), true);
79361 exportedNames = ts.append(exportedNames, name);
79362 }
79363 // we use the same helpers for `export * as ns` as we do for `import * as ns`
79364 hasImportStar = true;
79365 }
79366 }
79367 }
79368 else {
79369 // export { x, y }
79370 addExportedNamesForExportDeclaration(node);
79371 }
79372 break;
79373 case 263 /* ExportAssignment */:
79374 if (node.isExportEquals && !exportEquals) {
79375 // export = x
79376 exportEquals = node;
79377 }
79378 break;
79379 case 229 /* VariableStatement */:
79380 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
79381 for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) {
79382 var decl = _c[_b];
79383 exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
79384 }
79385 }
79386 break;
79387 case 248 /* FunctionDeclaration */:
79388 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
79389 if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
79390 // export default function() { }
79391 if (!hasExportDefault) {
79392 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
79393 hasExportDefault = true;
79394 }
79395 }
79396 else {
79397 // export function x() { }
79398 var name = node.name;
79399 if (!uniqueExports.get(ts.idText(name))) {
79400 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
79401 uniqueExports.set(ts.idText(name), true);
79402 exportedNames = ts.append(exportedNames, name);
79403 }
79404 }
79405 }
79406 break;
79407 case 249 /* ClassDeclaration */:
79408 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
79409 if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
79410 // export default class { }
79411 if (!hasExportDefault) {
79412 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
79413 hasExportDefault = true;
79414 }
79415 }
79416 else {
79417 // export class x { }
79418 var name = node.name;
79419 if (name && !uniqueExports.get(ts.idText(name))) {
79420 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
79421 uniqueExports.set(ts.idText(name), true);
79422 exportedNames = ts.append(exportedNames, name);
79423 }
79424 }
79425 }
79426 break;
79427 }
79428 }
79429 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
79430 if (externalHelpersImportDeclaration) {
79431 externalImports.unshift(externalHelpersImportDeclaration);
79432 }
79433 return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
79434 function addExportedNamesForExportDeclaration(node) {
79435 for (var _i = 0, _a = ts.cast(node.exportClause, ts.isNamedExports).elements; _i < _a.length; _i++) {
79436 var specifier = _a[_i];
79437 if (!uniqueExports.get(ts.idText(specifier.name))) {
79438 var name = specifier.propertyName || specifier.name;
79439 if (!node.moduleSpecifier) {
79440 exportSpecifiers.add(ts.idText(name), specifier);
79441 }
79442 var decl = resolver.getReferencedImportDeclaration(name)
79443 || resolver.getReferencedValueDeclaration(name);
79444 if (decl) {
79445 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
79446 }
79447 uniqueExports.set(ts.idText(specifier.name), true);
79448 exportedNames = ts.append(exportedNames, specifier.name);
79449 }
79450 }
79451 }
79452 }
79453 ts.collectExternalModuleInfo = collectExternalModuleInfo;
79454 function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
79455 if (ts.isBindingPattern(decl.name)) {
79456 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
79457 var element = _a[_i];
79458 if (!ts.isOmittedExpression(element)) {
79459 exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
79460 }
79461 }
79462 }
79463 else if (!ts.isGeneratedIdentifier(decl.name)) {
79464 var text = ts.idText(decl.name);
79465 if (!uniqueExports.get(text)) {
79466 uniqueExports.set(text, true);
79467 exportedNames = ts.append(exportedNames, decl.name);
79468 }
79469 }
79470 return exportedNames;
79471 }
79472 /** Use a sparse array as a multi-map. */
79473 function multiMapSparseArrayAdd(map, key, value) {
79474 var values = map[key];
79475 if (values) {
79476 values.push(value);
79477 }
79478 else {
79479 map[key] = values = [value];
79480 }
79481 return values;
79482 }
79483 /**
79484 * Used in the module transformer to check if an expression is reasonably without sideeffect,
79485 * and thus better to copy into multiple places rather than to cache in a temporary variable
79486 * - this is mostly subjective beyond the requirement that the expression not be sideeffecting
79487 */
79488 function isSimpleCopiableExpression(expression) {
79489 return ts.isStringLiteralLike(expression) ||
79490 expression.kind === 8 /* NumericLiteral */ ||
79491 ts.isKeyword(expression.kind) ||
79492 ts.isIdentifier(expression);
79493 }
79494 ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
79495 /**
79496 * A simple inlinable expression is an expression which can be copied into multiple locations
79497 * without risk of repeating any sideeffects and whose value could not possibly change between
79498 * any such locations
79499 */
79500 function isSimpleInlineableExpression(expression) {
79501 return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
79502 ts.isWellKnownSymbolSyntactically(expression);
79503 }
79504 ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
79505 function isCompoundAssignment(kind) {
79506 return kind >= 63 /* FirstCompoundAssignment */
79507 && kind <= 77 /* LastCompoundAssignment */;
79508 }
79509 ts.isCompoundAssignment = isCompoundAssignment;
79510 function getNonAssignmentOperatorForCompoundAssignment(kind) {
79511 switch (kind) {
79512 case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
79513 case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
79514 case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
79515 case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
79516 case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
79517 case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
79518 case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
79519 case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
79520 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
79521 case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
79522 case 73 /* BarEqualsToken */: return 51 /* BarToken */;
79523 case 77 /* CaretEqualsToken */: return 52 /* CaretToken */;
79524 case 74 /* BarBarEqualsToken */: return 56 /* BarBarToken */;
79525 case 75 /* AmpersandAmpersandEqualsToken */: return 55 /* AmpersandAmpersandToken */;
79526 case 76 /* QuestionQuestionEqualsToken */: return 60 /* QuestionQuestionToken */;
79527 }
79528 }
79529 ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
79530 /**
79531 * Adds super call and preceding prologue directives into the list of statements.
79532 *
79533 * @param ctor The constructor node.
79534 * @param result The list of statements.
79535 * @param visitor The visitor to apply to each node added to the result array.
79536 * @returns index of the statement that follows super call
79537 */
79538 function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) {
79539 if (ctor.body) {
79540 var statements = ctor.body.statements;
79541 // add prologue directives to the list (if any)
79542 var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
79543 if (index === statements.length) {
79544 // list contains nothing but prologue directives (or empty) - exit
79545 return index;
79546 }
79547 var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
79548 if (superIndex > -1) {
79549 for (var i = index; i <= superIndex; i++) {
79550 result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
79551 }
79552 return superIndex + 1;
79553 }
79554 return index;
79555 }
79556 return 0;
79557 }
79558 ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
79559 function getProperties(node, requireInitializer, isStatic) {
79560 return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
79561 }
79562 ts.getProperties = getProperties;
79563 /**
79564 * Is a class element either a static or an instance property declaration with an initializer?
79565 *
79566 * @param member The class element node.
79567 * @param isStatic A value indicating whether the member should be a static or instance member.
79568 */
79569 function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
79570 return ts.isPropertyDeclaration(member)
79571 && (!!member.initializer || !requireInitializer)
79572 && ts.hasStaticModifier(member) === isStatic;
79573 }
79574 /**
79575 * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
79576 *
79577 * @param member The class element node.
79578 * @param isStatic A value indicating whether the member should be a static or instance member.
79579 */
79580 function isInitializedProperty(member) {
79581 return member.kind === 162 /* PropertyDeclaration */
79582 && member.initializer !== undefined;
79583 }
79584 ts.isInitializedProperty = isInitializedProperty;
79585})(ts || (ts = {}));
79586/*@internal*/
79587var ts;
79588(function (ts) {
79589 var FlattenLevel;
79590 (function (FlattenLevel) {
79591 FlattenLevel[FlattenLevel["All"] = 0] = "All";
79592 FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
79593 })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
79594 /**
79595 * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
79596 *
79597 * @param node The node to flatten.
79598 * @param visitor An optional visitor used to visit initializers.
79599 * @param context The transformation context.
79600 * @param level Indicates the extent to which flattening should occur.
79601 * @param needsValue An optional value indicating whether the value from the right-hand-side of
79602 * the destructuring assignment is needed as part of a larger expression.
79603 * @param createAssignmentCallback An optional callback used to create the assignment expression.
79604 */
79605 function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
79606 var location = node;
79607 var value;
79608 if (ts.isDestructuringAssignment(node)) {
79609 value = node.right;
79610 while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
79611 if (ts.isDestructuringAssignment(value)) {
79612 location = node = value;
79613 value = node.right;
79614 }
79615 else {
79616 return ts.visitNode(value, visitor, ts.isExpression);
79617 }
79618 }
79619 }
79620 var expressions;
79621 var flattenContext = {
79622 context: context,
79623 level: level,
79624 downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
79625 hoistTempVariables: true,
79626 emitExpression: emitExpression,
79627 emitBindingOrAssignment: emitBindingOrAssignment,
79628 createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayAssignmentPattern(context.factory, elements); },
79629 createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectAssignmentPattern(context.factory, elements); },
79630 createArrayBindingOrAssignmentElement: makeAssignmentElement,
79631 visitor: visitor
79632 };
79633 if (value) {
79634 value = ts.visitNode(value, visitor, ts.isExpression);
79635 if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
79636 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
79637 // If the right-hand value of the assignment is also an assignment target then
79638 // we need to cache the right-hand value.
79639 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
79640 }
79641 else if (needsValue) {
79642 // If the right-hand value of the destructuring assignment needs to be preserved (as
79643 // is the case when the destructuring assignment is part of a larger expression),
79644 // then we need to cache the right-hand value.
79645 //
79646 // The source map location for the assignment should point to the entire binary
79647 // expression.
79648 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
79649 }
79650 else if (ts.nodeIsSynthesized(node)) {
79651 // Generally, the source map location for a destructuring assignment is the root
79652 // expression.
79653 //
79654 // However, if the root expression is synthesized (as in the case
79655 // of the initializer when transforming a ForOfStatement), then the source map
79656 // location should point to the right-hand value of the expression.
79657 location = value;
79658 }
79659 }
79660 flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
79661 if (value && needsValue) {
79662 if (!ts.some(expressions)) {
79663 return value;
79664 }
79665 expressions.push(value);
79666 }
79667 return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
79668 function emitExpression(expression) {
79669 expressions = ts.append(expressions, expression);
79670 }
79671 function emitBindingOrAssignment(target, value, location, original) {
79672 ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
79673 var expression = createAssignmentCallback
79674 ? createAssignmentCallback(target, value, location)
79675 : ts.setTextRange(context.factory.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
79676 expression.original = original;
79677 emitExpression(expression);
79678 }
79679 }
79680 ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
79681 function bindingOrAssignmentElementAssignsToName(element, escapedName) {
79682 var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
79683 if (ts.isBindingOrAssignmentPattern(target)) {
79684 return bindingOrAssignmentPatternAssignsToName(target, escapedName);
79685 }
79686 else if (ts.isIdentifier(target)) {
79687 return target.escapedText === escapedName;
79688 }
79689 return false;
79690 }
79691 function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
79692 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
79693 for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
79694 var element = elements_3[_i];
79695 if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
79696 return true;
79697 }
79698 }
79699 return false;
79700 }
79701 function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
79702 var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
79703 if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
79704 return true;
79705 }
79706 var target = ts.getTargetOfBindingOrAssignmentElement(element);
79707 return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
79708 }
79709 function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
79710 return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
79711 }
79712 /**
79713 * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
79714 *
79715 * @param node The node to flatten.
79716 * @param visitor An optional visitor used to visit initializers.
79717 * @param context The transformation context.
79718 * @param boundValue The value bound to the declaration.
79719 * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
79720 * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
79721 * @param level Indicates the extent to which flattening should occur.
79722 */
79723 function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
79724 if (hoistTempVariables === void 0) { hoistTempVariables = false; }
79725 var pendingExpressions;
79726 var pendingDeclarations = [];
79727 var declarations = [];
79728 var flattenContext = {
79729 context: context,
79730 level: level,
79731 downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
79732 hoistTempVariables: hoistTempVariables,
79733 emitExpression: emitExpression,
79734 emitBindingOrAssignment: emitBindingOrAssignment,
79735 createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayBindingPattern(context.factory, elements); },
79736 createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectBindingPattern(context.factory, elements); },
79737 createArrayBindingOrAssignmentElement: function (name) { return makeBindingElement(context.factory, name); },
79738 visitor: visitor
79739 };
79740 if (ts.isVariableDeclaration(node)) {
79741 var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
79742 if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
79743 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
79744 // If the right-hand value of the assignment is also an assignment target then
79745 // we need to cache the right-hand value.
79746 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
79747 node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
79748 }
79749 }
79750 flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
79751 if (pendingExpressions) {
79752 var temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined);
79753 if (hoistTempVariables) {
79754 var value = context.factory.inlineExpressions(pendingExpressions);
79755 pendingExpressions = undefined;
79756 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
79757 }
79758 else {
79759 context.hoistVariableDeclaration(temp);
79760 var pendingDeclaration = ts.last(pendingDeclarations);
79761 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value));
79762 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
79763 pendingDeclaration.value = temp;
79764 }
79765 }
79766 for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
79767 var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
79768 var variable = context.factory.createVariableDeclaration(name,
79769 /*exclamationToken*/ undefined,
79770 /*type*/ undefined, pendingExpressions_1 ? context.factory.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
79771 variable.original = original;
79772 ts.setTextRange(variable, location);
79773 declarations.push(variable);
79774 }
79775 return declarations;
79776 function emitExpression(value) {
79777 pendingExpressions = ts.append(pendingExpressions, value);
79778 }
79779 function emitBindingOrAssignment(target, value, location, original) {
79780 ts.Debug.assertNode(target, ts.isBindingName);
79781 if (pendingExpressions) {
79782 value = context.factory.inlineExpressions(ts.append(pendingExpressions, value));
79783 pendingExpressions = undefined;
79784 }
79785 pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
79786 }
79787 }
79788 ts.flattenDestructuringBinding = flattenDestructuringBinding;
79789 /**
79790 * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
79791 *
79792 * @param flattenContext Options used to control flattening.
79793 * @param element The element to flatten.
79794 * @param value The current RHS value to assign to the element.
79795 * @param location The location to use for source maps and comments.
79796 * @param skipInitializer An optional value indicating whether to include the initializer
79797 * for the element.
79798 */
79799 function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
79800 if (!skipInitializer) {
79801 var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
79802 if (initializer) {
79803 // Combine value and initializer
79804 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
79805 }
79806 else if (!value) {
79807 // Use 'void 0' in absence of value and initializer
79808 value = flattenContext.context.factory.createVoidZero();
79809 }
79810 }
79811 var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
79812 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
79813 flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
79814 }
79815 else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
79816 flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
79817 }
79818 else {
79819 flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
79820 }
79821 }
79822 /**
79823 * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
79824 *
79825 * @param flattenContext Options used to control flattening.
79826 * @param parent The parent element of the pattern.
79827 * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
79828 * @param value The current RHS value to assign to the element.
79829 * @param location The location to use for source maps and comments.
79830 */
79831 function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
79832 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
79833 var numElements = elements.length;
79834 if (numElements !== 1) {
79835 // For anything other than a single-element destructuring we need to generate a temporary
79836 // to ensure value is evaluated exactly once. Additionally, if we have zero elements
79837 // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
79838 // so in that case, we'll intentionally create that temporary.
79839 var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
79840 value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
79841 }
79842 var bindingElements;
79843 var computedTempVariables;
79844 for (var i = 0; i < numElements; i++) {
79845 var element = elements[i];
79846 if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
79847 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
79848 if (flattenContext.level >= 1 /* ObjectRest */
79849 && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
79850 && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
79851 && !ts.isComputedPropertyName(propertyName)) {
79852 bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
79853 }
79854 else {
79855 if (bindingElements) {
79856 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
79857 bindingElements = undefined;
79858 }
79859 var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
79860 if (ts.isComputedPropertyName(propertyName)) {
79861 computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
79862 }
79863 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
79864 }
79865 }
79866 else if (i === numElements - 1) {
79867 if (bindingElements) {
79868 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
79869 bindingElements = undefined;
79870 }
79871 var rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
79872 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
79873 }
79874 }
79875 if (bindingElements) {
79876 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
79877 }
79878 }
79879 /**
79880 * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
79881 *
79882 * @param flattenContext Options used to control flattening.
79883 * @param parent The parent element of the pattern.
79884 * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
79885 * @param value The current RHS value to assign to the element.
79886 * @param location The location to use for source maps and comments.
79887 */
79888 function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
79889 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
79890 var numElements = elements.length;
79891 if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
79892 // Read the elements of the iterable into an array
79893 value = ensureIdentifier(flattenContext, ts.setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
79894 ? undefined
79895 : numElements), location),
79896 /*reuseIdentifierExpressions*/ false, location);
79897 }
79898 else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
79899 || ts.every(elements, ts.isOmittedExpression)) {
79900 // For anything other than a single-element destructuring we need to generate a temporary
79901 // to ensure value is evaluated exactly once. Additionally, if we have zero elements
79902 // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
79903 // so in that case, we'll intentionally create that temporary.
79904 // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
79905 // then we will create temporary variable.
79906 var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
79907 value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
79908 }
79909 var bindingElements;
79910 var restContainingElements;
79911 for (var i = 0; i < numElements; i++) {
79912 var element = elements[i];
79913 if (flattenContext.level >= 1 /* ObjectRest */) {
79914 // If an array pattern contains an ObjectRest, we must cache the result so that we
79915 // can perform the ObjectRest destructuring in a different declaration
79916 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
79917 var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
79918 if (flattenContext.hoistTempVariables) {
79919 flattenContext.context.hoistVariableDeclaration(temp);
79920 }
79921 restContainingElements = ts.append(restContainingElements, [temp, element]);
79922 bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
79923 }
79924 else {
79925 bindingElements = ts.append(bindingElements, element);
79926 }
79927 }
79928 else if (ts.isOmittedExpression(element)) {
79929 continue;
79930 }
79931 else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
79932 var rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
79933 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
79934 }
79935 else if (i === numElements - 1) {
79936 var rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
79937 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
79938 }
79939 }
79940 if (bindingElements) {
79941 flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
79942 }
79943 if (restContainingElements) {
79944 for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
79945 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
79946 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
79947 }
79948 }
79949 }
79950 /**
79951 * Creates an expression used to provide a default value if a value is `undefined` at runtime.
79952 *
79953 * @param flattenContext Options used to control flattening.
79954 * @param value The RHS value to test.
79955 * @param defaultValue The default value to use if `value` is `undefined` at runtime.
79956 * @param location The location to use for source maps and comments.
79957 */
79958 function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
79959 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
79960 return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value);
79961 }
79962 /**
79963 * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
79964 * right-hand side of a transformed destructuring assignment.
79965 *
79966 * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
79967 *
79968 * @param flattenContext Options used to control flattening.
79969 * @param value The RHS value that is the source of the property.
79970 * @param propertyName The destructuring property name.
79971 */
79972 function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
79973 if (ts.isComputedPropertyName(propertyName)) {
79974 var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
79975 return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
79976 }
79977 else if (ts.isStringOrNumericLiteralLike(propertyName)) {
79978 var argumentExpression = ts.factory.cloneNode(propertyName);
79979 return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
79980 }
79981 else {
79982 var name = flattenContext.context.factory.createIdentifier(ts.idText(propertyName));
79983 return flattenContext.context.factory.createPropertyAccessExpression(value, name);
79984 }
79985 }
79986 /**
79987 * Ensures that there exists a declared identifier whose value holds the given expression.
79988 * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
79989 * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
79990 *
79991 * @param flattenContext Options used to control flattening.
79992 * @param value the expression whose value needs to be bound.
79993 * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
79994 * false if it is necessary to always emit an identifier.
79995 * @param location The location to use for source maps and comments.
79996 */
79997 function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
79998 if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
79999 return value;
80000 }
80001 else {
80002 var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
80003 if (flattenContext.hoistTempVariables) {
80004 flattenContext.context.hoistVariableDeclaration(temp);
80005 flattenContext.emitExpression(ts.setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
80006 }
80007 else {
80008 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
80009 }
80010 return temp;
80011 }
80012 }
80013 function makeArrayBindingPattern(factory, elements) {
80014 ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
80015 return factory.createArrayBindingPattern(elements);
80016 }
80017 function makeArrayAssignmentPattern(factory, elements) {
80018 return factory.createArrayLiteralExpression(ts.map(elements, factory.converters.convertToArrayAssignmentElement));
80019 }
80020 function makeObjectBindingPattern(factory, elements) {
80021 ts.Debug.assertEachNode(elements, ts.isBindingElement);
80022 return factory.createObjectBindingPattern(elements);
80023 }
80024 function makeObjectAssignmentPattern(factory, elements) {
80025 return factory.createObjectLiteralExpression(ts.map(elements, factory.converters.convertToObjectAssignmentElement));
80026 }
80027 function makeBindingElement(factory, name) {
80028 return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
80029 }
80030 function makeAssignmentElement(name) {
80031 return name;
80032 }
80033})(ts || (ts = {}));
80034/*@internal*/
80035var ts;
80036(function (ts) {
80037 var ProcessLevel;
80038 (function (ProcessLevel) {
80039 ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
80040 ProcessLevel[ProcessLevel["All"] = 1] = "All";
80041 })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
80042 function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
80043 // Visit the tag expression
80044 var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
80045 // Build up the template arguments and the raw and cooked strings for the template.
80046 // We start out with 'undefined' for the first argument and revisit later
80047 // to avoid walking over the template string twice and shifting all our arguments over after the fact.
80048 var templateArguments = [undefined];
80049 var cookedStrings = [];
80050 var rawStrings = [];
80051 var template = node.template;
80052 if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) {
80053 return ts.visitEachChild(node, visitor, context);
80054 }
80055 if (ts.isNoSubstitutionTemplateLiteral(template)) {
80056 cookedStrings.push(createTemplateCooked(template));
80057 rawStrings.push(getRawLiteral(template, currentSourceFile));
80058 }
80059 else {
80060 cookedStrings.push(createTemplateCooked(template.head));
80061 rawStrings.push(getRawLiteral(template.head, currentSourceFile));
80062 for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
80063 var templateSpan = _a[_i];
80064 cookedStrings.push(createTemplateCooked(templateSpan.literal));
80065 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
80066 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
80067 }
80068 }
80069 var helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(ts.factory.createArrayLiteralExpression(cookedStrings), ts.factory.createArrayLiteralExpression(rawStrings));
80070 // Create a variable to cache the template object if we're in a module.
80071 // Do not do this in the global scope, as any variable we currently generate could conflict with
80072 // variables from outside of the current compilation. In the future, we can revisit this behavior.
80073 if (ts.isExternalModule(currentSourceFile)) {
80074 var tempVar = ts.factory.createUniqueName("templateObject");
80075 recordTaggedTemplateString(tempVar);
80076 templateArguments[0] = ts.factory.createLogicalOr(tempVar, ts.factory.createAssignment(tempVar, helperCall));
80077 }
80078 else {
80079 templateArguments[0] = helperCall;
80080 }
80081 return ts.factory.createCallExpression(tag, /*typeArguments*/ undefined, templateArguments);
80082 }
80083 ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
80084 function createTemplateCooked(template) {
80085 return template.templateFlags ? ts.factory.createVoidZero() : ts.factory.createStringLiteral(template.text);
80086 }
80087 /**
80088 * Creates an ES5 compatible literal from an ES6 template literal.
80089 *
80090 * @param node The ES6 template literal.
80091 */
80092 function getRawLiteral(node, currentSourceFile) {
80093 // Find original source text, since we need to emit the raw strings of the tagged template.
80094 // The raw strings contain the (escaped) strings of what the user wrote.
80095 // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
80096 var text = node.rawText;
80097 if (text === undefined) {
80098 text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
80099 // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
80100 // thus we need to remove those characters.
80101 // First template piece starts with "`", others with "}"
80102 // Last template piece ends with "`", others with "${"
80103 var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
80104 text = text.substring(1, text.length - (isLast ? 1 : 2));
80105 }
80106 // Newline normalization:
80107 // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
80108 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
80109 text = text.replace(/\r\n?/g, "\n");
80110 return ts.setTextRange(ts.factory.createStringLiteral(text), node);
80111 }
80112})(ts || (ts = {}));
80113/*@internal*/
80114var ts;
80115(function (ts) {
80116 /**
80117 * Indicates whether to emit type metadata in the new format.
80118 */
80119 var USE_NEW_TYPE_METADATA_FORMAT = false;
80120 var TypeScriptSubstitutionFlags;
80121 (function (TypeScriptSubstitutionFlags) {
80122 /** Enables substitutions for decorated classes. */
80123 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80124 /** Enables substitutions for namespace exports. */
80125 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
80126 /* Enables substitutions for unqualified enum members */
80127 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
80128 })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
80129 var ClassFacts;
80130 (function (ClassFacts) {
80131 ClassFacts[ClassFacts["None"] = 0] = "None";
80132 ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
80133 ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
80134 ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
80135 ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
80136 ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
80137 ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
80138 ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
80139 ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
80140 ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
80141 ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
80142 ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
80143 ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
80144 })(ClassFacts || (ClassFacts = {}));
80145 function transformTypeScript(context) {
80146 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80147 var resolver = context.getEmitResolver();
80148 var compilerOptions = context.getCompilerOptions();
80149 var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
80150 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80151 var moduleKind = ts.getEmitModuleKind(compilerOptions);
80152 // Save the previous transformation hooks.
80153 var previousOnEmitNode = context.onEmitNode;
80154 var previousOnSubstituteNode = context.onSubstituteNode;
80155 // Set new transformation hooks.
80156 context.onEmitNode = onEmitNode;
80157 context.onSubstituteNode = onSubstituteNode;
80158 // Enable substitution for property/element access to emit const enum values.
80159 context.enableSubstitution(198 /* PropertyAccessExpression */);
80160 context.enableSubstitution(199 /* ElementAccessExpression */);
80161 // These variables contain state that changes as we descend into the tree.
80162 var currentSourceFile;
80163 var currentNamespace;
80164 var currentNamespaceContainerName;
80165 var currentLexicalScope;
80166 var currentNameScope;
80167 var currentScopeFirstDeclarationsOfName;
80168 var currentClassHasParameterProperties;
80169 /**
80170 * Keeps track of whether expression substitution has been enabled for specific edge cases.
80171 * They are persisted between each SourceFile transformation and should not be reset.
80172 */
80173 var enabledSubstitutions;
80174 /**
80175 * A map that keeps track of aliases created for classes with decorators to avoid issues
80176 * with the double-binding behavior of classes.
80177 */
80178 var classAliases;
80179 /**
80180 * Keeps track of whether we are within any containing namespaces when performing
80181 * just-in-time substitution while printing an expression identifier.
80182 */
80183 var applicableSubstitutions;
80184 return transformSourceFileOrBundle;
80185 function transformSourceFileOrBundle(node) {
80186 if (node.kind === 295 /* Bundle */) {
80187 return transformBundle(node);
80188 }
80189 return transformSourceFile(node);
80190 }
80191 function transformBundle(node) {
80192 return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
80193 if (prepend.kind === 297 /* InputFiles */) {
80194 return ts.createUnparsedSourceFile(prepend, "js");
80195 }
80196 return prepend;
80197 }));
80198 }
80199 /**
80200 * Transform TypeScript-specific syntax in a SourceFile.
80201 *
80202 * @param node A SourceFile node.
80203 */
80204 function transformSourceFile(node) {
80205 if (node.isDeclarationFile) {
80206 return node;
80207 }
80208 currentSourceFile = node;
80209 var visited = saveStateAndInvoke(node, visitSourceFile);
80210 ts.addEmitHelpers(visited, context.readEmitHelpers());
80211 currentSourceFile = undefined;
80212 return visited;
80213 }
80214 /**
80215 * Visits a node, saving and restoring state variables on the stack.
80216 *
80217 * @param node The node to visit.
80218 */
80219 function saveStateAndInvoke(node, f) {
80220 // Save state
80221 var savedCurrentScope = currentLexicalScope;
80222 var savedCurrentNameScope = currentNameScope;
80223 var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
80224 var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
80225 // Handle state changes before visiting a node.
80226 onBeforeVisitNode(node);
80227 var visited = f(node);
80228 // Restore state
80229 if (currentLexicalScope !== savedCurrentScope) {
80230 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
80231 }
80232 currentLexicalScope = savedCurrentScope;
80233 currentNameScope = savedCurrentNameScope;
80234 currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
80235 return visited;
80236 }
80237 /**
80238 * Performs actions that should always occur immediately before visiting a node.
80239 *
80240 * @param node The node to visit.
80241 */
80242 function onBeforeVisitNode(node) {
80243 switch (node.kind) {
80244 case 294 /* SourceFile */:
80245 case 255 /* CaseBlock */:
80246 case 254 /* ModuleBlock */:
80247 case 227 /* Block */:
80248 currentLexicalScope = node;
80249 currentNameScope = undefined;
80250 currentScopeFirstDeclarationsOfName = undefined;
80251 break;
80252 case 249 /* ClassDeclaration */:
80253 case 248 /* FunctionDeclaration */:
80254 if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
80255 break;
80256 }
80257 // Record these declarations provided that they have a name.
80258 if (node.name) {
80259 recordEmittedDeclarationInScope(node);
80260 }
80261 else {
80262 // These nodes should always have names unless they are default-exports;
80263 // however, class declaration parsing allows for undefined names, so syntactically invalid
80264 // programs may also have an undefined name.
80265 ts.Debug.assert(node.kind === 249 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */));
80266 }
80267 if (ts.isClassDeclaration(node)) {
80268 // XXX: should probably also cover interfaces and type aliases that can have type variables?
80269 currentNameScope = node;
80270 }
80271 break;
80272 }
80273 }
80274 /**
80275 * General-purpose node visitor.
80276 *
80277 * @param node The node to visit.
80278 */
80279 function visitor(node) {
80280 return saveStateAndInvoke(node, visitorWorker);
80281 }
80282 /**
80283 * Visits and possibly transforms any node.
80284 *
80285 * @param node The node to visit.
80286 */
80287 function visitorWorker(node) {
80288 if (node.transformFlags & 1 /* ContainsTypeScript */) {
80289 return visitTypeScript(node);
80290 }
80291 return node;
80292 }
80293 /**
80294 * Specialized visitor that visits the immediate children of a SourceFile.
80295 *
80296 * @param node The node to visit.
80297 */
80298 function sourceElementVisitor(node) {
80299 return saveStateAndInvoke(node, sourceElementVisitorWorker);
80300 }
80301 /**
80302 * Specialized visitor that visits the immediate children of a SourceFile.
80303 *
80304 * @param node The node to visit.
80305 */
80306 function sourceElementVisitorWorker(node) {
80307 switch (node.kind) {
80308 case 258 /* ImportDeclaration */:
80309 case 257 /* ImportEqualsDeclaration */:
80310 case 263 /* ExportAssignment */:
80311 case 264 /* ExportDeclaration */:
80312 return visitElidableStatement(node);
80313 default:
80314 return visitorWorker(node);
80315 }
80316 }
80317 function visitElidableStatement(node) {
80318 var parsed = ts.getParseTreeNode(node);
80319 if (parsed !== node) {
80320 // If the node has been transformed by a `before` transformer, perform no ellision on it
80321 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
80322 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
80323 // and will trigger debug failures when debug verbosity is turned up
80324 if (node.transformFlags & 1 /* ContainsTypeScript */) {
80325 // This node contains TypeScript, so we should visit its children.
80326 return ts.visitEachChild(node, visitor, context);
80327 }
80328 // Otherwise, we can just return the node
80329 return node;
80330 }
80331 switch (node.kind) {
80332 case 258 /* ImportDeclaration */:
80333 return visitImportDeclaration(node);
80334 case 257 /* ImportEqualsDeclaration */:
80335 return visitImportEqualsDeclaration(node);
80336 case 263 /* ExportAssignment */:
80337 return visitExportAssignment(node);
80338 case 264 /* ExportDeclaration */:
80339 return visitExportDeclaration(node);
80340 default:
80341 ts.Debug.fail("Unhandled ellided statement");
80342 }
80343 }
80344 /**
80345 * Specialized visitor that visits the immediate children of a namespace.
80346 *
80347 * @param node The node to visit.
80348 */
80349 function namespaceElementVisitor(node) {
80350 return saveStateAndInvoke(node, namespaceElementVisitorWorker);
80351 }
80352 /**
80353 * Specialized visitor that visits the immediate children of a namespace.
80354 *
80355 * @param node The node to visit.
80356 */
80357 function namespaceElementVisitorWorker(node) {
80358 if (node.kind === 264 /* ExportDeclaration */ ||
80359 node.kind === 258 /* ImportDeclaration */ ||
80360 node.kind === 259 /* ImportClause */ ||
80361 (node.kind === 257 /* ImportEqualsDeclaration */ &&
80362 node.moduleReference.kind === 269 /* ExternalModuleReference */)) {
80363 // do not emit ES6 imports and exports since they are illegal inside a namespace
80364 return undefined;
80365 }
80366 else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasSyntacticModifier(node, 1 /* Export */)) {
80367 return visitTypeScript(node);
80368 }
80369 return node;
80370 }
80371 /**
80372 * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
80373 *
80374 * @param node The node to visit.
80375 */
80376 function classElementVisitor(node) {
80377 return saveStateAndInvoke(node, classElementVisitorWorker);
80378 }
80379 /**
80380 * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
80381 *
80382 * @param node The node to visit.
80383 */
80384 function classElementVisitorWorker(node) {
80385 switch (node.kind) {
80386 case 165 /* Constructor */:
80387 return visitConstructor(node);
80388 case 162 /* PropertyDeclaration */:
80389 // Property declarations are not TypeScript syntax, but they must be visited
80390 // for the decorator transformation.
80391 return visitPropertyDeclaration(node);
80392 case 170 /* IndexSignature */:
80393 case 166 /* GetAccessor */:
80394 case 167 /* SetAccessor */:
80395 case 164 /* MethodDeclaration */:
80396 // Fallback to the default visit behavior.
80397 return visitorWorker(node);
80398 case 226 /* SemicolonClassElement */:
80399 return node;
80400 default:
80401 return ts.Debug.failBadSyntaxKind(node);
80402 }
80403 }
80404 function modifierVisitor(node) {
80405 if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
80406 return undefined;
80407 }
80408 else if (currentNamespace && node.kind === 92 /* ExportKeyword */) {
80409 return undefined;
80410 }
80411 return node;
80412 }
80413 /**
80414 * Branching visitor, visits a TypeScript syntax node.
80415 *
80416 * @param node The node to visit.
80417 */
80418 function visitTypeScript(node) {
80419 if (ts.isStatement(node) && ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
80420 // TypeScript ambient declarations are elided, but some comments may be preserved.
80421 // See the implementation of `getLeadingComments` in comments.ts for more details.
80422 return factory.createNotEmittedStatement(node);
80423 }
80424 switch (node.kind) {
80425 case 92 /* ExportKeyword */:
80426 case 87 /* DefaultKeyword */:
80427 // ES6 export and default modifiers are elided when inside a namespace.
80428 return currentNamespace ? undefined : node;
80429 case 122 /* PublicKeyword */:
80430 case 120 /* PrivateKeyword */:
80431 case 121 /* ProtectedKeyword */:
80432 case 125 /* AbstractKeyword */:
80433 case 84 /* ConstKeyword */:
80434 case 133 /* DeclareKeyword */:
80435 case 141 /* ReadonlyKeyword */:
80436 // TypeScript accessibility and readonly modifiers are elided
80437 // falls through
80438 case 177 /* ArrayType */:
80439 case 178 /* TupleType */:
80440 case 179 /* OptionalType */:
80441 case 180 /* RestType */:
80442 case 176 /* TypeLiteral */:
80443 case 171 /* TypePredicate */:
80444 case 158 /* TypeParameter */:
80445 case 128 /* AnyKeyword */:
80446 case 151 /* UnknownKeyword */:
80447 case 131 /* BooleanKeyword */:
80448 case 146 /* StringKeyword */:
80449 case 143 /* NumberKeyword */:
80450 case 140 /* NeverKeyword */:
80451 case 113 /* VoidKeyword */:
80452 case 147 /* SymbolKeyword */:
80453 case 174 /* ConstructorType */:
80454 case 173 /* FunctionType */:
80455 case 175 /* TypeQuery */:
80456 case 172 /* TypeReference */:
80457 case 181 /* UnionType */:
80458 case 182 /* IntersectionType */:
80459 case 183 /* ConditionalType */:
80460 case 185 /* ParenthesizedType */:
80461 case 186 /* ThisType */:
80462 case 187 /* TypeOperator */:
80463 case 188 /* IndexedAccessType */:
80464 case 189 /* MappedType */:
80465 case 190 /* LiteralType */:
80466 // TypeScript type nodes are elided.
80467 // falls through
80468 case 170 /* IndexSignature */:
80469 // TypeScript index signatures are elided.
80470 // falls through
80471 case 160 /* Decorator */:
80472 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
80473 // falls through
80474 case 251 /* TypeAliasDeclaration */:
80475 // TypeScript type-only declarations are elided.
80476 return undefined;
80477 case 162 /* PropertyDeclaration */:
80478 // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
80479 return visitPropertyDeclaration(node);
80480 case 256 /* NamespaceExportDeclaration */:
80481 // TypeScript namespace export declarations are elided.
80482 return undefined;
80483 case 165 /* Constructor */:
80484 return visitConstructor(node);
80485 case 250 /* InterfaceDeclaration */:
80486 // TypeScript interfaces are elided, but some comments may be preserved.
80487 // See the implementation of `getLeadingComments` in comments.ts for more details.
80488 return factory.createNotEmittedStatement(node);
80489 case 249 /* ClassDeclaration */:
80490 // This may be a class declaration with TypeScript syntax extensions.
80491 //
80492 // TypeScript class syntax extensions include:
80493 // - decorators
80494 // - optional `implements` heritage clause
80495 // - parameter property assignments in the constructor
80496 // - index signatures
80497 // - method overload signatures
80498 return visitClassDeclaration(node);
80499 case 218 /* ClassExpression */:
80500 // This may be a class expression with TypeScript syntax extensions.
80501 //
80502 // TypeScript class syntax extensions include:
80503 // - decorators
80504 // - optional `implements` heritage clause
80505 // - parameter property assignments in the constructor
80506 // - index signatures
80507 // - method overload signatures
80508 return visitClassExpression(node);
80509 case 283 /* HeritageClause */:
80510 // This may be a heritage clause with TypeScript syntax extensions.
80511 //
80512 // TypeScript heritage clause extensions include:
80513 // - `implements` clause
80514 return visitHeritageClause(node);
80515 case 220 /* ExpressionWithTypeArguments */:
80516 // TypeScript supports type arguments on an expression in an `extends` heritage clause.
80517 return visitExpressionWithTypeArguments(node);
80518 case 164 /* MethodDeclaration */:
80519 // TypeScript method declarations may have decorators, modifiers
80520 // or type annotations.
80521 return visitMethodDeclaration(node);
80522 case 166 /* GetAccessor */:
80523 // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
80524 return visitGetAccessor(node);
80525 case 167 /* SetAccessor */:
80526 // Set Accessors can have TypeScript modifiers and type annotations.
80527 return visitSetAccessor(node);
80528 case 248 /* FunctionDeclaration */:
80529 // Typescript function declarations can have modifiers, decorators, and type annotations.
80530 return visitFunctionDeclaration(node);
80531 case 205 /* FunctionExpression */:
80532 // TypeScript function expressions can have modifiers and type annotations.
80533 return visitFunctionExpression(node);
80534 case 206 /* ArrowFunction */:
80535 // TypeScript arrow functions can have modifiers and type annotations.
80536 return visitArrowFunction(node);
80537 case 159 /* Parameter */:
80538 // This may be a parameter declaration with TypeScript syntax extensions.
80539 //
80540 // TypeScript parameter declaration syntax extensions include:
80541 // - decorators
80542 // - accessibility modifiers
80543 // - the question mark (?) token for optional parameters
80544 // - type annotations
80545 // - this parameters
80546 return visitParameter(node);
80547 case 204 /* ParenthesizedExpression */:
80548 // ParenthesizedExpressions are TypeScript if their expression is a
80549 // TypeAssertion or AsExpression
80550 return visitParenthesizedExpression(node);
80551 case 203 /* TypeAssertionExpression */:
80552 case 221 /* AsExpression */:
80553 // TypeScript type assertions are removed, but their subtrees are preserved.
80554 return visitAssertionExpression(node);
80555 case 200 /* CallExpression */:
80556 return visitCallExpression(node);
80557 case 201 /* NewExpression */:
80558 return visitNewExpression(node);
80559 case 202 /* TaggedTemplateExpression */:
80560 return visitTaggedTemplateExpression(node);
80561 case 222 /* NonNullExpression */:
80562 // TypeScript non-null expressions are removed, but their subtrees are preserved.
80563 return visitNonNullExpression(node);
80564 case 252 /* EnumDeclaration */:
80565 // TypeScript enum declarations do not exist in ES6 and must be rewritten.
80566 return visitEnumDeclaration(node);
80567 case 229 /* VariableStatement */:
80568 // TypeScript namespace exports for variable statements must be transformed.
80569 return visitVariableStatement(node);
80570 case 246 /* VariableDeclaration */:
80571 return visitVariableDeclaration(node);
80572 case 253 /* ModuleDeclaration */:
80573 // TypeScript namespace declarations must be transformed.
80574 return visitModuleDeclaration(node);
80575 case 257 /* ImportEqualsDeclaration */:
80576 // TypeScript namespace or external module import.
80577 return visitImportEqualsDeclaration(node);
80578 case 271 /* JsxSelfClosingElement */:
80579 return visitJsxSelfClosingElement(node);
80580 case 272 /* JsxOpeningElement */:
80581 return visitJsxJsxOpeningElement(node);
80582 default:
80583 // node contains some other TypeScript syntax
80584 return ts.visitEachChild(node, visitor, context);
80585 }
80586 }
80587 function visitSourceFile(node) {
80588 var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
80589 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
80590 !ts.isJsonSourceFile(node);
80591 return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
80592 }
80593 /**
80594 * Tests whether we should emit a __decorate call for a class declaration.
80595 */
80596 function shouldEmitDecorateCallForClass(node) {
80597 if (node.decorators && node.decorators.length > 0) {
80598 return true;
80599 }
80600 var constructor = ts.getFirstConstructorWithBody(node);
80601 if (constructor) {
80602 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
80603 }
80604 return false;
80605 }
80606 /**
80607 * Tests whether we should emit a __decorate call for a parameter declaration.
80608 */
80609 function shouldEmitDecorateCallForParameter(parameter) {
80610 return parameter.decorators !== undefined && parameter.decorators.length > 0;
80611 }
80612 function getClassFacts(node, staticProperties) {
80613 var facts = 0 /* None */;
80614 if (ts.some(staticProperties))
80615 facts |= 1 /* HasStaticInitializedProperties */;
80616 var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80617 if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */)
80618 facts |= 64 /* IsDerivedClass */;
80619 if (shouldEmitDecorateCallForClass(node))
80620 facts |= 2 /* HasConstructorDecorators */;
80621 if (ts.childIsDecorated(node))
80622 facts |= 4 /* HasMemberDecorators */;
80623 if (isExportOfNamespace(node))
80624 facts |= 8 /* IsExportOfNamespace */;
80625 else if (isDefaultExternalModuleExport(node))
80626 facts |= 32 /* IsDefaultExternalExport */;
80627 else if (isNamedExternalModuleExport(node))
80628 facts |= 16 /* IsNamedExternalExport */;
80629 if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
80630 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
80631 return facts;
80632 }
80633 function hasTypeScriptClassSyntax(node) {
80634 return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
80635 }
80636 function isClassLikeDeclarationWithTypeScriptSyntax(node) {
80637 return ts.some(node.decorators)
80638 || ts.some(node.typeParameters)
80639 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
80640 || ts.some(node.members, hasTypeScriptClassSyntax);
80641 }
80642 function visitClassDeclaration(node) {
80643 if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* Export */))) {
80644 return ts.visitEachChild(node, visitor, context);
80645 }
80646 var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80647 var facts = getClassFacts(node, staticProperties);
80648 if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
80649 context.startLexicalEnvironment();
80650 }
80651 var name = node.name || (facts & 5 /* NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined);
80652 var classStatement = facts & 2 /* HasConstructorDecorators */
80653 ? createClassDeclarationHeadWithDecorators(node, name)
80654 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
80655 var statements = [classStatement];
80656 // Write any decorators of the node.
80657 addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
80658 addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
80659 addConstructorDecorationStatement(statements, node);
80660 if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
80661 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
80662 // 'es2015' transformer can properly nest static initializers and decorators. The result
80663 // looks something like:
80664 //
80665 // var C = function () {
80666 // class C {
80667 // }
80668 // C.static_prop = 1;
80669 // return C;
80670 // }();
80671 //
80672 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
80673 var localName = factory.getInternalName(node);
80674 // The following partially-emitted expression exists purely to align our sourcemap
80675 // emit with the original emitter.
80676 var outer = factory.createPartiallyEmittedExpression(localName);
80677 ts.setTextRangeEnd(outer, closingBraceLocation.end);
80678 ts.setEmitFlags(outer, 1536 /* NoComments */);
80679 var statement = factory.createReturnStatement(outer);
80680 ts.setTextRangePos(statement, closingBraceLocation.pos);
80681 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
80682 statements.push(statement);
80683 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
80684 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
80685 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
80686 var varStatement = factory.createVariableStatement(
80687 /*modifiers*/ undefined, factory.createVariableDeclarationList([
80688 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
80689 /*exclamationToken*/ undefined,
80690 /*type*/ undefined, iife)
80691 ]));
80692 ts.setOriginalNode(varStatement, node);
80693 ts.setCommentRange(varStatement, node);
80694 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
80695 ts.startOnNewLine(varStatement);
80696 statements = [varStatement];
80697 }
80698 // If the class is exported as part of a TypeScript namespace, emit the namespace export.
80699 // Otherwise, if the class was exported at the top level and was decorated, emit an export
80700 // declaration or export default for the class.
80701 if (facts & 8 /* IsExportOfNamespace */) {
80702 addExportMemberAssignment(statements, node);
80703 }
80704 else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
80705 if (facts & 32 /* IsDefaultExternalExport */) {
80706 statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
80707 }
80708 else if (facts & 16 /* IsNamedExternalExport */) {
80709 statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
80710 }
80711 }
80712 if (statements.length > 1) {
80713 // Add a DeclarationMarker as a marker for the end of the declaration
80714 statements.push(factory.createEndOfDeclarationMarker(node));
80715 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
80716 }
80717 return ts.singleOrMany(statements);
80718 }
80719 /**
80720 * Transforms a non-decorated class declaration and appends the resulting statements.
80721 *
80722 * @param node A ClassDeclaration node.
80723 * @param name The name of the class.
80724 * @param facts Precomputed facts about the class.
80725 */
80726 function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
80727 // ${modifiers} class ${name} ${heritageClauses} {
80728 // ${members}
80729 // }
80730 // we do not emit modifiers on the declaration if we are emitting an IIFE
80731 var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
80732 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
80733 : undefined;
80734 var classDeclaration = factory.createClassDeclaration(
80735 /*decorators*/ undefined, modifiers, name,
80736 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
80737 // To better align with the old emitter, we should not emit a trailing source map
80738 // entry if the class has static properties.
80739 var emitFlags = ts.getEmitFlags(node);
80740 if (facts & 1 /* HasStaticInitializedProperties */) {
80741 emitFlags |= 32 /* NoTrailingSourceMap */;
80742 }
80743 ts.setTextRange(classDeclaration, node);
80744 ts.setOriginalNode(classDeclaration, node);
80745 ts.setEmitFlags(classDeclaration, emitFlags);
80746 return classDeclaration;
80747 }
80748 /**
80749 * Transforms a decorated class declaration and appends the resulting statements. If
80750 * the class requires an alias to avoid issues with double-binding, the alias is returned.
80751 */
80752 function createClassDeclarationHeadWithDecorators(node, name) {
80753 // When we emit an ES6 class that has a class decorator, we must tailor the
80754 // emit to certain specific cases.
80755 //
80756 // In the simplest case, we emit the class declaration as a let declaration, and
80757 // evaluate decorators after the close of the class body:
80758 //
80759 // [Example 1]
80760 // ---------------------------------------------------------------------
80761 // TypeScript | Javascript
80762 // ---------------------------------------------------------------------
80763 // @dec | let C = class C {
80764 // class C { | }
80765 // } | C = __decorate([dec], C);
80766 // ---------------------------------------------------------------------
80767 // @dec | let C = class C {
80768 // export class C { | }
80769 // } | C = __decorate([dec], C);
80770 // | export { C };
80771 // ---------------------------------------------------------------------
80772 //
80773 // If a class declaration contains a reference to itself *inside* of the class body,
80774 // this introduces two bindings to the class: One outside of the class body, and one
80775 // inside of the class body. If we apply decorators as in [Example 1] above, there
80776 // is the possibility that the decorator `dec` will return a new value for the
80777 // constructor, which would result in the binding inside of the class no longer
80778 // pointing to the same reference as the binding outside of the class.
80779 //
80780 // As a result, we must instead rewrite all references to the class *inside* of the
80781 // class body to instead point to a local temporary alias for the class:
80782 //
80783 // [Example 2]
80784 // ---------------------------------------------------------------------
80785 // TypeScript | Javascript
80786 // ---------------------------------------------------------------------
80787 // @dec | let C = C_1 = class C {
80788 // class C { | static x() { return C_1.y; }
80789 // static x() { return C.y; } | }
80790 // static y = 1; | C.y = 1;
80791 // } | C = C_1 = __decorate([dec], C);
80792 // | var C_1;
80793 // ---------------------------------------------------------------------
80794 // @dec | let C = class C {
80795 // export class C { | static x() { return C_1.y; }
80796 // static x() { return C.y; } | }
80797 // static y = 1; | C.y = 1;
80798 // } | C = C_1 = __decorate([dec], C);
80799 // | export { C };
80800 // | var C_1;
80801 // ---------------------------------------------------------------------
80802 //
80803 // If a class declaration is the default export of a module, we instead emit
80804 // the export after the decorated declaration:
80805 //
80806 // [Example 3]
80807 // ---------------------------------------------------------------------
80808 // TypeScript | Javascript
80809 // ---------------------------------------------------------------------
80810 // @dec | let default_1 = class {
80811 // export default class { | }
80812 // } | default_1 = __decorate([dec], default_1);
80813 // | export default default_1;
80814 // ---------------------------------------------------------------------
80815 // @dec | let C = class C {
80816 // export default class C { | }
80817 // } | C = __decorate([dec], C);
80818 // | export default C;
80819 // ---------------------------------------------------------------------
80820 //
80821 // If the class declaration is the default export and a reference to itself
80822 // inside of the class body, we must emit both an alias for the class *and*
80823 // move the export after the declaration:
80824 //
80825 // [Example 4]
80826 // ---------------------------------------------------------------------
80827 // TypeScript | Javascript
80828 // ---------------------------------------------------------------------
80829 // @dec | let C = class C {
80830 // export default class C { | static x() { return C_1.y; }
80831 // static x() { return C.y; } | }
80832 // static y = 1; | C.y = 1;
80833 // } | C = C_1 = __decorate([dec], C);
80834 // | export default C;
80835 // | var C_1;
80836 // ---------------------------------------------------------------------
80837 //
80838 var location = ts.moveRangePastDecorators(node);
80839 var classAlias = getClassAliasIfNeeded(node);
80840 var declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
80841 // ... = class ${name} ${heritageClauses} {
80842 // ${members}
80843 // }
80844 var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
80845 var members = transformClassMembers(node);
80846 var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
80847 ts.setOriginalNode(classExpression, node);
80848 ts.setTextRange(classExpression, location);
80849 // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
80850 // or decoratedClassAlias if the class contain self-reference.
80851 var statement = factory.createVariableStatement(
80852 /*modifiers*/ undefined, factory.createVariableDeclarationList([
80853 factory.createVariableDeclaration(declName,
80854 /*exclamationToken*/ undefined,
80855 /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression)
80856 ], 1 /* Let */));
80857 ts.setOriginalNode(statement, node);
80858 ts.setTextRange(statement, location);
80859 ts.setCommentRange(statement, node);
80860 return statement;
80861 }
80862 function visitClassExpression(node) {
80863 if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
80864 return ts.visitEachChild(node, visitor, context);
80865 }
80866 var classExpression = factory.createClassExpression(
80867 /*decorators*/ undefined,
80868 /*modifiers*/ undefined, node.name,
80869 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
80870 ts.setOriginalNode(classExpression, node);
80871 ts.setTextRange(classExpression, node);
80872 return classExpression;
80873 }
80874 /**
80875 * Transforms the members of a class.
80876 *
80877 * @param node The current class.
80878 */
80879 function transformClassMembers(node) {
80880 var members = [];
80881 var constructor = ts.getFirstConstructorWithBody(node);
80882 var parametersWithPropertyAssignments = constructor &&
80883 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
80884 if (parametersWithPropertyAssignments) {
80885 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
80886 var parameter = parametersWithPropertyAssignments_1[_i];
80887 if (ts.isIdentifier(parameter.name)) {
80888 members.push(ts.setOriginalNode(factory.createPropertyDeclaration(
80889 /*decorators*/ undefined,
80890 /*modifiers*/ undefined, parameter.name,
80891 /*questionOrExclamationToken*/ undefined,
80892 /*type*/ undefined,
80893 /*initializer*/ undefined), parameter));
80894 }
80895 }
80896 }
80897 ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80898 return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
80899 }
80900 /**
80901 * Gets either the static or instance members of a class that are decorated, or have
80902 * parameters that are decorated.
80903 *
80904 * @param node The class containing the member.
80905 * @param isStatic A value indicating whether to retrieve static or instance members of
80906 * the class.
80907 */
80908 function getDecoratedClassElements(node, isStatic) {
80909 return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
80910 }
80911 /**
80912 * Determines whether a class member is a static member of a class that is decorated, or
80913 * has parameters that are decorated.
80914 *
80915 * @param member The class member.
80916 */
80917 function isStaticDecoratedClassElement(member, parent) {
80918 return isDecoratedClassElement(member, /*isStatic*/ true, parent);
80919 }
80920 /**
80921 * Determines whether a class member is an instance member of a class that is decorated,
80922 * or has parameters that are decorated.
80923 *
80924 * @param member The class member.
80925 */
80926 function isInstanceDecoratedClassElement(member, parent) {
80927 return isDecoratedClassElement(member, /*isStatic*/ false, parent);
80928 }
80929 /**
80930 * Determines whether a class member is either a static or an instance member of a class
80931 * that is decorated, or has parameters that are decorated.
80932 *
80933 * @param member The class member.
80934 */
80935 function isDecoratedClassElement(member, isStatic, parent) {
80936 return ts.nodeOrChildIsDecorated(member, parent)
80937 && isStatic === ts.hasSyntacticModifier(member, 32 /* Static */);
80938 }
80939 /**
80940 * Gets an array of arrays of decorators for the parameters of a function-like node.
80941 * The offset into the result array should correspond to the offset of the parameter.
80942 *
80943 * @param node The function-like node.
80944 */
80945 function getDecoratorsOfParameters(node) {
80946 var decorators;
80947 if (node) {
80948 var parameters = node.parameters;
80949 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
80950 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
80951 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
80952 for (var i = 0; i < numParameters; i++) {
80953 var parameter = parameters[i + firstParameterOffset];
80954 if (decorators || parameter.decorators) {
80955 if (!decorators) {
80956 decorators = new Array(numParameters);
80957 }
80958 decorators[i] = parameter.decorators;
80959 }
80960 }
80961 }
80962 return decorators;
80963 }
80964 /**
80965 * Gets an AllDecorators object containing the decorators for the class and the decorators for the
80966 * parameters of the constructor of the class.
80967 *
80968 * @param node The class node.
80969 */
80970 function getAllDecoratorsOfConstructor(node) {
80971 var decorators = node.decorators;
80972 var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
80973 if (!decorators && !parameters) {
80974 return undefined;
80975 }
80976 return {
80977 decorators: decorators,
80978 parameters: parameters
80979 };
80980 }
80981 /**
80982 * Gets an AllDecorators object containing the decorators for the member and its parameters.
80983 *
80984 * @param node The class node that contains the member.
80985 * @param member The class member.
80986 */
80987 function getAllDecoratorsOfClassElement(node, member) {
80988 switch (member.kind) {
80989 case 166 /* GetAccessor */:
80990 case 167 /* SetAccessor */:
80991 return getAllDecoratorsOfAccessors(node, member);
80992 case 164 /* MethodDeclaration */:
80993 return getAllDecoratorsOfMethod(member);
80994 case 162 /* PropertyDeclaration */:
80995 return getAllDecoratorsOfProperty(member);
80996 default:
80997 return undefined;
80998 }
80999 }
81000 /**
81001 * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
81002 *
81003 * @param node The class node that contains the accessor.
81004 * @param accessor The class accessor member.
81005 */
81006 function getAllDecoratorsOfAccessors(node, accessor) {
81007 if (!accessor.body) {
81008 return undefined;
81009 }
81010 var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
81011 var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
81012 if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
81013 return undefined;
81014 }
81015 var decorators = firstAccessorWithDecorators.decorators;
81016 var parameters = getDecoratorsOfParameters(setAccessor);
81017 if (!decorators && !parameters) {
81018 return undefined;
81019 }
81020 return { decorators: decorators, parameters: parameters };
81021 }
81022 /**
81023 * Gets an AllDecorators object containing the decorators for the method and its parameters.
81024 *
81025 * @param method The class method member.
81026 */
81027 function getAllDecoratorsOfMethod(method) {
81028 if (!method.body) {
81029 return undefined;
81030 }
81031 var decorators = method.decorators;
81032 var parameters = getDecoratorsOfParameters(method);
81033 if (!decorators && !parameters) {
81034 return undefined;
81035 }
81036 return { decorators: decorators, parameters: parameters };
81037 }
81038 /**
81039 * Gets an AllDecorators object containing the decorators for the property.
81040 *
81041 * @param property The class property member.
81042 */
81043 function getAllDecoratorsOfProperty(property) {
81044 var decorators = property.decorators;
81045 if (!decorators) {
81046 return undefined;
81047 }
81048 return { decorators: decorators };
81049 }
81050 /**
81051 * Transforms all of the decorators for a declaration into an array of expressions.
81052 *
81053 * @param node The declaration node.
81054 * @param allDecorators An object containing all of the decorators for the declaration.
81055 */
81056 function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
81057 if (!allDecorators) {
81058 return undefined;
81059 }
81060 var decoratorExpressions = [];
81061 ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
81062 ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
81063 addTypeMetadata(node, container, decoratorExpressions);
81064 return decoratorExpressions;
81065 }
81066 /**
81067 * Generates statements used to apply decorators to either the static or instance members
81068 * of a class.
81069 *
81070 * @param node The class node.
81071 * @param isStatic A value indicating whether to generate statements for static or
81072 * instance members.
81073 */
81074 function addClassElementDecorationStatements(statements, node, isStatic) {
81075 ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
81076 }
81077 /**
81078 * Generates expressions used to apply decorators to either the static or instance members
81079 * of a class.
81080 *
81081 * @param node The class node.
81082 * @param isStatic A value indicating whether to generate expressions for static or
81083 * instance members.
81084 */
81085 function generateClassElementDecorationExpressions(node, isStatic) {
81086 var members = getDecoratedClassElements(node, isStatic);
81087 var expressions;
81088 for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
81089 var member = members_6[_i];
81090 var expression = generateClassElementDecorationExpression(node, member);
81091 if (expression) {
81092 if (!expressions) {
81093 expressions = [expression];
81094 }
81095 else {
81096 expressions.push(expression);
81097 }
81098 }
81099 }
81100 return expressions;
81101 }
81102 /**
81103 * Generates an expression used to evaluate class element decorators at runtime.
81104 *
81105 * @param node The class node that contains the member.
81106 * @param member The class member.
81107 */
81108 function generateClassElementDecorationExpression(node, member) {
81109 var allDecorators = getAllDecoratorsOfClassElement(node, member);
81110 var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
81111 if (!decoratorExpressions) {
81112 return undefined;
81113 }
81114 // Emit the call to __decorate. Given the following:
81115 //
81116 // class C {
81117 // @dec method(@dec2 x) {}
81118 // @dec get accessor() {}
81119 // @dec prop;
81120 // }
81121 //
81122 // The emit for a method is:
81123 //
81124 // __decorate([
81125 // dec,
81126 // __param(0, dec2),
81127 // __metadata("design:type", Function),
81128 // __metadata("design:paramtypes", [Object]),
81129 // __metadata("design:returntype", void 0)
81130 // ], C.prototype, "method", null);
81131 //
81132 // The emit for an accessor is:
81133 //
81134 // __decorate([
81135 // dec
81136 // ], C.prototype, "accessor", null);
81137 //
81138 // The emit for a property is:
81139 //
81140 // __decorate([
81141 // dec
81142 // ], C.prototype, "prop");
81143 //
81144 var prefix = getClassMemberPrefix(node, member);
81145 var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
81146 var descriptor = languageVersion > 0 /* ES3 */
81147 ? member.kind === 162 /* PropertyDeclaration */
81148 // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
81149 // should not invoke `Object.getOwnPropertyDescriptor`.
81150 ? factory.createVoidZero()
81151 // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
81152 // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
81153 : factory.createNull()
81154 : undefined;
81155 var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor);
81156 ts.setTextRange(helper, ts.moveRangePastDecorators(member));
81157 ts.setEmitFlags(helper, 1536 /* NoComments */);
81158 return helper;
81159 }
81160 /**
81161 * Generates a __decorate helper call for a class constructor.
81162 *
81163 * @param node The class node.
81164 */
81165 function addConstructorDecorationStatement(statements, node) {
81166 var expression = generateConstructorDecorationExpression(node);
81167 if (expression) {
81168 statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node));
81169 }
81170 }
81171 /**
81172 * Generates a __decorate helper call for a class constructor.
81173 *
81174 * @param node The class node.
81175 */
81176 function generateConstructorDecorationExpression(node) {
81177 var allDecorators = getAllDecoratorsOfConstructor(node);
81178 var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
81179 if (!decoratorExpressions) {
81180 return undefined;
81181 }
81182 var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
81183 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
81184 var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
81185 var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate);
81186 ts.setEmitFlags(expression, 1536 /* NoComments */);
81187 ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
81188 return expression;
81189 }
81190 /**
81191 * Transforms a decorator into an expression.
81192 *
81193 * @param decorator The decorator node.
81194 */
81195 function transformDecorator(decorator) {
81196 return ts.visitNode(decorator.expression, visitor, ts.isExpression);
81197 }
81198 /**
81199 * Transforms the decorators of a parameter.
81200 *
81201 * @param decorators The decorators for the parameter at the provided offset.
81202 * @param parameterOffset The offset of the parameter.
81203 */
81204 function transformDecoratorsOfParameter(decorators, parameterOffset) {
81205 var expressions;
81206 if (decorators) {
81207 expressions = [];
81208 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
81209 var decorator = decorators_1[_i];
81210 var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset);
81211 ts.setTextRange(helper, decorator.expression);
81212 ts.setEmitFlags(helper, 1536 /* NoComments */);
81213 expressions.push(helper);
81214 }
81215 }
81216 return expressions;
81217 }
81218 /**
81219 * Adds optional type metadata for a declaration.
81220 *
81221 * @param node The declaration node.
81222 * @param decoratorExpressions The destination array to which to add new decorator expressions.
81223 */
81224 function addTypeMetadata(node, container, decoratorExpressions) {
81225 if (USE_NEW_TYPE_METADATA_FORMAT) {
81226 addNewTypeMetadata(node, container, decoratorExpressions);
81227 }
81228 else {
81229 addOldTypeMetadata(node, container, decoratorExpressions);
81230 }
81231 }
81232 function addOldTypeMetadata(node, container, decoratorExpressions) {
81233 if (compilerOptions.emitDecoratorMetadata) {
81234 if (shouldAddTypeMetadata(node)) {
81235 decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node)));
81236 }
81237 if (shouldAddParamTypesMetadata(node)) {
81238 decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container)));
81239 }
81240 if (shouldAddReturnTypeMetadata(node)) {
81241 decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node)));
81242 }
81243 }
81244 }
81245 function addNewTypeMetadata(node, container, decoratorExpressions) {
81246 if (compilerOptions.emitDecoratorMetadata) {
81247 var properties = void 0;
81248 if (shouldAddTypeMetadata(node)) {
81249 (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
81250 }
81251 if (shouldAddParamTypesMetadata(node)) {
81252 (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
81253 }
81254 if (shouldAddReturnTypeMetadata(node)) {
81255 (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
81256 }
81257 if (properties) {
81258 decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)));
81259 }
81260 }
81261 }
81262 /**
81263 * Determines whether to emit the "design:type" metadata based on the node's kind.
81264 * The caller should have already tested whether the node has decorators and whether the
81265 * emitDecoratorMetadata compiler option is set.
81266 *
81267 * @param node The node to test.
81268 */
81269 function shouldAddTypeMetadata(node) {
81270 var kind = node.kind;
81271 return kind === 164 /* MethodDeclaration */
81272 || kind === 166 /* GetAccessor */
81273 || kind === 167 /* SetAccessor */
81274 || kind === 162 /* PropertyDeclaration */;
81275 }
81276 /**
81277 * Determines whether to emit the "design:returntype" metadata based on the node's kind.
81278 * The caller should have already tested whether the node has decorators and whether the
81279 * emitDecoratorMetadata compiler option is set.
81280 *
81281 * @param node The node to test.
81282 */
81283 function shouldAddReturnTypeMetadata(node) {
81284 return node.kind === 164 /* MethodDeclaration */;
81285 }
81286 /**
81287 * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
81288 * The caller should have already tested whether the node has decorators and whether the
81289 * emitDecoratorMetadata compiler option is set.
81290 *
81291 * @param node The node to test.
81292 */
81293 function shouldAddParamTypesMetadata(node) {
81294 switch (node.kind) {
81295 case 249 /* ClassDeclaration */:
81296 case 218 /* ClassExpression */:
81297 return ts.getFirstConstructorWithBody(node) !== undefined;
81298 case 164 /* MethodDeclaration */:
81299 case 166 /* GetAccessor */:
81300 case 167 /* SetAccessor */:
81301 return true;
81302 }
81303 return false;
81304 }
81305 function getAccessorTypeNode(node) {
81306 var accessors = resolver.getAllAccessorDeclarations(node);
81307 return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
81308 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
81309 }
81310 /**
81311 * Serializes the type of a node for use with decorator type metadata.
81312 *
81313 * @param node The node that should have its type serialized.
81314 */
81315 function serializeTypeOfNode(node) {
81316 switch (node.kind) {
81317 case 162 /* PropertyDeclaration */:
81318 case 159 /* Parameter */:
81319 return serializeTypeNode(node.type);
81320 case 167 /* SetAccessor */:
81321 case 166 /* GetAccessor */:
81322 return serializeTypeNode(getAccessorTypeNode(node));
81323 case 249 /* ClassDeclaration */:
81324 case 218 /* ClassExpression */:
81325 case 164 /* MethodDeclaration */:
81326 return factory.createIdentifier("Function");
81327 default:
81328 return factory.createVoidZero();
81329 }
81330 }
81331 /**
81332 * Serializes the types of the parameters of a node for use with decorator type metadata.
81333 *
81334 * @param node The node that should have its parameter types serialized.
81335 */
81336 function serializeParameterTypesOfNode(node, container) {
81337 var valueDeclaration = ts.isClassLike(node)
81338 ? ts.getFirstConstructorWithBody(node)
81339 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
81340 ? node
81341 : undefined;
81342 var expressions = [];
81343 if (valueDeclaration) {
81344 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
81345 var numParameters = parameters.length;
81346 for (var i = 0; i < numParameters; i++) {
81347 var parameter = parameters[i];
81348 if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
81349 continue;
81350 }
81351 if (parameter.dotDotDotToken) {
81352 expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
81353 }
81354 else {
81355 expressions.push(serializeTypeOfNode(parameter));
81356 }
81357 }
81358 }
81359 return factory.createArrayLiteralExpression(expressions);
81360 }
81361 function getParametersOfDecoratedDeclaration(node, container) {
81362 if (container && node.kind === 166 /* GetAccessor */) {
81363 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
81364 if (setAccessor) {
81365 return setAccessor.parameters;
81366 }
81367 }
81368 return node.parameters;
81369 }
81370 /**
81371 * Serializes the return type of a node for use with decorator type metadata.
81372 *
81373 * @param node The node that should have its return type serialized.
81374 */
81375 function serializeReturnTypeOfNode(node) {
81376 if (ts.isFunctionLike(node) && node.type) {
81377 return serializeTypeNode(node.type);
81378 }
81379 else if (ts.isAsyncFunction(node)) {
81380 return factory.createIdentifier("Promise");
81381 }
81382 return factory.createVoidZero();
81383 }
81384 /**
81385 * Serializes a type node for use with decorator type metadata.
81386 *
81387 * Types are serialized in the following fashion:
81388 * - Void types point to "undefined" (e.g. "void 0")
81389 * - Function and Constructor types point to the global "Function" constructor.
81390 * - Interface types with a call or construct signature types point to the global
81391 * "Function" constructor.
81392 * - Array and Tuple types point to the global "Array" constructor.
81393 * - Type predicates and booleans point to the global "Boolean" constructor.
81394 * - String literal types and strings point to the global "String" constructor.
81395 * - Enum and number types point to the global "Number" constructor.
81396 * - Symbol types point to the global "Symbol" constructor.
81397 * - Type references to classes (or class-like variables) point to the constructor for the class.
81398 * - Anything else points to the global "Object" constructor.
81399 *
81400 * @param node The type node to serialize.
81401 */
81402 function serializeTypeNode(node) {
81403 if (node === undefined) {
81404 return factory.createIdentifier("Object");
81405 }
81406 switch (node.kind) {
81407 case 113 /* VoidKeyword */:
81408 case 149 /* UndefinedKeyword */:
81409 case 140 /* NeverKeyword */:
81410 return factory.createVoidZero();
81411 case 185 /* ParenthesizedType */:
81412 return serializeTypeNode(node.type);
81413 case 173 /* FunctionType */:
81414 case 174 /* ConstructorType */:
81415 return factory.createIdentifier("Function");
81416 case 177 /* ArrayType */:
81417 case 178 /* TupleType */:
81418 return factory.createIdentifier("Array");
81419 case 171 /* TypePredicate */:
81420 case 131 /* BooleanKeyword */:
81421 return factory.createIdentifier("Boolean");
81422 case 146 /* StringKeyword */:
81423 return factory.createIdentifier("String");
81424 case 144 /* ObjectKeyword */:
81425 return factory.createIdentifier("Object");
81426 case 190 /* LiteralType */:
81427 switch (node.literal.kind) {
81428 case 10 /* StringLiteral */:
81429 case 14 /* NoSubstitutionTemplateLiteral */:
81430 return factory.createIdentifier("String");
81431 case 211 /* PrefixUnaryExpression */:
81432 case 8 /* NumericLiteral */:
81433 return factory.createIdentifier("Number");
81434 case 9 /* BigIntLiteral */:
81435 return getGlobalBigIntNameWithFallback();
81436 case 109 /* TrueKeyword */:
81437 case 94 /* FalseKeyword */:
81438 return factory.createIdentifier("Boolean");
81439 case 103 /* NullKeyword */:
81440 return factory.createVoidZero();
81441 default:
81442 return ts.Debug.failBadSyntaxKind(node.literal);
81443 }
81444 case 143 /* NumberKeyword */:
81445 return factory.createIdentifier("Number");
81446 case 154 /* BigIntKeyword */:
81447 return getGlobalBigIntNameWithFallback();
81448 case 147 /* SymbolKeyword */:
81449 return languageVersion < 2 /* ES2015 */
81450 ? getGlobalSymbolNameWithFallback()
81451 : factory.createIdentifier("Symbol");
81452 case 172 /* TypeReference */:
81453 return serializeTypeReferenceNode(node);
81454 case 182 /* IntersectionType */:
81455 case 181 /* UnionType */:
81456 return serializeTypeList(node.types);
81457 case 183 /* ConditionalType */:
81458 return serializeTypeList([node.trueType, node.falseType]);
81459 case 187 /* TypeOperator */:
81460 if (node.operator === 141 /* ReadonlyKeyword */) {
81461 return serializeTypeNode(node.type);
81462 }
81463 break;
81464 case 175 /* TypeQuery */:
81465 case 188 /* IndexedAccessType */:
81466 case 189 /* MappedType */:
81467 case 176 /* TypeLiteral */:
81468 case 128 /* AnyKeyword */:
81469 case 151 /* UnknownKeyword */:
81470 case 186 /* ThisType */:
81471 case 192 /* ImportType */:
81472 break;
81473 // handle JSDoc types from an invalid parse
81474 case 299 /* JSDocAllType */:
81475 case 300 /* JSDocUnknownType */:
81476 case 304 /* JSDocFunctionType */:
81477 case 305 /* JSDocVariadicType */:
81478 case 306 /* JSDocNamepathType */:
81479 break;
81480 case 301 /* JSDocNullableType */:
81481 case 302 /* JSDocNonNullableType */:
81482 case 303 /* JSDocOptionalType */:
81483 return serializeTypeNode(node.type);
81484 default:
81485 return ts.Debug.failBadSyntaxKind(node);
81486 }
81487 return factory.createIdentifier("Object");
81488 }
81489 function serializeTypeList(types) {
81490 // Note when updating logic here also update getEntityNameForDecoratorMetadata
81491 // so that aliases can be marked as referenced
81492 var serializedUnion;
81493 for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
81494 var typeNode = types_21[_i];
81495 while (typeNode.kind === 185 /* ParenthesizedType */) {
81496 typeNode = typeNode.type; // Skip parens if need be
81497 }
81498 if (typeNode.kind === 140 /* NeverKeyword */) {
81499 continue; // Always elide `never` from the union/intersection if possible
81500 }
81501 if (!strictNullChecks && (typeNode.kind === 190 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 149 /* UndefinedKeyword */)) {
81502 continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
81503 }
81504 var serializedIndividual = serializeTypeNode(typeNode);
81505 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
81506 // One of the individual is global object, return immediately
81507 return serializedIndividual;
81508 }
81509 // If there exists union that is not void 0 expression, check if the the common type is identifier.
81510 // anything more complex and we will just default to Object
81511 else if (serializedUnion) {
81512 // Different types
81513 if (!ts.isIdentifier(serializedUnion) ||
81514 !ts.isIdentifier(serializedIndividual) ||
81515 serializedUnion.escapedText !== serializedIndividual.escapedText) {
81516 return factory.createIdentifier("Object");
81517 }
81518 }
81519 else {
81520 // Initialize the union type
81521 serializedUnion = serializedIndividual;
81522 }
81523 }
81524 // If we were able to find common type, use it
81525 return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
81526 }
81527 /**
81528 * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
81529 * decorator type metadata.
81530 *
81531 * @param node The type reference node.
81532 */
81533 function serializeTypeReferenceNode(node) {
81534 var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
81535 switch (kind) {
81536 case ts.TypeReferenceSerializationKind.Unknown:
81537 // From conditional type type reference that cannot be resolved is Similar to any or unknown
81538 if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
81539 return factory.createIdentifier("Object");
81540 }
81541 var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
81542 var temp = factory.createTempVariable(hoistVariableDeclaration);
81543 return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"),
81544 /*questionToken*/ undefined, temp,
81545 /*colonToken*/ undefined, factory.createIdentifier("Object"));
81546 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
81547 return serializeEntityNameAsExpression(node.typeName);
81548 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
81549 return factory.createVoidZero();
81550 case ts.TypeReferenceSerializationKind.BigIntLikeType:
81551 return getGlobalBigIntNameWithFallback();
81552 case ts.TypeReferenceSerializationKind.BooleanType:
81553 return factory.createIdentifier("Boolean");
81554 case ts.TypeReferenceSerializationKind.NumberLikeType:
81555 return factory.createIdentifier("Number");
81556 case ts.TypeReferenceSerializationKind.StringLikeType:
81557 return factory.createIdentifier("String");
81558 case ts.TypeReferenceSerializationKind.ArrayLikeType:
81559 return factory.createIdentifier("Array");
81560 case ts.TypeReferenceSerializationKind.ESSymbolType:
81561 return languageVersion < 2 /* ES2015 */
81562 ? getGlobalSymbolNameWithFallback()
81563 : factory.createIdentifier("Symbol");
81564 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
81565 return factory.createIdentifier("Function");
81566 case ts.TypeReferenceSerializationKind.Promise:
81567 return factory.createIdentifier("Promise");
81568 case ts.TypeReferenceSerializationKind.ObjectType:
81569 return factory.createIdentifier("Object");
81570 default:
81571 return ts.Debug.assertNever(kind);
81572 }
81573 }
81574 function createCheckedValue(left, right) {
81575 return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right);
81576 }
81577 /**
81578 * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
81579 *
81580 * @param node The entity name to serialize.
81581 */
81582 function serializeEntityNameAsExpressionFallback(node) {
81583 if (node.kind === 78 /* Identifier */) {
81584 // A -> typeof A !== undefined && A
81585 var copied = serializeEntityNameAsExpression(node);
81586 return createCheckedValue(copied, copied);
81587 }
81588 if (node.left.kind === 78 /* Identifier */) {
81589 // A.B -> typeof A !== undefined && A.B
81590 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
81591 }
81592 // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
81593 var left = serializeEntityNameAsExpressionFallback(node.left);
81594 var temp = factory.createTempVariable(hoistVariableDeclaration);
81595 return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right));
81596 }
81597 /**
81598 * Serializes an entity name as an expression for decorator type metadata.
81599 *
81600 * @param node The entity name to serialize.
81601 */
81602 function serializeEntityNameAsExpression(node) {
81603 switch (node.kind) {
81604 case 78 /* Identifier */:
81605 // Create a clone of the name with a new parent, and treat it as if it were
81606 // a source tree node for the purposes of the checker.
81607 var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent);
81608 name.original = undefined;
81609 ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
81610 return name;
81611 case 156 /* QualifiedName */:
81612 return serializeQualifiedNameAsExpression(node);
81613 }
81614 }
81615 /**
81616 * Serializes an qualified name as an expression for decorator type metadata.
81617 *
81618 * @param node The qualified name to serialize.
81619 * @param useFallback A value indicating whether to use logical operators to test for the
81620 * qualified name at runtime.
81621 */
81622 function serializeQualifiedNameAsExpression(node) {
81623 return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
81624 }
81625 /**
81626 * Gets an expression that points to the global "Symbol" constructor at runtime if it is
81627 * available.
81628 */
81629 function getGlobalSymbolNameWithFallback() {
81630 return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"),
81631 /*questionToken*/ undefined, factory.createIdentifier("Symbol"),
81632 /*colonToken*/ undefined, factory.createIdentifier("Object"));
81633 }
81634 /**
81635 * Gets an expression that points to the global "BigInt" constructor at runtime if it is
81636 * available.
81637 */
81638 function getGlobalBigIntNameWithFallback() {
81639 return languageVersion < 99 /* ESNext */
81640 ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"),
81641 /*questionToken*/ undefined, factory.createIdentifier("BigInt"),
81642 /*colonToken*/ undefined, factory.createIdentifier("Object"))
81643 : factory.createIdentifier("BigInt");
81644 }
81645 /**
81646 * Gets an expression that represents a property name (for decorated properties or enums).
81647 * For a computed property, a name is generated for the node.
81648 *
81649 * @param member The member whose name should be converted into an expression.
81650 */
81651 function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
81652 var name = member.name;
81653 if (ts.isPrivateIdentifier(name)) {
81654 return factory.createIdentifier("");
81655 }
81656 else if (ts.isComputedPropertyName(name)) {
81657 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
81658 ? factory.getGeneratedNameForNode(name)
81659 : name.expression;
81660 }
81661 else if (ts.isIdentifier(name)) {
81662 return factory.createStringLiteral(ts.idText(name));
81663 }
81664 else {
81665 return factory.cloneNode(name);
81666 }
81667 }
81668 /**
81669 * Visits the property name of a class element, for use when emitting property
81670 * initializers. For a computed property on a node with decorators, a temporary
81671 * value is stored for later use.
81672 *
81673 * @param member The member whose name should be visited.
81674 */
81675 function visitPropertyNameOfClassElement(member) {
81676 var name = member.name;
81677 // Computed property names need to be transformed into a hoisted variable when they are used more than once.
81678 // The names are used more than once when:
81679 // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
81680 // - the property has a decorator.
81681 if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
81682 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
81683 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
81684 if (!ts.isSimpleInlineableExpression(innerExpression)) {
81685 var generatedName = factory.getGeneratedNameForNode(name);
81686 hoistVariableDeclaration(generatedName);
81687 return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
81688 }
81689 }
81690 return ts.visitNode(name, visitor, ts.isPropertyName);
81691 }
81692 /**
81693 * Transforms a HeritageClause with TypeScript syntax.
81694 *
81695 * This function will only be called when one of the following conditions are met:
81696 * - The node is a non-`extends` heritage clause that should be elided.
81697 * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
81698 *
81699 * @param node The HeritageClause to transform.
81700 */
81701 function visitHeritageClause(node) {
81702 if (node.token === 116 /* ImplementsKeyword */) {
81703 // implements clauses are elided
81704 return undefined;
81705 }
81706 return ts.visitEachChild(node, visitor, context);
81707 }
81708 /**
81709 * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
81710 *
81711 * This function will only be called when one of the following conditions are met:
81712 * - The node contains type arguments that should be elided.
81713 *
81714 * @param node The ExpressionWithTypeArguments to transform.
81715 */
81716 function visitExpressionWithTypeArguments(node) {
81717 return factory.updateExpressionWithTypeArguments(node, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression),
81718 /*typeArguments*/ undefined);
81719 }
81720 /**
81721 * Determines whether to emit a function-like declaration. We should not emit the
81722 * declaration if it does not have a body.
81723 *
81724 * @param node The declaration node.
81725 */
81726 function shouldEmitFunctionLikeDeclaration(node) {
81727 return !ts.nodeIsMissing(node.body);
81728 }
81729 function visitPropertyDeclaration(node) {
81730 if (node.flags & 8388608 /* Ambient */) {
81731 return undefined;
81732 }
81733 var updated = factory.updatePropertyDeclaration(node,
81734 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node),
81735 /*questionOrExclamationToken*/ undefined,
81736 /*type*/ undefined, ts.visitNode(node.initializer, visitor));
81737 if (updated !== node) {
81738 // While we emit the source map for the node after skipping decorators and modifiers,
81739 // we need to emit the comments for the original range.
81740 ts.setCommentRange(updated, node);
81741 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
81742 }
81743 return updated;
81744 }
81745 function visitConstructor(node) {
81746 if (!shouldEmitFunctionLikeDeclaration(node)) {
81747 return undefined;
81748 }
81749 return factory.updateConstructorDeclaration(node,
81750 /*decorators*/ undefined,
81751 /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
81752 }
81753 function transformConstructorBody(body, constructor) {
81754 var parametersWithPropertyAssignments = constructor &&
81755 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
81756 if (!ts.some(parametersWithPropertyAssignments)) {
81757 return ts.visitFunctionBody(body, visitor, context);
81758 }
81759 var statements = [];
81760 var indexOfFirstStatement = 0;
81761 resumeLexicalEnvironment();
81762 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
81763 // Add parameters with property assignments. Transforms this:
81764 //
81765 // constructor (public x, public y) {
81766 // }
81767 //
81768 // Into this:
81769 //
81770 // constructor (x, y) {
81771 // this.x = x;
81772 // this.y = y;
81773 // }
81774 //
81775 ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
81776 // Add the existing statements, skipping the initial super call.
81777 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
81778 // End the lexical environment.
81779 statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
81780 var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true);
81781 ts.setTextRange(block, /*location*/ body);
81782 ts.setOriginalNode(block, body);
81783 return block;
81784 }
81785 /**
81786 * Transforms a parameter into a property assignment statement.
81787 *
81788 * @param node The parameter declaration.
81789 */
81790 function transformParameterWithPropertyAssignment(node) {
81791 var name = node.name;
81792 if (!ts.isIdentifier(name)) {
81793 return undefined;
81794 }
81795 // TODO(rbuckton): Does this need to be parented?
81796 var propertyName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
81797 ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
81798 // TODO(rbuckton): Does this need to be parented?
81799 var localName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
81800 ts.setEmitFlags(localName, 1536 /* NoComments */);
81801 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))));
81802 }
81803 function visitMethodDeclaration(node) {
81804 if (!shouldEmitFunctionLikeDeclaration(node)) {
81805 return undefined;
81806 }
81807 var updated = factory.updateMethodDeclaration(node,
81808 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node),
81809 /*questionToken*/ undefined,
81810 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
81811 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
81812 if (updated !== node) {
81813 // While we emit the source map for the node after skipping decorators and modifiers,
81814 // we need to emit the comments for the original range.
81815 ts.setCommentRange(updated, node);
81816 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
81817 }
81818 return updated;
81819 }
81820 /**
81821 * Determines whether to emit an accessor declaration. We should not emit the
81822 * declaration if it does not have a body and is abstract.
81823 *
81824 * @param node The declaration node.
81825 */
81826 function shouldEmitAccessorDeclaration(node) {
81827 return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* Abstract */));
81828 }
81829 function visitGetAccessor(node) {
81830 if (!shouldEmitAccessorDeclaration(node)) {
81831 return undefined;
81832 }
81833 var updated = factory.updateGetAccessorDeclaration(node,
81834 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context),
81835 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
81836 if (updated !== node) {
81837 // While we emit the source map for the node after skipping decorators and modifiers,
81838 // we need to emit the comments for the original range.
81839 ts.setCommentRange(updated, node);
81840 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
81841 }
81842 return updated;
81843 }
81844 function visitSetAccessor(node) {
81845 if (!shouldEmitAccessorDeclaration(node)) {
81846 return undefined;
81847 }
81848 var updated = factory.updateSetAccessorDeclaration(node,
81849 /*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([]));
81850 if (updated !== node) {
81851 // While we emit the source map for the node after skipping decorators and modifiers,
81852 // we need to emit the comments for the original range.
81853 ts.setCommentRange(updated, node);
81854 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
81855 }
81856 return updated;
81857 }
81858 function visitFunctionDeclaration(node) {
81859 if (!shouldEmitFunctionLikeDeclaration(node)) {
81860 return factory.createNotEmittedStatement(node);
81861 }
81862 var updated = factory.updateFunctionDeclaration(node,
81863 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
81864 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
81865 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
81866 if (isExportOfNamespace(node)) {
81867 var statements = [updated];
81868 addExportMemberAssignment(statements, node);
81869 return statements;
81870 }
81871 return updated;
81872 }
81873 function visitFunctionExpression(node) {
81874 if (!shouldEmitFunctionLikeDeclaration(node)) {
81875 return factory.createOmittedExpression();
81876 }
81877 var updated = factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
81878 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
81879 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
81880 return updated;
81881 }
81882 function visitArrowFunction(node) {
81883 var updated = factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
81884 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
81885 /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
81886 return updated;
81887 }
81888 function visitParameter(node) {
81889 if (ts.parameterIsThisKeyword(node)) {
81890 return undefined;
81891 }
81892 var updated = factory.updateParameterDeclaration(node,
81893 /*decorators*/ undefined,
81894 /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
81895 /*questionToken*/ undefined,
81896 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81897 if (updated !== node) {
81898 // While we emit the source map for the node after skipping decorators and modifiers,
81899 // we need to emit the comments for the original range.
81900 ts.setCommentRange(updated, node);
81901 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
81902 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
81903 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
81904 }
81905 return updated;
81906 }
81907 function visitVariableStatement(node) {
81908 if (isExportOfNamespace(node)) {
81909 var variables = ts.getInitializedVariables(node.declarationList);
81910 if (variables.length === 0) {
81911 // elide statement if there are no initialized variables.
81912 return undefined;
81913 }
81914 return ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
81915 }
81916 else {
81917 return ts.visitEachChild(node, visitor, context);
81918 }
81919 }
81920 function transformInitializedVariable(node) {
81921 var name = node.name;
81922 if (ts.isBindingPattern(name)) {
81923 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */,
81924 /*needsValue*/ false, createNamespaceExportExpression);
81925 }
81926 else {
81927 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)),
81928 /*location*/ node);
81929 }
81930 }
81931 function visitVariableDeclaration(node) {
81932 return factory.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
81933 /*exclamationToken*/ undefined,
81934 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81935 }
81936 function visitParenthesizedExpression(node) {
81937 var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
81938 if (ts.isAssertionExpression(innerExpression)) {
81939 // Make sure we consider all nested cast expressions, e.g.:
81940 // (<any><number><any>-A).x;
81941 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81942 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
81943 // is really not desirable. We would like to emit the subexpression as-is. Omitting
81944 // the parentheses, however, could cause change in the semantics of the generated
81945 // code if the casted expression has a lower precedence than the rest of the
81946 // expression.
81947 //
81948 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
81949 // preserve the position information of the original expression.
81950 //
81951 // Due to the auto-parenthesization rules used by the visitor and factory functions
81952 // we can safely elide the parentheses here, as a new synthetic
81953 // ParenthesizedExpression will be inserted if we remove parentheses too
81954 // aggressively.
81955 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
81956 // correctly for return and throw, we must keep the parenthesis
81957 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
81958 return factory.updateParenthesizedExpression(node, expression);
81959 }
81960 return factory.createPartiallyEmittedExpression(expression, node);
81961 }
81962 return ts.visitEachChild(node, visitor, context);
81963 }
81964 function visitAssertionExpression(node) {
81965 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81966 return factory.createPartiallyEmittedExpression(expression, node);
81967 }
81968 function visitNonNullExpression(node) {
81969 var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
81970 return factory.createPartiallyEmittedExpression(expression, node);
81971 }
81972 function visitCallExpression(node) {
81973 return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression),
81974 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
81975 }
81976 function visitNewExpression(node) {
81977 return factory.updateNewExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression),
81978 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
81979 }
81980 function visitTaggedTemplateExpression(node) {
81981 return factory.updateTaggedTemplateExpression(node, ts.visitNode(node.tag, visitor, ts.isExpression),
81982 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
81983 }
81984 function visitJsxSelfClosingElement(node) {
81985 return factory.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression),
81986 /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
81987 }
81988 function visitJsxJsxOpeningElement(node) {
81989 return factory.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression),
81990 /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
81991 }
81992 /**
81993 * Determines whether to emit an enum declaration.
81994 *
81995 * @param node The enum declaration node.
81996 */
81997 function shouldEmitEnumDeclaration(node) {
81998 return !ts.isEnumConst(node)
81999 || compilerOptions.preserveConstEnums
82000 || compilerOptions.isolatedModules;
82001 }
82002 /**
82003 * Visits an enum declaration.
82004 *
82005 * This function will be called any time a TypeScript enum is encountered.
82006 *
82007 * @param node The enum declaration node.
82008 */
82009 function visitEnumDeclaration(node) {
82010 if (!shouldEmitEnumDeclaration(node)) {
82011 return factory.createNotEmittedStatement(node);
82012 }
82013 var statements = [];
82014 // We request to be advised when the printer is about to print this node. This allows
82015 // us to set up the correct state for later substitutions.
82016 var emitFlags = 2 /* AdviseOnEmitNode */;
82017 // If needed, we should emit a variable declaration for the enum. If we emit
82018 // a leading variable declaration, we should not emit leading comments for the
82019 // enum body.
82020 var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
82021 if (varAdded) {
82022 // We should still emit the comments if we are emitting a system module.
82023 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
82024 emitFlags |= 512 /* NoLeadingComments */;
82025 }
82026 }
82027 // `parameterName` is the declaration name used inside of the enum.
82028 var parameterName = getNamespaceParameterName(node);
82029 // `containerName` is the expression used inside of the enum for assignments.
82030 var containerName = getNamespaceContainerName(node);
82031 // `exportName` is the expression used within this node's container for any exported references.
82032 var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
82033 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
82034 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82035 // x || (x = {})
82036 // exports.x || (exports.x = {})
82037 var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
82038 if (hasNamespaceQualifiedExportName(node)) {
82039 // `localName` is the expression used within this node's containing scope for any local references.
82040 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82041 // x = (exports.x || (exports.x = {}))
82042 moduleArg = factory.createAssignment(localName, moduleArg);
82043 }
82044 // (function (x) {
82045 // x[x["y"] = 0] = "y";
82046 // ...
82047 // })(x || (x = {}));
82048 var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
82049 /*modifiers*/ undefined,
82050 /*asteriskToken*/ undefined,
82051 /*name*/ undefined,
82052 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
82053 /*type*/ undefined, transformEnumBody(node, containerName)),
82054 /*typeArguments*/ undefined, [moduleArg]));
82055 ts.setOriginalNode(enumStatement, node);
82056 if (varAdded) {
82057 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
82058 ts.setSyntheticLeadingComments(enumStatement, undefined);
82059 ts.setSyntheticTrailingComments(enumStatement, undefined);
82060 }
82061 ts.setTextRange(enumStatement, node);
82062 ts.addEmitFlags(enumStatement, emitFlags);
82063 statements.push(enumStatement);
82064 // Add a DeclarationMarker for the enum to preserve trailing comments and mark
82065 // the end of the declaration.
82066 statements.push(factory.createEndOfDeclarationMarker(node));
82067 return statements;
82068 }
82069 /**
82070 * Transforms the body of an enum declaration.
82071 *
82072 * @param node The enum declaration node.
82073 */
82074 function transformEnumBody(node, localName) {
82075 var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
82076 currentNamespaceContainerName = localName;
82077 var statements = [];
82078 startLexicalEnvironment();
82079 var members = ts.map(node.members, transformEnumMember);
82080 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82081 ts.addRange(statements, members);
82082 currentNamespaceContainerName = savedCurrentNamespaceLocalName;
82083 return factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members),
82084 /*multiLine*/ true);
82085 }
82086 /**
82087 * Transforms an enum member into a statement.
82088 *
82089 * @param member The enum member node.
82090 */
82091 function transformEnumMember(member) {
82092 // enums don't support computed properties
82093 // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
82094 // old emitter always generate 'expression' part of the name as-is.
82095 var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
82096 var valueExpression = transformEnumMemberDeclarationValue(member);
82097 var innerAssignment = factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression);
82098 var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
82099 innerAssignment :
82100 factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name);
82101 return ts.setTextRange(factory.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
82102 }
82103 /**
82104 * Transforms the value of an enum member.
82105 *
82106 * @param member The enum member node.
82107 */
82108 function transformEnumMemberDeclarationValue(member) {
82109 var value = resolver.getConstantValue(member);
82110 if (value !== undefined) {
82111 return typeof value === "string" ? factory.createStringLiteral(value) : factory.createNumericLiteral(value);
82112 }
82113 else {
82114 enableSubstitutionForNonQualifiedEnumMembers();
82115 if (member.initializer) {
82116 return ts.visitNode(member.initializer, visitor, ts.isExpression);
82117 }
82118 else {
82119 return factory.createVoidZero();
82120 }
82121 }
82122 }
82123 /**
82124 * Determines whether to elide a module declaration.
82125 *
82126 * @param node The module declaration node.
82127 */
82128 function shouldEmitModuleDeclaration(nodeIn) {
82129 var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
82130 if (!node) {
82131 // If we can't find a parse tree node, assume the node is instantiated.
82132 return true;
82133 }
82134 return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
82135 }
82136 /**
82137 * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
82138 * or `exports.x`).
82139 */
82140 function hasNamespaceQualifiedExportName(node) {
82141 return isExportOfNamespace(node)
82142 || (isExternalModuleExport(node)
82143 && moduleKind !== ts.ModuleKind.ES2015
82144 && moduleKind !== ts.ModuleKind.ES2020
82145 && moduleKind !== ts.ModuleKind.ESNext
82146 && moduleKind !== ts.ModuleKind.System);
82147 }
82148 /**
82149 * Records that a declaration was emitted in the current scope, if it was the first
82150 * declaration for the provided symbol.
82151 */
82152 function recordEmittedDeclarationInScope(node) {
82153 if (!currentScopeFirstDeclarationsOfName) {
82154 currentScopeFirstDeclarationsOfName = new ts.Map();
82155 }
82156 var name = declaredNameInScope(node);
82157 if (!currentScopeFirstDeclarationsOfName.has(name)) {
82158 currentScopeFirstDeclarationsOfName.set(name, node);
82159 }
82160 }
82161 /**
82162 * Determines whether a declaration is the first declaration with
82163 * the same name emitted in the current scope.
82164 */
82165 function isFirstEmittedDeclarationInScope(node) {
82166 if (currentScopeFirstDeclarationsOfName) {
82167 var name = declaredNameInScope(node);
82168 return currentScopeFirstDeclarationsOfName.get(name) === node;
82169 }
82170 return true;
82171 }
82172 function declaredNameInScope(node) {
82173 ts.Debug.assertNode(node.name, ts.isIdentifier);
82174 return node.name.escapedText;
82175 }
82176 /**
82177 * Adds a leading VariableStatement for a enum or module declaration.
82178 */
82179 function addVarForEnumOrModuleDeclaration(statements, node) {
82180 // Emit a variable statement for the module. We emit top-level enums as a `var`
82181 // declaration to avoid static errors in global scripts scripts due to redeclaration.
82182 // enums in any other scope are emitted as a `let` declaration.
82183 var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
82184 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
82185 ], currentLexicalScope.kind === 294 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
82186 ts.setOriginalNode(statement, node);
82187 recordEmittedDeclarationInScope(node);
82188 if (isFirstEmittedDeclarationInScope(node)) {
82189 // Adjust the source map emit to match the old emitter.
82190 if (node.kind === 252 /* EnumDeclaration */) {
82191 ts.setSourceMapRange(statement.declarationList, node);
82192 }
82193 else {
82194 ts.setSourceMapRange(statement, node);
82195 }
82196 // Trailing comments for module declaration should be emitted after the function closure
82197 // instead of the variable statement:
82198 //
82199 // /** Module comment*/
82200 // module m1 {
82201 // function foo4Export() {
82202 // }
82203 // } // trailing comment module
82204 //
82205 // Should emit:
82206 //
82207 // /** Module comment*/
82208 // var m1;
82209 // (function (m1) {
82210 // function foo4Export() {
82211 // }
82212 // })(m1 || (m1 = {})); // trailing comment module
82213 //
82214 ts.setCommentRange(statement, node);
82215 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
82216 statements.push(statement);
82217 return true;
82218 }
82219 else {
82220 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
82221 // declaration we do not emit a leading variable declaration. To preserve the
82222 // begin/end semantics of the declararation and to properly handle exports
82223 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
82224 var mergeMarker = factory.createMergeDeclarationMarker(statement);
82225 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
82226 statements.push(mergeMarker);
82227 return false;
82228 }
82229 }
82230 /**
82231 * Visits a module declaration node.
82232 *
82233 * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
82234 *
82235 * @param node The module declaration node.
82236 */
82237 function visitModuleDeclaration(node) {
82238 if (!shouldEmitModuleDeclaration(node)) {
82239 return factory.createNotEmittedStatement(node);
82240 }
82241 ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
82242 enableSubstitutionForNamespaceExports();
82243 var statements = [];
82244 // We request to be advised when the printer is about to print this node. This allows
82245 // us to set up the correct state for later substitutions.
82246 var emitFlags = 2 /* AdviseOnEmitNode */;
82247 // If needed, we should emit a variable declaration for the module. If we emit
82248 // a leading variable declaration, we should not emit leading comments for the
82249 // module body.
82250 var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
82251 if (varAdded) {
82252 // We should still emit the comments if we are emitting a system module.
82253 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
82254 emitFlags |= 512 /* NoLeadingComments */;
82255 }
82256 }
82257 // `parameterName` is the declaration name used inside of the namespace.
82258 var parameterName = getNamespaceParameterName(node);
82259 // `containerName` is the expression used inside of the namespace for exports.
82260 var containerName = getNamespaceContainerName(node);
82261 // `exportName` is the expression used within this node's container for any exported references.
82262 var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
82263 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
82264 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82265 // x || (x = {})
82266 // exports.x || (exports.x = {})
82267 var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
82268 if (hasNamespaceQualifiedExportName(node)) {
82269 // `localName` is the expression used within this node's containing scope for any local references.
82270 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82271 // x = (exports.x || (exports.x = {}))
82272 moduleArg = factory.createAssignment(localName, moduleArg);
82273 }
82274 // (function (x_1) {
82275 // x_1.y = ...;
82276 // })(x || (x = {}));
82277 var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
82278 /*modifiers*/ undefined,
82279 /*asteriskToken*/ undefined,
82280 /*name*/ undefined,
82281 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
82282 /*type*/ undefined, transformModuleBody(node, containerName)),
82283 /*typeArguments*/ undefined, [moduleArg]));
82284 ts.setOriginalNode(moduleStatement, node);
82285 if (varAdded) {
82286 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
82287 ts.setSyntheticLeadingComments(moduleStatement, undefined);
82288 ts.setSyntheticTrailingComments(moduleStatement, undefined);
82289 }
82290 ts.setTextRange(moduleStatement, node);
82291 ts.addEmitFlags(moduleStatement, emitFlags);
82292 statements.push(moduleStatement);
82293 // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
82294 // the end of the declaration.
82295 statements.push(factory.createEndOfDeclarationMarker(node));
82296 return statements;
82297 }
82298 /**
82299 * Transforms the body of a module declaration.
82300 *
82301 * @param node The module declaration node.
82302 */
82303 function transformModuleBody(node, namespaceLocalName) {
82304 var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
82305 var savedCurrentNamespace = currentNamespace;
82306 var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
82307 currentNamespaceContainerName = namespaceLocalName;
82308 currentNamespace = node;
82309 currentScopeFirstDeclarationsOfName = undefined;
82310 var statements = [];
82311 startLexicalEnvironment();
82312 var statementsLocation;
82313 var blockLocation;
82314 if (node.body) {
82315 if (node.body.kind === 254 /* ModuleBlock */) {
82316 saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
82317 statementsLocation = node.body.statements;
82318 blockLocation = node.body;
82319 }
82320 else {
82321 var result = visitModuleDeclaration(node.body);
82322 if (result) {
82323 if (ts.isArray(result)) {
82324 ts.addRange(statements, result);
82325 }
82326 else {
82327 statements.push(result);
82328 }
82329 }
82330 var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
82331 statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
82332 }
82333 }
82334 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82335 currentNamespaceContainerName = savedCurrentNamespaceContainerName;
82336 currentNamespace = savedCurrentNamespace;
82337 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
82338 var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements),
82339 /*location*/ statementsLocation),
82340 /*multiLine*/ true);
82341 ts.setTextRange(block, blockLocation);
82342 // namespace hello.hi.world {
82343 // function foo() {}
82344 //
82345 // // TODO, blah
82346 // }
82347 //
82348 // should be emitted as
82349 //
82350 // var hello;
82351 // (function (hello) {
82352 // var hi;
82353 // (function (hi) {
82354 // var world;
82355 // (function (world) {
82356 // function foo() { }
82357 // // TODO, blah
82358 // })(world = hi.world || (hi.world = {}));
82359 // })(hi = hello.hi || (hello.hi = {}));
82360 // })(hello || (hello = {}));
82361 // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
82362 if (!node.body || node.body.kind !== 254 /* ModuleBlock */) {
82363 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
82364 }
82365 return block;
82366 }
82367 function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
82368 if (moduleDeclaration.body.kind === 253 /* ModuleDeclaration */) {
82369 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
82370 return recursiveInnerModule || moduleDeclaration.body;
82371 }
82372 }
82373 /**
82374 * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
82375 *
82376 * @param node The import declaration node.
82377 */
82378 function visitImportDeclaration(node) {
82379 if (!node.importClause) {
82380 // Do not elide a side-effect only import declaration.
82381 // import "foo";
82382 return node;
82383 }
82384 if (node.importClause.isTypeOnly) {
82385 // Always elide type-only imports
82386 return undefined;
82387 }
82388 // Elide the declaration if the import clause was elided.
82389 var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
82390 return importClause ||
82391 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
82392 compilerOptions.importsNotUsedAsValues === 2 /* Error */
82393 ? factory.updateImportDeclaration(node,
82394 /*decorators*/ undefined,
82395 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
82396 : undefined;
82397 }
82398 /**
82399 * Visits an import clause, eliding it if it is not referenced.
82400 *
82401 * @param node The import clause node.
82402 */
82403 function visitImportClause(node) {
82404 if (node.isTypeOnly) {
82405 return undefined;
82406 }
82407 // Elide the import clause if we elide both its name and its named bindings.
82408 var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
82409 var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
82410 return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined;
82411 }
82412 /**
82413 * Visits named import bindings, eliding it if it is not referenced.
82414 *
82415 * @param node The named import bindings node.
82416 */
82417 function visitNamedImportBindings(node) {
82418 if (node.kind === 260 /* NamespaceImport */) {
82419 // Elide a namespace import if it is not referenced.
82420 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
82421 }
82422 else {
82423 // Elide named imports if all of its import specifiers are elided.
82424 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
82425 return ts.some(elements) ? factory.updateNamedImports(node, elements) : undefined;
82426 }
82427 }
82428 /**
82429 * Visits an import specifier, eliding it if it is not referenced.
82430 *
82431 * @param node The import specifier node.
82432 */
82433 function visitImportSpecifier(node) {
82434 // Elide an import specifier if it is not referenced.
82435 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
82436 }
82437 /**
82438 * Visits an export assignment, eliding it if it does not contain a clause that resolves
82439 * to a value.
82440 *
82441 * @param node The export assignment node.
82442 */
82443 function visitExportAssignment(node) {
82444 // Elide the export assignment if it does not reference a value.
82445 return resolver.isValueAliasDeclaration(node)
82446 ? ts.visitEachChild(node, visitor, context)
82447 : undefined;
82448 }
82449 /**
82450 * Visits an export declaration, eliding it if it does not contain a clause that resolves
82451 * to a value.
82452 *
82453 * @param node The export declaration node.
82454 */
82455 function visitExportDeclaration(node) {
82456 if (node.isTypeOnly) {
82457 return undefined;
82458 }
82459 if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
82460 // never elide `export <whatever> from <whereever>` declarations -
82461 // they should be kept for sideffects/untyped exports, even when the
82462 // type checker doesn't know about any exports
82463 return node;
82464 }
82465 if (!resolver.isValueAliasDeclaration(node)) {
82466 // Elide the export declaration if it does not export a value.
82467 return undefined;
82468 }
82469 // Elide the export declaration if all of its named exports are elided.
82470 var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
82471 return exportClause
82472 ? factory.updateExportDeclaration(node,
82473 /*decorators*/ undefined,
82474 /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier)
82475 : undefined;
82476 }
82477 /**
82478 * Visits named exports, eliding it if it does not contain an export specifier that
82479 * resolves to a value.
82480 *
82481 * @param node The named exports node.
82482 */
82483 function visitNamedExports(node) {
82484 // Elide the named exports if all of its export specifiers were elided.
82485 var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
82486 return ts.some(elements) ? factory.updateNamedExports(node, elements) : undefined;
82487 }
82488 function visitNamespaceExports(node) {
82489 return factory.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
82490 }
82491 function visitNamedExportBindings(node) {
82492 return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
82493 }
82494 /**
82495 * Visits an export specifier, eliding it if it does not resolve to a value.
82496 *
82497 * @param node The export specifier node.
82498 */
82499 function visitExportSpecifier(node) {
82500 // Elide an export specifier if it does not reference a value.
82501 return resolver.isValueAliasDeclaration(node) ? node : undefined;
82502 }
82503 /**
82504 * Determines whether to emit an import equals declaration.
82505 *
82506 * @param node The import equals declaration node.
82507 */
82508 function shouldEmitImportEqualsDeclaration(node) {
82509 // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
82510 // - current file is not external module
82511 // - import declaration is top level and target is value imported by entity name
82512 return resolver.isReferencedAliasDeclaration(node)
82513 || (!ts.isExternalModule(currentSourceFile)
82514 && resolver.isTopLevelValueImportEqualsWithEntityName(node));
82515 }
82516 /**
82517 * Visits an import equals declaration.
82518 *
82519 * @param node The import equals declaration node.
82520 */
82521 function visitImportEqualsDeclaration(node) {
82522 if (ts.isExternalModuleImportEqualsDeclaration(node)) {
82523 var isReferenced = resolver.isReferencedAliasDeclaration(node);
82524 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
82525 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
82526 return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(
82527 /*decorators*/ undefined,
82528 /*modifiers*/ undefined,
82529 /*importClause*/ undefined, node.moduleReference.expression), node), node);
82530 }
82531 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
82532 }
82533 if (!shouldEmitImportEqualsDeclaration(node)) {
82534 return undefined;
82535 }
82536 var moduleReference = ts.createExpressionFromEntityName(factory, node.moduleReference);
82537 ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
82538 if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
82539 // export var ${name} = ${moduleReference};
82540 // var ${name} = ${moduleReference};
82541 return ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
82542 ts.setOriginalNode(factory.createVariableDeclaration(node.name,
82543 /*exclamationToken*/ undefined,
82544 /*type*/ undefined, moduleReference), node)
82545 ])), node), node);
82546 }
82547 else {
82548 // exports.${name} = ${moduleReference};
82549 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
82550 }
82551 }
82552 /**
82553 * Gets a value indicating whether the node is exported from a namespace.
82554 *
82555 * @param node The node to test.
82556 */
82557 function isExportOfNamespace(node) {
82558 return currentNamespace !== undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
82559 }
82560 /**
82561 * Gets a value indicating whether the node is exported from an external module.
82562 *
82563 * @param node The node to test.
82564 */
82565 function isExternalModuleExport(node) {
82566 return currentNamespace === undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
82567 }
82568 /**
82569 * Gets a value indicating whether the node is a named export from an external module.
82570 *
82571 * @param node The node to test.
82572 */
82573 function isNamedExternalModuleExport(node) {
82574 return isExternalModuleExport(node)
82575 && !ts.hasSyntacticModifier(node, 512 /* Default */);
82576 }
82577 /**
82578 * Gets a value indicating whether the node is the default export of an external module.
82579 *
82580 * @param node The node to test.
82581 */
82582 function isDefaultExternalModuleExport(node) {
82583 return isExternalModuleExport(node)
82584 && ts.hasSyntacticModifier(node, 512 /* Default */);
82585 }
82586 /**
82587 * Creates a statement for the provided expression. This is used in calls to `map`.
82588 */
82589 function expressionToStatement(expression) {
82590 return factory.createExpressionStatement(expression);
82591 }
82592 function addExportMemberAssignment(statements, node) {
82593 var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node));
82594 ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
82595 var statement = factory.createExpressionStatement(expression);
82596 ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
82597 statements.push(statement);
82598 }
82599 function createNamespaceExport(exportName, exportValue, location) {
82600 return ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
82601 }
82602 function createNamespaceExportExpression(exportName, exportValue, location) {
82603 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
82604 }
82605 function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
82606 return factory.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
82607 }
82608 /**
82609 * Gets the declaration name used inside of a namespace or enum.
82610 */
82611 function getNamespaceParameterName(node) {
82612 var name = factory.getGeneratedNameForNode(node);
82613 ts.setSourceMapRange(name, node.name);
82614 return name;
82615 }
82616 /**
82617 * Gets the expression used to refer to a namespace or enum within the body
82618 * of its declaration.
82619 */
82620 function getNamespaceContainerName(node) {
82621 return factory.getGeneratedNameForNode(node);
82622 }
82623 /**
82624 * Gets a local alias for a class declaration if it is a decorated class with an internal
82625 * reference to the static side of the class. This is necessary to avoid issues with
82626 * double-binding semantics for the class name.
82627 */
82628 function getClassAliasIfNeeded(node) {
82629 if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
82630 enableSubstitutionForClassAliases();
82631 var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
82632 classAliases[ts.getOriginalNodeId(node)] = classAlias;
82633 hoistVariableDeclaration(classAlias);
82634 return classAlias;
82635 }
82636 }
82637 function getClassPrototype(node) {
82638 return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype");
82639 }
82640 function getClassMemberPrefix(node, member) {
82641 return ts.hasSyntacticModifier(member, 32 /* Static */)
82642 ? factory.getDeclarationName(node)
82643 : getClassPrototype(node);
82644 }
82645 function enableSubstitutionForNonQualifiedEnumMembers() {
82646 if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
82647 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
82648 context.enableSubstitution(78 /* Identifier */);
82649 }
82650 }
82651 function enableSubstitutionForClassAliases() {
82652 if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
82653 enabledSubstitutions |= 1 /* ClassAliases */;
82654 // We need to enable substitutions for identifiers. This allows us to
82655 // substitute class names inside of a class declaration.
82656 context.enableSubstitution(78 /* Identifier */);
82657 // Keep track of class aliases.
82658 classAliases = [];
82659 }
82660 }
82661 function enableSubstitutionForNamespaceExports() {
82662 if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
82663 enabledSubstitutions |= 2 /* NamespaceExports */;
82664 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
82665 // substitute the names of exported members of a namespace.
82666 context.enableSubstitution(78 /* Identifier */);
82667 context.enableSubstitution(286 /* ShorthandPropertyAssignment */);
82668 // We need to be notified when entering and exiting namespaces.
82669 context.enableEmitNotification(253 /* ModuleDeclaration */);
82670 }
82671 }
82672 function isTransformedModuleDeclaration(node) {
82673 return ts.getOriginalNode(node).kind === 253 /* ModuleDeclaration */;
82674 }
82675 function isTransformedEnumDeclaration(node) {
82676 return ts.getOriginalNode(node).kind === 252 /* EnumDeclaration */;
82677 }
82678 /**
82679 * Hook for node emit.
82680 *
82681 * @param hint A hint as to the intended usage of the node.
82682 * @param node The node to emit.
82683 * @param emit A callback used to emit the node in the printer.
82684 */
82685 function onEmitNode(hint, node, emitCallback) {
82686 var savedApplicableSubstitutions = applicableSubstitutions;
82687 var savedCurrentSourceFile = currentSourceFile;
82688 if (ts.isSourceFile(node)) {
82689 currentSourceFile = node;
82690 }
82691 if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
82692 applicableSubstitutions |= 2 /* NamespaceExports */;
82693 }
82694 if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
82695 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
82696 }
82697 previousOnEmitNode(hint, node, emitCallback);
82698 applicableSubstitutions = savedApplicableSubstitutions;
82699 currentSourceFile = savedCurrentSourceFile;
82700 }
82701 /**
82702 * Hooks node substitutions.
82703 *
82704 * @param hint A hint as to the intended usage of the node.
82705 * @param node The node to substitute.
82706 */
82707 function onSubstituteNode(hint, node) {
82708 node = previousOnSubstituteNode(hint, node);
82709 if (hint === 1 /* Expression */) {
82710 return substituteExpression(node);
82711 }
82712 else if (ts.isShorthandPropertyAssignment(node)) {
82713 return substituteShorthandPropertyAssignment(node);
82714 }
82715 return node;
82716 }
82717 function substituteShorthandPropertyAssignment(node) {
82718 if (enabledSubstitutions & 2 /* NamespaceExports */) {
82719 var name = node.name;
82720 var exportedName = trySubstituteNamespaceExportedName(name);
82721 if (exportedName) {
82722 // A shorthand property with an assignment initializer is probably part of a
82723 // destructuring assignment
82724 if (node.objectAssignmentInitializer) {
82725 var initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer);
82726 return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
82727 }
82728 return ts.setTextRange(factory.createPropertyAssignment(name, exportedName), node);
82729 }
82730 }
82731 return node;
82732 }
82733 function substituteExpression(node) {
82734 switch (node.kind) {
82735 case 78 /* Identifier */:
82736 return substituteExpressionIdentifier(node);
82737 case 198 /* PropertyAccessExpression */:
82738 return substitutePropertyAccessExpression(node);
82739 case 199 /* ElementAccessExpression */:
82740 return substituteElementAccessExpression(node);
82741 }
82742 return node;
82743 }
82744 function substituteExpressionIdentifier(node) {
82745 return trySubstituteClassAlias(node)
82746 || trySubstituteNamespaceExportedName(node)
82747 || node;
82748 }
82749 function trySubstituteClassAlias(node) {
82750 if (enabledSubstitutions & 1 /* ClassAliases */) {
82751 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
82752 // Due to the emit for class decorators, any reference to the class from inside of the class body
82753 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
82754 // behavior of class names in ES6.
82755 // Also, when emitting statics for class expressions, we must substitute a class alias for
82756 // constructor references in static property initializers.
82757 var declaration = resolver.getReferencedValueDeclaration(node);
82758 if (declaration) {
82759 var classAlias = classAliases[declaration.id]; // TODO: GH#18217
82760 if (classAlias) {
82761 var clone_1 = factory.cloneNode(classAlias);
82762 ts.setSourceMapRange(clone_1, node);
82763 ts.setCommentRange(clone_1, node);
82764 return clone_1;
82765 }
82766 }
82767 }
82768 }
82769 return undefined;
82770 }
82771 function trySubstituteNamespaceExportedName(node) {
82772 // If this is explicitly a local name, do not substitute.
82773 if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
82774 // If we are nested within a namespace declaration, we may need to qualifiy
82775 // an identifier that is exported from a merged namespace.
82776 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
82777 if (container && container.kind !== 294 /* SourceFile */) {
82778 var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 253 /* ModuleDeclaration */) ||
82779 (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 252 /* EnumDeclaration */);
82780 if (substitute) {
82781 return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node),
82782 /*location*/ node);
82783 }
82784 }
82785 }
82786 return undefined;
82787 }
82788 function substitutePropertyAccessExpression(node) {
82789 return substituteConstantValue(node);
82790 }
82791 function substituteElementAccessExpression(node) {
82792 return substituteConstantValue(node);
82793 }
82794 function substituteConstantValue(node) {
82795 var constantValue = tryGetConstEnumValue(node);
82796 if (constantValue !== undefined) {
82797 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
82798 ts.setConstantValue(node, constantValue);
82799 var substitute = typeof constantValue === "string" ? factory.createStringLiteral(constantValue) : factory.createNumericLiteral(constantValue);
82800 if (!compilerOptions.removeComments) {
82801 var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
82802 var propertyName = ts.isPropertyAccessExpression(originalNode)
82803 ? ts.declarationNameToString(originalNode.name)
82804 : ts.getTextOfNode(originalNode.argumentExpression);
82805 ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
82806 }
82807 return substitute;
82808 }
82809 return node;
82810 }
82811 function tryGetConstEnumValue(node) {
82812 if (compilerOptions.isolatedModules) {
82813 return undefined;
82814 }
82815 return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
82816 }
82817 }
82818 ts.transformTypeScript = transformTypeScript;
82819})(ts || (ts = {}));
82820/*@internal*/
82821var ts;
82822(function (ts) {
82823 var ClassPropertySubstitutionFlags;
82824 (function (ClassPropertySubstitutionFlags) {
82825 /**
82826 * Enables substitutions for class expressions with static fields
82827 * which have initializers that reference the class name.
82828 */
82829 ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
82830 })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
82831 var PrivateIdentifierPlacement;
82832 (function (PrivateIdentifierPlacement) {
82833 PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
82834 })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
82835 /**
82836 * Transforms ECMAScript Class Syntax.
82837 * TypeScript parameter property syntax is transformed in the TypeScript transformer.
82838 * For now, this transforms public field declarations using TypeScript class semantics,
82839 * where declarations are elided and initializers are transformed as assignments in the constructor.
82840 * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
82841 */
82842 function transformClassFields(context) {
82843 var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
82844 var resolver = context.getEmitResolver();
82845 var compilerOptions = context.getCompilerOptions();
82846 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
82847 var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
82848 var previousOnSubstituteNode = context.onSubstituteNode;
82849 context.onSubstituteNode = onSubstituteNode;
82850 var enabledSubstitutions;
82851 var classAliases;
82852 /**
82853 * Tracks what computed name expressions originating from elided names must be inlined
82854 * at the next execution site, in document order
82855 */
82856 var pendingExpressions;
82857 /**
82858 * Tracks what computed name expression statements and static property initializers must be
82859 * emitted at the next execution site, in document order (for decorated classes).
82860 */
82861 var pendingStatements;
82862 var privateIdentifierEnvironmentStack = [];
82863 var currentPrivateIdentifierEnvironment;
82864 return ts.chainBundle(context, transformSourceFile);
82865 function transformSourceFile(node) {
82866 var options = context.getCompilerOptions();
82867 if (node.isDeclarationFile
82868 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
82869 return node;
82870 }
82871 var visited = ts.visitEachChild(node, visitor, context);
82872 ts.addEmitHelpers(visited, context.readEmitHelpers());
82873 return visited;
82874 }
82875 function visitor(node) {
82876 if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
82877 return node;
82878 switch (node.kind) {
82879 case 218 /* ClassExpression */:
82880 case 249 /* ClassDeclaration */:
82881 return visitClassLike(node);
82882 case 162 /* PropertyDeclaration */:
82883 return visitPropertyDeclaration(node);
82884 case 229 /* VariableStatement */:
82885 return visitVariableStatement(node);
82886 case 157 /* ComputedPropertyName */:
82887 return visitComputedPropertyName(node);
82888 case 198 /* PropertyAccessExpression */:
82889 return visitPropertyAccessExpression(node);
82890 case 211 /* PrefixUnaryExpression */:
82891 return visitPrefixUnaryExpression(node);
82892 case 212 /* PostfixUnaryExpression */:
82893 return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
82894 case 200 /* CallExpression */:
82895 return visitCallExpression(node);
82896 case 213 /* BinaryExpression */:
82897 return visitBinaryExpression(node);
82898 case 79 /* PrivateIdentifier */:
82899 return visitPrivateIdentifier(node);
82900 case 230 /* ExpressionStatement */:
82901 return visitExpressionStatement(node);
82902 case 234 /* ForStatement */:
82903 return visitForStatement(node);
82904 case 202 /* TaggedTemplateExpression */:
82905 return visitTaggedTemplateExpression(node);
82906 }
82907 return ts.visitEachChild(node, visitor, context);
82908 }
82909 function visitorDestructuringTarget(node) {
82910 switch (node.kind) {
82911 case 197 /* ObjectLiteralExpression */:
82912 case 196 /* ArrayLiteralExpression */:
82913 return visitAssignmentPattern(node);
82914 default:
82915 return visitor(node);
82916 }
82917 }
82918 /**
82919 * If we visit a private name, this means it is an undeclared private name.
82920 * Replace it with an empty identifier to indicate a problem with the code.
82921 */
82922 function visitPrivateIdentifier(node) {
82923 if (!shouldTransformPrivateFields) {
82924 return node;
82925 }
82926 return ts.setOriginalNode(factory.createIdentifier(""), node);
82927 }
82928 /**
82929 * Visits the members of a class that has fields.
82930 *
82931 * @param node The node to visit.
82932 */
82933 function classElementVisitor(node) {
82934 switch (node.kind) {
82935 case 165 /* Constructor */:
82936 // Constructors for classes using class fields are transformed in
82937 // `visitClassDeclaration` or `visitClassExpression`.
82938 return undefined;
82939 case 166 /* GetAccessor */:
82940 case 167 /* SetAccessor */:
82941 case 164 /* MethodDeclaration */:
82942 // Visit the name of the member (if it's a computed property name).
82943 return ts.visitEachChild(node, classElementVisitor, context);
82944 case 162 /* PropertyDeclaration */:
82945 return visitPropertyDeclaration(node);
82946 case 157 /* ComputedPropertyName */:
82947 return visitComputedPropertyName(node);
82948 case 226 /* SemicolonClassElement */:
82949 return node;
82950 default:
82951 return visitor(node);
82952 }
82953 }
82954 function visitVariableStatement(node) {
82955 var savedPendingStatements = pendingStatements;
82956 pendingStatements = [];
82957 var visitedNode = ts.visitEachChild(node, visitor, context);
82958 var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
82959 visitedNode;
82960 pendingStatements = savedPendingStatements;
82961 return statement;
82962 }
82963 function visitComputedPropertyName(name) {
82964 var node = ts.visitEachChild(name, visitor, context);
82965 if (ts.some(pendingExpressions)) {
82966 var expressions = pendingExpressions;
82967 expressions.push(name.expression);
82968 pendingExpressions = [];
82969 node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
82970 }
82971 return node;
82972 }
82973 function visitPropertyDeclaration(node) {
82974 ts.Debug.assert(!ts.some(node.decorators));
82975 if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
82976 // Initializer is elided as the field is initialized in transformConstructor.
82977 return factory.updatePropertyDeclaration(node,
82978 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name,
82979 /*questionOrExclamationToken*/ undefined,
82980 /*type*/ undefined,
82981 /*initializer*/ undefined);
82982 }
82983 // Create a temporary variable to store a computed property name (if necessary).
82984 // If it's not inlineable, then we emit an expression after the class which assigns
82985 // the property name to the temporary variable.
82986 var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
82987 if (expr && !ts.isSimpleInlineableExpression(expr)) {
82988 getPendingExpressions().push(expr);
82989 }
82990 return undefined;
82991 }
82992 function createPrivateIdentifierAccess(info, receiver) {
82993 receiver = ts.visitNode(receiver, visitor, ts.isExpression);
82994 switch (info.placement) {
82995 case 0 /* InstanceField */:
82996 return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName);
82997 default: return ts.Debug.fail("Unexpected private identifier placement");
82998 }
82999 }
83000 function visitPropertyAccessExpression(node) {
83001 if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
83002 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
83003 if (privateIdentifierInfo) {
83004 return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
83005 }
83006 }
83007 return ts.visitEachChild(node, visitor, context);
83008 }
83009 function visitPrefixUnaryExpression(node) {
83010 if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
83011 var operator = node.operator === 45 /* PlusPlusToken */ ?
83012 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
83013 40 /* MinusToken */ : undefined;
83014 var info = void 0;
83015 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
83016 var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
83017 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
83018 var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
83019 return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */), node);
83020 }
83021 }
83022 return ts.visitEachChild(node, visitor, context);
83023 }
83024 function visitPostfixUnaryExpression(node, valueIsDiscarded) {
83025 if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
83026 var operator = node.operator === 45 /* PlusPlusToken */ ?
83027 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
83028 40 /* MinusToken */ : undefined;
83029 var info = void 0;
83030 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
83031 var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
83032 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
83033 var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
83034 // Create a temporary variable to store the value returned by the expression.
83035 var returnValue = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
83036 return ts.setOriginalNode(factory.inlineExpressions(ts.compact([
83037 createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(returnValue ? factory.createAssignment(returnValue, existingValue) : existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */),
83038 returnValue
83039 ])), node);
83040 }
83041 }
83042 return ts.visitEachChild(node, visitor, context);
83043 }
83044 function visitForStatement(node) {
83045 if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
83046 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));
83047 }
83048 return ts.visitEachChild(node, visitor, context);
83049 }
83050 function visitExpressionStatement(node) {
83051 if (ts.isPostfixUnaryExpression(node.expression)) {
83052 return factory.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
83053 }
83054 return ts.visitEachChild(node, visitor, context);
83055 }
83056 function createCopiableReceiverExpr(receiver) {
83057 var clone = ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
83058 if (ts.isSimpleInlineableExpression(receiver)) {
83059 return { readExpression: clone, initializeExpression: undefined };
83060 }
83061 var readExpression = factory.createTempVariable(hoistVariableDeclaration);
83062 var initializeExpression = factory.createAssignment(readExpression, clone);
83063 return { readExpression: readExpression, initializeExpression: initializeExpression };
83064 }
83065 function visitCallExpression(node) {
83066 if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
83067 // Transform call expressions of private names to properly bind the `this` parameter.
83068 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
83069 return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"),
83070 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
83071 }
83072 return ts.visitEachChild(node, visitor, context);
83073 }
83074 function visitTaggedTemplateExpression(node) {
83075 if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
83076 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
83077 var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
83078 return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"),
83079 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]),
83080 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
83081 }
83082 return ts.visitEachChild(node, visitor, context);
83083 }
83084 function visitBinaryExpression(node) {
83085 if (shouldTransformPrivateFields) {
83086 if (ts.isDestructuringAssignment(node)) {
83087 var savedPendingExpressions = pendingExpressions;
83088 pendingExpressions = undefined;
83089 node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
83090 var expr = ts.some(pendingExpressions) ?
83091 factory.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
83092 node;
83093 pendingExpressions = savedPendingExpressions;
83094 return expr;
83095 }
83096 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
83097 var info = accessPrivateIdentifier(node.left.name);
83098 if (info) {
83099 return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
83100 }
83101 }
83102 }
83103 return ts.visitEachChild(node, visitor, context);
83104 }
83105 function createPrivateIdentifierAssignment(info, receiver, right, operator) {
83106 switch (info.placement) {
83107 case 0 /* InstanceField */: {
83108 return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
83109 }
83110 default: return ts.Debug.fail("Unexpected private identifier placement");
83111 }
83112 }
83113 function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
83114 receiver = ts.visitNode(receiver, visitor, ts.isExpression);
83115 right = ts.visitNode(right, visitor, ts.isExpression);
83116 if (ts.isCompoundAssignment(operator)) {
83117 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
83118 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
83119 }
83120 else {
83121 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right);
83122 }
83123 }
83124 /**
83125 * Set up the environment for a class.
83126 */
83127 function visitClassLike(node) {
83128 var savedPendingExpressions = pendingExpressions;
83129 pendingExpressions = undefined;
83130 if (shouldTransformPrivateFields) {
83131 startPrivateIdentifierEnvironment();
83132 }
83133 var result = ts.isClassDeclaration(node) ?
83134 visitClassDeclaration(node) :
83135 visitClassExpression(node);
83136 if (shouldTransformPrivateFields) {
83137 endPrivateIdentifierEnvironment();
83138 }
83139 pendingExpressions = savedPendingExpressions;
83140 return result;
83141 }
83142 function doesClassElementNeedTransform(node) {
83143 return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
83144 }
83145 function visitClassDeclaration(node) {
83146 if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
83147 return ts.visitEachChild(node, visitor, context);
83148 }
83149 var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
83150 var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
83151 var statements = [
83152 factory.updateClassDeclaration(node,
83153 /*decorators*/ undefined, node.modifiers, node.name,
83154 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
83155 ];
83156 // Write any pending expressions from elided or moved computed property names
83157 if (ts.some(pendingExpressions)) {
83158 statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
83159 }
83160 // Emit static property assignment. Because classDeclaration is lexically evaluated,
83161 // it is safe to emit static property assignment after classDeclaration
83162 // From ES6 specification:
83163 // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
83164 // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
83165 var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
83166 if (ts.some(staticProperties)) {
83167 addPropertyStatements(statements, staticProperties, factory.getInternalName(node));
83168 }
83169 return statements;
83170 }
83171 function visitClassExpression(node) {
83172 if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
83173 return ts.visitEachChild(node, visitor, context);
83174 }
83175 // If this class expression is a transformation of a decorated class declaration,
83176 // then we want to output the pendingExpressions as statements, not as inlined
83177 // expressions with the class statement.
83178 //
83179 // In this case, we use pendingStatements to produce the same output as the
83180 // class declaration transformation. The VariableStatement visitor will insert
83181 // these statements after the class expression variable statement.
83182 var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
83183 var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
83184 var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
83185 var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
83186 var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name,
83187 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
83188 if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
83189 if (isDecoratedClassDeclaration) {
83190 ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
83191 // Write any pending expressions from elided or moved computed property names
83192 if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
83193 pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
83194 }
83195 if (pendingStatements && ts.some(staticProperties)) {
83196 addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node));
83197 }
83198 return classExpression;
83199 }
83200 else {
83201 var expressions = [];
83202 var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
83203 var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
83204 if (isClassWithConstructorReference) {
83205 // record an alias as the class name is not in scope for statics.
83206 enableSubstitutionForClassAliases();
83207 var alias = factory.cloneNode(temp);
83208 alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
83209 classAliases[ts.getOriginalNodeId(node)] = alias;
83210 }
83211 // To preserve the behavior of the old emitter, we explicitly indent
83212 // the body of a class with static initializers.
83213 ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
83214 expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)));
83215 // Add any pending expressions leftover from elided or relocated computed property names
83216 ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
83217 ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
83218 expressions.push(ts.startOnNewLine(temp));
83219 return factory.inlineExpressions(expressions);
83220 }
83221 }
83222 return classExpression;
83223 }
83224 function transformClassMembers(node, isDerivedClass) {
83225 if (shouldTransformPrivateFields) {
83226 // Declare private names.
83227 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
83228 var member = _a[_i];
83229 if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
83230 addPrivateIdentifierToEnvironment(member.name);
83231 }
83232 }
83233 }
83234 var members = [];
83235 var constructor = transformConstructor(node, isDerivedClass);
83236 if (constructor) {
83237 members.push(constructor);
83238 }
83239 ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
83240 return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
83241 }
83242 function isPropertyDeclarationThatRequiresConstructorStatement(member) {
83243 if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
83244 return false;
83245 }
83246 if (context.getCompilerOptions().useDefineForClassFields) {
83247 // If we are using define semantics and targeting ESNext or higher,
83248 // then we don't need to transform any class properties.
83249 return languageVersion < 99 /* ESNext */;
83250 }
83251 return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
83252 }
83253 function transformConstructor(node, isDerivedClass) {
83254 var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
83255 var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
83256 if (!ts.some(properties)) {
83257 return constructor;
83258 }
83259 var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
83260 var body = transformConstructorBody(node, constructor, isDerivedClass);
83261 if (!body) {
83262 return undefined;
83263 }
83264 return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(
83265 /*decorators*/ undefined,
83266 /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
83267 }
83268 function transformConstructorBody(node, constructor, isDerivedClass) {
83269 var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
83270 var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
83271 if (!useDefineForClassFields) {
83272 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
83273 }
83274 // Only generate synthetic constructor when there are property initializers to move.
83275 if (!constructor && !ts.some(properties)) {
83276 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
83277 }
83278 resumeLexicalEnvironment();
83279 var indexOfFirstStatement = 0;
83280 var statements = [];
83281 if (!constructor && isDerivedClass) {
83282 // Add a synthetic `super` call:
83283 //
83284 // super(...arguments);
83285 //
83286 statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(),
83287 /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))])));
83288 }
83289 if (constructor) {
83290 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
83291 }
83292 // Add the property initializers. Transforms this:
83293 //
83294 // public x = 1;
83295 //
83296 // Into this:
83297 //
83298 // constructor() {
83299 // this.x = 1;
83300 // }
83301 //
83302 if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
83303 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
83304 if (afterParameterProperties === -1) {
83305 afterParameterProperties = constructor.body.statements.length;
83306 }
83307 if (afterParameterProperties > indexOfFirstStatement) {
83308 if (!useDefineForClassFields) {
83309 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
83310 }
83311 indexOfFirstStatement = afterParameterProperties;
83312 }
83313 }
83314 addPropertyStatements(statements, properties, factory.createThis());
83315 // Add existing statements, skipping the initial super call.
83316 if (constructor) {
83317 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
83318 }
83319 statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83320 return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements),
83321 /*location*/ constructor ? constructor.body.statements : node.members),
83322 /*multiLine*/ true),
83323 /*location*/ constructor ? constructor.body : undefined);
83324 }
83325 /**
83326 * Generates assignment statements for property initializers.
83327 *
83328 * @param properties An array of property declarations to transform.
83329 * @param receiver The receiver on which each property should be assigned.
83330 */
83331 function addPropertyStatements(statements, properties, receiver) {
83332 for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
83333 var property = properties_7[_i];
83334 var expression = transformProperty(property, receiver);
83335 if (!expression) {
83336 continue;
83337 }
83338 var statement = factory.createExpressionStatement(expression);
83339 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
83340 ts.setCommentRange(statement, property);
83341 ts.setOriginalNode(statement, property);
83342 statements.push(statement);
83343 }
83344 }
83345 /**
83346 * Generates assignment expressions for property initializers.
83347 *
83348 * @param properties An array of property declarations to transform.
83349 * @param receiver The receiver on which each property should be assigned.
83350 */
83351 function generateInitializedPropertyExpressions(properties, receiver) {
83352 var expressions = [];
83353 for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
83354 var property = properties_8[_i];
83355 var expression = transformProperty(property, receiver);
83356 if (!expression) {
83357 continue;
83358 }
83359 ts.startOnNewLine(expression);
83360 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
83361 ts.setCommentRange(expression, property);
83362 ts.setOriginalNode(expression, property);
83363 expressions.push(expression);
83364 }
83365 return expressions;
83366 }
83367 /**
83368 * Transforms a property initializer into an assignment statement.
83369 *
83370 * @param property The property declaration.
83371 * @param receiver The object receiving the property assignment.
83372 */
83373 function transformProperty(property, receiver) {
83374 var _a;
83375 // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
83376 var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
83377 var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
83378 ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
83379 : property.name;
83380 if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
83381 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
83382 if (privateIdentifierInfo) {
83383 switch (privateIdentifierInfo.placement) {
83384 case 0 /* InstanceField */: {
83385 return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
83386 }
83387 }
83388 }
83389 else {
83390 ts.Debug.fail("Undeclared private name for property declaration.");
83391 }
83392 }
83393 if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
83394 return undefined;
83395 }
83396 if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
83397 return undefined;
83398 }
83399 var propertyOriginalNode = ts.getOriginalNode(property);
83400 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
83401 : factory.createVoidZero();
83402 if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
83403 var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
83404 return factory.createAssignment(memberAccess, initializer);
83405 }
83406 else {
83407 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
83408 : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
83409 : propertyName;
83410 var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
83411 return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
83412 }
83413 }
83414 function enableSubstitutionForClassAliases() {
83415 if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
83416 enabledSubstitutions |= 1 /* ClassAliases */;
83417 // We need to enable substitutions for identifiers. This allows us to
83418 // substitute class names inside of a class declaration.
83419 context.enableSubstitution(78 /* Identifier */);
83420 // Keep track of class aliases.
83421 classAliases = [];
83422 }
83423 }
83424 /**
83425 * Hooks node substitutions.
83426 *
83427 * @param hint The context for the emitter.
83428 * @param node The node to substitute.
83429 */
83430 function onSubstituteNode(hint, node) {
83431 node = previousOnSubstituteNode(hint, node);
83432 if (hint === 1 /* Expression */) {
83433 return substituteExpression(node);
83434 }
83435 return node;
83436 }
83437 function substituteExpression(node) {
83438 switch (node.kind) {
83439 case 78 /* Identifier */:
83440 return substituteExpressionIdentifier(node);
83441 }
83442 return node;
83443 }
83444 function substituteExpressionIdentifier(node) {
83445 return trySubstituteClassAlias(node) || node;
83446 }
83447 function trySubstituteClassAlias(node) {
83448 if (enabledSubstitutions & 1 /* ClassAliases */) {
83449 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
83450 // Due to the emit for class decorators, any reference to the class from inside of the class body
83451 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
83452 // behavior of class names in ES6.
83453 // Also, when emitting statics for class expressions, we must substitute a class alias for
83454 // constructor references in static property initializers.
83455 var declaration = resolver.getReferencedValueDeclaration(node);
83456 if (declaration) {
83457 var classAlias = classAliases[declaration.id]; // TODO: GH#18217
83458 if (classAlias) {
83459 var clone_2 = factory.cloneNode(classAlias);
83460 ts.setSourceMapRange(clone_2, node);
83461 ts.setCommentRange(clone_2, node);
83462 return clone_2;
83463 }
83464 }
83465 }
83466 }
83467 return undefined;
83468 }
83469 /**
83470 * If the name is a computed property, this function transforms it, then either returns an expression which caches the
83471 * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
83472 * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
83473 */
83474 function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
83475 if (ts.isComputedPropertyName(name)) {
83476 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
83477 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
83478 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
83479 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
83480 if (!alreadyTransformed && !inlinable && shouldHoist) {
83481 var generatedName = factory.getGeneratedNameForNode(name);
83482 hoistVariableDeclaration(generatedName);
83483 return factory.createAssignment(generatedName, expression);
83484 }
83485 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
83486 }
83487 }
83488 function startPrivateIdentifierEnvironment() {
83489 privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
83490 currentPrivateIdentifierEnvironment = undefined;
83491 }
83492 function endPrivateIdentifierEnvironment() {
83493 currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
83494 }
83495 function getPrivateIdentifierEnvironment() {
83496 return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map());
83497 }
83498 function getPendingExpressions() {
83499 return pendingExpressions || (pendingExpressions = []);
83500 }
83501 function addPrivateIdentifierToEnvironment(name) {
83502 var text = ts.getTextOfPropertyName(name);
83503 var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */);
83504 hoistVariableDeclaration(weakMapName);
83505 getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
83506 getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"),
83507 /*typeArguments*/ undefined, [])));
83508 }
83509 function accessPrivateIdentifier(name) {
83510 if (currentPrivateIdentifierEnvironment) {
83511 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
83512 if (info) {
83513 return info;
83514 }
83515 }
83516 for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
83517 var env = privateIdentifierEnvironmentStack[i];
83518 if (!env) {
83519 continue;
83520 }
83521 var info = env.get(name.escapedText);
83522 if (info) {
83523 return info;
83524 }
83525 }
83526 return undefined;
83527 }
83528 function wrapPrivateIdentifierForDestructuringTarget(node) {
83529 var parameter = factory.getGeneratedNameForNode(node);
83530 var info = accessPrivateIdentifier(node.name);
83531 if (!info) {
83532 return ts.visitEachChild(node, visitor, context);
83533 }
83534 var receiver = node.expression;
83535 // We cannot copy `this` or `super` into the function because they will be bound
83536 // differently inside the function.
83537 if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
83538 receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
83539 getPendingExpressions().push(factory.createBinaryExpression(receiver, 62 /* EqualsToken */, node.expression));
83540 }
83541 return factory.createPropertyAccessExpression(
83542 // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
83543 factory.createParenthesizedExpression(factory.createObjectLiteralExpression([
83544 factory.createSetAccessorDeclaration(
83545 /*decorators*/ undefined,
83546 /*modifiers*/ undefined, "value", [factory.createParameterDeclaration(
83547 /*decorators*/ undefined,
83548 /*modifiers*/ undefined,
83549 /*dotDotDotToken*/ undefined, parameter,
83550 /*questionToken*/ undefined,
83551 /*type*/ undefined,
83552 /*initializer*/ undefined)], factory.createBlock([factory.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
83553 ])), "value");
83554 }
83555 function visitArrayAssignmentTarget(node) {
83556 var target = ts.getTargetOfBindingOrAssignmentElement(node);
83557 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
83558 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
83559 if (ts.isAssignmentExpression(node)) {
83560 return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
83561 }
83562 else if (ts.isSpreadElement(node)) {
83563 return factory.updateSpreadElement(node, wrapped);
83564 }
83565 else {
83566 return wrapped;
83567 }
83568 }
83569 return ts.visitNode(node, visitorDestructuringTarget);
83570 }
83571 function visitObjectAssignmentTarget(node) {
83572 if (ts.isPropertyAssignment(node)) {
83573 var target = ts.getTargetOfBindingOrAssignmentElement(node);
83574 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
83575 var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
83576 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
83577 return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
83578 }
83579 return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
83580 }
83581 return ts.visitNode(node, visitor);
83582 }
83583 function visitAssignmentPattern(node) {
83584 if (ts.isArrayLiteralExpression(node)) {
83585 // Transforms private names in destructuring assignment array bindings.
83586 //
83587 // Source:
83588 // ([ this.#myProp ] = [ "hello" ]);
83589 //
83590 // Transformation:
83591 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
83592 return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
83593 }
83594 else {
83595 // Transforms private names in destructuring assignment object bindings.
83596 //
83597 // Source:
83598 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
83599 //
83600 // Transformation:
83601 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
83602 return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
83603 }
83604 }
83605 }
83606 ts.transformClassFields = transformClassFields;
83607 function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
83608 return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"),
83609 /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]);
83610 }
83611})(ts || (ts = {}));
83612/*@internal*/
83613var ts;
83614(function (ts) {
83615 var ES2017SubstitutionFlags;
83616 (function (ES2017SubstitutionFlags) {
83617 /** Enables substitutions for async methods with `super` calls. */
83618 ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
83619 })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
83620 var ContextFlags;
83621 (function (ContextFlags) {
83622 ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
83623 ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
83624 })(ContextFlags || (ContextFlags = {}));
83625 function transformES2017(context) {
83626 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83627 var resolver = context.getEmitResolver();
83628 var compilerOptions = context.getCompilerOptions();
83629 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
83630 /**
83631 * Keeps track of whether expression substitution has been enabled for specific edge cases.
83632 * They are persisted between each SourceFile transformation and should not be reset.
83633 */
83634 var enabledSubstitutions;
83635 /**
83636 * This keeps track of containers where `super` is valid, for use with
83637 * just-in-time substitution for `super` expressions inside of async methods.
83638 */
83639 var enclosingSuperContainerFlags = 0;
83640 var enclosingFunctionParameterNames;
83641 /**
83642 * Keeps track of property names accessed on super (`super.x`) within async functions.
83643 */
83644 var capturedSuperProperties;
83645 /** Whether the async function contains an element access on super (`super[x]`). */
83646 var hasSuperElementAccess;
83647 /** A set of node IDs for generated super accessors (variable statements). */
83648 var substitutedSuperAccessors = [];
83649 var contextFlags = 0;
83650 // Save the previous transformation hooks.
83651 var previousOnEmitNode = context.onEmitNode;
83652 var previousOnSubstituteNode = context.onSubstituteNode;
83653 // Set new transformation hooks.
83654 context.onEmitNode = onEmitNode;
83655 context.onSubstituteNode = onSubstituteNode;
83656 return ts.chainBundle(context, transformSourceFile);
83657 function transformSourceFile(node) {
83658 if (node.isDeclarationFile) {
83659 return node;
83660 }
83661 setContextFlag(1 /* NonTopLevel */, false);
83662 setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
83663 var visited = ts.visitEachChild(node, visitor, context);
83664 ts.addEmitHelpers(visited, context.readEmitHelpers());
83665 return visited;
83666 }
83667 function setContextFlag(flag, val) {
83668 contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
83669 }
83670 function inContext(flags) {
83671 return (contextFlags & flags) !== 0;
83672 }
83673 function inTopLevelContext() {
83674 return !inContext(1 /* NonTopLevel */);
83675 }
83676 function inHasLexicalThisContext() {
83677 return inContext(2 /* HasLexicalThis */);
83678 }
83679 function doWithContext(flags, cb, value) {
83680 var contextFlagsToSet = flags & ~contextFlags;
83681 if (contextFlagsToSet) {
83682 setContextFlag(contextFlagsToSet, /*val*/ true);
83683 var result = cb(value);
83684 setContextFlag(contextFlagsToSet, /*val*/ false);
83685 return result;
83686 }
83687 return cb(value);
83688 }
83689 function visitDefault(node) {
83690 return ts.visitEachChild(node, visitor, context);
83691 }
83692 function visitor(node) {
83693 if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
83694 return node;
83695 }
83696 switch (node.kind) {
83697 case 129 /* AsyncKeyword */:
83698 // ES2017 async modifier should be elided for targets < ES2017
83699 return undefined;
83700 case 210 /* AwaitExpression */:
83701 return visitAwaitExpression(node);
83702 case 164 /* MethodDeclaration */:
83703 return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
83704 case 248 /* FunctionDeclaration */:
83705 return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
83706 case 205 /* FunctionExpression */:
83707 return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
83708 case 206 /* ArrowFunction */:
83709 return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
83710 case 198 /* PropertyAccessExpression */:
83711 if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
83712 capturedSuperProperties.add(node.name.escapedText);
83713 }
83714 return ts.visitEachChild(node, visitor, context);
83715 case 199 /* ElementAccessExpression */:
83716 if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
83717 hasSuperElementAccess = true;
83718 }
83719 return ts.visitEachChild(node, visitor, context);
83720 case 166 /* GetAccessor */:
83721 case 167 /* SetAccessor */:
83722 case 165 /* Constructor */:
83723 case 249 /* ClassDeclaration */:
83724 case 218 /* ClassExpression */:
83725 return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
83726 default:
83727 return ts.visitEachChild(node, visitor, context);
83728 }
83729 }
83730 function asyncBodyVisitor(node) {
83731 if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
83732 switch (node.kind) {
83733 case 229 /* VariableStatement */:
83734 return visitVariableStatementInAsyncBody(node);
83735 case 234 /* ForStatement */:
83736 return visitForStatementInAsyncBody(node);
83737 case 235 /* ForInStatement */:
83738 return visitForInStatementInAsyncBody(node);
83739 case 236 /* ForOfStatement */:
83740 return visitForOfStatementInAsyncBody(node);
83741 case 284 /* CatchClause */:
83742 return visitCatchClauseInAsyncBody(node);
83743 case 227 /* Block */:
83744 case 241 /* SwitchStatement */:
83745 case 255 /* CaseBlock */:
83746 case 281 /* CaseClause */:
83747 case 282 /* DefaultClause */:
83748 case 244 /* TryStatement */:
83749 case 232 /* DoStatement */:
83750 case 233 /* WhileStatement */:
83751 case 231 /* IfStatement */:
83752 case 240 /* WithStatement */:
83753 case 242 /* LabeledStatement */:
83754 return ts.visitEachChild(node, asyncBodyVisitor, context);
83755 default:
83756 return ts.Debug.assertNever(node, "Unhandled node.");
83757 }
83758 }
83759 return visitor(node);
83760 }
83761 function visitCatchClauseInAsyncBody(node) {
83762 var catchClauseNames = new ts.Set();
83763 recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
83764 // names declared in a catch variable are block scoped
83765 var catchClauseUnshadowedNames;
83766 catchClauseNames.forEach(function (_, escapedName) {
83767 if (enclosingFunctionParameterNames.has(escapedName)) {
83768 if (!catchClauseUnshadowedNames) {
83769 catchClauseUnshadowedNames = new ts.Set(enclosingFunctionParameterNames);
83770 }
83771 catchClauseUnshadowedNames.delete(escapedName);
83772 }
83773 });
83774 if (catchClauseUnshadowedNames) {
83775 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
83776 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
83777 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
83778 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
83779 return result;
83780 }
83781 else {
83782 return ts.visitEachChild(node, asyncBodyVisitor, context);
83783 }
83784 }
83785 function visitVariableStatementInAsyncBody(node) {
83786 if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
83787 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
83788 return expression ? factory.createExpressionStatement(expression) : undefined;
83789 }
83790 return ts.visitEachChild(node, visitor, context);
83791 }
83792 function visitForInStatementInAsyncBody(node) {
83793 return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer)
83794 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
83795 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
83796 }
83797 function visitForOfStatementInAsyncBody(node) {
83798 return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
83799 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
83800 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
83801 }
83802 function visitForStatementInAsyncBody(node) {
83803 var initializer = node.initializer; // TODO: GH#18217
83804 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer)
83805 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
83806 : 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));
83807 }
83808 /**
83809 * Visits an AwaitExpression node.
83810 *
83811 * This function will be called any time a ES2017 await expression is encountered.
83812 *
83813 * @param node The node to visit.
83814 */
83815 function visitAwaitExpression(node) {
83816 // do not downlevel a top-level await as it is module syntax...
83817 if (inTopLevelContext()) {
83818 return ts.visitEachChild(node, visitor, context);
83819 }
83820 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
83821 /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
83822 }
83823 /**
83824 * Visits a MethodDeclaration node.
83825 *
83826 * This function will be called when one of the following conditions are met:
83827 * - The node is marked as async
83828 *
83829 * @param node The node to visit.
83830 */
83831 function visitMethodDeclaration(node) {
83832 return factory.updateMethodDeclaration(node,
83833 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
83834 /*questionToken*/ undefined,
83835 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
83836 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
83837 ? transformAsyncFunctionBody(node)
83838 : ts.visitFunctionBody(node.body, visitor, context));
83839 }
83840 /**
83841 * Visits a FunctionDeclaration node.
83842 *
83843 * This function will be called when one of the following conditions are met:
83844 * - The node is marked async
83845 *
83846 * @param node The node to visit.
83847 */
83848 function visitFunctionDeclaration(node) {
83849 return factory.updateFunctionDeclaration(node,
83850 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
83851 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
83852 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
83853 ? transformAsyncFunctionBody(node)
83854 : ts.visitFunctionBody(node.body, visitor, context));
83855 }
83856 /**
83857 * Visits a FunctionExpression node.
83858 *
83859 * This function will be called when one of the following conditions are met:
83860 * - The node is marked async
83861 *
83862 * @param node The node to visit.
83863 */
83864 function visitFunctionExpression(node) {
83865 return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
83866 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
83867 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
83868 ? transformAsyncFunctionBody(node)
83869 : ts.visitFunctionBody(node.body, visitor, context));
83870 }
83871 /**
83872 * Visits an ArrowFunction.
83873 *
83874 * This function will be called when one of the following conditions are met:
83875 * - The node is marked async
83876 *
83877 * @param node The node to visit.
83878 */
83879 function visitArrowFunction(node) {
83880 return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier),
83881 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
83882 /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
83883 ? transformAsyncFunctionBody(node)
83884 : ts.visitFunctionBody(node.body, visitor, context));
83885 }
83886 function recordDeclarationName(_a, names) {
83887 var name = _a.name;
83888 if (ts.isIdentifier(name)) {
83889 names.add(name.escapedText);
83890 }
83891 else {
83892 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
83893 var element = _b[_i];
83894 if (!ts.isOmittedExpression(element)) {
83895 recordDeclarationName(element, names);
83896 }
83897 }
83898 }
83899 }
83900 function isVariableDeclarationListWithCollidingName(node) {
83901 return !!node
83902 && ts.isVariableDeclarationList(node)
83903 && !(node.flags & 3 /* BlockScoped */)
83904 && node.declarations.some(collidesWithParameterName);
83905 }
83906 function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
83907 hoistVariableDeclarationList(node);
83908 var variables = ts.getInitializedVariables(node);
83909 if (variables.length === 0) {
83910 if (hasReceiver) {
83911 return ts.visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
83912 }
83913 return undefined;
83914 }
83915 return factory.inlineExpressions(ts.map(variables, transformInitializedVariable));
83916 }
83917 function hoistVariableDeclarationList(node) {
83918 ts.forEach(node.declarations, hoistVariable);
83919 }
83920 function hoistVariable(_a) {
83921 var name = _a.name;
83922 if (ts.isIdentifier(name)) {
83923 hoistVariableDeclaration(name);
83924 }
83925 else {
83926 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
83927 var element = _b[_i];
83928 if (!ts.isOmittedExpression(element)) {
83929 hoistVariable(element);
83930 }
83931 }
83932 }
83933 }
83934 function transformInitializedVariable(node) {
83935 var converted = ts.setSourceMapRange(factory.createAssignment(factory.converters.convertToAssignmentElementTarget(node.name), node.initializer), node);
83936 return ts.visitNode(converted, visitor, ts.isExpression);
83937 }
83938 function collidesWithParameterName(_a) {
83939 var name = _a.name;
83940 if (ts.isIdentifier(name)) {
83941 return enclosingFunctionParameterNames.has(name.escapedText);
83942 }
83943 else {
83944 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
83945 var element = _b[_i];
83946 if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
83947 return true;
83948 }
83949 }
83950 }
83951 return false;
83952 }
83953 function transformAsyncFunctionBody(node) {
83954 resumeLexicalEnvironment();
83955 var original = ts.getOriginalNode(node, ts.isFunctionLike);
83956 var nodeType = original.type;
83957 var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
83958 var isArrowFunction = node.kind === 206 /* ArrowFunction */;
83959 var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
83960 // An async function is emit as an outer function that calls an inner
83961 // generator function. To preserve lexical bindings, we pass the current
83962 // `this` and `arguments` objects to `__awaiter`. The generator function
83963 // passed to `__awaiter` is executed inside of the callback to the
83964 // promise constructor.
83965 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
83966 enclosingFunctionParameterNames = new ts.Set();
83967 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83968 var parameter = _a[_i];
83969 recordDeclarationName(parameter, enclosingFunctionParameterNames);
83970 }
83971 var savedCapturedSuperProperties = capturedSuperProperties;
83972 var savedHasSuperElementAccess = hasSuperElementAccess;
83973 if (!isArrowFunction) {
83974 capturedSuperProperties = new ts.Set();
83975 hasSuperElementAccess = false;
83976 }
83977 var result;
83978 if (!isArrowFunction) {
83979 var statements = [];
83980 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
83981 statements.push(factory.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
83982 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83983 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
83984 // This step isn't needed if we eventually transform this to ES5.
83985 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
83986 if (emitSuperHelpers) {
83987 enableSubstitutionForAsyncMethodsWithSuper();
83988 if (capturedSuperProperties.size) {
83989 var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
83990 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
83991 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
83992 }
83993 }
83994 var block = factory.createBlock(statements, /*multiLine*/ true);
83995 ts.setTextRange(block, node.body);
83996 if (emitSuperHelpers && hasSuperElementAccess) {
83997 // Emit helpers for super element access expressions (`super[x]`).
83998 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
83999 ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
84000 }
84001 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
84002 ts.addEmitHelper(block, ts.asyncSuperHelper);
84003 }
84004 }
84005 result = block;
84006 }
84007 else {
84008 var expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
84009 var declarations = endLexicalEnvironment();
84010 if (ts.some(declarations)) {
84011 var block = factory.converters.convertToFunctionBlock(expression);
84012 result = factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
84013 }
84014 else {
84015 result = expression;
84016 }
84017 }
84018 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
84019 if (!isArrowFunction) {
84020 capturedSuperProperties = savedCapturedSuperProperties;
84021 hasSuperElementAccess = savedHasSuperElementAccess;
84022 }
84023 return result;
84024 }
84025 function transformAsyncFunctionBodyWorker(body, start) {
84026 if (ts.isBlock(body)) {
84027 return factory.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
84028 }
84029 else {
84030 return factory.converters.convertToFunctionBlock(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
84031 }
84032 }
84033 function getPromiseConstructor(type) {
84034 var typeName = type && ts.getEntityNameFromTypeNode(type);
84035 if (typeName && ts.isEntityName(typeName)) {
84036 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
84037 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
84038 || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
84039 return typeName;
84040 }
84041 }
84042 return undefined;
84043 }
84044 function enableSubstitutionForAsyncMethodsWithSuper() {
84045 if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
84046 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
84047 // We need to enable substitutions for call, property access, and element access
84048 // if we need to rewrite super calls.
84049 context.enableSubstitution(200 /* CallExpression */);
84050 context.enableSubstitution(198 /* PropertyAccessExpression */);
84051 context.enableSubstitution(199 /* ElementAccessExpression */);
84052 // We need to be notified when entering and exiting declarations that bind super.
84053 context.enableEmitNotification(249 /* ClassDeclaration */);
84054 context.enableEmitNotification(164 /* MethodDeclaration */);
84055 context.enableEmitNotification(166 /* GetAccessor */);
84056 context.enableEmitNotification(167 /* SetAccessor */);
84057 context.enableEmitNotification(165 /* Constructor */);
84058 // We need to be notified when entering the generated accessor arrow functions.
84059 context.enableEmitNotification(229 /* VariableStatement */);
84060 }
84061 }
84062 /**
84063 * Hook for node emit.
84064 *
84065 * @param hint A hint as to the intended usage of the node.
84066 * @param node The node to emit.
84067 * @param emit A callback used to emit the node in the printer.
84068 */
84069 function onEmitNode(hint, node, emitCallback) {
84070 // If we need to support substitutions for `super` in an async method,
84071 // we should track it here.
84072 if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
84073 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
84074 if (superContainerFlags !== enclosingSuperContainerFlags) {
84075 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
84076 enclosingSuperContainerFlags = superContainerFlags;
84077 previousOnEmitNode(hint, node, emitCallback);
84078 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
84079 return;
84080 }
84081 }
84082 // Disable substitution in the generated super accessor itself.
84083 else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
84084 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
84085 enclosingSuperContainerFlags = 0;
84086 previousOnEmitNode(hint, node, emitCallback);
84087 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
84088 return;
84089 }
84090 previousOnEmitNode(hint, node, emitCallback);
84091 }
84092 /**
84093 * Hooks node substitutions.
84094 *
84095 * @param hint A hint as to the intended usage of the node.
84096 * @param node The node to substitute.
84097 */
84098 function onSubstituteNode(hint, node) {
84099 node = previousOnSubstituteNode(hint, node);
84100 if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
84101 return substituteExpression(node);
84102 }
84103 return node;
84104 }
84105 function substituteExpression(node) {
84106 switch (node.kind) {
84107 case 198 /* PropertyAccessExpression */:
84108 return substitutePropertyAccessExpression(node);
84109 case 199 /* ElementAccessExpression */:
84110 return substituteElementAccessExpression(node);
84111 case 200 /* CallExpression */:
84112 return substituteCallExpression(node);
84113 }
84114 return node;
84115 }
84116 function substitutePropertyAccessExpression(node) {
84117 if (node.expression.kind === 105 /* SuperKeyword */) {
84118 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
84119 }
84120 return node;
84121 }
84122 function substituteElementAccessExpression(node) {
84123 if (node.expression.kind === 105 /* SuperKeyword */) {
84124 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
84125 }
84126 return node;
84127 }
84128 function substituteCallExpression(node) {
84129 var expression = node.expression;
84130 if (ts.isSuperProperty(expression)) {
84131 var argumentExpression = ts.isPropertyAccessExpression(expression)
84132 ? substitutePropertyAccessExpression(expression)
84133 : substituteElementAccessExpression(expression);
84134 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"),
84135 /*typeArguments*/ undefined, __spreadArrays([
84136 factory.createThis()
84137 ], node.arguments));
84138 }
84139 return node;
84140 }
84141 function isSuperContainer(node) {
84142 var kind = node.kind;
84143 return kind === 249 /* ClassDeclaration */
84144 || kind === 165 /* Constructor */
84145 || kind === 164 /* MethodDeclaration */
84146 || kind === 166 /* GetAccessor */
84147 || kind === 167 /* SetAccessor */;
84148 }
84149 function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
84150 if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
84151 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */),
84152 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
84153 }
84154 else {
84155 return ts.setTextRange(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */),
84156 /*typeArguments*/ undefined, [argumentExpression]), location);
84157 }
84158 }
84159 }
84160 ts.transformES2017 = transformES2017;
84161 /** Creates a variable named `_super` with accessor properties for the given property names. */
84162 function createSuperAccessVariableStatement(factory, resolver, node, names) {
84163 // Create a variable declaration with a getter/setter (if binding) definition for each name:
84164 // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
84165 var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
84166 var accessors = [];
84167 names.forEach(function (_, key) {
84168 var name = ts.unescapeLeadingUnderscores(key);
84169 var getterAndSetter = [];
84170 getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(
84171 /* modifiers */ undefined,
84172 /* typeParameters */ undefined,
84173 /* parameters */ [],
84174 /* type */ undefined,
84175 /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
84176 if (hasBinding) {
84177 getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(
84178 /* modifiers */ undefined,
84179 /* typeParameters */ undefined,
84180 /* parameters */ [
84181 factory.createParameterDeclaration(
84182 /* decorators */ undefined,
84183 /* modifiers */ undefined,
84184 /* dotDotDotToken */ undefined, "v",
84185 /* questionToken */ undefined,
84186 /* type */ undefined,
84187 /* initializer */ undefined)
84188 ],
84189 /* type */ undefined,
84190 /* equalsGreaterThanToken */ undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), factory.createIdentifier("v")))));
84191 }
84192 accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter)));
84193 });
84194 return factory.createVariableStatement(
84195 /* modifiers */ undefined, factory.createVariableDeclarationList([
84196 factory.createVariableDeclaration(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
84197 /*exclamationToken*/ undefined,
84198 /* type */ undefined, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"),
84199 /* typeArguments */ undefined, [
84200 factory.createNull(),
84201 factory.createObjectLiteralExpression(accessors, /* multiline */ true)
84202 ]))
84203 ], 2 /* Const */));
84204 }
84205 ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
84206})(ts || (ts = {}));
84207/*@internal*/
84208var ts;
84209(function (ts) {
84210 var ESNextSubstitutionFlags;
84211 (function (ESNextSubstitutionFlags) {
84212 /** Enables substitutions for async methods with `super` calls. */
84213 ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
84214 })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
84215 // Facts we track as we traverse the tree
84216 var HierarchyFacts;
84217 (function (HierarchyFacts) {
84218 HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
84219 //
84220 // Ancestor facts
84221 //
84222 HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
84223 HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
84224 // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
84225 //
84226 // Ancestor masks
84227 //
84228 HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
84229 HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
84230 HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
84231 HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
84232 HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
84233 HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
84234 HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
84235 HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
84236 HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
84237 HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
84238 })(HierarchyFacts || (HierarchyFacts = {}));
84239 function transformES2018(context) {
84240 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
84241 var resolver = context.getEmitResolver();
84242 var compilerOptions = context.getCompilerOptions();
84243 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
84244 var previousOnEmitNode = context.onEmitNode;
84245 context.onEmitNode = onEmitNode;
84246 var previousOnSubstituteNode = context.onSubstituteNode;
84247 context.onSubstituteNode = onSubstituteNode;
84248 var exportedVariableStatement = false;
84249 var enabledSubstitutions;
84250 var enclosingFunctionFlags;
84251 var enclosingSuperContainerFlags = 0;
84252 var hierarchyFacts = 0;
84253 var currentSourceFile;
84254 var taggedTemplateStringDeclarations;
84255 /** Keeps track of property names accessed on super (`super.x`) within async functions. */
84256 var capturedSuperProperties;
84257 /** Whether the async function contains an element access on super (`super[x]`). */
84258 var hasSuperElementAccess;
84259 /** A set of node IDs for generated super accessors. */
84260 var substitutedSuperAccessors = [];
84261 return ts.chainBundle(context, transformSourceFile);
84262 function affectsSubtree(excludeFacts, includeFacts) {
84263 return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
84264 }
84265 /**
84266 * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
84267 * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
84268 * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
84269 */
84270 function enterSubtree(excludeFacts, includeFacts) {
84271 var ancestorFacts = hierarchyFacts;
84272 hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
84273 return ancestorFacts;
84274 }
84275 /**
84276 * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
84277 * subtree.
84278 * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
84279 */
84280 function exitSubtree(ancestorFacts) {
84281 hierarchyFacts = ancestorFacts;
84282 }
84283 function recordTaggedTemplateString(temp) {
84284 taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
84285 }
84286 function transformSourceFile(node) {
84287 if (node.isDeclarationFile) {
84288 return node;
84289 }
84290 currentSourceFile = node;
84291 var visited = visitSourceFile(node);
84292 ts.addEmitHelpers(visited, context.readEmitHelpers());
84293 currentSourceFile = undefined;
84294 taggedTemplateStringDeclarations = undefined;
84295 return visited;
84296 }
84297 function visitor(node) {
84298 return visitorWorker(node, /*noDestructuringValue*/ false);
84299 }
84300 function visitorNoDestructuringValue(node) {
84301 return visitorWorker(node, /*noDestructuringValue*/ true);
84302 }
84303 function visitorNoAsyncModifier(node) {
84304 if (node.kind === 129 /* AsyncKeyword */) {
84305 return undefined;
84306 }
84307 return node;
84308 }
84309 function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
84310 if (affectsSubtree(excludeFacts, includeFacts)) {
84311 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84312 var result = cb(value);
84313 exitSubtree(ancestorFacts);
84314 return result;
84315 }
84316 return cb(value);
84317 }
84318 function visitDefault(node) {
84319 return ts.visitEachChild(node, visitor, context);
84320 }
84321 function visitorWorker(node, noDestructuringValue) {
84322 if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
84323 return node;
84324 }
84325 switch (node.kind) {
84326 case 210 /* AwaitExpression */:
84327 return visitAwaitExpression(node);
84328 case 216 /* YieldExpression */:
84329 return visitYieldExpression(node);
84330 case 239 /* ReturnStatement */:
84331 return visitReturnStatement(node);
84332 case 242 /* LabeledStatement */:
84333 return visitLabeledStatement(node);
84334 case 197 /* ObjectLiteralExpression */:
84335 return visitObjectLiteralExpression(node);
84336 case 213 /* BinaryExpression */:
84337 return visitBinaryExpression(node, noDestructuringValue);
84338 case 284 /* CatchClause */:
84339 return visitCatchClause(node);
84340 case 229 /* VariableStatement */:
84341 return visitVariableStatement(node);
84342 case 246 /* VariableDeclaration */:
84343 return visitVariableDeclaration(node);
84344 case 232 /* DoStatement */:
84345 case 233 /* WhileStatement */:
84346 case 235 /* ForInStatement */:
84347 return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
84348 case 236 /* ForOfStatement */:
84349 return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
84350 case 234 /* ForStatement */:
84351 return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
84352 case 209 /* VoidExpression */:
84353 return visitVoidExpression(node);
84354 case 165 /* Constructor */:
84355 return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84356 case 164 /* MethodDeclaration */:
84357 return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84358 case 166 /* GetAccessor */:
84359 return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84360 case 167 /* SetAccessor */:
84361 return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84362 case 248 /* FunctionDeclaration */:
84363 return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84364 case 205 /* FunctionExpression */:
84365 return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84366 case 206 /* ArrowFunction */:
84367 return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
84368 case 159 /* Parameter */:
84369 return visitParameter(node);
84370 case 230 /* ExpressionStatement */:
84371 return visitExpressionStatement(node);
84372 case 204 /* ParenthesizedExpression */:
84373 return visitParenthesizedExpression(node, noDestructuringValue);
84374 case 202 /* TaggedTemplateExpression */:
84375 return visitTaggedTemplateExpression(node);
84376 case 198 /* PropertyAccessExpression */:
84377 if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
84378 capturedSuperProperties.add(node.name.escapedText);
84379 }
84380 return ts.visitEachChild(node, visitor, context);
84381 case 199 /* ElementAccessExpression */:
84382 if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
84383 hasSuperElementAccess = true;
84384 }
84385 return ts.visitEachChild(node, visitor, context);
84386 case 249 /* ClassDeclaration */:
84387 case 218 /* ClassExpression */:
84388 return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
84389 default:
84390 return ts.visitEachChild(node, visitor, context);
84391 }
84392 }
84393 function visitAwaitExpression(node) {
84394 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
84395 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(ts.visitNode(node.expression, visitor, ts.isExpression))),
84396 /*location*/ node), node);
84397 }
84398 return ts.visitEachChild(node, visitor, context);
84399 }
84400 function visitYieldExpression(node) {
84401 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
84402 if (node.asteriskToken) {
84403 var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression);
84404 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
84405 /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node);
84406 }
84407 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
84408 /*asteriskToken*/ undefined, createDownlevelAwait(node.expression
84409 ? ts.visitNode(node.expression, visitor, ts.isExpression)
84410 : factory.createVoidZero())), node), node);
84411 }
84412 return ts.visitEachChild(node, visitor, context);
84413 }
84414 function visitReturnStatement(node) {
84415 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
84416 return factory.updateReturnStatement(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : factory.createVoidZero()));
84417 }
84418 return ts.visitEachChild(node, visitor, context);
84419 }
84420 function visitLabeledStatement(node) {
84421 if (enclosingFunctionFlags & 2 /* Async */) {
84422 var statement = ts.unwrapInnermostStatementOfLabel(node);
84423 if (statement.kind === 236 /* ForOfStatement */ && statement.awaitModifier) {
84424 return visitForOfStatement(statement, node);
84425 }
84426 return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node);
84427 }
84428 return ts.visitEachChild(node, visitor, context);
84429 }
84430 function chunkObjectLiteralElements(elements) {
84431 var chunkObject;
84432 var objects = [];
84433 for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
84434 var e = elements_4[_i];
84435 if (e.kind === 287 /* SpreadAssignment */) {
84436 if (chunkObject) {
84437 objects.push(factory.createObjectLiteralExpression(chunkObject));
84438 chunkObject = undefined;
84439 }
84440 var target = e.expression;
84441 objects.push(ts.visitNode(target, visitor, ts.isExpression));
84442 }
84443 else {
84444 chunkObject = ts.append(chunkObject, e.kind === 285 /* PropertyAssignment */
84445 ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
84446 : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
84447 }
84448 }
84449 if (chunkObject) {
84450 objects.push(factory.createObjectLiteralExpression(chunkObject));
84451 }
84452 return objects;
84453 }
84454 function visitObjectLiteralExpression(node) {
84455 if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84456 // spread elements emit like so:
84457 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
84458 // { a, ...o, b } => __assign(__assign({a}, o), {b});
84459 // If the first element is a spread element, then the first argument to __assign is {}:
84460 // { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
84461 //
84462 // We cannot call __assign with more than two elements, since any element could cause side effects. For
84463 // example:
84464 // var k = { a: 1, b: 2 };
84465 // var o = { a: 3, ...k, b: k.a++ };
84466 // // expected: { a: 1, b: 1 }
84467 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
84468 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
84469 //
84470 // This also occurs for spread elements, not just property assignments:
84471 // var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
84472 // var l = { c: 3 };
84473 // var o = { ...k, ...l };
84474 // // expected: { a: 1, b: 2, z: 9 }
84475 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
84476 // end up with `{ a: 1, b: 2, c: 3 }`
84477 var objects = chunkObjectLiteralElements(node.properties);
84478 if (objects.length && objects[0].kind !== 197 /* ObjectLiteralExpression */) {
84479 objects.unshift(factory.createObjectLiteralExpression());
84480 }
84481 var expression = objects[0];
84482 if (objects.length > 1) {
84483 for (var i = 1; i < objects.length; i++) {
84484 expression = emitHelpers().createAssignHelper([expression, objects[i]]);
84485 }
84486 return expression;
84487 }
84488 else {
84489 return emitHelpers().createAssignHelper(objects);
84490 }
84491 }
84492 return ts.visitEachChild(node, visitor, context);
84493 }
84494 function visitExpressionStatement(node) {
84495 return ts.visitEachChild(node, visitorNoDestructuringValue, context);
84496 }
84497 function visitParenthesizedExpression(node, noDestructuringValue) {
84498 return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
84499 }
84500 function visitSourceFile(node) {
84501 var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
84502 0 /* StrictModeSourceFileIncludes */ :
84503 1 /* SourceFileIncludes */);
84504 exportedVariableStatement = false;
84505 var visited = ts.visitEachChild(node, visitor, context);
84506 var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
84507 factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
84508 ]);
84509 var result = factory.updateSourceFile(visited, ts.setTextRange(factory.createNodeArray(statement), node.statements));
84510 exitSubtree(ancestorFacts);
84511 return result;
84512 }
84513 function visitTaggedTemplateExpression(node) {
84514 return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
84515 }
84516 /**
84517 * Visits a BinaryExpression that contains a destructuring assignment.
84518 *
84519 * @param node A BinaryExpression node.
84520 */
84521 function visitBinaryExpression(node, noDestructuringValue) {
84522 if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84523 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
84524 }
84525 else if (node.operatorToken.kind === 27 /* CommaToken */) {
84526 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), node.operatorToken, ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
84527 }
84528 return ts.visitEachChild(node, visitor, context);
84529 }
84530 function visitCatchClause(node) {
84531 if (node.variableDeclaration &&
84532 ts.isBindingPattern(node.variableDeclaration.name) &&
84533 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84534 var name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
84535 var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
84536 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
84537 var block = ts.visitNode(node.block, visitor, ts.isBlock);
84538 if (ts.some(visitedBindings)) {
84539 block = factory.updateBlock(block, __spreadArrays([
84540 factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
84541 ], block.statements));
84542 }
84543 return factory.updateCatchClause(node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), block);
84544 }
84545 return ts.visitEachChild(node, visitor, context);
84546 }
84547 function visitVariableStatement(node) {
84548 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
84549 var savedExportedVariableStatement = exportedVariableStatement;
84550 exportedVariableStatement = true;
84551 var visited = ts.visitEachChild(node, visitor, context);
84552 exportedVariableStatement = savedExportedVariableStatement;
84553 return visited;
84554 }
84555 return ts.visitEachChild(node, visitor, context);
84556 }
84557 /**
84558 * Visits a VariableDeclaration node with a binding pattern.
84559 *
84560 * @param node A VariableDeclaration node.
84561 */
84562 function visitVariableDeclaration(node) {
84563 if (exportedVariableStatement) {
84564 var savedExportedVariableStatement = exportedVariableStatement;
84565 exportedVariableStatement = false;
84566 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
84567 exportedVariableStatement = savedExportedVariableStatement;
84568 return visited;
84569 }
84570 return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
84571 }
84572 function visitVariableDeclarationWorker(node, exportedVariableStatement) {
84573 // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
84574 if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84575 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */,
84576 /*rval*/ undefined, exportedVariableStatement);
84577 }
84578 return ts.visitEachChild(node, visitor, context);
84579 }
84580 function visitForStatement(node) {
84581 return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
84582 }
84583 function visitVoidExpression(node) {
84584 return ts.visitEachChild(node, visitorNoDestructuringValue, context);
84585 }
84586 /**
84587 * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
84588 *
84589 * @param node A ForOfStatement.
84590 */
84591 function visitForOfStatement(node, outermostLabeledStatement) {
84592 var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
84593 if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84594 node = transformForOfStatementWithObjectRest(node);
84595 }
84596 var result = node.awaitModifier ?
84597 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
84598 factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
84599 exitSubtree(ancestorFacts);
84600 return result;
84601 }
84602 function transformForOfStatementWithObjectRest(node) {
84603 var initializerWithoutParens = ts.skipParentheses(node.initializer);
84604 if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
84605 var bodyLocation = void 0;
84606 var statementsLocation = void 0;
84607 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
84608 var statements = [ts.createForOfBindingStatement(factory, initializerWithoutParens, temp)];
84609 if (ts.isBlock(node.statement)) {
84610 ts.addRange(statements, node.statement.statements);
84611 bodyLocation = node.statement;
84612 statementsLocation = node.statement.statements;
84613 }
84614 else if (node.statement) {
84615 ts.append(statements, node.statement);
84616 bodyLocation = node.statement;
84617 statementsLocation = node.statement;
84618 }
84619 return factory.updateForOfStatement(node, node.awaitModifier, ts.setTextRange(factory.createVariableDeclarationList([
84620 ts.setTextRange(factory.createVariableDeclaration(temp), node.initializer)
84621 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation),
84622 /*multiLine*/ true), bodyLocation));
84623 }
84624 return node;
84625 }
84626 function convertForOfStatementHead(node, boundValue) {
84627 var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue);
84628 var bodyLocation;
84629 var statementsLocation;
84630 var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
84631 var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
84632 if (ts.isBlock(statement)) {
84633 ts.addRange(statements, statement.statements);
84634 bodyLocation = statement;
84635 statementsLocation = statement.statements;
84636 }
84637 else {
84638 statements.push(statement);
84639 }
84640 return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation),
84641 /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84642 }
84643 function createDownlevelAwait(expression) {
84644 return enclosingFunctionFlags & 1 /* Generator */
84645 ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
84646 : factory.createAwaitExpression(expression);
84647 }
84648 function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
84649 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84650 var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
84651 var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
84652 var errorRecord = factory.createUniqueName("e");
84653 var catchVariable = factory.getGeneratedNameForNode(errorRecord);
84654 var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
84655 var callValues = ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
84656 var callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
84657 var getDone = factory.createPropertyAccessExpression(result, "done");
84658 var getValue = factory.createPropertyAccessExpression(result, "value");
84659 var callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
84660 hoistVariableDeclaration(errorRecord);
84661 hoistVariableDeclaration(returnMethod);
84662 // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84663 var initializer = ancestorFacts & 2 /* IterationContainer */ ?
84664 factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
84665 callValues;
84666 var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
84667 /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
84668 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
84669 factory.createVariableDeclaration(result)
84670 ]), node.expression), 2097152 /* NoHoisting */),
84671 /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)),
84672 /*incrementor*/ undefined,
84673 /*statement*/ convertForOfStatementHead(node, getValue)),
84674 /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84675 return factory.createTryStatement(factory.createBlock([
84676 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
84677 ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
84678 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
84679 factory.createPropertyAssignment("error", catchVariable)
84680 ])))
84681 ]), 1 /* SingleLine */)), factory.createBlock([
84682 factory.createTryStatement(
84683 /*tryBlock*/ factory.createBlock([
84684 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 */)
84685 ]),
84686 /*catchClause*/ undefined,
84687 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
84688 ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
84689 ]), 1 /* SingleLine */))
84690 ]));
84691 }
84692 function visitParameter(node) {
84693 if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84694 // Binding patterns are converted into a generated name and are
84695 // evaluated inside the function body.
84696 return factory.updateParameterDeclaration(node,
84697 /*decorators*/ undefined,
84698 /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node),
84699 /*questionToken*/ undefined,
84700 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
84701 }
84702 return ts.visitEachChild(node, visitor, context);
84703 }
84704 function visitConstructorDeclaration(node) {
84705 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84706 enclosingFunctionFlags = 0 /* Normal */;
84707 var updated = factory.updateConstructorDeclaration(node,
84708 /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
84709 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84710 return updated;
84711 }
84712 function visitGetAccessorDeclaration(node) {
84713 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84714 enclosingFunctionFlags = 0 /* Normal */;
84715 var updated = factory.updateGetAccessorDeclaration(node,
84716 /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context),
84717 /*type*/ undefined, transformFunctionBody(node));
84718 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84719 return updated;
84720 }
84721 function visitSetAccessorDeclaration(node) {
84722 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84723 enclosingFunctionFlags = 0 /* Normal */;
84724 var updated = factory.updateSetAccessorDeclaration(node,
84725 /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
84726 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84727 return updated;
84728 }
84729 function visitMethodDeclaration(node) {
84730 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84731 enclosingFunctionFlags = ts.getFunctionFlags(node);
84732 var updated = factory.updateMethodDeclaration(node,
84733 /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
84734 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
84735 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
84736 ? undefined
84737 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken),
84738 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
84739 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
84740 ? transformAsyncGeneratorFunctionBody(node)
84741 : transformFunctionBody(node));
84742 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84743 return updated;
84744 }
84745 function visitFunctionDeclaration(node) {
84746 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84747 enclosingFunctionFlags = ts.getFunctionFlags(node);
84748 var updated = factory.updateFunctionDeclaration(node,
84749 /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
84750 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
84751 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
84752 ? undefined
84753 : node.asteriskToken, node.name,
84754 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
84755 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
84756 ? transformAsyncGeneratorFunctionBody(node)
84757 : transformFunctionBody(node));
84758 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84759 return updated;
84760 }
84761 function visitArrowFunction(node) {
84762 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84763 enclosingFunctionFlags = ts.getFunctionFlags(node);
84764 var updated = factory.updateArrowFunction(node, node.modifiers,
84765 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
84766 /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
84767 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84768 return updated;
84769 }
84770 function visitFunctionExpression(node) {
84771 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
84772 enclosingFunctionFlags = ts.getFunctionFlags(node);
84773 var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
84774 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
84775 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
84776 ? undefined
84777 : node.asteriskToken, node.name,
84778 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
84779 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
84780 ? transformAsyncGeneratorFunctionBody(node)
84781 : transformFunctionBody(node));
84782 enclosingFunctionFlags = savedEnclosingFunctionFlags;
84783 return updated;
84784 }
84785 function transformAsyncGeneratorFunctionBody(node) {
84786 resumeLexicalEnvironment();
84787 var statements = [];
84788 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
84789 appendObjectRestAssignmentsIfNeeded(statements, node);
84790 var savedCapturedSuperProperties = capturedSuperProperties;
84791 var savedHasSuperElementAccess = hasSuperElementAccess;
84792 capturedSuperProperties = new ts.Set();
84793 hasSuperElementAccess = false;
84794 var returnStatement = factory.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory.createFunctionExpression(
84795 /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), node.name && factory.getGeneratedNameForNode(node.name),
84796 /*typeParameters*/ undefined,
84797 /*parameters*/ [],
84798 /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
84799 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
84800 // This step isn't needed if we eventually transform this to ES5.
84801 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
84802 if (emitSuperHelpers) {
84803 enableSubstitutionForAsyncMethodsWithSuper();
84804 var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
84805 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
84806 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
84807 }
84808 statements.push(returnStatement);
84809 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
84810 var block = factory.updateBlock(node.body, statements);
84811 if (emitSuperHelpers && hasSuperElementAccess) {
84812 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
84813 ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
84814 }
84815 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
84816 ts.addEmitHelper(block, ts.asyncSuperHelper);
84817 }
84818 }
84819 capturedSuperProperties = savedCapturedSuperProperties;
84820 hasSuperElementAccess = savedHasSuperElementAccess;
84821 return block;
84822 }
84823 function transformFunctionBody(node) {
84824 var _a;
84825 resumeLexicalEnvironment();
84826 var statementOffset = 0;
84827 var statements = [];
84828 var body = (_a = ts.visitNode(node.body, visitor, ts.isConciseBody)) !== null && _a !== void 0 ? _a : factory.createBlock([]);
84829 if (ts.isBlock(body)) {
84830 statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
84831 }
84832 ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
84833 var leadingStatements = endLexicalEnvironment();
84834 if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
84835 var block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
84836 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
84837 ts.addRange(statements, block.statements.slice(statementOffset));
84838 return factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(statements), block.statements));
84839 }
84840 return body;
84841 }
84842 function appendObjectRestAssignmentsIfNeeded(statements, node) {
84843 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
84844 var parameter = _a[_i];
84845 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
84846 var temp = factory.getGeneratedNameForNode(parameter);
84847 var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
84848 /*doNotRecordTempVariablesInLine*/ false,
84849 /*skipInitializer*/ true);
84850 if (ts.some(declarations)) {
84851 var statement = factory.createVariableStatement(
84852 /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations));
84853 ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
84854 statements = ts.append(statements, statement);
84855 }
84856 }
84857 }
84858 return statements;
84859 }
84860 function enableSubstitutionForAsyncMethodsWithSuper() {
84861 if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
84862 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
84863 // We need to enable substitutions for call, property access, and element access
84864 // if we need to rewrite super calls.
84865 context.enableSubstitution(200 /* CallExpression */);
84866 context.enableSubstitution(198 /* PropertyAccessExpression */);
84867 context.enableSubstitution(199 /* ElementAccessExpression */);
84868 // We need to be notified when entering and exiting declarations that bind super.
84869 context.enableEmitNotification(249 /* ClassDeclaration */);
84870 context.enableEmitNotification(164 /* MethodDeclaration */);
84871 context.enableEmitNotification(166 /* GetAccessor */);
84872 context.enableEmitNotification(167 /* SetAccessor */);
84873 context.enableEmitNotification(165 /* Constructor */);
84874 // We need to be notified when entering the generated accessor arrow functions.
84875 context.enableEmitNotification(229 /* VariableStatement */);
84876 }
84877 }
84878 /**
84879 * Called by the printer just before a node is printed.
84880 *
84881 * @param hint A hint as to the intended usage of the node.
84882 * @param node The node to be printed.
84883 * @param emitCallback The callback used to emit the node.
84884 */
84885 function onEmitNode(hint, node, emitCallback) {
84886 // If we need to support substitutions for `super` in an async method,
84887 // we should track it here.
84888 if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
84889 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
84890 if (superContainerFlags !== enclosingSuperContainerFlags) {
84891 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
84892 enclosingSuperContainerFlags = superContainerFlags;
84893 previousOnEmitNode(hint, node, emitCallback);
84894 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
84895 return;
84896 }
84897 }
84898 // Disable substitution in the generated super accessor itself.
84899 else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
84900 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
84901 enclosingSuperContainerFlags = 0;
84902 previousOnEmitNode(hint, node, emitCallback);
84903 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
84904 return;
84905 }
84906 previousOnEmitNode(hint, node, emitCallback);
84907 }
84908 /**
84909 * Hooks node substitutions.
84910 *
84911 * @param hint The context for the emitter.
84912 * @param node The node to substitute.
84913 */
84914 function onSubstituteNode(hint, node) {
84915 node = previousOnSubstituteNode(hint, node);
84916 if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
84917 return substituteExpression(node);
84918 }
84919 return node;
84920 }
84921 function substituteExpression(node) {
84922 switch (node.kind) {
84923 case 198 /* PropertyAccessExpression */:
84924 return substitutePropertyAccessExpression(node);
84925 case 199 /* ElementAccessExpression */:
84926 return substituteElementAccessExpression(node);
84927 case 200 /* CallExpression */:
84928 return substituteCallExpression(node);
84929 }
84930 return node;
84931 }
84932 function substitutePropertyAccessExpression(node) {
84933 if (node.expression.kind === 105 /* SuperKeyword */) {
84934 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
84935 }
84936 return node;
84937 }
84938 function substituteElementAccessExpression(node) {
84939 if (node.expression.kind === 105 /* SuperKeyword */) {
84940 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
84941 }
84942 return node;
84943 }
84944 function substituteCallExpression(node) {
84945 var expression = node.expression;
84946 if (ts.isSuperProperty(expression)) {
84947 var argumentExpression = ts.isPropertyAccessExpression(expression)
84948 ? substitutePropertyAccessExpression(expression)
84949 : substituteElementAccessExpression(expression);
84950 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"),
84951 /*typeArguments*/ undefined, __spreadArrays([
84952 factory.createThis()
84953 ], node.arguments));
84954 }
84955 return node;
84956 }
84957 function isSuperContainer(node) {
84958 var kind = node.kind;
84959 return kind === 249 /* ClassDeclaration */
84960 || kind === 165 /* Constructor */
84961 || kind === 164 /* MethodDeclaration */
84962 || kind === 166 /* GetAccessor */
84963 || kind === 167 /* SetAccessor */;
84964 }
84965 function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
84966 if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
84967 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"),
84968 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
84969 }
84970 else {
84971 return ts.setTextRange(factory.createCallExpression(factory.createIdentifier("_superIndex"),
84972 /*typeArguments*/ undefined, [argumentExpression]), location);
84973 }
84974 }
84975 }
84976 ts.transformES2018 = transformES2018;
84977})(ts || (ts = {}));
84978/*@internal*/
84979var ts;
84980(function (ts) {
84981 function transformES2019(context) {
84982 var factory = context.factory;
84983 return ts.chainBundle(context, transformSourceFile);
84984 function transformSourceFile(node) {
84985 if (node.isDeclarationFile) {
84986 return node;
84987 }
84988 return ts.visitEachChild(node, visitor, context);
84989 }
84990 function visitor(node) {
84991 if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
84992 return node;
84993 }
84994 switch (node.kind) {
84995 case 284 /* CatchClause */:
84996 return visitCatchClause(node);
84997 default:
84998 return ts.visitEachChild(node, visitor, context);
84999 }
85000 }
85001 function visitCatchClause(node) {
85002 if (!node.variableDeclaration) {
85003 return factory.updateCatchClause(node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
85004 }
85005 return ts.visitEachChild(node, visitor, context);
85006 }
85007 }
85008 ts.transformES2019 = transformES2019;
85009})(ts || (ts = {}));
85010/*@internal*/
85011var ts;
85012(function (ts) {
85013 function transformES2020(context) {
85014 var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
85015 return ts.chainBundle(context, transformSourceFile);
85016 function transformSourceFile(node) {
85017 if (node.isDeclarationFile) {
85018 return node;
85019 }
85020 return ts.visitEachChild(node, visitor, context);
85021 }
85022 function visitor(node) {
85023 if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
85024 return node;
85025 }
85026 switch (node.kind) {
85027 case 198 /* PropertyAccessExpression */:
85028 case 199 /* ElementAccessExpression */:
85029 case 200 /* CallExpression */:
85030 if (node.flags & 32 /* OptionalChain */) {
85031 var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
85032 ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
85033 return updated;
85034 }
85035 return ts.visitEachChild(node, visitor, context);
85036 case 213 /* BinaryExpression */:
85037 if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
85038 return transformNullishCoalescingExpression(node);
85039 }
85040 return ts.visitEachChild(node, visitor, context);
85041 case 207 /* DeleteExpression */:
85042 return visitDeleteExpression(node);
85043 default:
85044 return ts.visitEachChild(node, visitor, context);
85045 }
85046 }
85047 function flattenChain(chain) {
85048 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
85049 var links = [chain];
85050 while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
85051 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
85052 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
85053 links.unshift(chain);
85054 }
85055 return { expression: chain.expression, chain: links };
85056 }
85057 function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
85058 var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
85059 if (ts.isSyntheticReference(expression)) {
85060 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
85061 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
85062 return factory.createSyntheticReferenceExpression(factory.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
85063 }
85064 return factory.updateParenthesizedExpression(node, expression);
85065 }
85066 function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
85067 if (ts.isOptionalChain(node)) {
85068 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
85069 return visitOptionalExpression(node, captureThisArg, isDelete);
85070 }
85071 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
85072 ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
85073 var thisArg;
85074 if (captureThisArg) {
85075 if (!ts.isSimpleCopiableExpression(expression)) {
85076 thisArg = factory.createTempVariable(hoistVariableDeclaration);
85077 expression = factory.createAssignment(thisArg, expression);
85078 // if (inParameterInitializer) tempVariableInParameter = true;
85079 }
85080 else {
85081 thisArg = expression;
85082 }
85083 }
85084 expression = node.kind === 198 /* PropertyAccessExpression */
85085 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
85086 : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
85087 return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression;
85088 }
85089 function visitNonOptionalCallExpression(node, captureThisArg) {
85090 if (ts.isOptionalChain(node)) {
85091 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
85092 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
85093 }
85094 return ts.visitEachChild(node, visitor, context);
85095 }
85096 function visitNonOptionalExpression(node, captureThisArg, isDelete) {
85097 switch (node.kind) {
85098 case 204 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
85099 case 198 /* PropertyAccessExpression */:
85100 case 199 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
85101 case 200 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
85102 default: return ts.visitNode(node, visitor, ts.isExpression);
85103 }
85104 }
85105 function visitOptionalExpression(node, captureThisArg, isDelete) {
85106 var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
85107 var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
85108 var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
85109 var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
85110 var capturedLeft = leftExpression;
85111 if (!ts.isSimpleCopiableExpression(leftExpression)) {
85112 capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
85113 leftExpression = factory.createAssignment(capturedLeft, leftExpression);
85114 // if (inParameterInitializer) tempVariableInParameter = true;
85115 }
85116 var rightExpression = capturedLeft;
85117 var thisArg;
85118 for (var i = 0; i < chain.length; i++) {
85119 var segment = chain[i];
85120 switch (segment.kind) {
85121 case 198 /* PropertyAccessExpression */:
85122 case 199 /* ElementAccessExpression */:
85123 if (i === chain.length - 1 && captureThisArg) {
85124 if (!ts.isSimpleCopiableExpression(rightExpression)) {
85125 thisArg = factory.createTempVariable(hoistVariableDeclaration);
85126 rightExpression = factory.createAssignment(thisArg, rightExpression);
85127 // if (inParameterInitializer) tempVariableInParameter = true;
85128 }
85129 else {
85130 thisArg = rightExpression;
85131 }
85132 }
85133 rightExpression = segment.kind === 198 /* PropertyAccessExpression */
85134 ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
85135 : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
85136 break;
85137 case 200 /* CallExpression */:
85138 if (i === 0 && leftThisArg) {
85139 rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
85140 }
85141 else {
85142 rightExpression = factory.createCallExpression(rightExpression,
85143 /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
85144 }
85145 break;
85146 }
85147 ts.setOriginalNode(rightExpression, segment);
85148 }
85149 var target = isDelete
85150 ? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
85151 : factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
85152 return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
85153 }
85154 function createNotNullCondition(left, right, invert) {
85155 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()));
85156 }
85157 function transformNullishCoalescingExpression(node) {
85158 var left = ts.visitNode(node.left, visitor, ts.isExpression);
85159 var right = left;
85160 if (!ts.isSimpleCopiableExpression(left)) {
85161 right = factory.createTempVariable(hoistVariableDeclaration);
85162 left = factory.createAssignment(right, left);
85163 // if (inParameterInitializer) tempVariableInParameter = true;
85164 }
85165 return factory.createConditionalExpression(createNotNullCondition(left, right),
85166 /*questionToken*/ undefined, right,
85167 /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression));
85168 }
85169 function visitDeleteExpression(node) {
85170 return ts.isOptionalChain(ts.skipParentheses(node.expression))
85171 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
85172 : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression));
85173 }
85174 }
85175 ts.transformES2020 = transformES2020;
85176})(ts || (ts = {}));
85177/*@internal*/
85178var ts;
85179(function (ts) {
85180 function transformESNext(context) {
85181 var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory;
85182 return ts.chainBundle(context, transformSourceFile);
85183 function transformSourceFile(node) {
85184 if (node.isDeclarationFile) {
85185 return node;
85186 }
85187 return ts.visitEachChild(node, visitor, context);
85188 }
85189 function visitor(node) {
85190 if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
85191 return node;
85192 }
85193 switch (node.kind) {
85194 case 213 /* BinaryExpression */:
85195 var binaryExpression = node;
85196 if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
85197 return transformLogicalAssignment(binaryExpression);
85198 }
85199 // falls through
85200 default:
85201 return ts.visitEachChild(node, visitor, context);
85202 }
85203 }
85204 function transformLogicalAssignment(binaryExpression) {
85205 var operator = binaryExpression.operatorToken;
85206 var nonAssignmentOperator = ts.getNonAssignmentOperatorForCompoundAssignment(operator.kind);
85207 var left = ts.skipParentheses(ts.visitNode(binaryExpression.left, visitor, ts.isLeftHandSideExpression));
85208 var assignmentTarget = left;
85209 var right = ts.skipParentheses(ts.visitNode(binaryExpression.right, visitor, ts.isExpression));
85210 if (ts.isAccessExpression(left)) {
85211 var propertyAccessTargetSimpleCopiable = ts.isSimpleCopiableExpression(left.expression);
85212 var propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression :
85213 factory.createTempVariable(hoistVariableDeclaration);
85214 var propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment(propertyAccessTarget, left.expression);
85215 if (ts.isPropertyAccessExpression(left)) {
85216 assignmentTarget = factory.createPropertyAccessExpression(propertyAccessTarget, left.name);
85217 left = factory.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name);
85218 }
85219 else {
85220 var elementAccessArgumentSimpleCopiable = ts.isSimpleCopiableExpression(left.argumentExpression);
85221 var elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression :
85222 factory.createTempVariable(hoistVariableDeclaration);
85223 assignmentTarget = factory.createElementAccessExpression(propertyAccessTarget, elementAccessArgument);
85224 left = factory.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment(elementAccessArgument, left.argumentExpression));
85225 }
85226 }
85227 return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right)));
85228 }
85229 }
85230 ts.transformESNext = transformESNext;
85231})(ts || (ts = {}));
85232/*@internal*/
85233var ts;
85234(function (ts) {
85235 function transformJsx(context) {
85236 var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
85237 var compilerOptions = context.getCompilerOptions();
85238 var currentSourceFile;
85239 return ts.chainBundle(context, transformSourceFile);
85240 /**
85241 * Transform JSX-specific syntax in a SourceFile.
85242 *
85243 * @param node A SourceFile node.
85244 */
85245 function transformSourceFile(node) {
85246 if (node.isDeclarationFile) {
85247 return node;
85248 }
85249 currentSourceFile = node;
85250 var visited = ts.visitEachChild(node, visitor, context);
85251 ts.addEmitHelpers(visited, context.readEmitHelpers());
85252 return visited;
85253 }
85254 function visitor(node) {
85255 if (node.transformFlags & 2 /* ContainsJsx */) {
85256 return visitorWorker(node);
85257 }
85258 else {
85259 return node;
85260 }
85261 }
85262 function visitorWorker(node) {
85263 switch (node.kind) {
85264 case 270 /* JsxElement */:
85265 return visitJsxElement(node, /*isChild*/ false);
85266 case 271 /* JsxSelfClosingElement */:
85267 return visitJsxSelfClosingElement(node, /*isChild*/ false);
85268 case 274 /* JsxFragment */:
85269 return visitJsxFragment(node, /*isChild*/ false);
85270 case 280 /* JsxExpression */:
85271 return visitJsxExpression(node);
85272 default:
85273 return ts.visitEachChild(node, visitor, context);
85274 }
85275 }
85276 function transformJsxChildToExpression(node) {
85277 switch (node.kind) {
85278 case 11 /* JsxText */:
85279 return visitJsxText(node);
85280 case 280 /* JsxExpression */:
85281 return visitJsxExpression(node);
85282 case 270 /* JsxElement */:
85283 return visitJsxElement(node, /*isChild*/ true);
85284 case 271 /* JsxSelfClosingElement */:
85285 return visitJsxSelfClosingElement(node, /*isChild*/ true);
85286 case 274 /* JsxFragment */:
85287 return visitJsxFragment(node, /*isChild*/ true);
85288 default:
85289 return ts.Debug.failBadSyntaxKind(node);
85290 }
85291 }
85292 function visitJsxElement(node, isChild) {
85293 return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
85294 }
85295 function visitJsxSelfClosingElement(node, isChild) {
85296 return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
85297 }
85298 function visitJsxFragment(node, isChild) {
85299 return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
85300 }
85301 function visitJsxOpeningLikeElement(node, children, isChild, location) {
85302 var tagName = getTagName(node);
85303 var objectProperties;
85304 var attrs = node.attributes.properties;
85305 if (attrs.length === 0) {
85306 objectProperties = factory.createNull();
85307 // When there are no attributes, React wants "null"
85308 }
85309 else {
85310 // Map spans of JsxAttribute nodes into object literals and spans
85311 // of JsxSpreadAttribute nodes into expressions.
85312 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
85313 ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
85314 : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
85315 if (ts.isJsxSpreadAttribute(attrs[0])) {
85316 // We must always emit at least one object literal before a spread
85317 // argument.factory.createObjectLiteral
85318 segments.unshift(factory.createObjectLiteralExpression());
85319 }
85320 // Either emit one big object literal (no spread attribs), or
85321 // a call to the __assign helper.
85322 objectProperties = ts.singleOrUndefined(segments);
85323 if (!objectProperties) {
85324 objectProperties = emitHelpers().createAssignHelper(segments);
85325 }
85326 }
85327 var element = ts.createExpressionForJsxElement(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
85328 tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
85329 if (isChild) {
85330 ts.startOnNewLine(element);
85331 }
85332 return element;
85333 }
85334 function visitJsxOpeningFragment(node, children, isChild, location) {
85335 var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
85336 ts.mapDefined(children, transformJsxChildToExpression), node, location);
85337 if (isChild) {
85338 ts.startOnNewLine(element);
85339 }
85340 return element;
85341 }
85342 function transformJsxSpreadAttributeToExpression(node) {
85343 return ts.visitNode(node.expression, visitor, ts.isExpression);
85344 }
85345 function transformJsxAttributeToObjectLiteralElement(node) {
85346 var name = getAttributeName(node);
85347 var expression = transformJsxAttributeInitializer(node.initializer);
85348 return factory.createPropertyAssignment(name, expression);
85349 }
85350 function transformJsxAttributeInitializer(node) {
85351 if (node === undefined) {
85352 return factory.createTrue();
85353 }
85354 else if (node.kind === 10 /* StringLiteral */) {
85355 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
85356 // Need to be escaped to be handled correctly in a normal string
85357 var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
85358 var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
85359 return ts.setTextRange(literal, node);
85360 }
85361 else if (node.kind === 280 /* JsxExpression */) {
85362 if (node.expression === undefined) {
85363 return factory.createTrue();
85364 }
85365 return ts.visitNode(node.expression, visitor, ts.isExpression);
85366 }
85367 else {
85368 return ts.Debug.failBadSyntaxKind(node);
85369 }
85370 }
85371 function visitJsxText(node) {
85372 var fixed = fixupWhitespaceAndDecodeEntities(node.text);
85373 return fixed === undefined ? undefined : factory.createStringLiteral(fixed);
85374 }
85375 /**
85376 * JSX trims whitespace at the end and beginning of lines, except that the
85377 * start/end of a tag is considered a start/end of a line only if that line is
85378 * on the same line as the closing tag. See examples in
85379 * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
85380 * 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
85381 *
85382 * An equivalent algorithm would be:
85383 * - If there is only one line, return it.
85384 * - If there is only whitespace (but multiple lines), return `undefined`.
85385 * - Split the text into lines.
85386 * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
85387 * - Decode entities on each line (individually).
85388 * - Remove empty lines and join the rest with " ".
85389 */
85390 function fixupWhitespaceAndDecodeEntities(text) {
85391 var acc;
85392 // First non-whitespace character on this line.
85393 var firstNonWhitespace = 0;
85394 // Last non-whitespace character on this line.
85395 var lastNonWhitespace = -1;
85396 // These initial values are special because the first line is:
85397 // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
85398 // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
85399 for (var i = 0; i < text.length; i++) {
85400 var c = text.charCodeAt(i);
85401 if (ts.isLineBreak(c)) {
85402 // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
85403 // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
85404 if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
85405 acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
85406 }
85407 // Reset firstNonWhitespace for the next line.
85408 // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
85409 firstNonWhitespace = -1;
85410 }
85411 else if (!ts.isWhiteSpaceSingleLine(c)) {
85412 lastNonWhitespace = i;
85413 if (firstNonWhitespace === -1) {
85414 firstNonWhitespace = i;
85415 }
85416 }
85417 }
85418 return firstNonWhitespace !== -1
85419 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
85420 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
85421 // Last line was all whitespace, so ignore it
85422 : acc;
85423 }
85424 function addLineOfJsxText(acc, trimmedLine) {
85425 // We do not escape the string here as that is handled by the printer
85426 // when it emits the literal. We do, however, need to decode JSX entities.
85427 var decoded = decodeEntities(trimmedLine);
85428 return acc === undefined ? decoded : acc + " " + decoded;
85429 }
85430 /**
85431 * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
85432 * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
85433 */
85434 function decodeEntities(text) {
85435 return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
85436 if (decimal) {
85437 return ts.utf16EncodeAsString(parseInt(decimal, 10));
85438 }
85439 else if (hex) {
85440 return ts.utf16EncodeAsString(parseInt(hex, 16));
85441 }
85442 else {
85443 var ch = entities.get(word);
85444 // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
85445 return ch ? ts.utf16EncodeAsString(ch) : match;
85446 }
85447 });
85448 }
85449 /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
85450 function tryDecodeEntities(text) {
85451 var decoded = decodeEntities(text);
85452 return decoded === text ? undefined : decoded;
85453 }
85454 function getTagName(node) {
85455 if (node.kind === 270 /* JsxElement */) {
85456 return getTagName(node.openingElement);
85457 }
85458 else {
85459 var name = node.tagName;
85460 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
85461 return factory.createStringLiteral(ts.idText(name));
85462 }
85463 else {
85464 return ts.createExpressionFromEntityName(factory, name);
85465 }
85466 }
85467 }
85468 /**
85469 * Emit an attribute name, which is quoted if it needs to be quoted. Because
85470 * these emit into an object literal property name, we don't need to be worried
85471 * about keywords, just non-identifier characters
85472 */
85473 function getAttributeName(node) {
85474 var name = node.name;
85475 var text = ts.idText(name);
85476 if (/^[A-Za-z_]\w*$/.test(text)) {
85477 return name;
85478 }
85479 else {
85480 return factory.createStringLiteral(text);
85481 }
85482 }
85483 function visitJsxExpression(node) {
85484 return ts.visitNode(node.expression, visitor, ts.isExpression);
85485 }
85486 }
85487 ts.transformJsx = transformJsx;
85488 var entities = new ts.Map(ts.getEntries({
85489 quot: 0x0022,
85490 amp: 0x0026,
85491 apos: 0x0027,
85492 lt: 0x003C,
85493 gt: 0x003E,
85494 nbsp: 0x00A0,
85495 iexcl: 0x00A1,
85496 cent: 0x00A2,
85497 pound: 0x00A3,
85498 curren: 0x00A4,
85499 yen: 0x00A5,
85500 brvbar: 0x00A6,
85501 sect: 0x00A7,
85502 uml: 0x00A8,
85503 copy: 0x00A9,
85504 ordf: 0x00AA,
85505 laquo: 0x00AB,
85506 not: 0x00AC,
85507 shy: 0x00AD,
85508 reg: 0x00AE,
85509 macr: 0x00AF,
85510 deg: 0x00B0,
85511 plusmn: 0x00B1,
85512 sup2: 0x00B2,
85513 sup3: 0x00B3,
85514 acute: 0x00B4,
85515 micro: 0x00B5,
85516 para: 0x00B6,
85517 middot: 0x00B7,
85518 cedil: 0x00B8,
85519 sup1: 0x00B9,
85520 ordm: 0x00BA,
85521 raquo: 0x00BB,
85522 frac14: 0x00BC,
85523 frac12: 0x00BD,
85524 frac34: 0x00BE,
85525 iquest: 0x00BF,
85526 Agrave: 0x00C0,
85527 Aacute: 0x00C1,
85528 Acirc: 0x00C2,
85529 Atilde: 0x00C3,
85530 Auml: 0x00C4,
85531 Aring: 0x00C5,
85532 AElig: 0x00C6,
85533 Ccedil: 0x00C7,
85534 Egrave: 0x00C8,
85535 Eacute: 0x00C9,
85536 Ecirc: 0x00CA,
85537 Euml: 0x00CB,
85538 Igrave: 0x00CC,
85539 Iacute: 0x00CD,
85540 Icirc: 0x00CE,
85541 Iuml: 0x00CF,
85542 ETH: 0x00D0,
85543 Ntilde: 0x00D1,
85544 Ograve: 0x00D2,
85545 Oacute: 0x00D3,
85546 Ocirc: 0x00D4,
85547 Otilde: 0x00D5,
85548 Ouml: 0x00D6,
85549 times: 0x00D7,
85550 Oslash: 0x00D8,
85551 Ugrave: 0x00D9,
85552 Uacute: 0x00DA,
85553 Ucirc: 0x00DB,
85554 Uuml: 0x00DC,
85555 Yacute: 0x00DD,
85556 THORN: 0x00DE,
85557 szlig: 0x00DF,
85558 agrave: 0x00E0,
85559 aacute: 0x00E1,
85560 acirc: 0x00E2,
85561 atilde: 0x00E3,
85562 auml: 0x00E4,
85563 aring: 0x00E5,
85564 aelig: 0x00E6,
85565 ccedil: 0x00E7,
85566 egrave: 0x00E8,
85567 eacute: 0x00E9,
85568 ecirc: 0x00EA,
85569 euml: 0x00EB,
85570 igrave: 0x00EC,
85571 iacute: 0x00ED,
85572 icirc: 0x00EE,
85573 iuml: 0x00EF,
85574 eth: 0x00F0,
85575 ntilde: 0x00F1,
85576 ograve: 0x00F2,
85577 oacute: 0x00F3,
85578 ocirc: 0x00F4,
85579 otilde: 0x00F5,
85580 ouml: 0x00F6,
85581 divide: 0x00F7,
85582 oslash: 0x00F8,
85583 ugrave: 0x00F9,
85584 uacute: 0x00FA,
85585 ucirc: 0x00FB,
85586 uuml: 0x00FC,
85587 yacute: 0x00FD,
85588 thorn: 0x00FE,
85589 yuml: 0x00FF,
85590 OElig: 0x0152,
85591 oelig: 0x0153,
85592 Scaron: 0x0160,
85593 scaron: 0x0161,
85594 Yuml: 0x0178,
85595 fnof: 0x0192,
85596 circ: 0x02C6,
85597 tilde: 0x02DC,
85598 Alpha: 0x0391,
85599 Beta: 0x0392,
85600 Gamma: 0x0393,
85601 Delta: 0x0394,
85602 Epsilon: 0x0395,
85603 Zeta: 0x0396,
85604 Eta: 0x0397,
85605 Theta: 0x0398,
85606 Iota: 0x0399,
85607 Kappa: 0x039A,
85608 Lambda: 0x039B,
85609 Mu: 0x039C,
85610 Nu: 0x039D,
85611 Xi: 0x039E,
85612 Omicron: 0x039F,
85613 Pi: 0x03A0,
85614 Rho: 0x03A1,
85615 Sigma: 0x03A3,
85616 Tau: 0x03A4,
85617 Upsilon: 0x03A5,
85618 Phi: 0x03A6,
85619 Chi: 0x03A7,
85620 Psi: 0x03A8,
85621 Omega: 0x03A9,
85622 alpha: 0x03B1,
85623 beta: 0x03B2,
85624 gamma: 0x03B3,
85625 delta: 0x03B4,
85626 epsilon: 0x03B5,
85627 zeta: 0x03B6,
85628 eta: 0x03B7,
85629 theta: 0x03B8,
85630 iota: 0x03B9,
85631 kappa: 0x03BA,
85632 lambda: 0x03BB,
85633 mu: 0x03BC,
85634 nu: 0x03BD,
85635 xi: 0x03BE,
85636 omicron: 0x03BF,
85637 pi: 0x03C0,
85638 rho: 0x03C1,
85639 sigmaf: 0x03C2,
85640 sigma: 0x03C3,
85641 tau: 0x03C4,
85642 upsilon: 0x03C5,
85643 phi: 0x03C6,
85644 chi: 0x03C7,
85645 psi: 0x03C8,
85646 omega: 0x03C9,
85647 thetasym: 0x03D1,
85648 upsih: 0x03D2,
85649 piv: 0x03D6,
85650 ensp: 0x2002,
85651 emsp: 0x2003,
85652 thinsp: 0x2009,
85653 zwnj: 0x200C,
85654 zwj: 0x200D,
85655 lrm: 0x200E,
85656 rlm: 0x200F,
85657 ndash: 0x2013,
85658 mdash: 0x2014,
85659 lsquo: 0x2018,
85660 rsquo: 0x2019,
85661 sbquo: 0x201A,
85662 ldquo: 0x201C,
85663 rdquo: 0x201D,
85664 bdquo: 0x201E,
85665 dagger: 0x2020,
85666 Dagger: 0x2021,
85667 bull: 0x2022,
85668 hellip: 0x2026,
85669 permil: 0x2030,
85670 prime: 0x2032,
85671 Prime: 0x2033,
85672 lsaquo: 0x2039,
85673 rsaquo: 0x203A,
85674 oline: 0x203E,
85675 frasl: 0x2044,
85676 euro: 0x20AC,
85677 image: 0x2111,
85678 weierp: 0x2118,
85679 real: 0x211C,
85680 trade: 0x2122,
85681 alefsym: 0x2135,
85682 larr: 0x2190,
85683 uarr: 0x2191,
85684 rarr: 0x2192,
85685 darr: 0x2193,
85686 harr: 0x2194,
85687 crarr: 0x21B5,
85688 lArr: 0x21D0,
85689 uArr: 0x21D1,
85690 rArr: 0x21D2,
85691 dArr: 0x21D3,
85692 hArr: 0x21D4,
85693 forall: 0x2200,
85694 part: 0x2202,
85695 exist: 0x2203,
85696 empty: 0x2205,
85697 nabla: 0x2207,
85698 isin: 0x2208,
85699 notin: 0x2209,
85700 ni: 0x220B,
85701 prod: 0x220F,
85702 sum: 0x2211,
85703 minus: 0x2212,
85704 lowast: 0x2217,
85705 radic: 0x221A,
85706 prop: 0x221D,
85707 infin: 0x221E,
85708 ang: 0x2220,
85709 and: 0x2227,
85710 or: 0x2228,
85711 cap: 0x2229,
85712 cup: 0x222A,
85713 int: 0x222B,
85714 there4: 0x2234,
85715 sim: 0x223C,
85716 cong: 0x2245,
85717 asymp: 0x2248,
85718 ne: 0x2260,
85719 equiv: 0x2261,
85720 le: 0x2264,
85721 ge: 0x2265,
85722 sub: 0x2282,
85723 sup: 0x2283,
85724 nsub: 0x2284,
85725 sube: 0x2286,
85726 supe: 0x2287,
85727 oplus: 0x2295,
85728 otimes: 0x2297,
85729 perp: 0x22A5,
85730 sdot: 0x22C5,
85731 lceil: 0x2308,
85732 rceil: 0x2309,
85733 lfloor: 0x230A,
85734 rfloor: 0x230B,
85735 lang: 0x2329,
85736 rang: 0x232A,
85737 loz: 0x25CA,
85738 spades: 0x2660,
85739 clubs: 0x2663,
85740 hearts: 0x2665,
85741 diams: 0x2666
85742 }));
85743})(ts || (ts = {}));
85744/*@internal*/
85745var ts;
85746(function (ts) {
85747 function transformES2016(context) {
85748 var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
85749 return ts.chainBundle(context, transformSourceFile);
85750 function transformSourceFile(node) {
85751 if (node.isDeclarationFile) {
85752 return node;
85753 }
85754 return ts.visitEachChild(node, visitor, context);
85755 }
85756 function visitor(node) {
85757 if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
85758 return node;
85759 }
85760 switch (node.kind) {
85761 case 213 /* BinaryExpression */:
85762 return visitBinaryExpression(node);
85763 default:
85764 return ts.visitEachChild(node, visitor, context);
85765 }
85766 }
85767 function visitBinaryExpression(node) {
85768 switch (node.operatorToken.kind) {
85769 case 66 /* AsteriskAsteriskEqualsToken */:
85770 return visitExponentiationAssignmentExpression(node);
85771 case 42 /* AsteriskAsteriskToken */:
85772 return visitExponentiationExpression(node);
85773 default:
85774 return ts.visitEachChild(node, visitor, context);
85775 }
85776 }
85777 function visitExponentiationAssignmentExpression(node) {
85778 var target;
85779 var value;
85780 var left = ts.visitNode(node.left, visitor, ts.isExpression);
85781 var right = ts.visitNode(node.right, visitor, ts.isExpression);
85782 if (ts.isElementAccessExpression(left)) {
85783 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
85784 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
85785 var argumentExpressionTemp = factory.createTempVariable(hoistVariableDeclaration);
85786 target = ts.setTextRange(factory.createElementAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
85787 value = ts.setTextRange(factory.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left);
85788 }
85789 else if (ts.isPropertyAccessExpression(left)) {
85790 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
85791 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
85792 target = ts.setTextRange(factory.createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
85793 value = ts.setTextRange(factory.createPropertyAccessExpression(expressionTemp, left.name), left);
85794 }
85795 else {
85796 // Transforms `a **= b` into `a = Math.pow(a, b)`
85797 target = left;
85798 value = left;
85799 }
85800 return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node)), node);
85801 }
85802 function visitExponentiationExpression(node) {
85803 // Transforms `a ** b` into `Math.pow(a, b)`
85804 var left = ts.visitNode(node.left, visitor, ts.isExpression);
85805 var right = ts.visitNode(node.right, visitor, ts.isExpression);
85806 return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node);
85807 }
85808 }
85809 ts.transformES2016 = transformES2016;
85810})(ts || (ts = {}));
85811/*@internal*/
85812var ts;
85813(function (ts) {
85814 var ES2015SubstitutionFlags;
85815 (function (ES2015SubstitutionFlags) {
85816 /** Enables substitutions for captured `this` */
85817 ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
85818 /** Enables substitutions for block-scoped bindings. */
85819 ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
85820 })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
85821 var LoopOutParameterFlags;
85822 (function (LoopOutParameterFlags) {
85823 LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
85824 LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
85825 })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
85826 var CopyDirection;
85827 (function (CopyDirection) {
85828 CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
85829 CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
85830 })(CopyDirection || (CopyDirection = {}));
85831 var Jump;
85832 (function (Jump) {
85833 Jump[Jump["Break"] = 2] = "Break";
85834 Jump[Jump["Continue"] = 4] = "Continue";
85835 Jump[Jump["Return"] = 8] = "Return";
85836 })(Jump || (Jump = {}));
85837 // Facts we track as we traverse the tree
85838 var HierarchyFacts;
85839 (function (HierarchyFacts) {
85840 HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
85841 //
85842 // Ancestor facts
85843 //
85844 HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
85845 HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
85846 HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
85847 HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
85848 HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
85849 HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
85850 HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
85851 HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
85852 HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
85853 HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
85854 HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
85855 HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
85856 HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
85857 HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
85858 // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
85859 // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
85860 //
85861 // Ancestor masks
85862 //
85863 HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
85864 // We are always in *some* kind of block scope, but only specific block-scope containers are
85865 // top-level or Blocks.
85866 HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
85867 HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
85868 // A source file is a top-level block scope.
85869 HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
85870 HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
85871 // Functions, methods, and accessors are both new lexical scopes and new block scopes.
85872 HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
85873 HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
85874 HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
85875 HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
85876 // Arrow functions are lexically scoped to their container, but are new block scopes.
85877 HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
85878 HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
85879 // Constructors are both new lexical scopes and new block scopes. Constructors are also
85880 // always considered non-static members of a class.
85881 HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
85882 HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
85883 // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
85884 // within an IterationStatement to indicate whether the embedded statement is an
85885 // IterationStatementBlock.
85886 HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
85887 HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
85888 // 'for' statements are new block scopes and have special handling for 'let' declarations.
85889 HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
85890 HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
85891 // 'for-in' and 'for-of' statements are new block scopes and have special handling for
85892 // 'let' declarations.
85893 HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
85894 HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
85895 // Blocks (other than function bodies) are new block scopes.
85896 HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
85897 HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
85898 HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
85899 HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
85900 //
85901 // Subtree facts
85902 //
85903 HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
85904 HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
85905 //
85906 // Subtree masks
85907 //
85908 HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
85909 HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
85910 HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
85911 })(HierarchyFacts || (HierarchyFacts = {}));
85912 function transformES2015(context) {
85913 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
85914 var compilerOptions = context.getCompilerOptions();
85915 var resolver = context.getEmitResolver();
85916 var previousOnSubstituteNode = context.onSubstituteNode;
85917 var previousOnEmitNode = context.onEmitNode;
85918 context.onEmitNode = onEmitNode;
85919 context.onSubstituteNode = onSubstituteNode;
85920 var currentSourceFile;
85921 var currentText;
85922 var hierarchyFacts;
85923 var taggedTemplateStringDeclarations;
85924 function recordTaggedTemplateString(temp) {
85925 taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
85926 }
85927 /**
85928 * Used to track if we are emitting body of the converted loop
85929 */
85930 var convertedLoopState;
85931 /**
85932 * Keeps track of whether substitutions have been enabled for specific cases.
85933 * They are persisted between each SourceFile transformation and should not
85934 * be reset.
85935 */
85936 var enabledSubstitutions;
85937 return ts.chainBundle(context, transformSourceFile);
85938 function transformSourceFile(node) {
85939 if (node.isDeclarationFile) {
85940 return node;
85941 }
85942 currentSourceFile = node;
85943 currentText = node.text;
85944 var visited = visitSourceFile(node);
85945 ts.addEmitHelpers(visited, context.readEmitHelpers());
85946 currentSourceFile = undefined;
85947 currentText = undefined;
85948 taggedTemplateStringDeclarations = undefined;
85949 hierarchyFacts = 0 /* None */;
85950 return visited;
85951 }
85952 /**
85953 * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
85954 * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
85955 * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
85956 */
85957 function enterSubtree(excludeFacts, includeFacts) {
85958 var ancestorFacts = hierarchyFacts;
85959 hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
85960 return ancestorFacts;
85961 }
85962 /**
85963 * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
85964 * subtree, propagating specific facts from the subtree.
85965 * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
85966 * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
85967 * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
85968 */
85969 function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
85970 hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
85971 }
85972 function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
85973 return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
85974 && node.kind === 239 /* ReturnStatement */
85975 && !node.expression;
85976 }
85977 function isOrMayContainReturnCompletion(node) {
85978 return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */
85979 && (ts.isReturnStatement(node)
85980 || ts.isIfStatement(node)
85981 || ts.isWithStatement(node)
85982 || ts.isSwitchStatement(node)
85983 || ts.isCaseBlock(node)
85984 || ts.isCaseClause(node)
85985 || ts.isDefaultClause(node)
85986 || ts.isTryStatement(node)
85987 || ts.isCatchClause(node)
85988 || ts.isLabeledStatement(node)
85989 || ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)
85990 || ts.isBlock(node));
85991 }
85992 function shouldVisitNode(node) {
85993 return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
85994 || convertedLoopState !== undefined
85995 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node))
85996 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
85997 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
85998 }
85999 function visitor(node) {
86000 if (shouldVisitNode(node)) {
86001 return visitJavaScript(node);
86002 }
86003 else {
86004 return node;
86005 }
86006 }
86007 function callExpressionVisitor(node) {
86008 if (node.kind === 105 /* SuperKeyword */) {
86009 return visitSuperKeyword(/*isExpressionOfCall*/ true);
86010 }
86011 return visitor(node);
86012 }
86013 function visitJavaScript(node) {
86014 switch (node.kind) {
86015 case 123 /* StaticKeyword */:
86016 return undefined; // elide static keyword
86017 case 249 /* ClassDeclaration */:
86018 return visitClassDeclaration(node);
86019 case 218 /* ClassExpression */:
86020 return visitClassExpression(node);
86021 case 159 /* Parameter */:
86022 return visitParameter(node);
86023 case 248 /* FunctionDeclaration */:
86024 return visitFunctionDeclaration(node);
86025 case 206 /* ArrowFunction */:
86026 return visitArrowFunction(node);
86027 case 205 /* FunctionExpression */:
86028 return visitFunctionExpression(node);
86029 case 246 /* VariableDeclaration */:
86030 return visitVariableDeclaration(node);
86031 case 78 /* Identifier */:
86032 return visitIdentifier(node);
86033 case 247 /* VariableDeclarationList */:
86034 return visitVariableDeclarationList(node);
86035 case 241 /* SwitchStatement */:
86036 return visitSwitchStatement(node);
86037 case 255 /* CaseBlock */:
86038 return visitCaseBlock(node);
86039 case 227 /* Block */:
86040 return visitBlock(node, /*isFunctionBody*/ false);
86041 case 238 /* BreakStatement */:
86042 case 237 /* ContinueStatement */:
86043 return visitBreakOrContinueStatement(node);
86044 case 242 /* LabeledStatement */:
86045 return visitLabeledStatement(node);
86046 case 232 /* DoStatement */:
86047 case 233 /* WhileStatement */:
86048 return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
86049 case 234 /* ForStatement */:
86050 return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
86051 case 235 /* ForInStatement */:
86052 return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
86053 case 236 /* ForOfStatement */:
86054 return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
86055 case 230 /* ExpressionStatement */:
86056 return visitExpressionStatement(node);
86057 case 197 /* ObjectLiteralExpression */:
86058 return visitObjectLiteralExpression(node);
86059 case 284 /* CatchClause */:
86060 return visitCatchClause(node);
86061 case 286 /* ShorthandPropertyAssignment */:
86062 return visitShorthandPropertyAssignment(node);
86063 case 157 /* ComputedPropertyName */:
86064 return visitComputedPropertyName(node);
86065 case 196 /* ArrayLiteralExpression */:
86066 return visitArrayLiteralExpression(node);
86067 case 200 /* CallExpression */:
86068 return visitCallExpression(node);
86069 case 201 /* NewExpression */:
86070 return visitNewExpression(node);
86071 case 204 /* ParenthesizedExpression */:
86072 return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
86073 case 213 /* BinaryExpression */:
86074 return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
86075 case 14 /* NoSubstitutionTemplateLiteral */:
86076 case 15 /* TemplateHead */:
86077 case 16 /* TemplateMiddle */:
86078 case 17 /* TemplateTail */:
86079 return visitTemplateLiteral(node);
86080 case 10 /* StringLiteral */:
86081 return visitStringLiteral(node);
86082 case 8 /* NumericLiteral */:
86083 return visitNumericLiteral(node);
86084 case 202 /* TaggedTemplateExpression */:
86085 return visitTaggedTemplateExpression(node);
86086 case 215 /* TemplateExpression */:
86087 return visitTemplateExpression(node);
86088 case 216 /* YieldExpression */:
86089 return visitYieldExpression(node);
86090 case 217 /* SpreadElement */:
86091 return visitSpreadElement(node);
86092 case 105 /* SuperKeyword */:
86093 return visitSuperKeyword(/*isExpressionOfCall*/ false);
86094 case 107 /* ThisKeyword */:
86095 return visitThisKeyword(node);
86096 case 223 /* MetaProperty */:
86097 return visitMetaProperty(node);
86098 case 164 /* MethodDeclaration */:
86099 return visitMethodDeclaration(node);
86100 case 166 /* GetAccessor */:
86101 case 167 /* SetAccessor */:
86102 return visitAccessorDeclaration(node);
86103 case 229 /* VariableStatement */:
86104 return visitVariableStatement(node);
86105 case 239 /* ReturnStatement */:
86106 return visitReturnStatement(node);
86107 default:
86108 return ts.visitEachChild(node, visitor, context);
86109 }
86110 }
86111 function visitSourceFile(node) {
86112 var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
86113 var prologue = [];
86114 var statements = [];
86115 startLexicalEnvironment();
86116 var statementOffset = factory.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ false, visitor);
86117 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
86118 if (taggedTemplateStringDeclarations) {
86119 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)));
86120 }
86121 factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
86122 insertCaptureThisForNodeIfNeeded(prologue, node);
86123 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86124 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
86125 }
86126 function visitSwitchStatement(node) {
86127 if (convertedLoopState !== undefined) {
86128 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
86129 // for switch statement allow only non-labeled break
86130 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
86131 var result = ts.visitEachChild(node, visitor, context);
86132 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
86133 return result;
86134 }
86135 return ts.visitEachChild(node, visitor, context);
86136 }
86137 function visitCaseBlock(node) {
86138 var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
86139 var updated = ts.visitEachChild(node, visitor, context);
86140 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86141 return updated;
86142 }
86143 function returnCapturedThis(node) {
86144 return ts.setOriginalNode(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
86145 }
86146 function visitReturnStatement(node) {
86147 if (convertedLoopState) {
86148 convertedLoopState.nonLocalJumps |= 8 /* Return */;
86149 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
86150 node = returnCapturedThis(node);
86151 }
86152 return factory.createReturnStatement(factory.createObjectLiteralExpression([
86153 factory.createPropertyAssignment(factory.createIdentifier("value"), node.expression
86154 ? ts.visitNode(node.expression, visitor, ts.isExpression)
86155 : factory.createVoidZero())
86156 ]));
86157 }
86158 else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
86159 return returnCapturedThis(node);
86160 }
86161 return ts.visitEachChild(node, visitor, context);
86162 }
86163 function visitThisKeyword(node) {
86164 if (hierarchyFacts & 2 /* ArrowFunction */) {
86165 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
86166 }
86167 if (convertedLoopState) {
86168 if (hierarchyFacts & 2 /* ArrowFunction */) {
86169 // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
86170 convertedLoopState.containsLexicalThis = true;
86171 return node;
86172 }
86173 return convertedLoopState.thisName || (convertedLoopState.thisName = factory.createUniqueName("this"));
86174 }
86175 return node;
86176 }
86177 function visitIdentifier(node) {
86178 if (!convertedLoopState) {
86179 return node;
86180 }
86181 if (resolver.isArgumentsLocalBinding(node)) {
86182 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
86183 }
86184 return node;
86185 }
86186 function visitBreakOrContinueStatement(node) {
86187 if (convertedLoopState) {
86188 // check if we can emit break/continue as is
86189 // it is possible if either
86190 // - break/continue is labeled and label is located inside the converted loop
86191 // - break/continue is non-labeled and located in non-converted loop/switch statement
86192 var jump = node.kind === 238 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
86193 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
86194 (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
86195 if (!canUseBreakOrContinue) {
86196 var labelMarker = void 0;
86197 var label = node.label;
86198 if (!label) {
86199 if (node.kind === 238 /* BreakStatement */) {
86200 convertedLoopState.nonLocalJumps |= 2 /* Break */;
86201 labelMarker = "break";
86202 }
86203 else {
86204 convertedLoopState.nonLocalJumps |= 4 /* Continue */;
86205 // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
86206 labelMarker = "continue";
86207 }
86208 }
86209 else {
86210 if (node.kind === 238 /* BreakStatement */) {
86211 labelMarker = "break-" + label.escapedText;
86212 setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
86213 }
86214 else {
86215 labelMarker = "continue-" + label.escapedText;
86216 setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
86217 }
86218 }
86219 var returnExpression = factory.createStringLiteral(labelMarker);
86220 if (convertedLoopState.loopOutParameters.length) {
86221 var outParams = convertedLoopState.loopOutParameters;
86222 var expr = void 0;
86223 for (var i = 0; i < outParams.length; i++) {
86224 var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
86225 if (i === 0) {
86226 expr = copyExpr;
86227 }
86228 else {
86229 expr = factory.createBinaryExpression(expr, 27 /* CommaToken */, copyExpr);
86230 }
86231 }
86232 returnExpression = factory.createBinaryExpression(expr, 27 /* CommaToken */, returnExpression);
86233 }
86234 return factory.createReturnStatement(returnExpression);
86235 }
86236 }
86237 return ts.visitEachChild(node, visitor, context);
86238 }
86239 /**
86240 * Visits a ClassDeclaration and transforms it into a variable statement.
86241 *
86242 * @param node A ClassDeclaration node.
86243 */
86244 function visitClassDeclaration(node) {
86245 // [source]
86246 // class C { }
86247 //
86248 // [output]
86249 // var C = (function () {
86250 // function C() {
86251 // }
86252 // return C;
86253 // }());
86254 var variable = factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ true),
86255 /*exclamationToken*/ undefined,
86256 /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
86257 ts.setOriginalNode(variable, node);
86258 var statements = [];
86259 var statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([variable]));
86260 ts.setOriginalNode(statement, node);
86261 ts.setTextRange(statement, node);
86262 ts.startOnNewLine(statement);
86263 statements.push(statement);
86264 // Add an `export default` statement for default exports (for `--target es5 --module es6`)
86265 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
86266 var exportStatement = ts.hasSyntacticModifier(node, 512 /* Default */)
86267 ? factory.createExportDefault(factory.getLocalName(node))
86268 : factory.createExternalModuleExport(factory.getLocalName(node));
86269 ts.setOriginalNode(exportStatement, statement);
86270 statements.push(exportStatement);
86271 }
86272 var emitFlags = ts.getEmitFlags(node);
86273 if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
86274 // Add a DeclarationMarker as a marker for the end of the declaration
86275 statements.push(factory.createEndOfDeclarationMarker(node));
86276 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
86277 }
86278 return ts.singleOrMany(statements);
86279 }
86280 /**
86281 * Visits a ClassExpression and transforms it into an expression.
86282 *
86283 * @param node A ClassExpression node.
86284 */
86285 function visitClassExpression(node) {
86286 // [source]
86287 // C = class { }
86288 //
86289 // [output]
86290 // C = (function () {
86291 // function class_1() {
86292 // }
86293 // return class_1;
86294 // }())
86295 return transformClassLikeDeclarationToExpression(node);
86296 }
86297 /**
86298 * Transforms a ClassExpression or ClassDeclaration into an expression.
86299 *
86300 * @param node A ClassExpression or ClassDeclaration node.
86301 */
86302 function transformClassLikeDeclarationToExpression(node) {
86303 // [source]
86304 // class C extends D {
86305 // constructor() {}
86306 // method() {}
86307 // get prop() {}
86308 // set prop(v) {}
86309 // }
86310 //
86311 // [output]
86312 // (function (_super) {
86313 // __extends(C, _super);
86314 // function C() {
86315 // }
86316 // C.prototype.method = function () {}
86317 // Object.defineProperty(C.prototype, "prop", {
86318 // get: function() {},
86319 // set: function() {},
86320 // enumerable: true,
86321 // configurable: true
86322 // });
86323 // return C;
86324 // }(D))
86325 if (node.name) {
86326 enableSubstitutionsForBlockScopedBindings();
86327 }
86328 var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
86329 var classFunction = factory.createFunctionExpression(
86330 /*modifiers*/ undefined,
86331 /*asteriskToken*/ undefined,
86332 /*name*/ undefined,
86333 /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */))] : [],
86334 /*type*/ undefined, transformClassBody(node, extendsClauseElement));
86335 // To preserve the behavior of the old emitter, we explicitly indent
86336 // the body of the function here if it was requested in an earlier
86337 // transformation.
86338 ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
86339 // "inner" and "outer" below are added purely to preserve source map locations from
86340 // the old emitter
86341 var inner = factory.createPartiallyEmittedExpression(classFunction);
86342 ts.setTextRangeEnd(inner, node.end);
86343 ts.setEmitFlags(inner, 1536 /* NoComments */);
86344 var outer = factory.createPartiallyEmittedExpression(inner);
86345 ts.setTextRangeEnd(outer, ts.skipTrivia(currentText, node.pos));
86346 ts.setEmitFlags(outer, 1536 /* NoComments */);
86347 var result = factory.createParenthesizedExpression(factory.createCallExpression(outer,
86348 /*typeArguments*/ undefined, extendsClauseElement
86349 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
86350 : []));
86351 ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
86352 return result;
86353 }
86354 /**
86355 * Transforms a ClassExpression or ClassDeclaration into a function body.
86356 *
86357 * @param node A ClassExpression or ClassDeclaration node.
86358 * @param extendsClauseElement The expression for the class `extends` clause.
86359 */
86360 function transformClassBody(node, extendsClauseElement) {
86361 var statements = [];
86362 startLexicalEnvironment();
86363 addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
86364 addConstructor(statements, node, extendsClauseElement);
86365 addClassMembers(statements, node);
86366 // Create a synthetic text range for the return statement.
86367 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
86368 var localName = factory.getInternalName(node);
86369 // The following partially-emitted expression exists purely to align our sourcemap
86370 // emit with the original emitter.
86371 var outer = factory.createPartiallyEmittedExpression(localName);
86372 ts.setTextRangeEnd(outer, closingBraceLocation.end);
86373 ts.setEmitFlags(outer, 1536 /* NoComments */);
86374 var statement = factory.createReturnStatement(outer);
86375 ts.setTextRangePos(statement, closingBraceLocation.pos);
86376 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
86377 statements.push(statement);
86378 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86379 var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
86380 ts.setEmitFlags(block, 1536 /* NoComments */);
86381 return block;
86382 }
86383 /**
86384 * Adds a call to the `__extends` helper if needed for a class.
86385 *
86386 * @param statements The statements of the class body function.
86387 * @param node The ClassExpression or ClassDeclaration node.
86388 * @param extendsClauseElement The expression for the class `extends` clause.
86389 */
86390 function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
86391 if (extendsClauseElement) {
86392 statements.push(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExtendsHelper(factory.getInternalName(node))),
86393 /*location*/ extendsClauseElement));
86394 }
86395 }
86396 /**
86397 * Adds the constructor of the class to a class body function.
86398 *
86399 * @param statements The statements of the class body function.
86400 * @param node The ClassExpression or ClassDeclaration node.
86401 * @param extendsClauseElement The expression for the class `extends` clause.
86402 */
86403 function addConstructor(statements, node, extendsClauseElement) {
86404 var savedConvertedLoopState = convertedLoopState;
86405 convertedLoopState = undefined;
86406 var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
86407 var constructor = ts.getFirstConstructorWithBody(node);
86408 var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
86409 var constructorFunction = factory.createFunctionDeclaration(
86410 /*decorators*/ undefined,
86411 /*modifiers*/ undefined,
86412 /*asteriskToken*/ undefined, factory.getInternalName(node),
86413 /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper),
86414 /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
86415 ts.setTextRange(constructorFunction, constructor || node);
86416 if (extendsClauseElement) {
86417 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
86418 }
86419 statements.push(constructorFunction);
86420 exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
86421 convertedLoopState = savedConvertedLoopState;
86422 }
86423 /**
86424 * Transforms the parameters of the constructor declaration of a class.
86425 *
86426 * @param constructor The constructor for the class.
86427 * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
86428 * synthesized `super` call.
86429 */
86430 function transformConstructorParameters(constructor, hasSynthesizedSuper) {
86431 // If the TypeScript transformer needed to synthesize a constructor for property
86432 // initializers, it would have also added a synthetic `...args` parameter and
86433 // `super` call.
86434 // If this is the case, we do not include the synthetic `...args` parameter and
86435 // will instead use the `arguments` object in ES5/3.
86436 return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
86437 || [];
86438 }
86439 function createDefaultConstructorBody(node, isDerivedClass) {
86440 // We must be here because the user didn't write a constructor
86441 // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
86442 // If that's the case we can just immediately return the result of a 'super()' call.
86443 var statements = [];
86444 resumeLexicalEnvironment();
86445 factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
86446 if (isDerivedClass) {
86447 // return _super !== null && _super.apply(this, arguments) || this;
86448 statements.push(factory.createReturnStatement(createDefaultSuperCallOrThis()));
86449 }
86450 var statementsArray = factory.createNodeArray(statements);
86451 ts.setTextRange(statementsArray, node.members);
86452 var block = factory.createBlock(statementsArray, /*multiLine*/ true);
86453 ts.setTextRange(block, node);
86454 ts.setEmitFlags(block, 1536 /* NoComments */);
86455 return block;
86456 }
86457 /**
86458 * Transforms the body of a constructor declaration of a class.
86459 *
86460 * @param constructor The constructor for the class.
86461 * @param node The node which contains the constructor.
86462 * @param extendsClauseElement The expression for the class `extends` clause.
86463 * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
86464 * synthesized `super` call.
86465 */
86466 function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
86467 // determine whether the class is known syntactically to be a derived class (e.g. a
86468 // class that extends a value that is not syntactically known to be `null`).
86469 var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */;
86470 // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
86471 // representation:
86472 //
86473 // ```
86474 // // es2015 (source)
86475 // class C extends Base { }
86476 //
86477 // // es5 (transformed)
86478 // var C = (function (_super) {
86479 // function C() {
86480 // return _super.apply(this, arguments) || this;
86481 // }
86482 // return C;
86483 // })(Base);
86484 // ```
86485 if (!constructor)
86486 return createDefaultConstructorBody(node, isDerivedClass);
86487 // The prologue will contain all leading standard and custom prologue statements added by this transform
86488 var prologue = [];
86489 var statements = [];
86490 resumeLexicalEnvironment();
86491 // If a super call has already been synthesized,
86492 // we're going to assume that we should just transform everything after that.
86493 // The assumption is that no prior step in the pipeline has added any prologue directives.
86494 var statementOffset = 0;
86495 if (!hasSynthesizedSuper)
86496 statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
86497 addDefaultValueAssignmentsIfNeeded(statements, constructor);
86498 addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
86499 if (!hasSynthesizedSuper)
86500 statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
86501 // If the first statement is a call to `super()`, visit the statement directly
86502 var superCallExpression;
86503 if (hasSynthesizedSuper) {
86504 superCallExpression = createDefaultSuperCallOrThis();
86505 }
86506 else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
86507 var firstStatement = constructor.body.statements[statementOffset];
86508 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
86509 superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
86510 }
86511 }
86512 if (superCallExpression) {
86513 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
86514 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
86515 }
86516 // visit the remaining statements
86517 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
86518 factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
86519 insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
86520 if (isDerivedClass) {
86521 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
86522 // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
86523 // following representation:
86524 //
86525 // ```
86526 // // es2015 (source)
86527 // class C extends Base {
86528 // constructor() {
86529 // super("foo");
86530 // }
86531 // }
86532 //
86533 // // es5 (transformed)
86534 // var C = (function (_super) {
86535 // function C() {
86536 // return _super.call(this, "foo") || this;
86537 // }
86538 // return C;
86539 // })(Base);
86540 // ```
86541 var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
86542 var returnStatement = factory.createReturnStatement(superCallExpression);
86543 ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
86544 ts.setEmitFlags(superCall, 1536 /* NoComments */);
86545 statements.push(returnStatement);
86546 }
86547 else {
86548 // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
86549 //
86550 // ```
86551 // // es2015 (source)
86552 // class C extends Base {
86553 // constructor() {
86554 // super("foo");
86555 // this.x = 1;
86556 // }
86557 // }
86558 //
86559 // // es5 (transformed)
86560 // var C = (function (_super) {
86561 // function C() {
86562 // var _this = _super.call(this, "foo") || this;
86563 // _this.x = 1;
86564 // return _this;
86565 // }
86566 // return C;
86567 // })(Base);
86568 // ```
86569 // Since the `super()` call was the first statement, we insert the `this` capturing call to
86570 // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
86571 insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
86572 if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
86573 statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
86574 }
86575 }
86576 }
86577 else {
86578 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
86579 // captured when necessitated by an arrow function capturing the lexical `this`:
86580 //
86581 // ```
86582 // // es2015
86583 // class C {}
86584 //
86585 // // es5
86586 // var C = (function () {
86587 // function C() {
86588 // }
86589 // return C;
86590 // })();
86591 // ```
86592 insertCaptureThisForNodeIfNeeded(prologue, constructor);
86593 }
86594 var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)),
86595 /*location*/ constructor.body.statements),
86596 /*multiLine*/ true);
86597 ts.setTextRange(block, constructor.body);
86598 return block;
86599 }
86600 /**
86601 * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
86602 * It would generate obviously dead code, so we'll try to make things a little bit prettier
86603 * by doing a minimal check on whether some common patterns always explicitly return.
86604 */
86605 function isSufficientlyCoveredByReturnStatements(statement) {
86606 // A return statement is considered covered.
86607 if (statement.kind === 239 /* ReturnStatement */) {
86608 return true;
86609 }
86610 // An if-statement with two covered branches is covered.
86611 else if (statement.kind === 231 /* IfStatement */) {
86612 var ifStatement = statement;
86613 if (ifStatement.elseStatement) {
86614 return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
86615 isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
86616 }
86617 }
86618 // A block is covered if it has a last statement which is covered.
86619 else if (statement.kind === 227 /* Block */) {
86620 var lastStatement = ts.lastOrUndefined(statement.statements);
86621 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
86622 return true;
86623 }
86624 }
86625 return false;
86626 }
86627 function createActualThis() {
86628 return ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */);
86629 }
86630 function createDefaultSuperCallOrThis() {
86631 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());
86632 }
86633 /**
86634 * Visits a parameter declaration.
86635 *
86636 * @param node A ParameterDeclaration node.
86637 */
86638 function visitParameter(node) {
86639 if (node.dotDotDotToken) {
86640 // rest parameters are elided
86641 return undefined;
86642 }
86643 else if (ts.isBindingPattern(node.name)) {
86644 // Binding patterns are converted into a generated name and are
86645 // evaluated inside the function body.
86646 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
86647 /*decorators*/ undefined,
86648 /*modifiers*/ undefined,
86649 /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node),
86650 /*questionToken*/ undefined,
86651 /*type*/ undefined,
86652 /*initializer*/ undefined),
86653 /*location*/ node),
86654 /*original*/ node);
86655 }
86656 else if (node.initializer) {
86657 // Initializers are elided
86658 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
86659 /*decorators*/ undefined,
86660 /*modifiers*/ undefined,
86661 /*dotDotDotToken*/ undefined, node.name,
86662 /*questionToken*/ undefined,
86663 /*type*/ undefined,
86664 /*initializer*/ undefined),
86665 /*location*/ node),
86666 /*original*/ node);
86667 }
86668 else {
86669 return node;
86670 }
86671 }
86672 function hasDefaultValueOrBindingPattern(node) {
86673 return node.initializer !== undefined
86674 || ts.isBindingPattern(node.name);
86675 }
86676 /**
86677 * Adds statements to the body of a function-like node if it contains parameters with
86678 * binding patterns or initializers.
86679 *
86680 * @param statements The statements for the new function body.
86681 * @param node A function-like node.
86682 */
86683 function addDefaultValueAssignmentsIfNeeded(statements, node) {
86684 if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
86685 return false;
86686 }
86687 var added = false;
86688 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
86689 var parameter = _a[_i];
86690 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
86691 // A rest parameter cannot have a binding pattern or an initializer,
86692 // so let's just ignore it.
86693 if (dotDotDotToken) {
86694 continue;
86695 }
86696 if (ts.isBindingPattern(name)) {
86697 added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
86698 }
86699 else if (initializer) {
86700 insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
86701 added = true;
86702 }
86703 }
86704 return added;
86705 }
86706 /**
86707 * Adds statements to the body of a function-like node for parameters with binding patterns
86708 *
86709 * @param statements The statements for the new function body.
86710 * @param parameter The parameter for the function.
86711 * @param name The name of the parameter.
86712 * @param initializer The initializer for the parameter.
86713 */
86714 function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
86715 // In cases where a binding pattern is simply '[]' or '{}',
86716 // we usually don't want to emit a var declaration; however, in the presence
86717 // of an initializer, we must emit that expression to preserve side effects.
86718 if (name.elements.length > 0) {
86719 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createVariableStatement(
86720 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
86721 return true;
86722 }
86723 else if (initializer) {
86724 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createExpressionStatement(factory.createAssignment(factory.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
86725 return true;
86726 }
86727 return false;
86728 }
86729 /**
86730 * Adds statements to the body of a function-like node for parameters with initializers.
86731 *
86732 * @param statements The statements for the new function body.
86733 * @param parameter The parameter for the function.
86734 * @param name The name of the parameter.
86735 * @param initializer The initializer for the parameter.
86736 */
86737 function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
86738 initializer = ts.visitNode(initializer, visitor, ts.isExpression);
86739 var statement = factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
86740 factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(
86741 // TODO(rbuckton): Does this need to be parented?
86742 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 */))
86743 ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
86744 ts.startOnNewLine(statement);
86745 ts.setTextRange(statement, parameter);
86746 ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
86747 ts.insertStatementAfterCustomPrologue(statements, statement);
86748 }
86749 /**
86750 * Gets a value indicating whether we need to add statements to handle a rest parameter.
86751 *
86752 * @param node A ParameterDeclaration node.
86753 * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
86754 * part of a constructor declaration with a
86755 * synthesized call to `super`
86756 */
86757 function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
86758 return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
86759 }
86760 /**
86761 * Adds statements to the body of a function-like node if it contains a rest parameter.
86762 *
86763 * @param statements The statements for the new function body.
86764 * @param node A function-like node.
86765 * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
86766 * part of a constructor declaration with a
86767 * synthesized call to `super`
86768 */
86769 function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
86770 var prologueStatements = [];
86771 var parameter = ts.lastOrUndefined(node.parameters);
86772 if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
86773 return false;
86774 }
86775 // `declarationName` is the name of the local declaration for the parameter.
86776 // TODO(rbuckton): Does this need to be parented?
86777 var declarationName = parameter.name.kind === 78 /* Identifier */ ? ts.setParent(ts.setTextRange(factory.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory.createTempVariable(/*recordTempVariable*/ undefined);
86778 ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
86779 // `expressionName` is the name of the parameter used in expressions.
86780 var expressionName = parameter.name.kind === 78 /* Identifier */ ? factory.cloneNode(parameter.name) : declarationName;
86781 var restIndex = node.parameters.length - 1;
86782 var temp = factory.createLoopVariable();
86783 // var param = [];
86784 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
86785 /*modifiers*/ undefined, factory.createVariableDeclarationList([
86786 factory.createVariableDeclaration(declarationName,
86787 /*exclamationToken*/ undefined,
86788 /*type*/ undefined, factory.createArrayLiteralExpression([]))
86789 ])),
86790 /*location*/ parameter), 1048576 /* CustomPrologue */));
86791 // for (var _i = restIndex; _i < arguments.length; _i++) {
86792 // param[_i - restIndex] = arguments[_i];
86793 // }
86794 var forStatement = factory.createForStatement(ts.setTextRange(factory.createVariableDeclarationList([
86795 factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex))
86796 ]), parameter), ts.setTextRange(factory.createLessThan(temp, factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([
86797 ts.startOnNewLine(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(expressionName, restIndex === 0
86798 ? temp
86799 : factory.createSubtract(temp, factory.createNumericLiteral(restIndex))), factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp))),
86800 /*location*/ parameter))
86801 ]));
86802 ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
86803 ts.startOnNewLine(forStatement);
86804 prologueStatements.push(forStatement);
86805 if (parameter.name.kind !== 78 /* Identifier */) {
86806 // do the actual destructuring of the rest parameter if necessary
86807 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
86808 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
86809 }
86810 ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
86811 return true;
86812 }
86813 /**
86814 * Adds a statement to capture the `this` of a function declaration if it is needed.
86815 * NOTE: This must be executed *after* the subtree has been visited.
86816 *
86817 * @param statements The statements for the new function body.
86818 * @param node A node.
86819 */
86820 function insertCaptureThisForNodeIfNeeded(statements, node) {
86821 if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 206 /* ArrowFunction */) {
86822 insertCaptureThisForNode(statements, node, factory.createThis());
86823 return true;
86824 }
86825 return false;
86826 }
86827 function insertCaptureThisForNode(statements, node, initializer) {
86828 enableSubstitutionsForCapturedThis();
86829 var captureThisStatement = factory.createVariableStatement(
86830 /*modifiers*/ undefined, factory.createVariableDeclarationList([
86831 factory.createVariableDeclaration(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */),
86832 /*exclamationToken*/ undefined,
86833 /*type*/ undefined, initializer)
86834 ]));
86835 ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
86836 ts.setSourceMapRange(captureThisStatement, node);
86837 ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
86838 }
86839 function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
86840 if (hierarchyFacts & 16384 /* NewTarget */) {
86841 var newTarget = void 0;
86842 switch (node.kind) {
86843 case 206 /* ArrowFunction */:
86844 return statements;
86845 case 164 /* MethodDeclaration */:
86846 case 166 /* GetAccessor */:
86847 case 167 /* SetAccessor */:
86848 // Methods and accessors cannot be constructors, so 'new.target' will
86849 // always return 'undefined'.
86850 newTarget = factory.createVoidZero();
86851 break;
86852 case 165 /* Constructor */:
86853 // Class constructors can only be called with `new`, so `this.constructor`
86854 // should be relatively safe to use.
86855 newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor");
86856 break;
86857 case 248 /* FunctionDeclaration */:
86858 case 205 /* FunctionExpression */:
86859 // Functions can be called or constructed, and may have a `this` due to
86860 // being a member or when calling an imported function via `other_1.f()`.
86861 newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))),
86862 /*questionToken*/ undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"),
86863 /*colonToken*/ undefined, factory.createVoidZero());
86864 break;
86865 default:
86866 return ts.Debug.failBadSyntaxKind(node);
86867 }
86868 var captureNewTargetStatement = factory.createVariableStatement(
86869 /*modifiers*/ undefined, factory.createVariableDeclarationList([
86870 factory.createVariableDeclaration(factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */),
86871 /*exclamationToken*/ undefined,
86872 /*type*/ undefined, newTarget)
86873 ]));
86874 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
86875 if (copyOnWrite) {
86876 statements = statements.slice();
86877 }
86878 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
86879 }
86880 return statements;
86881 }
86882 /**
86883 * Adds statements to the class body function for a class to define the members of the
86884 * class.
86885 *
86886 * @param statements The statements for the class body function.
86887 * @param node The ClassExpression or ClassDeclaration node.
86888 */
86889 function addClassMembers(statements, node) {
86890 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
86891 var member = _a[_i];
86892 switch (member.kind) {
86893 case 226 /* SemicolonClassElement */:
86894 statements.push(transformSemicolonClassElementToStatement(member));
86895 break;
86896 case 164 /* MethodDeclaration */:
86897 statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
86898 break;
86899 case 166 /* GetAccessor */:
86900 case 167 /* SetAccessor */:
86901 var accessors = ts.getAllAccessorDeclarations(node.members, member);
86902 if (member === accessors.firstAccessor) {
86903 statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
86904 }
86905 break;
86906 case 165 /* Constructor */:
86907 // Constructors are handled in visitClassExpression/visitClassDeclaration
86908 break;
86909 default:
86910 ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
86911 break;
86912 }
86913 }
86914 }
86915 /**
86916 * Transforms a SemicolonClassElement into a statement for a class body function.
86917 *
86918 * @param member The SemicolonClassElement node.
86919 */
86920 function transformSemicolonClassElementToStatement(member) {
86921 return ts.setTextRange(factory.createEmptyStatement(), member);
86922 }
86923 /**
86924 * Transforms a MethodDeclaration into a statement for a class body function.
86925 *
86926 * @param receiver The receiver for the member.
86927 * @param member The MethodDeclaration node.
86928 */
86929 function transformClassMethodDeclarationToStatement(receiver, member, container) {
86930 var commentRange = ts.getCommentRange(member);
86931 var sourceMapRange = ts.getSourceMapRange(member);
86932 var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
86933 var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
86934 var e;
86935 if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
86936 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
86937 : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
86938 : propertyName;
86939 e = factory.createObjectDefinePropertyCall(receiver, name, factory.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
86940 }
86941 else {
86942 var memberName = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ member.name);
86943 e = factory.createAssignment(memberName, memberFunction);
86944 }
86945 ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
86946 ts.setSourceMapRange(memberFunction, sourceMapRange);
86947 var statement = ts.setTextRange(factory.createExpressionStatement(e), /*location*/ member);
86948 ts.setOriginalNode(statement, member);
86949 ts.setCommentRange(statement, commentRange);
86950 // The location for the statement is used to emit comments only.
86951 // No source map should be emitted for this statement to align with the
86952 // old emitter.
86953 ts.setEmitFlags(statement, 48 /* NoSourceMap */);
86954 return statement;
86955 }
86956 /**
86957 * Transforms a set of related of get/set accessors into a statement for a class body function.
86958 *
86959 * @param receiver The receiver for the member.
86960 * @param accessors The set of related get/set accessors.
86961 */
86962 function transformAccessorsToStatement(receiver, accessors, container) {
86963 var statement = factory.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
86964 // The location for the statement is used to emit source maps only.
86965 // No comments should be emitted for this statement to align with the
86966 // old emitter.
86967 ts.setEmitFlags(statement, 1536 /* NoComments */);
86968 ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
86969 return statement;
86970 }
86971 /**
86972 * Transforms a set of related get/set accessors into an expression for either a class
86973 * body function or an ObjectLiteralExpression with computed properties.
86974 *
86975 * @param receiver The receiver for the member.
86976 */
86977 function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
86978 var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
86979 // To align with source maps in the old emitter, the receiver and property name
86980 // arguments are both mapped contiguously to the accessor name.
86981 // TODO(rbuckton): Does this need to be parented?
86982 var target = ts.setParent(ts.setTextRange(factory.cloneNode(receiver), receiver), receiver.parent);
86983 ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
86984 ts.setSourceMapRange(target, firstAccessor.name);
86985 var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
86986 if (ts.isPrivateIdentifier(visitedAccessorName)) {
86987 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
86988 }
86989 var propertyName = ts.createExpressionForPropertyName(factory, visitedAccessorName);
86990 ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
86991 ts.setSourceMapRange(propertyName, firstAccessor.name);
86992 var properties = [];
86993 if (getAccessor) {
86994 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
86995 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
86996 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
86997 var getter = factory.createPropertyAssignment("get", getterFunction);
86998 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
86999 properties.push(getter);
87000 }
87001 if (setAccessor) {
87002 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
87003 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
87004 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
87005 var setter = factory.createPropertyAssignment("set", setterFunction);
87006 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
87007 properties.push(setter);
87008 }
87009 properties.push(factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), factory.createPropertyAssignment("configurable", factory.createTrue()));
87010 var call = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"),
87011 /*typeArguments*/ undefined, [
87012 target,
87013 propertyName,
87014 factory.createObjectLiteralExpression(properties, /*multiLine*/ true)
87015 ]);
87016 if (startsOnNewLine) {
87017 ts.startOnNewLine(call);
87018 }
87019 return call;
87020 }
87021 /**
87022 * Visits an ArrowFunction and transforms it into a FunctionExpression.
87023 *
87024 * @param node An ArrowFunction node.
87025 */
87026 function visitArrowFunction(node) {
87027 if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
87028 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
87029 }
87030 var savedConvertedLoopState = convertedLoopState;
87031 convertedLoopState = undefined;
87032 var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
87033 var func = factory.createFunctionExpression(
87034 /*modifiers*/ undefined,
87035 /*asteriskToken*/ undefined,
87036 /*name*/ undefined,
87037 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
87038 /*type*/ undefined, transformFunctionBody(node));
87039 ts.setTextRange(func, node);
87040 ts.setOriginalNode(func, node);
87041 ts.setEmitFlags(func, 8 /* CapturesThis */);
87042 if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
87043 enableSubstitutionsForCapturedThis();
87044 }
87045 // If an arrow function contains
87046 exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
87047 convertedLoopState = savedConvertedLoopState;
87048 return func;
87049 }
87050 /**
87051 * Visits a FunctionExpression node.
87052 *
87053 * @param node a FunctionExpression node.
87054 */
87055 function visitFunctionExpression(node) {
87056 var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
87057 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
87058 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
87059 var savedConvertedLoopState = convertedLoopState;
87060 convertedLoopState = undefined;
87061 var parameters = ts.visitParameterList(node.parameters, visitor, context);
87062 var body = transformFunctionBody(node);
87063 var name = hierarchyFacts & 16384 /* NewTarget */
87064 ? factory.getLocalName(node)
87065 : node.name;
87066 exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
87067 convertedLoopState = savedConvertedLoopState;
87068 return factory.updateFunctionExpression(node,
87069 /*modifiers*/ undefined, node.asteriskToken, name,
87070 /*typeParameters*/ undefined, parameters,
87071 /*type*/ undefined, body);
87072 }
87073 /**
87074 * Visits a FunctionDeclaration node.
87075 *
87076 * @param node a FunctionDeclaration node.
87077 */
87078 function visitFunctionDeclaration(node) {
87079 var savedConvertedLoopState = convertedLoopState;
87080 convertedLoopState = undefined;
87081 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
87082 var parameters = ts.visitParameterList(node.parameters, visitor, context);
87083 var body = transformFunctionBody(node);
87084 var name = hierarchyFacts & 16384 /* NewTarget */
87085 ? factory.getLocalName(node)
87086 : node.name;
87087 exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
87088 convertedLoopState = savedConvertedLoopState;
87089 return factory.updateFunctionDeclaration(node,
87090 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
87091 /*typeParameters*/ undefined, parameters,
87092 /*type*/ undefined, body);
87093 }
87094 /**
87095 * Transforms a function-like node into a FunctionExpression.
87096 *
87097 * @param node The function-like node to transform.
87098 * @param location The source-map location for the new FunctionExpression.
87099 * @param name The name of the new FunctionExpression.
87100 */
87101 function transformFunctionLikeToExpression(node, location, name, container) {
87102 var savedConvertedLoopState = convertedLoopState;
87103 convertedLoopState = undefined;
87104 var ancestorFacts = container && ts.isClassLike(container) && !ts.hasSyntacticModifier(node, 32 /* Static */)
87105 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
87106 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
87107 var parameters = ts.visitParameterList(node.parameters, visitor, context);
87108 var body = transformFunctionBody(node);
87109 if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 248 /* FunctionDeclaration */ || node.kind === 205 /* FunctionExpression */)) {
87110 name = factory.getGeneratedNameForNode(node);
87111 }
87112 exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
87113 convertedLoopState = savedConvertedLoopState;
87114 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
87115 /*modifiers*/ undefined, node.asteriskToken, name,
87116 /*typeParameters*/ undefined, parameters,
87117 /*type*/ undefined, body), location),
87118 /*original*/ node);
87119 }
87120 /**
87121 * Transforms the body of a function-like node.
87122 *
87123 * @param node A function-like node.
87124 */
87125 function transformFunctionBody(node) {
87126 var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
87127 var singleLine = false; // indicates whether the block *may* be emitted as a single line
87128 var statementsLocation;
87129 var closeBraceLocation;
87130 var prologue = [];
87131 var statements = [];
87132 var body = node.body;
87133 var statementOffset;
87134 resumeLexicalEnvironment();
87135 if (ts.isBlock(body)) {
87136 // ensureUseStrict is false because no new prologue-directive should be added.
87137 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
87138 statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
87139 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction);
87140 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement);
87141 }
87142 multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
87143 multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
87144 if (ts.isBlock(body)) {
87145 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
87146 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
87147 statementsLocation = body.statements;
87148 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
87149 // If the original body was a multi-line block, this must be a multi-line block.
87150 if (!multiLine && body.multiLine) {
87151 multiLine = true;
87152 }
87153 }
87154 else {
87155 ts.Debug.assert(node.kind === 206 /* ArrowFunction */);
87156 // To align with the old emitter, we use a synthetic end position on the location
87157 // for the statement list we synthesize when we down-level an arrow function with
87158 // an expression function body. This prevents both comments and source maps from
87159 // being emitted for the end position only.
87160 statementsLocation = ts.moveRangeEnd(body, -1);
87161 var equalsGreaterThanToken = node.equalsGreaterThanToken;
87162 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
87163 if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
87164 singleLine = true;
87165 }
87166 else {
87167 multiLine = true;
87168 }
87169 }
87170 var expression = ts.visitNode(body, visitor, ts.isExpression);
87171 var returnStatement = factory.createReturnStatement(expression);
87172 ts.setTextRange(returnStatement, body);
87173 ts.moveSyntheticComments(returnStatement, body);
87174 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
87175 statements.push(returnStatement);
87176 // To align with the source map emit for the old emitter, we set a custom
87177 // source map location for the close brace.
87178 closeBraceLocation = body;
87179 }
87180 factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
87181 insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
87182 insertCaptureThisForNodeIfNeeded(prologue, node);
87183 // If we added any final generated statements, this must be a multi-line block
87184 if (ts.some(prologue)) {
87185 multiLine = true;
87186 }
87187 statements.unshift.apply(statements, prologue);
87188 if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
87189 // no changes were made, preserve the tree
87190 return body;
87191 }
87192 var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), multiLine);
87193 ts.setTextRange(block, node.body);
87194 if (!multiLine && singleLine) {
87195 ts.setEmitFlags(block, 1 /* SingleLine */);
87196 }
87197 if (closeBraceLocation) {
87198 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
87199 }
87200 ts.setOriginalNode(block, node.body);
87201 return block;
87202 }
87203 function visitBlock(node, isFunctionBody) {
87204 if (isFunctionBody) {
87205 // A function body is not a block scope.
87206 return ts.visitEachChild(node, visitor, context);
87207 }
87208 var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
87209 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
87210 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
87211 var updated = ts.visitEachChild(node, visitor, context);
87212 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
87213 return updated;
87214 }
87215 /**
87216 * Visits an ExpressionStatement that contains a destructuring assignment.
87217 *
87218 * @param node An ExpressionStatement node.
87219 */
87220 function visitExpressionStatement(node) {
87221 // If we are here it is most likely because our expression is a destructuring assignment.
87222 switch (node.expression.kind) {
87223 case 204 /* ParenthesizedExpression */:
87224 return factory.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
87225 case 213 /* BinaryExpression */:
87226 return factory.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
87227 }
87228 return ts.visitEachChild(node, visitor, context);
87229 }
87230 /**
87231 * Visits a ParenthesizedExpression that may contain a destructuring assignment.
87232 *
87233 * @param node A ParenthesizedExpression node.
87234 * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
87235 * of a destructuring assignment.
87236 */
87237 function visitParenthesizedExpression(node, needsDestructuringValue) {
87238 // If we are here it is most likely because our expression is a destructuring assignment.
87239 if (!needsDestructuringValue) {
87240 // By default we always emit the RHS at the end of a flattened destructuring
87241 // expression. If we are in a state where we do not need the destructuring value,
87242 // we pass that information along to the children that care about it.
87243 switch (node.expression.kind) {
87244 case 204 /* ParenthesizedExpression */:
87245 return factory.updateParenthesizedExpression(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
87246 case 213 /* BinaryExpression */:
87247 return factory.updateParenthesizedExpression(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
87248 }
87249 }
87250 return ts.visitEachChild(node, visitor, context);
87251 }
87252 /**
87253 * Visits a BinaryExpression that contains a destructuring assignment.
87254 *
87255 * @param node A BinaryExpression node.
87256 * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
87257 * of a destructuring assignment.
87258 */
87259 function visitBinaryExpression(node, needsDestructuringValue) {
87260 // If we are here it is because this is a destructuring assignment.
87261 if (ts.isDestructuringAssignment(node)) {
87262 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
87263 }
87264 return ts.visitEachChild(node, visitor, context);
87265 }
87266 function isVariableStatementOfTypeScriptClassWrapper(node) {
87267 return node.declarationList.declarations.length === 1
87268 && !!node.declarationList.declarations[0].initializer
87269 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
87270 }
87271 function visitVariableStatement(node) {
87272 var ancestorFacts = enterSubtree(0 /* None */, ts.hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
87273 var updated;
87274 if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
87275 // we are inside a converted loop - hoist variable declarations
87276 var assignments = void 0;
87277 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
87278 var decl = _a[_i];
87279 hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
87280 if (decl.initializer) {
87281 var assignment = void 0;
87282 if (ts.isBindingPattern(decl.name)) {
87283 assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
87284 }
87285 else {
87286 assignment = factory.createBinaryExpression(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
87287 ts.setTextRange(assignment, decl);
87288 }
87289 assignments = ts.append(assignments, assignment);
87290 }
87291 }
87292 if (assignments) {
87293 updated = ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(assignments)), node);
87294 }
87295 else {
87296 // none of declarations has initializer - the entire variable statement can be deleted
87297 updated = undefined;
87298 }
87299 }
87300 else {
87301 updated = ts.visitEachChild(node, visitor, context);
87302 }
87303 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
87304 return updated;
87305 }
87306 /**
87307 * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
87308 *
87309 * @param node A VariableDeclarationList node.
87310 */
87311 function visitVariableDeclarationList(node) {
87312 if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
87313 if (node.flags & 3 /* BlockScoped */) {
87314 enableSubstitutionsForBlockScopedBindings();
87315 }
87316 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
87317 ? visitVariableDeclarationInLetDeclarationList
87318 : visitVariableDeclaration);
87319 var declarationList = factory.createVariableDeclarationList(declarations);
87320 ts.setOriginalNode(declarationList, node);
87321 ts.setTextRange(declarationList, node);
87322 ts.setCommentRange(declarationList, node);
87323 // If the first or last declaration is a binding pattern, we need to modify
87324 // the source map range for the declaration list.
87325 if (node.transformFlags & 131072 /* ContainsBindingPattern */
87326 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
87327 ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
87328 }
87329 return declarationList;
87330 }
87331 return ts.visitEachChild(node, visitor, context);
87332 }
87333 function getRangeUnion(declarations) {
87334 // declarations may not be sorted by position.
87335 // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
87336 var pos = -1, end = -1;
87337 for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
87338 var node = declarations_10[_i];
87339 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
87340 end = Math.max(end, node.end);
87341 }
87342 return ts.createRange(pos, end);
87343 }
87344 /**
87345 * Gets a value indicating whether we should emit an explicit initializer for a variable
87346 * declaration in a `let` declaration list.
87347 *
87348 * @param node A VariableDeclaration node.
87349 */
87350 function shouldEmitExplicitInitializerForLetDeclaration(node) {
87351 // Nested let bindings might need to be initialized explicitly to preserve
87352 // ES6 semantic:
87353 //
87354 // { let x = 1; }
87355 // { let x; } // x here should be undefined. not 1
87356 //
87357 // Top level bindings never collide with anything and thus don't require
87358 // explicit initialization. As for nested let bindings there are two cases:
87359 //
87360 // - Nested let bindings that were not renamed definitely should be
87361 // initialized explicitly:
87362 //
87363 // { let x = 1; }
87364 // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
87365 //
87366 // Without explicit initialization code in /*1*/ can be executed even if
87367 // some-condition is evaluated to false.
87368 //
87369 // - Renaming introduces fresh name that should not collide with any
87370 // existing names, however renamed bindings sometimes also should be
87371 // explicitly initialized. One particular case: non-captured binding
87372 // declared inside loop body (but not in loop initializer):
87373 //
87374 // let x;
87375 // for (;;) {
87376 // let x;
87377 // }
87378 //
87379 // In downlevel codegen inner 'x' will be renamed so it won't collide
87380 // with outer 'x' however it will should be reset on every iteration as
87381 // if it was declared anew.
87382 //
87383 // * Why non-captured binding?
87384 // - Because if loop contains block scoped binding captured in some
87385 // function then loop body will be rewritten to have a fresh scope
87386 // on every iteration so everything will just work.
87387 //
87388 // * Why loop initializer is excluded?
87389 // - Since we've introduced a fresh name it already will be undefined.
87390 var flags = resolver.getNodeCheckFlags(node);
87391 var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
87392 var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
87393 var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
87394 || (isCapturedInFunction
87395 && isDeclaredInLoop
87396 && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
87397 var emitExplicitInitializer = !emittedAsTopLevel
87398 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
87399 && (!resolver.isDeclarationWithCollidingName(node)
87400 || (isDeclaredInLoop
87401 && !isCapturedInFunction
87402 && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
87403 return emitExplicitInitializer;
87404 }
87405 /**
87406 * Visits a VariableDeclaration in a `let` declaration list.
87407 *
87408 * @param node A VariableDeclaration node.
87409 */
87410 function visitVariableDeclarationInLetDeclarationList(node) {
87411 // For binding pattern names that lack initializers there is no point to emit
87412 // explicit initializer since downlevel codegen for destructuring will fail
87413 // in the absence of initializer so all binding elements will say uninitialized
87414 var name = node.name;
87415 if (ts.isBindingPattern(name)) {
87416 return visitVariableDeclaration(node);
87417 }
87418 if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
87419 return factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createVoidZero());
87420 }
87421 return ts.visitEachChild(node, visitor, context);
87422 }
87423 /**
87424 * Visits a VariableDeclaration node with a binding pattern.
87425 *
87426 * @param node A VariableDeclaration node.
87427 */
87428 function visitVariableDeclaration(node) {
87429 var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
87430 var updated;
87431 if (ts.isBindingPattern(node.name)) {
87432 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */,
87433 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
87434 }
87435 else {
87436 updated = ts.visitEachChild(node, visitor, context);
87437 }
87438 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
87439 return updated;
87440 }
87441 function recordLabel(node) {
87442 convertedLoopState.labels.set(ts.idText(node.label), true);
87443 }
87444 function resetLabel(node) {
87445 convertedLoopState.labels.set(ts.idText(node.label), false);
87446 }
87447 function visitLabeledStatement(node) {
87448 if (convertedLoopState && !convertedLoopState.labels) {
87449 convertedLoopState.labels = new ts.Map();
87450 }
87451 var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
87452 return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
87453 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
87454 : factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node, convertedLoopState && resetLabel);
87455 }
87456 function visitIterationStatement(node, outermostLabeledStatement) {
87457 switch (node.kind) {
87458 case 232 /* DoStatement */:
87459 case 233 /* WhileStatement */:
87460 return visitDoOrWhileStatement(node, outermostLabeledStatement);
87461 case 234 /* ForStatement */:
87462 return visitForStatement(node, outermostLabeledStatement);
87463 case 235 /* ForInStatement */:
87464 return visitForInStatement(node, outermostLabeledStatement);
87465 case 236 /* ForOfStatement */:
87466 return visitForOfStatement(node, outermostLabeledStatement);
87467 }
87468 }
87469 function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
87470 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
87471 var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
87472 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
87473 return updated;
87474 }
87475 function visitDoOrWhileStatement(node, outermostLabeledStatement) {
87476 return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
87477 }
87478 function visitForStatement(node, outermostLabeledStatement) {
87479 return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
87480 }
87481 function visitForInStatement(node, outermostLabeledStatement) {
87482 return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
87483 }
87484 function visitForOfStatement(node, outermostLabeledStatement) {
87485 return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
87486 }
87487 function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
87488 var statements = [];
87489 var initializer = node.initializer;
87490 if (ts.isVariableDeclarationList(initializer)) {
87491 if (node.initializer.flags & 3 /* BlockScoped */) {
87492 enableSubstitutionsForBlockScopedBindings();
87493 }
87494 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
87495 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
87496 // This works whether the declaration is a var, let, or const.
87497 // It will use rhsIterationValue _a[_i] as the initializer.
87498 var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
87499 var declarationList = ts.setTextRange(factory.createVariableDeclarationList(declarations), node.initializer);
87500 ts.setOriginalNode(declarationList, node.initializer);
87501 // Adjust the source map range for the first declaration to align with the old
87502 // emitter.
87503 ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
87504 statements.push(factory.createVariableStatement(
87505 /*modifiers*/ undefined, declarationList));
87506 }
87507 else {
87508 // The following call does not include the initializer, so we have
87509 // to emit it separately.
87510 statements.push(ts.setTextRange(factory.createVariableStatement(
87511 /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclarationList([
87512 factory.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined),
87513 /*exclamationToken*/ undefined,
87514 /*type*/ undefined, boundValue)
87515 ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
87516 }
87517 }
87518 else {
87519 // Initializer is an expression. Emit the expression in the body, so that it's
87520 // evaluated on every iteration.
87521 var assignment = factory.createAssignment(initializer, boundValue);
87522 if (ts.isDestructuringAssignment(assignment)) {
87523 statements.push(factory.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
87524 }
87525 else {
87526 ts.setTextRangeEnd(assignment, initializer.end);
87527 statements.push(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
87528 }
87529 }
87530 if (convertedLoopBodyStatements) {
87531 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
87532 }
87533 else {
87534 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
87535 if (ts.isBlock(statement)) {
87536 return factory.updateBlock(statement, ts.setTextRange(factory.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
87537 }
87538 else {
87539 statements.push(statement);
87540 return createSyntheticBlockForConvertedStatements(statements);
87541 }
87542 }
87543 }
87544 function createSyntheticBlockForConvertedStatements(statements) {
87545 return ts.setEmitFlags(factory.createBlock(factory.createNodeArray(statements),
87546 /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
87547 }
87548 function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
87549 // The following ES6 code:
87550 //
87551 // for (let v of expr) { }
87552 //
87553 // should be emitted as
87554 //
87555 // for (var _i = 0, _a = expr; _i < _a.length; _i++) {
87556 // var v = _a[_i];
87557 // }
87558 //
87559 // where _a and _i are temps emitted to capture the RHS and the counter,
87560 // respectively.
87561 // When the left hand side is an expression instead of a let declaration,
87562 // the "let v" is not emitted.
87563 // When the left hand side is a let/const, the v is renamed if there is
87564 // another v in scope.
87565 // Note that all assignments to the LHS are emitted in the body, including
87566 // all destructuring.
87567 // Note also that because an extra statement is needed to assign to the LHS,
87568 // for-of bodies are always emitted as blocks.
87569 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87570 // In the case where the user wrote an identifier as the RHS, like this:
87571 //
87572 // for (let v of arr) { }
87573 //
87574 // we don't want to emit a temporary variable for the RHS, just use it directly.
87575 var counter = factory.createLoopVariable();
87576 var rhsReference = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
87577 // The old emitter does not emit source maps for the expression
87578 ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
87579 var forStatement = ts.setTextRange(factory.createForStatement(
87580 /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
87581 ts.setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), ts.moveRangePos(node.expression, -1)),
87582 ts.setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression)
87583 ]), node.expression), 2097152 /* NoHoisting */),
87584 /*condition*/ ts.setTextRange(factory.createLessThan(counter, factory.createPropertyAccessExpression(rhsReference, "length")), node.expression),
87585 /*incrementor*/ ts.setTextRange(factory.createPostfixIncrement(counter), node.expression),
87586 /*statement*/ convertForOfStatementHead(node, factory.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)),
87587 /*location*/ node);
87588 // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
87589 ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
87590 ts.setTextRange(forStatement, node);
87591 return factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
87592 }
87593 function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
87594 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87595 var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
87596 var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
87597 var errorRecord = factory.createUniqueName("e");
87598 var catchVariable = factory.getGeneratedNameForNode(errorRecord);
87599 var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
87600 var values = ts.setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
87601 var next = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
87602 hoistVariableDeclaration(errorRecord);
87603 hoistVariableDeclaration(returnMethod);
87604 // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
87605 var initializer = ancestorFacts & 1024 /* IterationContainer */
87606 ? factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), values])
87607 : values;
87608 var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
87609 /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
87610 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
87611 factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next)
87612 ]), node.expression), 2097152 /* NoHoisting */),
87613 /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")),
87614 /*incrementor*/ factory.createAssignment(result, next),
87615 /*statement*/ convertForOfStatementHead(node, factory.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)),
87616 /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
87617 return factory.createTryStatement(factory.createBlock([
87618 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
87619 ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
87620 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
87621 factory.createPropertyAssignment("error", catchVariable)
87622 ])))
87623 ]), 1 /* SingleLine */)), factory.createBlock([
87624 factory.createTryStatement(
87625 /*tryBlock*/ factory.createBlock([
87626 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 */),
87627 ]),
87628 /*catchClause*/ undefined,
87629 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
87630 ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
87631 ]), 1 /* SingleLine */))
87632 ]));
87633 }
87634 /**
87635 * Visits an ObjectLiteralExpression with computed property names.
87636 *
87637 * @param node An ObjectLiteralExpression node.
87638 */
87639 function visitObjectLiteralExpression(node) {
87640 var properties = node.properties;
87641 // Find the first computed property.
87642 // Everything until that point can be emitted as part of the initial object literal.
87643 var numInitialProperties = -1, hasComputed = false;
87644 for (var i = 0; i < properties.length; i++) {
87645 var property = properties[i];
87646 if ((property.transformFlags & 262144 /* ContainsYield */ &&
87647 hierarchyFacts & 4 /* AsyncFunctionBody */)
87648 || (hasComputed = ts.Debug.checkDefined(property.name).kind === 157 /* ComputedPropertyName */)) {
87649 numInitialProperties = i;
87650 break;
87651 }
87652 }
87653 if (numInitialProperties < 0) {
87654 return ts.visitEachChild(node, visitor, context);
87655 }
87656 // For computed properties, we need to create a unique handle to the object
87657 // literal so we can modify it without risking internal assignments tainting the object.
87658 var temp = factory.createTempVariable(hoistVariableDeclaration);
87659 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
87660 var expressions = [];
87661 var assignment = factory.createAssignment(temp, ts.setEmitFlags(factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 65536 /* Indented */ : 0));
87662 if (node.multiLine) {
87663 ts.startOnNewLine(assignment);
87664 }
87665 expressions.push(assignment);
87666 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
87667 // We need to clone the temporary identifier so that we can write it on a
87668 // new line
87669 expressions.push(node.multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
87670 return factory.inlineExpressions(expressions);
87671 }
87672 function shouldConvertPartOfIterationStatement(node) {
87673 return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
87674 }
87675 function shouldConvertInitializerOfForStatement(node) {
87676 return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
87677 }
87678 function shouldConvertConditionOfForStatement(node) {
87679 return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
87680 }
87681 function shouldConvertIncrementorOfForStatement(node) {
87682 return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
87683 }
87684 function shouldConvertIterationStatement(node) {
87685 return shouldConvertBodyOfIterationStatement(node)
87686 || shouldConvertInitializerOfForStatement(node);
87687 }
87688 function shouldConvertBodyOfIterationStatement(node) {
87689 return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
87690 }
87691 /**
87692 * Records constituents of name for the given variable to be hoisted in the outer scope.
87693 */
87694 function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
87695 if (!state.hoistedLocalVariables) {
87696 state.hoistedLocalVariables = [];
87697 }
87698 visit(node.name);
87699 function visit(node) {
87700 if (node.kind === 78 /* Identifier */) {
87701 state.hoistedLocalVariables.push(node);
87702 }
87703 else {
87704 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
87705 var element = _a[_i];
87706 if (!ts.isOmittedExpression(element)) {
87707 visit(element.name);
87708 }
87709 }
87710 }
87711 }
87712 }
87713 function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
87714 if (!shouldConvertIterationStatement(node)) {
87715 var saveAllowedNonLabeledJumps = void 0;
87716 if (convertedLoopState) {
87717 // we get here if we are trying to emit normal loop loop inside converted loop
87718 // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
87719 saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
87720 convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
87721 }
87722 var result = convert
87723 ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
87724 : factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
87725 if (convertedLoopState) {
87726 convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
87727 }
87728 return result;
87729 }
87730 var currentState = createConvertedLoopState(node);
87731 var statements = [];
87732 var outerConvertedLoopState = convertedLoopState;
87733 convertedLoopState = currentState;
87734 var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
87735 var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
87736 convertedLoopState = outerConvertedLoopState;
87737 if (initializerFunction)
87738 statements.push(initializerFunction.functionDeclaration);
87739 if (bodyFunction)
87740 statements.push(bodyFunction.functionDeclaration);
87741 addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
87742 if (initializerFunction) {
87743 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
87744 }
87745 var loop;
87746 if (bodyFunction) {
87747 if (convert) {
87748 loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
87749 }
87750 else {
87751 var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true));
87752 loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
87753 }
87754 }
87755 else {
87756 var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
87757 loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
87758 }
87759 statements.push(loop);
87760 return statements;
87761 }
87762 function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
87763 switch (node.kind) {
87764 case 234 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
87765 case 235 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
87766 case 236 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
87767 case 232 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
87768 case 233 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
87769 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
87770 }
87771 }
87772 function convertForStatement(node, initializerFunction, convertedLoopBody) {
87773 var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
87774 var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
87775 return factory.updateForStatement(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody);
87776 }
87777 function convertForOfStatement(node, convertedLoopBody) {
87778 return factory.updateForOfStatement(node,
87779 /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
87780 }
87781 function convertForInStatement(node, convertedLoopBody) {
87782 return factory.updateForInStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
87783 }
87784 function convertDoStatement(node, convertedLoopBody) {
87785 return factory.updateDoStatement(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
87786 }
87787 function convertWhileStatement(node, convertedLoopBody) {
87788 return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
87789 }
87790 function createConvertedLoopState(node) {
87791 var loopInitializer;
87792 switch (node.kind) {
87793 case 234 /* ForStatement */:
87794 case 235 /* ForInStatement */:
87795 case 236 /* ForOfStatement */:
87796 var initializer = node.initializer;
87797 if (initializer && initializer.kind === 247 /* VariableDeclarationList */) {
87798 loopInitializer = initializer;
87799 }
87800 break;
87801 }
87802 // variables that will be passed to the loop as parameters
87803 var loopParameters = [];
87804 // variables declared in the loop initializer that will be changed inside the loop
87805 var loopOutParameters = [];
87806 if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
87807 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
87808 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
87809 var decl = _a[_i];
87810 processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
87811 }
87812 }
87813 var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
87814 if (convertedLoopState) {
87815 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
87816 // if outer converted loop has already accumulated some state - pass it through
87817 if (convertedLoopState.argumentsName) {
87818 // outer loop has already used 'arguments' so we've already have some name to alias it
87819 // use the same name in all nested loops
87820 currentState.argumentsName = convertedLoopState.argumentsName;
87821 }
87822 if (convertedLoopState.thisName) {
87823 // outer loop has already used 'this' so we've already have some name to alias it
87824 // use the same name in all nested loops
87825 currentState.thisName = convertedLoopState.thisName;
87826 }
87827 if (convertedLoopState.hoistedLocalVariables) {
87828 // we've already collected some non-block scoped variable declarations in enclosing loop
87829 // use the same storage in nested loop
87830 currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
87831 }
87832 }
87833 return currentState;
87834 }
87835 function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
87836 var extraVariableDeclarations;
87837 // propagate state from the inner loop to the outer loop if necessary
87838 if (state.argumentsName) {
87839 // if alias for arguments is set
87840 if (outerState) {
87841 // pass it to outer converted loop
87842 outerState.argumentsName = state.argumentsName;
87843 }
87844 else {
87845 // this is top level converted loop and we need to create an alias for 'arguments' object
87846 (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.argumentsName,
87847 /*exclamationToken*/ undefined,
87848 /*type*/ undefined, factory.createIdentifier("arguments")));
87849 }
87850 }
87851 if (state.thisName) {
87852 // if alias for this is set
87853 if (outerState) {
87854 // pass it to outer converted loop
87855 outerState.thisName = state.thisName;
87856 }
87857 else {
87858 // this is top level converted loop so we need to create an alias for 'this' here
87859 // NOTE:
87860 // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
87861 // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
87862 (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.thisName,
87863 /*exclamationToken*/ undefined,
87864 /*type*/ undefined, factory.createIdentifier("this")));
87865 }
87866 }
87867 if (state.hoistedLocalVariables) {
87868 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
87869 if (outerState) {
87870 // pass them to outer converted loop
87871 outerState.hoistedLocalVariables = state.hoistedLocalVariables;
87872 }
87873 else {
87874 if (!extraVariableDeclarations) {
87875 extraVariableDeclarations = [];
87876 }
87877 // hoist collected variable declarations
87878 for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
87879 var identifier = _a[_i];
87880 extraVariableDeclarations.push(factory.createVariableDeclaration(identifier));
87881 }
87882 }
87883 }
87884 // add extra variables to hold out parameters if necessary
87885 if (state.loopOutParameters.length) {
87886 if (!extraVariableDeclarations) {
87887 extraVariableDeclarations = [];
87888 }
87889 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
87890 var outParam = _c[_b];
87891 extraVariableDeclarations.push(factory.createVariableDeclaration(outParam.outParamName));
87892 }
87893 }
87894 if (state.conditionVariable) {
87895 if (!extraVariableDeclarations) {
87896 extraVariableDeclarations = [];
87897 }
87898 extraVariableDeclarations.push(factory.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createFalse()));
87899 }
87900 // create variable statement to hold all introduced variable declarations
87901 if (extraVariableDeclarations) {
87902 statements.push(factory.createVariableStatement(
87903 /*modifiers*/ undefined, factory.createVariableDeclarationList(extraVariableDeclarations)));
87904 }
87905 }
87906 function createOutVariable(p) {
87907 return factory.createVariableDeclaration(p.originalName, /*exclamationToken*/ undefined, /*type*/ undefined, p.outParamName);
87908 }
87909 /**
87910 * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
87911 * that is captured in a closure inside of the initializer. The `_loop_init` function is
87912 * used to preserve the per-iteration environment semantics of
87913 * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
87914 */
87915 function createFunctionForInitializerOfForStatement(node, currentState) {
87916 var functionName = factory.createUniqueName("_loop_init");
87917 var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
87918 var emitFlags = 0 /* None */;
87919 if (currentState.containsLexicalThis)
87920 emitFlags |= 8 /* CapturesThis */;
87921 if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
87922 emitFlags |= 262144 /* AsyncFunctionBody */;
87923 var statements = [];
87924 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, node.initializer));
87925 copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
87926 // This transforms the following ES2015 syntax:
87927 //
87928 // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
87929 // // loop body
87930 // }
87931 //
87932 // Into the following ES5 syntax:
87933 //
87934 // var _loop_init_1 = function () {
87935 // var i = (setImmediate(() => console.log(i)), 0);
87936 // out_i_1 = i;
87937 // };
87938 // var out_i_1;
87939 // _loop_init_1();
87940 // for (var i = out_i_1; i < 2; i++) {
87941 // // loop body
87942 // }
87943 //
87944 // Which prevents mutations to `i` in the per-iteration environment of the body
87945 // from affecting the initial value for `i` outside of the per-iteration environment.
87946 var functionDeclaration = factory.createVariableStatement(
87947 /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
87948 factory.createVariableDeclaration(functionName,
87949 /*exclamationToken*/ undefined,
87950 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
87951 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined,
87952 /*name*/ undefined,
87953 /*typeParameters*/ undefined,
87954 /*parameters*/ undefined,
87955 /*type*/ undefined, ts.visitNode(factory.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
87956 ]), 2097152 /* NoHoisting */));
87957 var part = factory.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
87958 return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
87959 }
87960 /**
87961 * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
87962 * that is captured in a closure inside of the loop body. The `_loop` function is used to
87963 * preserve the per-iteration environment semantics of
87964 * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
87965 */
87966 function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
87967 var functionName = factory.createUniqueName("_loop");
87968 startLexicalEnvironment();
87969 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
87970 var lexicalEnvironment = endLexicalEnvironment();
87971 var statements = [];
87972 if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
87973 // If a block-scoped variable declared in the initializer of `node` is captured in
87974 // the condition or incrementor, we must move the condition and incrementor into
87975 // the body of the for loop.
87976 //
87977 // This transforms the following ES2015 syntax:
87978 //
87979 // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
87980 // // loop body
87981 // }
87982 //
87983 // Into the following ES5 syntax:
87984 //
87985 // var _loop_1 = function (i) {
87986 // if (inc_1)
87987 // setImmediate(() => console.log(i)), i++;
87988 // else
87989 // inc_1 = true;
87990 // if (!(setImmediate(() => console.log(i)), i < 2))
87991 // return out_i_1 = i, "break";
87992 // // loop body
87993 // out_i_1 = i;
87994 // }
87995 // var out_i_1, inc_1 = false;
87996 // for (var i = 0;;) {
87997 // var state_1 = _loop_1(i);
87998 // i = out_i_1;
87999 // if (state_1 === "break")
88000 // break;
88001 // }
88002 //
88003 // Which prevents mutations to `i` in the per-iteration environment of the body
88004 // from affecting the value of `i` in the previous per-iteration environment.
88005 //
88006 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
88007 // environment that is carried over to the next iteration of the loop. As a result,
88008 // we must indicate whether this is the first evaluation of the loop body so that
88009 // we only evaluate the incrementor on subsequent evaluations.
88010 currentState.conditionVariable = factory.createUniqueName("inc");
88011 if (node.incrementor) {
88012 statements.push(factory.createIfStatement(currentState.conditionVariable, factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
88013 }
88014 else {
88015 statements.push(factory.createIfStatement(factory.createLogicalNot(currentState.conditionVariable), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
88016 }
88017 if (shouldConvertConditionOfForStatement(node)) {
88018 statements.push(factory.createIfStatement(factory.createPrefixUnaryExpression(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(factory.createBreakStatement(), visitor, ts.isStatement)));
88019 }
88020 }
88021 if (ts.isBlock(statement)) {
88022 ts.addRange(statements, statement.statements);
88023 }
88024 else {
88025 statements.push(statement);
88026 }
88027 copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
88028 ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
88029 var loopBody = factory.createBlock(statements, /*multiLine*/ true);
88030 if (ts.isBlock(statement))
88031 ts.setOriginalNode(loopBody, statement);
88032 var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
88033 var emitFlags = 0;
88034 if (currentState.containsLexicalThis)
88035 emitFlags |= 8 /* CapturesThis */;
88036 if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
88037 emitFlags |= 262144 /* AsyncFunctionBody */;
88038 // This transforms the following ES2015 syntax (in addition to other variations):
88039 //
88040 // for (let i = 0; i < 2; i++) {
88041 // setImmediate(() => console.log(i));
88042 // }
88043 //
88044 // Into the following ES5 syntax:
88045 //
88046 // var _loop_1 = function (i) {
88047 // setImmediate(() => console.log(i));
88048 // };
88049 // for (var i = 0; i < 2; i++) {
88050 // _loop_1(i);
88051 // }
88052 var functionDeclaration = factory.createVariableStatement(
88053 /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
88054 factory.createVariableDeclaration(functionName,
88055 /*exclamationToken*/ undefined,
88056 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
88057 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined,
88058 /*name*/ undefined,
88059 /*typeParameters*/ undefined, currentState.loopParameters,
88060 /*type*/ undefined, loopBody), emitFlags))
88061 ]), 2097152 /* NoHoisting */));
88062 var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
88063 return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
88064 }
88065 function copyOutParameter(outParam, copyDirection) {
88066 var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
88067 var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
88068 return factory.createBinaryExpression(target, 62 /* EqualsToken */, source);
88069 }
88070 function copyOutParameters(outParams, partFlags, copyDirection, statements) {
88071 for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
88072 var outParam = outParams_1[_i];
88073 if (outParam.flags & partFlags) {
88074 statements.push(factory.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
88075 }
88076 }
88077 }
88078 function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
88079 var call = factory.createCallExpression(initFunctionExpressionName, /*typeArguments*/ undefined, []);
88080 var callResult = containsYield
88081 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
88082 : call;
88083 return factory.createExpressionStatement(callResult);
88084 }
88085 function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
88086 var statements = [];
88087 // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
88088 // simple loops are emitted as just 'loop()';
88089 // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
88090 var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
88091 !state.labeledNonLocalBreaks &&
88092 !state.labeledNonLocalContinues;
88093 var call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
88094 var callResult = containsYield
88095 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
88096 : call;
88097 if (isSimpleLoop) {
88098 statements.push(factory.createExpressionStatement(callResult));
88099 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
88100 }
88101 else {
88102 var loopResultName = factory.createUniqueName("state");
88103 var stateVariable = factory.createVariableStatement(
88104 /*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)]));
88105 statements.push(stateVariable);
88106 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
88107 if (state.nonLocalJumps & 8 /* Return */) {
88108 var returnStatement = void 0;
88109 if (outerState) {
88110 outerState.nonLocalJumps |= 8 /* Return */;
88111 returnStatement = factory.createReturnStatement(loopResultName);
88112 }
88113 else {
88114 returnStatement = factory.createReturnStatement(factory.createPropertyAccessExpression(loopResultName, "value"));
88115 }
88116 statements.push(factory.createIfStatement(factory.createTypeCheck(loopResultName, "object"), returnStatement));
88117 }
88118 if (state.nonLocalJumps & 2 /* Break */) {
88119 statements.push(factory.createIfStatement(factory.createStrictEquality(loopResultName, factory.createStringLiteral("break")), factory.createBreakStatement()));
88120 }
88121 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
88122 var caseClauses = [];
88123 processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
88124 processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
88125 statements.push(factory.createSwitchStatement(loopResultName, factory.createCaseBlock(caseClauses)));
88126 }
88127 }
88128 return statements;
88129 }
88130 function setLabeledJump(state, isBreak, labelText, labelMarker) {
88131 if (isBreak) {
88132 if (!state.labeledNonLocalBreaks) {
88133 state.labeledNonLocalBreaks = new ts.Map();
88134 }
88135 state.labeledNonLocalBreaks.set(labelText, labelMarker);
88136 }
88137 else {
88138 if (!state.labeledNonLocalContinues) {
88139 state.labeledNonLocalContinues = new ts.Map();
88140 }
88141 state.labeledNonLocalContinues.set(labelText, labelMarker);
88142 }
88143 }
88144 function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
88145 if (!table) {
88146 return;
88147 }
88148 table.forEach(function (labelMarker, labelText) {
88149 var statements = [];
88150 // if there are no outer converted loop or outer label in question is located inside outer converted loop
88151 // then emit labeled break\continue
88152 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
88153 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
88154 var label = factory.createIdentifier(labelText);
88155 statements.push(isBreak ? factory.createBreakStatement(label) : factory.createContinueStatement(label));
88156 }
88157 else {
88158 setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
88159 statements.push(factory.createReturnStatement(loopResultName));
88160 }
88161 caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements));
88162 });
88163 }
88164 function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
88165 var name = decl.name;
88166 if (ts.isBindingPattern(name)) {
88167 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
88168 var element = _a[_i];
88169 if (!ts.isOmittedExpression(element)) {
88170 processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
88171 }
88172 }
88173 }
88174 else {
88175 loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
88176 var checkFlags = resolver.getNodeCheckFlags(decl);
88177 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
88178 var outParamName = factory.createUniqueName("out_" + ts.idText(name));
88179 var flags = 0;
88180 if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
88181 flags |= 1 /* Body */;
88182 }
88183 if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
88184 flags |= 2 /* Initializer */;
88185 }
88186 loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
88187 }
88188 }
88189 }
88190 /**
88191 * Adds the members of an object literal to an array of expressions.
88192 *
88193 * @param expressions An array of expressions.
88194 * @param node An ObjectLiteralExpression node.
88195 * @param receiver The receiver for members of the ObjectLiteralExpression.
88196 * @param numInitialNonComputedProperties The number of initial properties without
88197 * computed property names.
88198 */
88199 function addObjectLiteralMembers(expressions, node, receiver, start) {
88200 var properties = node.properties;
88201 var numProperties = properties.length;
88202 for (var i = start; i < numProperties; i++) {
88203 var property = properties[i];
88204 switch (property.kind) {
88205 case 166 /* GetAccessor */:
88206 case 167 /* SetAccessor */:
88207 var accessors = ts.getAllAccessorDeclarations(node.properties, property);
88208 if (property === accessors.firstAccessor) {
88209 expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
88210 }
88211 break;
88212 case 164 /* MethodDeclaration */:
88213 expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
88214 break;
88215 case 285 /* PropertyAssignment */:
88216 expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
88217 break;
88218 case 286 /* ShorthandPropertyAssignment */:
88219 expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
88220 break;
88221 default:
88222 ts.Debug.failBadSyntaxKind(node);
88223 break;
88224 }
88225 }
88226 }
88227 /**
88228 * Transforms a PropertyAssignment node into an expression.
88229 *
88230 * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
88231 * @param property The PropertyAssignment node.
88232 * @param receiver The receiver for the assignment.
88233 */
88234 function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
88235 var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
88236 ts.setTextRange(expression, property);
88237 if (startsOnNewLine) {
88238 ts.startOnNewLine(expression);
88239 }
88240 return expression;
88241 }
88242 /**
88243 * Transforms a ShorthandPropertyAssignment node into an expression.
88244 *
88245 * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
88246 * @param property The ShorthandPropertyAssignment node.
88247 * @param receiver The receiver for the assignment.
88248 */
88249 function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
88250 var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), factory.cloneNode(property.name));
88251 ts.setTextRange(expression, property);
88252 if (startsOnNewLine) {
88253 ts.startOnNewLine(expression);
88254 }
88255 return expression;
88256 }
88257 /**
88258 * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
88259 *
88260 * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
88261 * @param method The MethodDeclaration node.
88262 * @param receiver The receiver for the assignment.
88263 */
88264 function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
88265 var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
88266 ts.setTextRange(expression, method);
88267 if (startsOnNewLine) {
88268 ts.startOnNewLine(expression);
88269 }
88270 return expression;
88271 }
88272 function visitCatchClause(node) {
88273 var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
88274 var updated;
88275 ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
88276 if (ts.isBindingPattern(node.variableDeclaration.name)) {
88277 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
88278 var newVariableDeclaration = factory.createVariableDeclaration(temp);
88279 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
88280 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
88281 var list = factory.createVariableDeclarationList(vars);
88282 ts.setTextRange(list, node.variableDeclaration);
88283 var destructure = factory.createVariableStatement(/*modifiers*/ undefined, list);
88284 updated = factory.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
88285 }
88286 else {
88287 updated = ts.visitEachChild(node, visitor, context);
88288 }
88289 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88290 return updated;
88291 }
88292 function addStatementToStartOfBlock(block, statement) {
88293 var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
88294 return factory.updateBlock(block, __spreadArrays([statement], transformedStatements));
88295 }
88296 /**
88297 * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
88298 * PropertyAssignment.
88299 *
88300 * @param node A MethodDeclaration node.
88301 */
88302 function visitMethodDeclaration(node) {
88303 // We should only get here for methods on an object literal with regular identifier names.
88304 // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
88305 // Methods with computed property names are handled in visitObjectLiteralExpression.
88306 ts.Debug.assert(!ts.isComputedPropertyName(node.name));
88307 var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
88308 ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
88309 return ts.setTextRange(factory.createPropertyAssignment(node.name, functionExpression),
88310 /*location*/ node);
88311 }
88312 /**
88313 * Visits an AccessorDeclaration of an ObjectLiteralExpression.
88314 *
88315 * @param node An AccessorDeclaration node.
88316 */
88317 function visitAccessorDeclaration(node) {
88318 ts.Debug.assert(!ts.isComputedPropertyName(node.name));
88319 var savedConvertedLoopState = convertedLoopState;
88320 convertedLoopState = undefined;
88321 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
88322 var updated;
88323 var parameters = ts.visitParameterList(node.parameters, visitor, context);
88324 var body = transformFunctionBody(node);
88325 if (node.kind === 166 /* GetAccessor */) {
88326 updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
88327 }
88328 else {
88329 updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body);
88330 }
88331 exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
88332 convertedLoopState = savedConvertedLoopState;
88333 return updated;
88334 }
88335 /**
88336 * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
88337 *
88338 * @param node A ShorthandPropertyAssignment node.
88339 */
88340 function visitShorthandPropertyAssignment(node) {
88341 return ts.setTextRange(factory.createPropertyAssignment(node.name, visitIdentifier(factory.cloneNode(node.name))),
88342 /*location*/ node);
88343 }
88344 function visitComputedPropertyName(node) {
88345 return ts.visitEachChild(node, visitor, context);
88346 }
88347 /**
88348 * Visits a YieldExpression node.
88349 *
88350 * @param node A YieldExpression node.
88351 */
88352 function visitYieldExpression(node) {
88353 // `yield` expressions are transformed using the generators transformer.
88354 return ts.visitEachChild(node, visitor, context);
88355 }
88356 /**
88357 * Visits an ArrayLiteralExpression that contains a spread element.
88358 *
88359 * @param node An ArrayLiteralExpression node.
88360 */
88361 function visitArrayLiteralExpression(node) {
88362 if (ts.some(node.elements, ts.isSpreadElement)) {
88363 // We are here because we contain a SpreadElementExpression.
88364 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
88365 }
88366 return ts.visitEachChild(node, visitor, context);
88367 }
88368 /**
88369 * Visits a CallExpression that contains either a spread element or `super`.
88370 *
88371 * @param node a CallExpression.
88372 */
88373 function visitCallExpression(node) {
88374 if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
88375 return visitTypeScriptClassWrapper(node);
88376 }
88377 var expression = ts.skipOuterExpressions(node.expression);
88378 if (expression.kind === 105 /* SuperKeyword */ ||
88379 ts.isSuperProperty(expression) ||
88380 ts.some(node.arguments, ts.isSpreadElement)) {
88381 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
88382 }
88383 return factory.updateCallExpression(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
88384 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
88385 }
88386 function visitTypeScriptClassWrapper(node) {
88387 // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
88388 // The wrapper has a form similar to:
88389 //
88390 // (function() {
88391 // class C { // 1
88392 // }
88393 // C.x = 1; // 2
88394 // return C;
88395 // }())
88396 //
88397 // When we transform the class, we end up with something like this:
88398 //
88399 // (function () {
88400 // var C = (function () { // 3
88401 // function C() {
88402 // }
88403 // return C; // 4
88404 // }());
88405 // C.x = 1;
88406 // return C;
88407 // }())
88408 //
88409 // We want to simplify the two nested IIFEs to end up with something like this:
88410 //
88411 // (function () {
88412 // function C() {
88413 // }
88414 // C.x = 1;
88415 // return C;
88416 // }())
88417 // We skip any outer expressions in a number of places to get to the innermost
88418 // expression, but we will restore them later to preserve comments and source maps.
88419 var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
88420 // The class statements are the statements generated by visiting the first statement with initializer of the
88421 // body (1), while all other statements are added to remainingStatements (2)
88422 var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
88423 // visit the class body statements outside of any converted loop body.
88424 var savedConvertedLoopState = convertedLoopState;
88425 convertedLoopState = undefined;
88426 var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
88427 convertedLoopState = savedConvertedLoopState;
88428 var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
88429 var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
88430 var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
88431 // We know there is only one variable declaration here as we verified this in an
88432 // earlier call to isTypeScriptClassWrapper
88433 var variable = varStatement.declarationList.declarations[0];
88434 var initializer = ts.skipOuterExpressions(variable.initializer);
88435 // Under certain conditions, the 'ts' transformer may introduce a class alias, which
88436 // we see as an assignment, for example:
88437 //
88438 // (function () {
88439 // var C_1;
88440 // var C = C_1 = (function () {
88441 // function C() {
88442 // }
88443 // C.x = function () { return C_1; }
88444 // return C;
88445 // }());
88446 // C = C_1 = __decorate([dec], C);
88447 // return C;
88448 // }())
88449 //
88450 var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
88451 // The underlying call (3) is another IIFE that may contain a '_super' argument.
88452 var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
88453 var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
88454 var funcStatements = func.body.statements;
88455 var classBodyStart = 0;
88456 var classBodyEnd = -1;
88457 var statements = [];
88458 if (aliasAssignment) {
88459 // If we have a class alias assignment, we need to move it to the down-level constructor
88460 // function we generated for the class.
88461 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
88462 if (extendsCall) {
88463 statements.push(extendsCall);
88464 classBodyStart++;
88465 }
88466 // The next statement is the function declaration.
88467 statements.push(funcStatements[classBodyStart]);
88468 classBodyStart++;
88469 // Add the class alias following the declaration.
88470 statements.push(factory.createExpressionStatement(factory.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
88471 }
88472 // Find the trailing 'return' statement (4)
88473 while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
88474 classBodyEnd--;
88475 }
88476 // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
88477 // as we already have one that has been introduced by the 'ts' transformer.
88478 ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
88479 if (classBodyEnd < -1) {
88480 // If there were any hoisted declarations following the return statement, we should
88481 // append them.
88482 ts.addRange(statements, funcStatements, classBodyEnd + 1);
88483 }
88484 // Add the remaining statements of the outer wrapper.
88485 ts.addRange(statements, remainingStatements);
88486 // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
88487 // after the remaining statements from the 'ts' transformer.
88488 ts.addRange(statements, classStatements, /*start*/ 1);
88489 // Recreate any outer parentheses or partially-emitted expressions to preserve source map
88490 // and comment locations.
88491 return factory.restoreOuterExpressions(node.expression, factory.restoreOuterExpressions(variable.initializer, factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory.updateCallExpression(call, factory.restoreOuterExpressions(call.expression, factory.updateFunctionExpression(func,
88492 /*modifiers*/ undefined,
88493 /*asteriskToken*/ undefined,
88494 /*name*/ undefined,
88495 /*typeParameters*/ undefined, func.parameters,
88496 /*type*/ undefined, factory.updateBlock(func.body, statements))),
88497 /*typeArguments*/ undefined, call.arguments))));
88498 }
88499 function visitImmediateSuperCallInBody(node) {
88500 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
88501 }
88502 function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
88503 // We are here either because SuperKeyword was used somewhere in the expression, or
88504 // because we contain a SpreadElementExpression.
88505 if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
88506 node.expression.kind === 105 /* SuperKeyword */ ||
88507 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
88508 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
88509 if (node.expression.kind === 105 /* SuperKeyword */) {
88510 ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
88511 }
88512 var resultingCall = void 0;
88513 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
88514 // [source]
88515 // f(...a, b)
88516 // x.m(...a, b)
88517 // super(...a, b)
88518 // super.m(...a, b) // in static
88519 // super.m(...a, b) // in instance
88520 //
88521 // [output]
88522 // f.apply(void 0, a.concat([b]))
88523 // (_a = x).m.apply(_a, a.concat([b]))
88524 // _super.apply(this, a.concat([b]))
88525 // _super.m.apply(this, a.concat([b]))
88526 // _super.prototype.m.apply(this, a.concat([b]))
88527 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));
88528 }
88529 else {
88530 // [source]
88531 // super(a)
88532 // super.m(a) // in static
88533 // super.m(a) // in instance
88534 //
88535 // [output]
88536 // _super.call(this, a)
88537 // _super.m.call(this, a)
88538 // _super.prototype.m.call(this, a)
88539 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);
88540 }
88541 if (node.expression.kind === 105 /* SuperKeyword */) {
88542 var initializer = factory.createLogicalOr(resultingCall, createActualThis());
88543 resultingCall = assignToCapturedThis
88544 ? factory.createAssignment(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer)
88545 : initializer;
88546 }
88547 return ts.setOriginalNode(resultingCall, node);
88548 }
88549 return ts.visitEachChild(node, visitor, context);
88550 }
88551 /**
88552 * Visits a NewExpression that contains a spread element.
88553 *
88554 * @param node A NewExpression node.
88555 */
88556 function visitNewExpression(node) {
88557 if (ts.some(node.arguments, ts.isSpreadElement)) {
88558 // We are here because we contain a SpreadElementExpression.
88559 // [source]
88560 // new C(...a)
88561 //
88562 // [output]
88563 // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
88564 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
88565 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)),
88566 /*typeArguments*/ undefined, []);
88567 }
88568 return ts.visitEachChild(node, visitor, context);
88569 }
88570 /**
88571 * Transforms an array of Expression nodes that contains a SpreadExpression.
88572 *
88573 * @param elements The array of Expression nodes.
88574 * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
88575 * @param multiLine A value indicating whether the result should be emitted on multiple lines.
88576 */
88577 function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
88578 // [source]
88579 // [a, ...b, c]
88580 //
88581 // [output (downlevelIteration)]
88582 // __spread([a], b, [c])
88583 //
88584 // [output]
88585 // __spreadArrays([a], b, [c])
88586 // Map spans of spread expressions into their expressions and spans of other
88587 // expressions into an array literal.
88588 var numElements = elements.length;
88589 var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
88590 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
88591 }));
88592 if (compilerOptions.downlevelIteration) {
88593 if (segments.length === 1) {
88594 var firstSegment = segments[0];
88595 if (isCallToHelper(firstSegment, "___spread")) {
88596 return segments[0];
88597 }
88598 }
88599 return emitHelpers().createSpreadHelper(segments);
88600 }
88601 else {
88602 if (segments.length === 1) {
88603 var firstSegment = segments[0];
88604 if (!needsUniqueCopy
88605 || isPackedArrayLiteral(firstSegment)
88606 || isCallToHelper(firstSegment, "___spreadArrays")) {
88607 return segments[0];
88608 }
88609 }
88610 return emitHelpers().createSpreadArraysHelper(segments);
88611 }
88612 }
88613 function isPackedElement(node) {
88614 return !ts.isOmittedExpression(node);
88615 }
88616 function isPackedArrayLiteral(node) {
88617 return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
88618 }
88619 function isCallToHelper(firstSegment, helperName) {
88620 return ts.isCallExpression(firstSegment)
88621 && ts.isIdentifier(firstSegment.expression)
88622 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
88623 && firstSegment.expression.escapedText === helperName;
88624 }
88625 function partitionSpread(node) {
88626 return ts.isSpreadElement(node)
88627 ? visitSpanOfSpreads
88628 : visitSpanOfNonSpreads;
88629 }
88630 function visitSpanOfSpreads(chunk) {
88631 return ts.map(chunk, visitExpressionOfSpread);
88632 }
88633 function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
88634 return factory.createArrayLiteralExpression(ts.visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
88635 }
88636 function visitSpreadElement(node) {
88637 return ts.visitNode(node.expression, visitor, ts.isExpression);
88638 }
88639 /**
88640 * Transforms the expression of a SpreadExpression node.
88641 *
88642 * @param node A SpreadExpression node.
88643 */
88644 function visitExpressionOfSpread(node) {
88645 return ts.visitNode(node.expression, visitor, ts.isExpression);
88646 }
88647 /**
88648 * Visits a template literal.
88649 *
88650 * @param node A template literal.
88651 */
88652 function visitTemplateLiteral(node) {
88653 return ts.setTextRange(factory.createStringLiteral(node.text), node);
88654 }
88655 /**
88656 * Visits a string literal with an extended unicode escape.
88657 *
88658 * @param node A string literal.
88659 */
88660 function visitStringLiteral(node) {
88661 if (node.hasExtendedUnicodeEscape) {
88662 return ts.setTextRange(factory.createStringLiteral(node.text), node);
88663 }
88664 return node;
88665 }
88666 /**
88667 * Visits a binary or octal (ES6) numeric literal.
88668 *
88669 * @param node A string literal.
88670 */
88671 function visitNumericLiteral(node) {
88672 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
88673 return ts.setTextRange(factory.createNumericLiteral(node.text), node);
88674 }
88675 return node;
88676 }
88677 /**
88678 * Visits a TaggedTemplateExpression node.
88679 *
88680 * @param node A TaggedTemplateExpression node.
88681 */
88682 function visitTaggedTemplateExpression(node) {
88683 return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
88684 }
88685 /**
88686 * Visits a TemplateExpression node.
88687 *
88688 * @param node A TemplateExpression node.
88689 */
88690 function visitTemplateExpression(node) {
88691 var expressions = [];
88692 addTemplateHead(expressions, node);
88693 addTemplateSpans(expressions, node);
88694 // createAdd will check if each expression binds less closely than binary '+'.
88695 // If it does, it wraps the expression in parentheses. Otherwise, something like
88696 // `abc${ 1 << 2 }`
88697 // becomes
88698 // "abc" + 1 << 2 + ""
88699 // which is really
88700 // ("abc" + 1) << (2 + "")
88701 // rather than
88702 // "abc" + (1 << 2) + ""
88703 var expression = ts.reduceLeft(expressions, factory.createAdd);
88704 if (ts.nodeIsSynthesized(expression)) {
88705 ts.setTextRange(expression, node);
88706 }
88707 return expression;
88708 }
88709 /**
88710 * Gets a value indicating whether we need to include the head of a TemplateExpression.
88711 *
88712 * @param node A TemplateExpression node.
88713 */
88714 function shouldAddTemplateHead(node) {
88715 // If this expression has an empty head literal and the first template span has a non-empty
88716 // literal, then emitting the empty head literal is not necessary.
88717 // `${ foo } and ${ bar }`
88718 // can be emitted as
88719 // foo + " and " + bar
88720 // This is because it is only required that one of the first two operands in the emit
88721 // output must be a string literal, so that the other operand and all following operands
88722 // are forced into strings.
88723 //
88724 // If the first template span has an empty literal, then the head must still be emitted.
88725 // `${ foo }${ bar }`
88726 // must still be emitted as
88727 // "" + foo + bar
88728 // There is always atleast one templateSpan in this code path, since
88729 // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
88730 ts.Debug.assert(node.templateSpans.length !== 0);
88731 return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
88732 }
88733 /**
88734 * Adds the head of a TemplateExpression to an array of expressions.
88735 *
88736 * @param expressions An array of expressions.
88737 * @param node A TemplateExpression node.
88738 */
88739 function addTemplateHead(expressions, node) {
88740 if (!shouldAddTemplateHead(node)) {
88741 return;
88742 }
88743 expressions.push(factory.createStringLiteral(node.head.text));
88744 }
88745 /**
88746 * Visits and adds the template spans of a TemplateExpression to an array of expressions.
88747 *
88748 * @param expressions An array of expressions.
88749 * @param node A TemplateExpression node.
88750 */
88751 function addTemplateSpans(expressions, node) {
88752 for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
88753 var span = _a[_i];
88754 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
88755 // Only emit if the literal is non-empty.
88756 // The binary '+' operator is left-associative, so the first string concatenation
88757 // with the head will force the result up to this point to be a string.
88758 // Emitting a '+ ""' has no semantic effect for middles and tails.
88759 if (span.literal.text.length !== 0) {
88760 expressions.push(factory.createStringLiteral(span.literal.text));
88761 }
88762 }
88763 }
88764 /**
88765 * Visits the `super` keyword
88766 */
88767 function visitSuperKeyword(isExpressionOfCall) {
88768 return hierarchyFacts & 8 /* NonStaticClassElement */
88769 && !isExpressionOfCall
88770 ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype")
88771 : factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
88772 }
88773 function visitMetaProperty(node) {
88774 if (node.keywordToken === 102 /* NewKeyword */ && node.name.escapedText === "target") {
88775 hierarchyFacts |= 16384 /* NewTarget */;
88776 return factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
88777 }
88778 return node;
88779 }
88780 /**
88781 * Called by the printer just before a node is printed.
88782 *
88783 * @param hint A hint as to the intended usage of the node.
88784 * @param node The node to be printed.
88785 * @param emitCallback The callback used to emit the node.
88786 */
88787 function onEmitNode(hint, node, emitCallback) {
88788 if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
88789 // If we are tracking a captured `this`, keep track of the enclosing function.
88790 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
88791 ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
88792 : 65 /* FunctionIncludes */);
88793 previousOnEmitNode(hint, node, emitCallback);
88794 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88795 return;
88796 }
88797 previousOnEmitNode(hint, node, emitCallback);
88798 }
88799 /**
88800 * Enables a more costly code path for substitutions when we determine a source file
88801 * contains block-scoped bindings (e.g. `let` or `const`).
88802 */
88803 function enableSubstitutionsForBlockScopedBindings() {
88804 if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
88805 enabledSubstitutions |= 2 /* BlockScopedBindings */;
88806 context.enableSubstitution(78 /* Identifier */);
88807 }
88808 }
88809 /**
88810 * Enables a more costly code path for substitutions when we determine a source file
88811 * contains a captured `this`.
88812 */
88813 function enableSubstitutionsForCapturedThis() {
88814 if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
88815 enabledSubstitutions |= 1 /* CapturedThis */;
88816 context.enableSubstitution(107 /* ThisKeyword */);
88817 context.enableEmitNotification(165 /* Constructor */);
88818 context.enableEmitNotification(164 /* MethodDeclaration */);
88819 context.enableEmitNotification(166 /* GetAccessor */);
88820 context.enableEmitNotification(167 /* SetAccessor */);
88821 context.enableEmitNotification(206 /* ArrowFunction */);
88822 context.enableEmitNotification(205 /* FunctionExpression */);
88823 context.enableEmitNotification(248 /* FunctionDeclaration */);
88824 }
88825 }
88826 /**
88827 * Hooks node substitutions.
88828 *
88829 * @param hint The context for the emitter.
88830 * @param node The node to substitute.
88831 */
88832 function onSubstituteNode(hint, node) {
88833 node = previousOnSubstituteNode(hint, node);
88834 if (hint === 1 /* Expression */) {
88835 return substituteExpression(node);
88836 }
88837 if (ts.isIdentifier(node)) {
88838 return substituteIdentifier(node);
88839 }
88840 return node;
88841 }
88842 /**
88843 * Hooks substitutions for non-expression identifiers.
88844 */
88845 function substituteIdentifier(node) {
88846 // Only substitute the identifier if we have enabled substitutions for block-scoped
88847 // bindings.
88848 if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
88849 var original = ts.getParseTreeNode(node, ts.isIdentifier);
88850 if (original && isNameOfDeclarationWithCollidingName(original)) {
88851 return ts.setTextRange(factory.getGeneratedNameForNode(original), node);
88852 }
88853 }
88854 return node;
88855 }
88856 /**
88857 * Determines whether a name is the name of a declaration with a colliding name.
88858 * NOTE: This function expects to be called with an original source tree node.
88859 *
88860 * @param node An original source tree node.
88861 */
88862 function isNameOfDeclarationWithCollidingName(node) {
88863 switch (node.parent.kind) {
88864 case 195 /* BindingElement */:
88865 case 249 /* ClassDeclaration */:
88866 case 252 /* EnumDeclaration */:
88867 case 246 /* VariableDeclaration */:
88868 return node.parent.name === node
88869 && resolver.isDeclarationWithCollidingName(node.parent);
88870 }
88871 return false;
88872 }
88873 /**
88874 * Substitutes an expression.
88875 *
88876 * @param node An Expression node.
88877 */
88878 function substituteExpression(node) {
88879 switch (node.kind) {
88880 case 78 /* Identifier */:
88881 return substituteExpressionIdentifier(node);
88882 case 107 /* ThisKeyword */:
88883 return substituteThisKeyword(node);
88884 }
88885 return node;
88886 }
88887 /**
88888 * Substitutes an expression identifier.
88889 *
88890 * @param node An Identifier node.
88891 */
88892 function substituteExpressionIdentifier(node) {
88893 if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
88894 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
88895 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
88896 return ts.setTextRange(factory.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
88897 }
88898 }
88899 return node;
88900 }
88901 function isPartOfClassBody(declaration, node) {
88902 var currentNode = ts.getParseTreeNode(node);
88903 if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
88904 // if the node has no correlation to a parse tree node, its definitely not
88905 // part of the body.
88906 // if the node is outside of the document range of the declaration, its
88907 // definitely not part of the body.
88908 return false;
88909 }
88910 var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
88911 while (currentNode) {
88912 if (currentNode === blockScope || currentNode === declaration) {
88913 // if we are in the enclosing block scope of the declaration, we are definitely
88914 // not inside the class body.
88915 return false;
88916 }
88917 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
88918 return true;
88919 }
88920 currentNode = currentNode.parent;
88921 }
88922 return false;
88923 }
88924 /**
88925 * Substitutes `this` when contained within an arrow function.
88926 *
88927 * @param node The ThisKeyword node.
88928 */
88929 function substituteThisKeyword(node) {
88930 if (enabledSubstitutions & 1 /* CapturedThis */
88931 && hierarchyFacts & 16 /* CapturesThis */) {
88932 return ts.setTextRange(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
88933 }
88934 return node;
88935 }
88936 function getClassMemberPrefix(node, member) {
88937 return ts.hasSyntacticModifier(member, 32 /* Static */)
88938 ? factory.getInternalName(node)
88939 : factory.createPropertyAccessExpression(factory.getInternalName(node), "prototype");
88940 }
88941 function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
88942 if (!constructor || !hasExtendsClause) {
88943 return false;
88944 }
88945 if (ts.some(constructor.parameters)) {
88946 return false;
88947 }
88948 var statement = ts.firstOrUndefined(constructor.body.statements);
88949 if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 230 /* ExpressionStatement */) {
88950 return false;
88951 }
88952 var statementExpression = statement.expression;
88953 if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 200 /* CallExpression */) {
88954 return false;
88955 }
88956 var callTarget = statementExpression.expression;
88957 if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 105 /* SuperKeyword */) {
88958 return false;
88959 }
88960 var callArgument = ts.singleOrUndefined(statementExpression.arguments);
88961 if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 217 /* SpreadElement */) {
88962 return false;
88963 }
88964 var expression = callArgument.expression;
88965 return ts.isIdentifier(expression) && expression.escapedText === "arguments";
88966 }
88967 }
88968 ts.transformES2015 = transformES2015;
88969})(ts || (ts = {}));
88970/*@internal*/
88971var ts;
88972(function (ts) {
88973 /**
88974 * Transforms ES5 syntax into ES3 syntax.
88975 *
88976 * @param context Context and state information for the transformation.
88977 */
88978 function transformES5(context) {
88979 var factory = context.factory;
88980 var compilerOptions = context.getCompilerOptions();
88981 // enable emit notification only if using --jsx preserve or react-native
88982 var previousOnEmitNode;
88983 var noSubstitution;
88984 if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
88985 previousOnEmitNode = context.onEmitNode;
88986 context.onEmitNode = onEmitNode;
88987 context.enableEmitNotification(272 /* JsxOpeningElement */);
88988 context.enableEmitNotification(273 /* JsxClosingElement */);
88989 context.enableEmitNotification(271 /* JsxSelfClosingElement */);
88990 noSubstitution = [];
88991 }
88992 var previousOnSubstituteNode = context.onSubstituteNode;
88993 context.onSubstituteNode = onSubstituteNode;
88994 context.enableSubstitution(198 /* PropertyAccessExpression */);
88995 context.enableSubstitution(285 /* PropertyAssignment */);
88996 return ts.chainBundle(context, transformSourceFile);
88997 /**
88998 * Transforms an ES5 source file to ES3.
88999 *
89000 * @param node A SourceFile
89001 */
89002 function transformSourceFile(node) {
89003 return node;
89004 }
89005 /**
89006 * Called by the printer just before a node is printed.
89007 *
89008 * @param hint A hint as to the intended usage of the node.
89009 * @param node The node to emit.
89010 * @param emitCallback A callback used to emit the node.
89011 */
89012 function onEmitNode(hint, node, emitCallback) {
89013 switch (node.kind) {
89014 case 272 /* JsxOpeningElement */:
89015 case 273 /* JsxClosingElement */:
89016 case 271 /* JsxSelfClosingElement */:
89017 var tagName = node.tagName;
89018 noSubstitution[ts.getOriginalNodeId(tagName)] = true;
89019 break;
89020 }
89021 previousOnEmitNode(hint, node, emitCallback);
89022 }
89023 /**
89024 * Hooks node substitutions.
89025 *
89026 * @param hint A hint as to the intended usage of the node.
89027 * @param node The node to substitute.
89028 */
89029 function onSubstituteNode(hint, node) {
89030 if (node.id && noSubstitution && noSubstitution[node.id]) {
89031 return previousOnSubstituteNode(hint, node);
89032 }
89033 node = previousOnSubstituteNode(hint, node);
89034 if (ts.isPropertyAccessExpression(node)) {
89035 return substitutePropertyAccessExpression(node);
89036 }
89037 else if (ts.isPropertyAssignment(node)) {
89038 return substitutePropertyAssignment(node);
89039 }
89040 return node;
89041 }
89042 /**
89043 * Substitutes a PropertyAccessExpression whose name is a reserved word.
89044 *
89045 * @param node A PropertyAccessExpression
89046 */
89047 function substitutePropertyAccessExpression(node) {
89048 if (ts.isPrivateIdentifier(node.name)) {
89049 return node;
89050 }
89051 var literalName = trySubstituteReservedName(node.name);
89052 if (literalName) {
89053 return ts.setTextRange(factory.createElementAccessExpression(node.expression, literalName), node);
89054 }
89055 return node;
89056 }
89057 /**
89058 * Substitutes a PropertyAssignment whose name is a reserved word.
89059 *
89060 * @param node A PropertyAssignment
89061 */
89062 function substitutePropertyAssignment(node) {
89063 var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
89064 if (literalName) {
89065 return factory.updatePropertyAssignment(node, literalName, node.initializer);
89066 }
89067 return node;
89068 }
89069 /**
89070 * If an identifier name is a reserved word, returns a string literal for the name.
89071 *
89072 * @param name An Identifier
89073 */
89074 function trySubstituteReservedName(name) {
89075 var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
89076 if (token !== undefined && token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */) {
89077 return ts.setTextRange(factory.createStringLiteralFromNode(name), name);
89078 }
89079 return undefined;
89080 }
89081 }
89082 ts.transformES5 = transformES5;
89083})(ts || (ts = {}));
89084// Transforms generator functions into a compatible ES5 representation with similar runtime
89085// semantics. This is accomplished by first transforming the body of each generator
89086// function into an intermediate representation that is the compiled into a JavaScript
89087// switch statement.
89088//
89089// Many functions in this transformer will contain comments indicating the expected
89090// intermediate representation. For illustrative purposes, the following intermediate
89091// language is used to define this intermediate representation:
89092//
89093// .nop - Performs no operation.
89094// .local NAME, ... - Define local variable declarations.
89095// .mark LABEL - Mark the location of a label.
89096// .br LABEL - Jump to a label. If jumping out of a protected
89097// region, all .finally blocks are executed.
89098// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy.
89099// If jumping out of a protected region, all .finally
89100// blocks are executed.
89101// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey.
89102// If jumping out of a protected region, all .finally
89103// blocks are executed.
89104// .yield (x) - Yield the value of the optional expression `x`.
89105// Resume at the next label.
89106// .yieldstar (x) - Delegate yield to the value of the optional
89107// expression `x`. Resume at the next label.
89108// NOTE: `x` must be an Iterator, not an Iterable.
89109// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or
89110// "break" abrupt completions jump to the CONTINUE or
89111// BREAK labels, respectively.
89112// .endloop - Marks the end of a loop.
89113// .with (x) - Marks the beginning of a WithStatement block, using
89114// the supplied expression.
89115// .endwith - Marks the end of a WithStatement.
89116// .switch - Marks the beginning of a SwitchStatement.
89117// .endswitch - Marks the end of a SwitchStatement.
89118// .labeled NAME - Marks the beginning of a LabeledStatement with the
89119// supplied name.
89120// .endlabeled - Marks the end of a LabeledStatement.
89121// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the
89122// labels for each block.
89123// .catch (x) - Marks the beginning of a catch block.
89124// .finally - Marks the beginning of a finally block.
89125// .endfinally - Marks the end of a finally block.
89126// .endtry - Marks the end of a protected region.
89127// .throw (x) - Throws the value of the expression `x`.
89128// .return (x) - Returns the value of the expression `x`.
89129//
89130// In addition, the illustrative intermediate representation introduces some special
89131// variables:
89132//
89133// %sent% - Either returns the next value sent to the generator,
89134// returns the result of a delegated yield, or throws
89135// the exception sent to the generator.
89136// %error% - Returns the value of the current exception in a
89137// catch block.
89138//
89139// This intermediate representation is then compiled into JavaScript syntax. The resulting
89140// compilation output looks something like the following:
89141//
89142// function f() {
89143// var /*locals*/;
89144// /*functions*/
89145// return __generator(function (state) {
89146// switch (state.label) {
89147// /*cases per label*/
89148// }
89149// });
89150// }
89151//
89152// Each of the above instructions corresponds to JavaScript emit similar to the following:
89153//
89154// .local NAME | var NAME;
89155// -------------------------------|----------------------------------------------
89156// .mark LABEL | case LABEL:
89157// -------------------------------|----------------------------------------------
89158// .br LABEL | return [3 /*break*/, LABEL];
89159// -------------------------------|----------------------------------------------
89160// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL];
89161// -------------------------------|----------------------------------------------
89162// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL];
89163// -------------------------------|----------------------------------------------
89164// .yield (x) | return [4 /*yield*/, x];
89165// .mark RESUME | case RESUME:
89166// a = %sent%; | a = state.sent();
89167// -------------------------------|----------------------------------------------
89168// .yieldstar (x) | return [5 /*yield**/, x];
89169// .mark RESUME | case RESUME:
89170// a = %sent%; | a = state.sent();
89171// -------------------------------|----------------------------------------------
89172// .with (_a) | with (_a) {
89173// a(); | a();
89174// | }
89175// | state.label = LABEL;
89176// .mark LABEL | case LABEL:
89177// | with (_a) {
89178// b(); | b();
89179// | }
89180// .endwith |
89181// -------------------------------|----------------------------------------------
89182// | case 0:
89183// | state.trys = [];
89184// | ...
89185// .try TRY, CATCH, FINALLY, END |
89186// .mark TRY | case TRY:
89187// | state.trys.push([TRY, CATCH, FINALLY, END]);
89188// .nop |
89189// a(); | a();
89190// .br END | return [3 /*break*/, END];
89191// .catch (e) |
89192// .mark CATCH | case CATCH:
89193// | e = state.sent();
89194// b(); | b();
89195// .br END | return [3 /*break*/, END];
89196// .finally |
89197// .mark FINALLY | case FINALLY:
89198// c(); | c();
89199// .endfinally | return [7 /*endfinally*/];
89200// .endtry |
89201// .mark END | case END:
89202/*@internal*/
89203var ts;
89204(function (ts) {
89205 var OpCode;
89206 (function (OpCode) {
89207 OpCode[OpCode["Nop"] = 0] = "Nop";
89208 OpCode[OpCode["Statement"] = 1] = "Statement";
89209 OpCode[OpCode["Assign"] = 2] = "Assign";
89210 OpCode[OpCode["Break"] = 3] = "Break";
89211 OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
89212 OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
89213 OpCode[OpCode["Yield"] = 6] = "Yield";
89214 OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
89215 OpCode[OpCode["Return"] = 8] = "Return";
89216 OpCode[OpCode["Throw"] = 9] = "Throw";
89217 OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
89218 })(OpCode || (OpCode = {}));
89219 // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
89220 var BlockAction;
89221 (function (BlockAction) {
89222 BlockAction[BlockAction["Open"] = 0] = "Open";
89223 BlockAction[BlockAction["Close"] = 1] = "Close";
89224 })(BlockAction || (BlockAction = {}));
89225 // the kind for a generated code block in a FunctionBuilder
89226 var CodeBlockKind;
89227 (function (CodeBlockKind) {
89228 CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
89229 CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
89230 CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
89231 CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
89232 CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
89233 })(CodeBlockKind || (CodeBlockKind = {}));
89234 // the state for a generated code exception block
89235 var ExceptionBlockState;
89236 (function (ExceptionBlockState) {
89237 ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
89238 ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
89239 ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
89240 ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
89241 })(ExceptionBlockState || (ExceptionBlockState = {}));
89242 // NOTE: changes to this enum should be reflected in the __generator helper.
89243 var Instruction;
89244 (function (Instruction) {
89245 Instruction[Instruction["Next"] = 0] = "Next";
89246 Instruction[Instruction["Throw"] = 1] = "Throw";
89247 Instruction[Instruction["Return"] = 2] = "Return";
89248 Instruction[Instruction["Break"] = 3] = "Break";
89249 Instruction[Instruction["Yield"] = 4] = "Yield";
89250 Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
89251 Instruction[Instruction["Catch"] = 6] = "Catch";
89252 Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
89253 })(Instruction || (Instruction = {}));
89254 function getInstructionName(instruction) {
89255 switch (instruction) {
89256 case 2 /* Return */: return "return";
89257 case 3 /* Break */: return "break";
89258 case 4 /* Yield */: return "yield";
89259 case 5 /* YieldStar */: return "yield*";
89260 case 7 /* Endfinally */: return "endfinally";
89261 default: return undefined; // TODO: GH#18217
89262 }
89263 }
89264 function transformGenerators(context) {
89265 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
89266 var compilerOptions = context.getCompilerOptions();
89267 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
89268 var resolver = context.getEmitResolver();
89269 var previousOnSubstituteNode = context.onSubstituteNode;
89270 context.onSubstituteNode = onSubstituteNode;
89271 var renamedCatchVariables;
89272 var renamedCatchVariableDeclarations;
89273 var inGeneratorFunctionBody;
89274 var inStatementContainingYield;
89275 // The following three arrays store information about generated code blocks.
89276 // All three arrays are correlated by their index. This approach is used over allocating
89277 // objects to store the same information to avoid GC overhead.
89278 //
89279 var blocks; // Information about the code block
89280 var blockOffsets; // The operation offset at which a code block begins or ends
89281 var blockActions; // Whether the code block is opened or closed
89282 var blockStack; // A stack of currently open code blocks
89283 // Labels are used to mark locations in the code that can be the target of a Break (jump)
89284 // operation. These are translated into case clauses in a switch statement.
89285 // The following two arrays are correlated by their index. This approach is used over
89286 // allocating objects to store the same information to avoid GC overhead.
89287 //
89288 var labelOffsets; // The operation offset at which the label is defined.
89289 var labelExpressions; // The NumericLiteral nodes bound to each label.
89290 var nextLabelId = 1; // The next label id to use.
89291 // Operations store information about generated code for the function body. This
89292 // Includes things like statements, assignments, breaks (jumps), and yields.
89293 // The following three arrays are correlated by their index. This approach is used over
89294 // allocating objects to store the same information to avoid GC overhead.
89295 //
89296 var operations; // The operation to perform.
89297 var operationArguments; // The arguments to the operation.
89298 var operationLocations; // The source map location for the operation.
89299 var state; // The name of the state object used by the generator at runtime.
89300 // The following variables store information used by the `build` function:
89301 //
89302 var blockIndex = 0; // The index of the current block.
89303 var labelNumber = 0; // The current label number.
89304 var labelNumbers;
89305 var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
89306 var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
89307 var clauses; // The case clauses generated for labels.
89308 var statements; // The statements for the current label.
89309 var exceptionBlockStack; // A stack of containing exception blocks.
89310 var currentExceptionBlock; // The current exception block.
89311 var withBlockStack; // A stack containing `with` blocks.
89312 return ts.chainBundle(context, transformSourceFile);
89313 function transformSourceFile(node) {
89314 if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
89315 return node;
89316 }
89317 var visited = ts.visitEachChild(node, visitor, context);
89318 ts.addEmitHelpers(visited, context.readEmitHelpers());
89319 return visited;
89320 }
89321 /**
89322 * Visits a node.
89323 *
89324 * @param node The node to visit.
89325 */
89326 function visitor(node) {
89327 var transformFlags = node.transformFlags;
89328 if (inStatementContainingYield) {
89329 return visitJavaScriptInStatementContainingYield(node);
89330 }
89331 else if (inGeneratorFunctionBody) {
89332 return visitJavaScriptInGeneratorFunctionBody(node);
89333 }
89334 else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
89335 return visitGenerator(node);
89336 }
89337 else if (transformFlags & 512 /* ContainsGenerator */) {
89338 return ts.visitEachChild(node, visitor, context);
89339 }
89340 else {
89341 return node;
89342 }
89343 }
89344 /**
89345 * Visits a node that is contained within a statement that contains yield.
89346 *
89347 * @param node The node to visit.
89348 */
89349 function visitJavaScriptInStatementContainingYield(node) {
89350 switch (node.kind) {
89351 case 232 /* DoStatement */:
89352 return visitDoStatement(node);
89353 case 233 /* WhileStatement */:
89354 return visitWhileStatement(node);
89355 case 241 /* SwitchStatement */:
89356 return visitSwitchStatement(node);
89357 case 242 /* LabeledStatement */:
89358 return visitLabeledStatement(node);
89359 default:
89360 return visitJavaScriptInGeneratorFunctionBody(node);
89361 }
89362 }
89363 /**
89364 * Visits a node that is contained within a generator function.
89365 *
89366 * @param node The node to visit.
89367 */
89368 function visitJavaScriptInGeneratorFunctionBody(node) {
89369 switch (node.kind) {
89370 case 248 /* FunctionDeclaration */:
89371 return visitFunctionDeclaration(node);
89372 case 205 /* FunctionExpression */:
89373 return visitFunctionExpression(node);
89374 case 166 /* GetAccessor */:
89375 case 167 /* SetAccessor */:
89376 return visitAccessorDeclaration(node);
89377 case 229 /* VariableStatement */:
89378 return visitVariableStatement(node);
89379 case 234 /* ForStatement */:
89380 return visitForStatement(node);
89381 case 235 /* ForInStatement */:
89382 return visitForInStatement(node);
89383 case 238 /* BreakStatement */:
89384 return visitBreakStatement(node);
89385 case 237 /* ContinueStatement */:
89386 return visitContinueStatement(node);
89387 case 239 /* ReturnStatement */:
89388 return visitReturnStatement(node);
89389 default:
89390 if (node.transformFlags & 262144 /* ContainsYield */) {
89391 return visitJavaScriptContainingYield(node);
89392 }
89393 else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
89394 return ts.visitEachChild(node, visitor, context);
89395 }
89396 else {
89397 return node;
89398 }
89399 }
89400 }
89401 /**
89402 * Visits a node that contains a YieldExpression.
89403 *
89404 * @param node The node to visit.
89405 */
89406 function visitJavaScriptContainingYield(node) {
89407 switch (node.kind) {
89408 case 213 /* BinaryExpression */:
89409 return visitBinaryExpression(node);
89410 case 332 /* CommaListExpression */:
89411 return visitCommaListExpression(node);
89412 case 214 /* ConditionalExpression */:
89413 return visitConditionalExpression(node);
89414 case 216 /* YieldExpression */:
89415 return visitYieldExpression(node);
89416 case 196 /* ArrayLiteralExpression */:
89417 return visitArrayLiteralExpression(node);
89418 case 197 /* ObjectLiteralExpression */:
89419 return visitObjectLiteralExpression(node);
89420 case 199 /* ElementAccessExpression */:
89421 return visitElementAccessExpression(node);
89422 case 200 /* CallExpression */:
89423 return visitCallExpression(node);
89424 case 201 /* NewExpression */:
89425 return visitNewExpression(node);
89426 default:
89427 return ts.visitEachChild(node, visitor, context);
89428 }
89429 }
89430 /**
89431 * Visits a generator function.
89432 *
89433 * @param node The node to visit.
89434 */
89435 function visitGenerator(node) {
89436 switch (node.kind) {
89437 case 248 /* FunctionDeclaration */:
89438 return visitFunctionDeclaration(node);
89439 case 205 /* FunctionExpression */:
89440 return visitFunctionExpression(node);
89441 default:
89442 return ts.Debug.failBadSyntaxKind(node);
89443 }
89444 }
89445 /**
89446 * Visits a function declaration.
89447 *
89448 * This will be called when one of the following conditions are met:
89449 * - The function declaration is a generator function.
89450 * - The function declaration is contained within the body of a generator function.
89451 *
89452 * @param node The node to visit.
89453 */
89454 function visitFunctionDeclaration(node) {
89455 // Currently, we only support generators that were originally async functions.
89456 if (node.asteriskToken) {
89457 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
89458 /*decorators*/ undefined, node.modifiers,
89459 /*asteriskToken*/ undefined, node.name,
89460 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
89461 /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
89462 /*location*/ node), node);
89463 }
89464 else {
89465 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
89466 var savedInStatementContainingYield = inStatementContainingYield;
89467 inGeneratorFunctionBody = false;
89468 inStatementContainingYield = false;
89469 node = ts.visitEachChild(node, visitor, context);
89470 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
89471 inStatementContainingYield = savedInStatementContainingYield;
89472 }
89473 if (inGeneratorFunctionBody) {
89474 // Function declarations in a generator function body are hoisted
89475 // to the top of the lexical scope and elided from the current statement.
89476 hoistFunctionDeclaration(node);
89477 return undefined;
89478 }
89479 else {
89480 return node;
89481 }
89482 }
89483 /**
89484 * Visits a function expression.
89485 *
89486 * This will be called when one of the following conditions are met:
89487 * - The function expression is a generator function.
89488 * - The function expression is contained within the body of a generator function.
89489 *
89490 * @param node The node to visit.
89491 */
89492 function visitFunctionExpression(node) {
89493 // Currently, we only support generators that were originally async functions.
89494 if (node.asteriskToken) {
89495 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
89496 /*modifiers*/ undefined,
89497 /*asteriskToken*/ undefined, node.name,
89498 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
89499 /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
89500 /*location*/ node), node);
89501 }
89502 else {
89503 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
89504 var savedInStatementContainingYield = inStatementContainingYield;
89505 inGeneratorFunctionBody = false;
89506 inStatementContainingYield = false;
89507 node = ts.visitEachChild(node, visitor, context);
89508 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
89509 inStatementContainingYield = savedInStatementContainingYield;
89510 }
89511 return node;
89512 }
89513 /**
89514 * Visits a get or set accessor declaration.
89515 *
89516 * This will be called when one of the following conditions are met:
89517 * - The accessor is contained within the body of a generator function.
89518 *
89519 * @param node The node to visit.
89520 */
89521 function visitAccessorDeclaration(node) {
89522 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
89523 var savedInStatementContainingYield = inStatementContainingYield;
89524 inGeneratorFunctionBody = false;
89525 inStatementContainingYield = false;
89526 node = ts.visitEachChild(node, visitor, context);
89527 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
89528 inStatementContainingYield = savedInStatementContainingYield;
89529 return node;
89530 }
89531 /**
89532 * Transforms the body of a generator function declaration.
89533 *
89534 * @param node The function body to transform.
89535 */
89536 function transformGeneratorFunctionBody(body) {
89537 // Save existing generator state
89538 var statements = [];
89539 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
89540 var savedInStatementContainingYield = inStatementContainingYield;
89541 var savedBlocks = blocks;
89542 var savedBlockOffsets = blockOffsets;
89543 var savedBlockActions = blockActions;
89544 var savedBlockStack = blockStack;
89545 var savedLabelOffsets = labelOffsets;
89546 var savedLabelExpressions = labelExpressions;
89547 var savedNextLabelId = nextLabelId;
89548 var savedOperations = operations;
89549 var savedOperationArguments = operationArguments;
89550 var savedOperationLocations = operationLocations;
89551 var savedState = state;
89552 // Initialize generator state
89553 inGeneratorFunctionBody = true;
89554 inStatementContainingYield = false;
89555 blocks = undefined;
89556 blockOffsets = undefined;
89557 blockActions = undefined;
89558 blockStack = undefined;
89559 labelOffsets = undefined;
89560 labelExpressions = undefined;
89561 nextLabelId = 1;
89562 operations = undefined;
89563 operationArguments = undefined;
89564 operationLocations = undefined;
89565 state = factory.createTempVariable(/*recordTempVariable*/ undefined);
89566 // Build the generator
89567 resumeLexicalEnvironment();
89568 var statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
89569 transformAndEmitStatements(body.statements, statementOffset);
89570 var buildResult = build();
89571 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89572 statements.push(factory.createReturnStatement(buildResult));
89573 // Restore previous generator state
89574 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
89575 inStatementContainingYield = savedInStatementContainingYield;
89576 blocks = savedBlocks;
89577 blockOffsets = savedBlockOffsets;
89578 blockActions = savedBlockActions;
89579 blockStack = savedBlockStack;
89580 labelOffsets = savedLabelOffsets;
89581 labelExpressions = savedLabelExpressions;
89582 nextLabelId = savedNextLabelId;
89583 operations = savedOperations;
89584 operationArguments = savedOperationArguments;
89585 operationLocations = savedOperationLocations;
89586 state = savedState;
89587 return ts.setTextRange(factory.createBlock(statements, body.multiLine), body);
89588 }
89589 /**
89590 * Visits a variable statement.
89591 *
89592 * This will be called when one of the following conditions are met:
89593 * - The variable statement is contained within the body of a generator function.
89594 *
89595 * @param node The node to visit.
89596 */
89597 function visitVariableStatement(node) {
89598 if (node.transformFlags & 262144 /* ContainsYield */) {
89599 transformAndEmitVariableDeclarationList(node.declarationList);
89600 return undefined;
89601 }
89602 else {
89603 // Do not hoist custom prologues.
89604 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
89605 return node;
89606 }
89607 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89608 var variable = _a[_i];
89609 hoistVariableDeclaration(variable.name);
89610 }
89611 var variables = ts.getInitializedVariables(node.declarationList);
89612 if (variables.length === 0) {
89613 return undefined;
89614 }
89615 return ts.setSourceMapRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
89616 }
89617 }
89618 /**
89619 * Visits a binary expression.
89620 *
89621 * This will be called when one of the following conditions are met:
89622 * - The node contains a YieldExpression.
89623 *
89624 * @param node The node to visit.
89625 */
89626 function visitBinaryExpression(node) {
89627 var assoc = ts.getExpressionAssociativity(node);
89628 switch (assoc) {
89629 case 0 /* Left */:
89630 return visitLeftAssociativeBinaryExpression(node);
89631 case 1 /* Right */:
89632 return visitRightAssociativeBinaryExpression(node);
89633 default:
89634 return ts.Debug.assertNever(assoc);
89635 }
89636 }
89637 /**
89638 * Visits a right-associative binary expression containing `yield`.
89639 *
89640 * @param node The node to visit.
89641 */
89642 function visitRightAssociativeBinaryExpression(node) {
89643 var left = node.left, right = node.right;
89644 if (containsYield(right)) {
89645 var target = void 0;
89646 switch (left.kind) {
89647 case 198 /* PropertyAccessExpression */:
89648 // [source]
89649 // a.b = yield;
89650 //
89651 // [intermediate]
89652 // .local _a
89653 // _a = a;
89654 // .yield resumeLabel
89655 // .mark resumeLabel
89656 // _a.b = %sent%;
89657 target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
89658 break;
89659 case 199 /* ElementAccessExpression */:
89660 // [source]
89661 // a[b] = yield;
89662 //
89663 // [intermediate]
89664 // .local _a, _b
89665 // _a = a;
89666 // _b = b;
89667 // .yield resumeLabel
89668 // .mark resumeLabel
89669 // _a[_b] = %sent%;
89670 target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
89671 break;
89672 default:
89673 target = ts.visitNode(left, visitor, ts.isExpression);
89674 break;
89675 }
89676 var operator = node.operatorToken.kind;
89677 if (ts.isCompoundAssignment(operator)) {
89678 return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createBinaryExpression(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
89679 }
89680 else {
89681 return factory.updateBinaryExpression(node, target, node.operatorToken, ts.visitNode(right, visitor, ts.isExpression));
89682 }
89683 }
89684 return ts.visitEachChild(node, visitor, context);
89685 }
89686 function visitLeftAssociativeBinaryExpression(node) {
89687 if (containsYield(node.right)) {
89688 if (ts.isLogicalOperator(node.operatorToken.kind)) {
89689 return visitLogicalBinaryExpression(node);
89690 }
89691 else if (node.operatorToken.kind === 27 /* CommaToken */) {
89692 return visitCommaExpression(node);
89693 }
89694 // [source]
89695 // a() + (yield) + c()
89696 //
89697 // [intermediate]
89698 // .local _a
89699 // _a = a();
89700 // .yield resumeLabel
89701 // _a + %sent% + c()
89702 return factory.updateBinaryExpression(node, cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
89703 }
89704 return ts.visitEachChild(node, visitor, context);
89705 }
89706 /**
89707 * Visits a comma expression containing `yield`.
89708 *
89709 * @param node The node to visit.
89710 */
89711 function visitCommaExpression(node) {
89712 // [source]
89713 // x = a(), yield, b();
89714 //
89715 // [intermediate]
89716 // a();
89717 // .yield resumeLabel
89718 // .mark resumeLabel
89719 // x = %sent%, b();
89720 var pendingExpressions = [];
89721 visit(node.left);
89722 visit(node.right);
89723 return factory.inlineExpressions(pendingExpressions);
89724 function visit(node) {
89725 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
89726 visit(node.left);
89727 visit(node.right);
89728 }
89729 else {
89730 if (containsYield(node) && pendingExpressions.length > 0) {
89731 emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
89732 pendingExpressions = [];
89733 }
89734 pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
89735 }
89736 }
89737 }
89738 /**
89739 * Visits a comma-list expression.
89740 *
89741 * @param node The node to visit.
89742 */
89743 function visitCommaListExpression(node) {
89744 // flattened version of `visitCommaExpression`
89745 var pendingExpressions = [];
89746 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
89747 var elem = _a[_i];
89748 if (ts.isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */) {
89749 pendingExpressions.push(visitCommaExpression(elem));
89750 }
89751 else {
89752 if (containsYield(elem) && pendingExpressions.length > 0) {
89753 emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
89754 pendingExpressions = [];
89755 }
89756 pendingExpressions.push(ts.visitNode(elem, visitor, ts.isExpression));
89757 }
89758 }
89759 return factory.inlineExpressions(pendingExpressions);
89760 }
89761 /**
89762 * Visits a logical binary expression containing `yield`.
89763 *
89764 * @param node A node to visit.
89765 */
89766 function visitLogicalBinaryExpression(node) {
89767 // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
89768 // to be transformed as such:
89769 //
89770 // [source]
89771 // x = a() && yield;
89772 //
89773 // [intermediate]
89774 // .local _a
89775 // _a = a();
89776 // .brfalse resultLabel, (_a)
89777 // .yield resumeLabel
89778 // .mark resumeLabel
89779 // _a = %sent%;
89780 // .mark resultLabel
89781 // x = _a;
89782 //
89783 // [source]
89784 // x = a() || yield;
89785 //
89786 // [intermediate]
89787 // .local _a
89788 // _a = a();
89789 // .brtrue resultLabel, (_a)
89790 // .yield resumeLabel
89791 // .mark resumeLabel
89792 // _a = %sent%;
89793 // .mark resultLabel
89794 // x = _a;
89795 var resultLabel = defineLabel();
89796 var resultLocal = declareLocal();
89797 emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
89798 if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
89799 // Logical `&&` shortcuts when the left-hand operand is falsey.
89800 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
89801 }
89802 else {
89803 // Logical `||` shortcuts when the left-hand operand is truthy.
89804 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
89805 }
89806 emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
89807 markLabel(resultLabel);
89808 return resultLocal;
89809 }
89810 /**
89811 * Visits a conditional expression containing `yield`.
89812 *
89813 * @param node The node to visit.
89814 */
89815 function visitConditionalExpression(node) {
89816 // [source]
89817 // x = a() ? yield : b();
89818 //
89819 // [intermediate]
89820 // .local _a
89821 // .brfalse whenFalseLabel, (a())
89822 // .yield resumeLabel
89823 // .mark resumeLabel
89824 // _a = %sent%;
89825 // .br resultLabel
89826 // .mark whenFalseLabel
89827 // _a = b();
89828 // .mark resultLabel
89829 // x = _a;
89830 // We only need to perform a specific transformation if a `yield` expression exists
89831 // in either the `whenTrue` or `whenFalse` branches.
89832 // A `yield` in the condition will be handled by the normal visitor.
89833 if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
89834 var whenFalseLabel = defineLabel();
89835 var resultLabel = defineLabel();
89836 var resultLocal = declareLocal();
89837 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
89838 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
89839 emitBreak(resultLabel);
89840 markLabel(whenFalseLabel);
89841 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
89842 markLabel(resultLabel);
89843 return resultLocal;
89844 }
89845 return ts.visitEachChild(node, visitor, context);
89846 }
89847 /**
89848 * Visits a `yield` expression.
89849 *
89850 * @param node The node to visit.
89851 */
89852 function visitYieldExpression(node) {
89853 // [source]
89854 // x = yield a();
89855 //
89856 // [intermediate]
89857 // .yield resumeLabel, (a())
89858 // .mark resumeLabel
89859 // x = %sent%;
89860 var resumeLabel = defineLabel();
89861 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
89862 if (node.asteriskToken) {
89863 // NOTE: `expression` must be defined for `yield*`.
89864 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
89865 ? ts.setTextRange(emitHelpers().createValuesHelper(expression), node)
89866 : expression;
89867 emitYieldStar(iterator, /*location*/ node);
89868 }
89869 else {
89870 emitYield(expression, /*location*/ node);
89871 }
89872 markLabel(resumeLabel);
89873 return createGeneratorResume(/*location*/ node);
89874 }
89875 /**
89876 * Visits an ArrayLiteralExpression that contains a YieldExpression.
89877 *
89878 * @param node The node to visit.
89879 */
89880 function visitArrayLiteralExpression(node) {
89881 return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
89882 }
89883 /**
89884 * Visits an array of expressions containing one or more YieldExpression nodes
89885 * and returns an expression for the resulting value.
89886 *
89887 * @param elements The elements to visit.
89888 * @param multiLine Whether array literals created should be emitted on multiple lines.
89889 */
89890 function visitElements(elements, leadingElement, location, multiLine) {
89891 // [source]
89892 // ar = [1, yield, 2];
89893 //
89894 // [intermediate]
89895 // .local _a
89896 // _a = [1];
89897 // .yield resumeLabel
89898 // .mark resumeLabel
89899 // ar = _a.concat([%sent%, 2]);
89900 var numInitialElements = countInitialNodesWithoutYield(elements);
89901 var temp;
89902 if (numInitialElements > 0) {
89903 temp = declareLocal();
89904 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
89905 emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
89906 ? __spreadArrays([leadingElement], initialElements) : initialElements));
89907 leadingElement = undefined;
89908 }
89909 var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
89910 return temp
89911 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
89912 : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
89913 function reduceElement(expressions, element) {
89914 if (containsYield(element) && expressions.length > 0) {
89915 var hasAssignedTemp = temp !== undefined;
89916 if (!temp) {
89917 temp = declareLocal();
89918 }
89919 emitAssignment(temp, hasAssignedTemp
89920 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
89921 : factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
89922 leadingElement = undefined;
89923 expressions = [];
89924 }
89925 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
89926 return expressions;
89927 }
89928 }
89929 function visitObjectLiteralExpression(node) {
89930 // [source]
89931 // o = {
89932 // a: 1,
89933 // b: yield,
89934 // c: 2
89935 // };
89936 //
89937 // [intermediate]
89938 // .local _a
89939 // _a = {
89940 // a: 1
89941 // };
89942 // .yield resumeLabel
89943 // .mark resumeLabel
89944 // o = (_a.b = %sent%,
89945 // _a.c = 2,
89946 // _a);
89947 var properties = node.properties;
89948 var multiLine = node.multiLine;
89949 var numInitialProperties = countInitialNodesWithoutYield(properties);
89950 var temp = declareLocal();
89951 emitAssignment(temp, factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
89952 var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
89953 // TODO(rbuckton): Does this need to be parented?
89954 expressions.push(multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
89955 return factory.inlineExpressions(expressions);
89956 function reduceProperty(expressions, property) {
89957 if (containsYield(property) && expressions.length > 0) {
89958 emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions)));
89959 expressions = [];
89960 }
89961 var expression = ts.createExpressionForObjectLiteralElementLike(factory, node, property, temp);
89962 var visited = ts.visitNode(expression, visitor, ts.isExpression);
89963 if (visited) {
89964 if (multiLine) {
89965 ts.startOnNewLine(visited);
89966 }
89967 expressions.push(visited);
89968 }
89969 return expressions;
89970 }
89971 }
89972 /**
89973 * Visits an ElementAccessExpression that contains a YieldExpression.
89974 *
89975 * @param node The node to visit.
89976 */
89977 function visitElementAccessExpression(node) {
89978 if (containsYield(node.argumentExpression)) {
89979 // [source]
89980 // a = x[yield];
89981 //
89982 // [intermediate]
89983 // .local _a
89984 // _a = x;
89985 // .yield resumeLabel
89986 // .mark resumeLabel
89987 // a = _a[%sent%]
89988 return factory.updateElementAccessExpression(node, cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
89989 }
89990 return ts.visitEachChild(node, visitor, context);
89991 }
89992 function visitCallExpression(node) {
89993 if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
89994 // [source]
89995 // a.b(1, yield, 2);
89996 //
89997 // [intermediate]
89998 // .local _a, _b, _c
89999 // _b = (_a = a).b;
90000 // _c = [1];
90001 // .yield resumeLabel
90002 // .mark resumeLabel
90003 // _b.apply(_a, _c.concat([%sent%, 2]));
90004 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
90005 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments)), node), node);
90006 }
90007 return ts.visitEachChild(node, visitor, context);
90008 }
90009 function visitNewExpression(node) {
90010 if (ts.forEach(node.arguments, containsYield)) {
90011 // [source]
90012 // new a.b(1, yield, 2);
90013 //
90014 // [intermediate]
90015 // .local _a, _b, _c
90016 // _b = (_a = a.b).bind;
90017 // _c = [1];
90018 // .yield resumeLabel
90019 // .mark resumeLabel
90020 // new (_b.apply(_a, _c.concat([%sent%, 2])));
90021 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
90022 return ts.setOriginalNode(ts.setTextRange(factory.createNewExpression(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments,
90023 /*leadingElement*/ factory.createVoidZero())),
90024 /*typeArguments*/ undefined, []), node), node);
90025 }
90026 return ts.visitEachChild(node, visitor, context);
90027 }
90028 function transformAndEmitStatements(statements, start) {
90029 if (start === void 0) { start = 0; }
90030 var numStatements = statements.length;
90031 for (var i = start; i < numStatements; i++) {
90032 transformAndEmitStatement(statements[i]);
90033 }
90034 }
90035 function transformAndEmitEmbeddedStatement(node) {
90036 if (ts.isBlock(node)) {
90037 transformAndEmitStatements(node.statements);
90038 }
90039 else {
90040 transformAndEmitStatement(node);
90041 }
90042 }
90043 function transformAndEmitStatement(node) {
90044 var savedInStatementContainingYield = inStatementContainingYield;
90045 if (!inStatementContainingYield) {
90046 inStatementContainingYield = containsYield(node);
90047 }
90048 transformAndEmitStatementWorker(node);
90049 inStatementContainingYield = savedInStatementContainingYield;
90050 }
90051 function transformAndEmitStatementWorker(node) {
90052 switch (node.kind) {
90053 case 227 /* Block */:
90054 return transformAndEmitBlock(node);
90055 case 230 /* ExpressionStatement */:
90056 return transformAndEmitExpressionStatement(node);
90057 case 231 /* IfStatement */:
90058 return transformAndEmitIfStatement(node);
90059 case 232 /* DoStatement */:
90060 return transformAndEmitDoStatement(node);
90061 case 233 /* WhileStatement */:
90062 return transformAndEmitWhileStatement(node);
90063 case 234 /* ForStatement */:
90064 return transformAndEmitForStatement(node);
90065 case 235 /* ForInStatement */:
90066 return transformAndEmitForInStatement(node);
90067 case 237 /* ContinueStatement */:
90068 return transformAndEmitContinueStatement(node);
90069 case 238 /* BreakStatement */:
90070 return transformAndEmitBreakStatement(node);
90071 case 239 /* ReturnStatement */:
90072 return transformAndEmitReturnStatement(node);
90073 case 240 /* WithStatement */:
90074 return transformAndEmitWithStatement(node);
90075 case 241 /* SwitchStatement */:
90076 return transformAndEmitSwitchStatement(node);
90077 case 242 /* LabeledStatement */:
90078 return transformAndEmitLabeledStatement(node);
90079 case 243 /* ThrowStatement */:
90080 return transformAndEmitThrowStatement(node);
90081 case 244 /* TryStatement */:
90082 return transformAndEmitTryStatement(node);
90083 default:
90084 return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90085 }
90086 }
90087 function transformAndEmitBlock(node) {
90088 if (containsYield(node)) {
90089 transformAndEmitStatements(node.statements);
90090 }
90091 else {
90092 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90093 }
90094 }
90095 function transformAndEmitExpressionStatement(node) {
90096 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90097 }
90098 function transformAndEmitVariableDeclarationList(node) {
90099 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
90100 var variable = _a[_i];
90101 var name = factory.cloneNode(variable.name);
90102 ts.setCommentRange(name, variable.name);
90103 hoistVariableDeclaration(name);
90104 }
90105 var variables = ts.getInitializedVariables(node);
90106 var numVariables = variables.length;
90107 var variablesWritten = 0;
90108 var pendingExpressions = [];
90109 while (variablesWritten < numVariables) {
90110 for (var i = variablesWritten; i < numVariables; i++) {
90111 var variable = variables[i];
90112 if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
90113 break;
90114 }
90115 pendingExpressions.push(transformInitializedVariable(variable));
90116 }
90117 if (pendingExpressions.length) {
90118 emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
90119 variablesWritten += pendingExpressions.length;
90120 pendingExpressions = [];
90121 }
90122 }
90123 return undefined;
90124 }
90125 function transformInitializedVariable(node) {
90126 return ts.setSourceMapRange(factory.createAssignment(ts.setSourceMapRange(factory.cloneNode(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
90127 }
90128 function transformAndEmitIfStatement(node) {
90129 if (containsYield(node)) {
90130 // [source]
90131 // if (x)
90132 // /*thenStatement*/
90133 // else
90134 // /*elseStatement*/
90135 //
90136 // [intermediate]
90137 // .brfalse elseLabel, (x)
90138 // /*thenStatement*/
90139 // .br endLabel
90140 // .mark elseLabel
90141 // /*elseStatement*/
90142 // .mark endLabel
90143 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
90144 var endLabel = defineLabel();
90145 var elseLabel = node.elseStatement ? defineLabel() : undefined;
90146 emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
90147 transformAndEmitEmbeddedStatement(node.thenStatement);
90148 if (node.elseStatement) {
90149 emitBreak(endLabel);
90150 markLabel(elseLabel);
90151 transformAndEmitEmbeddedStatement(node.elseStatement);
90152 }
90153 markLabel(endLabel);
90154 }
90155 else {
90156 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90157 }
90158 }
90159 else {
90160 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90161 }
90162 }
90163 function transformAndEmitDoStatement(node) {
90164 if (containsYield(node)) {
90165 // [source]
90166 // do {
90167 // /*body*/
90168 // }
90169 // while (i < 10);
90170 //
90171 // [intermediate]
90172 // .loop conditionLabel, endLabel
90173 // .mark loopLabel
90174 // /*body*/
90175 // .mark conditionLabel
90176 // .brtrue loopLabel, (i < 10)
90177 // .endloop
90178 // .mark endLabel
90179 var conditionLabel = defineLabel();
90180 var loopLabel = defineLabel();
90181 beginLoopBlock(/*continueLabel*/ conditionLabel);
90182 markLabel(loopLabel);
90183 transformAndEmitEmbeddedStatement(node.statement);
90184 markLabel(conditionLabel);
90185 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
90186 endLoopBlock();
90187 }
90188 else {
90189 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90190 }
90191 }
90192 function visitDoStatement(node) {
90193 if (inStatementContainingYield) {
90194 beginScriptLoopBlock();
90195 node = ts.visitEachChild(node, visitor, context);
90196 endLoopBlock();
90197 return node;
90198 }
90199 else {
90200 return ts.visitEachChild(node, visitor, context);
90201 }
90202 }
90203 function transformAndEmitWhileStatement(node) {
90204 if (containsYield(node)) {
90205 // [source]
90206 // while (i < 10) {
90207 // /*body*/
90208 // }
90209 //
90210 // [intermediate]
90211 // .loop loopLabel, endLabel
90212 // .mark loopLabel
90213 // .brfalse endLabel, (i < 10)
90214 // /*body*/
90215 // .br loopLabel
90216 // .endloop
90217 // .mark endLabel
90218 var loopLabel = defineLabel();
90219 var endLabel = beginLoopBlock(loopLabel);
90220 markLabel(loopLabel);
90221 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
90222 transformAndEmitEmbeddedStatement(node.statement);
90223 emitBreak(loopLabel);
90224 endLoopBlock();
90225 }
90226 else {
90227 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90228 }
90229 }
90230 function visitWhileStatement(node) {
90231 if (inStatementContainingYield) {
90232 beginScriptLoopBlock();
90233 node = ts.visitEachChild(node, visitor, context);
90234 endLoopBlock();
90235 return node;
90236 }
90237 else {
90238 return ts.visitEachChild(node, visitor, context);
90239 }
90240 }
90241 function transformAndEmitForStatement(node) {
90242 if (containsYield(node)) {
90243 // [source]
90244 // for (var i = 0; i < 10; i++) {
90245 // /*body*/
90246 // }
90247 //
90248 // [intermediate]
90249 // .local i
90250 // i = 0;
90251 // .loop incrementLabel, endLoopLabel
90252 // .mark conditionLabel
90253 // .brfalse endLoopLabel, (i < 10)
90254 // /*body*/
90255 // .mark incrementLabel
90256 // i++;
90257 // .br conditionLabel
90258 // .endloop
90259 // .mark endLoopLabel
90260 var conditionLabel = defineLabel();
90261 var incrementLabel = defineLabel();
90262 var endLabel = beginLoopBlock(incrementLabel);
90263 if (node.initializer) {
90264 var initializer = node.initializer;
90265 if (ts.isVariableDeclarationList(initializer)) {
90266 transformAndEmitVariableDeclarationList(initializer);
90267 }
90268 else {
90269 emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
90270 }
90271 }
90272 markLabel(conditionLabel);
90273 if (node.condition) {
90274 emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
90275 }
90276 transformAndEmitEmbeddedStatement(node.statement);
90277 markLabel(incrementLabel);
90278 if (node.incrementor) {
90279 emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
90280 }
90281 emitBreak(conditionLabel);
90282 endLoopBlock();
90283 }
90284 else {
90285 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90286 }
90287 }
90288 function visitForStatement(node) {
90289 if (inStatementContainingYield) {
90290 beginScriptLoopBlock();
90291 }
90292 var initializer = node.initializer;
90293 if (initializer && ts.isVariableDeclarationList(initializer)) {
90294 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
90295 var variable = _a[_i];
90296 hoistVariableDeclaration(variable.name);
90297 }
90298 var variables = ts.getInitializedVariables(initializer);
90299 node = factory.updateForStatement(node, variables.length > 0
90300 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable))
90301 : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
90302 }
90303 else {
90304 node = ts.visitEachChild(node, visitor, context);
90305 }
90306 if (inStatementContainingYield) {
90307 endLoopBlock();
90308 }
90309 return node;
90310 }
90311 function transformAndEmitForInStatement(node) {
90312 // TODO(rbuckton): Source map locations
90313 if (containsYield(node)) {
90314 // [source]
90315 // for (var p in o) {
90316 // /*body*/
90317 // }
90318 //
90319 // [intermediate]
90320 // .local _a, _b, _i
90321 // _a = [];
90322 // for (_b in o) _a.push(_b);
90323 // _i = 0;
90324 // .loop incrementLabel, endLoopLabel
90325 // .mark conditionLabel
90326 // .brfalse endLoopLabel, (_i < _a.length)
90327 // p = _a[_i];
90328 // /*body*/
90329 // .mark incrementLabel
90330 // _b++;
90331 // .br conditionLabel
90332 // .endloop
90333 // .mark endLoopLabel
90334 var keysArray = declareLocal(); // _a
90335 var key = declareLocal(); // _b
90336 var keysIndex = factory.createLoopVariable(); // _i
90337 var initializer = node.initializer;
90338 hoistVariableDeclaration(keysIndex);
90339 emitAssignment(keysArray, factory.createArrayLiteralExpression());
90340 emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"),
90341 /*typeArguments*/ undefined, [key]))));
90342 emitAssignment(keysIndex, factory.createNumericLiteral(0));
90343 var conditionLabel = defineLabel();
90344 var incrementLabel = defineLabel();
90345 var endLabel = beginLoopBlock(incrementLabel);
90346 markLabel(conditionLabel);
90347 emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length")));
90348 var variable = void 0;
90349 if (ts.isVariableDeclarationList(initializer)) {
90350 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
90351 var variable_1 = _a[_i];
90352 hoistVariableDeclaration(variable_1.name);
90353 }
90354 variable = factory.cloneNode(initializer.declarations[0].name);
90355 }
90356 else {
90357 variable = ts.visitNode(initializer, visitor, ts.isExpression);
90358 ts.Debug.assert(ts.isLeftHandSideExpression(variable));
90359 }
90360 emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex));
90361 transformAndEmitEmbeddedStatement(node.statement);
90362 markLabel(incrementLabel);
90363 emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex)));
90364 emitBreak(conditionLabel);
90365 endLoopBlock();
90366 }
90367 else {
90368 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90369 }
90370 }
90371 function visitForInStatement(node) {
90372 // [source]
90373 // for (var x in a) {
90374 // /*body*/
90375 // }
90376 //
90377 // [intermediate]
90378 // .local x
90379 // .loop
90380 // for (x in a) {
90381 // /*body*/
90382 // }
90383 // .endloop
90384 if (inStatementContainingYield) {
90385 beginScriptLoopBlock();
90386 }
90387 var initializer = node.initializer;
90388 if (ts.isVariableDeclarationList(initializer)) {
90389 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
90390 var variable = _a[_i];
90391 hoistVariableDeclaration(variable.name);
90392 }
90393 node = factory.updateForInStatement(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
90394 }
90395 else {
90396 node = ts.visitEachChild(node, visitor, context);
90397 }
90398 if (inStatementContainingYield) {
90399 endLoopBlock();
90400 }
90401 return node;
90402 }
90403 function transformAndEmitContinueStatement(node) {
90404 var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
90405 if (label > 0) {
90406 emitBreak(label, /*location*/ node);
90407 }
90408 else {
90409 // invalid continue without a containing loop. Leave the node as is, per #17875.
90410 emitStatement(node);
90411 }
90412 }
90413 function visitContinueStatement(node) {
90414 if (inStatementContainingYield) {
90415 var label = findContinueTarget(node.label && ts.idText(node.label));
90416 if (label > 0) {
90417 return createInlineBreak(label, /*location*/ node);
90418 }
90419 }
90420 return ts.visitEachChild(node, visitor, context);
90421 }
90422 function transformAndEmitBreakStatement(node) {
90423 var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
90424 if (label > 0) {
90425 emitBreak(label, /*location*/ node);
90426 }
90427 else {
90428 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
90429 emitStatement(node);
90430 }
90431 }
90432 function visitBreakStatement(node) {
90433 if (inStatementContainingYield) {
90434 var label = findBreakTarget(node.label && ts.idText(node.label));
90435 if (label > 0) {
90436 return createInlineBreak(label, /*location*/ node);
90437 }
90438 }
90439 return ts.visitEachChild(node, visitor, context);
90440 }
90441 function transformAndEmitReturnStatement(node) {
90442 emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
90443 /*location*/ node);
90444 }
90445 function visitReturnStatement(node) {
90446 return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
90447 /*location*/ node);
90448 }
90449 function transformAndEmitWithStatement(node) {
90450 if (containsYield(node)) {
90451 // [source]
90452 // with (x) {
90453 // /*body*/
90454 // }
90455 //
90456 // [intermediate]
90457 // .with (x)
90458 // /*body*/
90459 // .endwith
90460 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
90461 transformAndEmitEmbeddedStatement(node.statement);
90462 endWithBlock();
90463 }
90464 else {
90465 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90466 }
90467 }
90468 function transformAndEmitSwitchStatement(node) {
90469 if (containsYield(node.caseBlock)) {
90470 // [source]
90471 // switch (x) {
90472 // case a:
90473 // /*caseStatements*/
90474 // case b:
90475 // /*caseStatements*/
90476 // default:
90477 // /*defaultStatements*/
90478 // }
90479 //
90480 // [intermediate]
90481 // .local _a
90482 // .switch endLabel
90483 // _a = x;
90484 // switch (_a) {
90485 // case a:
90486 // .br clauseLabels[0]
90487 // }
90488 // switch (_a) {
90489 // case b:
90490 // .br clauseLabels[1]
90491 // }
90492 // .br clauseLabels[2]
90493 // .mark clauseLabels[0]
90494 // /*caseStatements*/
90495 // .mark clauseLabels[1]
90496 // /*caseStatements*/
90497 // .mark clauseLabels[2]
90498 // /*caseStatements*/
90499 // .endswitch
90500 // .mark endLabel
90501 var caseBlock = node.caseBlock;
90502 var numClauses = caseBlock.clauses.length;
90503 var endLabel = beginSwitchBlock();
90504 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
90505 // Create labels for each clause and find the index of the first default clause.
90506 var clauseLabels = [];
90507 var defaultClauseIndex = -1;
90508 for (var i = 0; i < numClauses; i++) {
90509 var clause = caseBlock.clauses[i];
90510 clauseLabels.push(defineLabel());
90511 if (clause.kind === 282 /* DefaultClause */ && defaultClauseIndex === -1) {
90512 defaultClauseIndex = i;
90513 }
90514 }
90515 // Emit switch statements for each run of case clauses either from the first case
90516 // clause or the next case clause with a `yield` in its expression, up to the next
90517 // case clause with a `yield` in its expression.
90518 var clausesWritten = 0;
90519 var pendingClauses = [];
90520 while (clausesWritten < numClauses) {
90521 var defaultClausesSkipped = 0;
90522 for (var i = clausesWritten; i < numClauses; i++) {
90523 var clause = caseBlock.clauses[i];
90524 if (clause.kind === 281 /* CaseClause */) {
90525 if (containsYield(clause.expression) && pendingClauses.length > 0) {
90526 break;
90527 }
90528 pendingClauses.push(factory.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
90529 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
90530 ]));
90531 }
90532 else {
90533 defaultClausesSkipped++;
90534 }
90535 }
90536 if (pendingClauses.length) {
90537 emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses)));
90538 clausesWritten += pendingClauses.length;
90539 pendingClauses = [];
90540 }
90541 if (defaultClausesSkipped > 0) {
90542 clausesWritten += defaultClausesSkipped;
90543 defaultClausesSkipped = 0;
90544 }
90545 }
90546 if (defaultClauseIndex >= 0) {
90547 emitBreak(clauseLabels[defaultClauseIndex]);
90548 }
90549 else {
90550 emitBreak(endLabel);
90551 }
90552 for (var i = 0; i < numClauses; i++) {
90553 markLabel(clauseLabels[i]);
90554 transformAndEmitStatements(caseBlock.clauses[i].statements);
90555 }
90556 endSwitchBlock();
90557 }
90558 else {
90559 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90560 }
90561 }
90562 function visitSwitchStatement(node) {
90563 if (inStatementContainingYield) {
90564 beginScriptSwitchBlock();
90565 }
90566 node = ts.visitEachChild(node, visitor, context);
90567 if (inStatementContainingYield) {
90568 endSwitchBlock();
90569 }
90570 return node;
90571 }
90572 function transformAndEmitLabeledStatement(node) {
90573 if (containsYield(node)) {
90574 // [source]
90575 // x: {
90576 // /*body*/
90577 // }
90578 //
90579 // [intermediate]
90580 // .labeled "x", endLabel
90581 // /*body*/
90582 // .endlabeled
90583 // .mark endLabel
90584 beginLabeledBlock(ts.idText(node.label));
90585 transformAndEmitEmbeddedStatement(node.statement);
90586 endLabeledBlock();
90587 }
90588 else {
90589 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
90590 }
90591 }
90592 function visitLabeledStatement(node) {
90593 if (inStatementContainingYield) {
90594 beginScriptLabeledBlock(ts.idText(node.label));
90595 }
90596 node = ts.visitEachChild(node, visitor, context);
90597 if (inStatementContainingYield) {
90598 endLabeledBlock();
90599 }
90600 return node;
90601 }
90602 function transformAndEmitThrowStatement(node) {
90603 var _a;
90604 // TODO(rbuckton): `expression` should be required on `throw`.
90605 emitThrow(ts.visitNode((_a = node.expression) !== null && _a !== void 0 ? _a : factory.createVoidZero(), visitor, ts.isExpression),
90606 /*location*/ node);
90607 }
90608 function transformAndEmitTryStatement(node) {
90609 if (containsYield(node)) {
90610 // [source]
90611 // try {
90612 // /*tryBlock*/
90613 // }
90614 // catch (e) {
90615 // /*catchBlock*/
90616 // }
90617 // finally {
90618 // /*finallyBlock*/
90619 // }
90620 //
90621 // [intermediate]
90622 // .local _a
90623 // .try tryLabel, catchLabel, finallyLabel, endLabel
90624 // .mark tryLabel
90625 // .nop
90626 // /*tryBlock*/
90627 // .br endLabel
90628 // .catch
90629 // .mark catchLabel
90630 // _a = %error%;
90631 // /*catchBlock*/
90632 // .br endLabel
90633 // .finally
90634 // .mark finallyLabel
90635 // /*finallyBlock*/
90636 // .endfinally
90637 // .endtry
90638 // .mark endLabel
90639 beginExceptionBlock();
90640 transformAndEmitEmbeddedStatement(node.tryBlock);
90641 if (node.catchClause) {
90642 beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
90643 transformAndEmitEmbeddedStatement(node.catchClause.block);
90644 }
90645 if (node.finallyBlock) {
90646 beginFinallyBlock();
90647 transformAndEmitEmbeddedStatement(node.finallyBlock);
90648 }
90649 endExceptionBlock();
90650 }
90651 else {
90652 emitStatement(ts.visitEachChild(node, visitor, context));
90653 }
90654 }
90655 function containsYield(node) {
90656 return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
90657 }
90658 function countInitialNodesWithoutYield(nodes) {
90659 var numNodes = nodes.length;
90660 for (var i = 0; i < numNodes; i++) {
90661 if (containsYield(nodes[i])) {
90662 return i;
90663 }
90664 }
90665 return -1;
90666 }
90667 function onSubstituteNode(hint, node) {
90668 node = previousOnSubstituteNode(hint, node);
90669 if (hint === 1 /* Expression */) {
90670 return substituteExpression(node);
90671 }
90672 return node;
90673 }
90674 function substituteExpression(node) {
90675 if (ts.isIdentifier(node)) {
90676 return substituteExpressionIdentifier(node);
90677 }
90678 return node;
90679 }
90680 function substituteExpressionIdentifier(node) {
90681 if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
90682 var original = ts.getOriginalNode(node);
90683 if (ts.isIdentifier(original) && original.parent) {
90684 var declaration = resolver.getReferencedValueDeclaration(original);
90685 if (declaration) {
90686 var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
90687 if (name) {
90688 // TODO(rbuckton): Does this need to be parented?
90689 var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
90690 ts.setSourceMapRange(clone_5, node);
90691 ts.setCommentRange(clone_5, node);
90692 return clone_5;
90693 }
90694 }
90695 }
90696 }
90697 return node;
90698 }
90699 function cacheExpression(node) {
90700 if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
90701 return node;
90702 }
90703 var temp = factory.createTempVariable(hoistVariableDeclaration);
90704 emitAssignment(temp, node, /*location*/ node);
90705 return temp;
90706 }
90707 function declareLocal(name) {
90708 var temp = name
90709 ? factory.createUniqueName(name)
90710 : factory.createTempVariable(/*recordTempVariable*/ undefined);
90711 hoistVariableDeclaration(temp);
90712 return temp;
90713 }
90714 /**
90715 * Defines a label, uses as the target of a Break operation.
90716 */
90717 function defineLabel() {
90718 if (!labelOffsets) {
90719 labelOffsets = [];
90720 }
90721 var label = nextLabelId;
90722 nextLabelId++;
90723 labelOffsets[label] = -1;
90724 return label;
90725 }
90726 /**
90727 * Marks the current operation with the specified label.
90728 */
90729 function markLabel(label) {
90730 ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
90731 labelOffsets[label] = operations ? operations.length : 0;
90732 }
90733 /**
90734 * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
90735 *
90736 * @param block Information about the block.
90737 */
90738 function beginBlock(block) {
90739 if (!blocks) {
90740 blocks = [];
90741 blockActions = [];
90742 blockOffsets = [];
90743 blockStack = [];
90744 }
90745 var index = blockActions.length;
90746 blockActions[index] = 0 /* Open */;
90747 blockOffsets[index] = operations ? operations.length : 0;
90748 blocks[index] = block;
90749 blockStack.push(block);
90750 return index;
90751 }
90752 /**
90753 * Ends the current block operation.
90754 */
90755 function endBlock() {
90756 var block = peekBlock();
90757 if (block === undefined)
90758 return ts.Debug.fail("beginBlock was never called.");
90759 var index = blockActions.length;
90760 blockActions[index] = 1 /* Close */;
90761 blockOffsets[index] = operations ? operations.length : 0;
90762 blocks[index] = block;
90763 blockStack.pop();
90764 return block;
90765 }
90766 /**
90767 * Gets the current open block.
90768 */
90769 function peekBlock() {
90770 return ts.lastOrUndefined(blockStack);
90771 }
90772 /**
90773 * Gets the kind of the current open block.
90774 */
90775 function peekBlockKind() {
90776 var block = peekBlock();
90777 return block && block.kind;
90778 }
90779 /**
90780 * Begins a code block for a generated `with` statement.
90781 *
90782 * @param expression An identifier representing expression for the `with` block.
90783 */
90784 function beginWithBlock(expression) {
90785 var startLabel = defineLabel();
90786 var endLabel = defineLabel();
90787 markLabel(startLabel);
90788 beginBlock({
90789 kind: 1 /* With */,
90790 expression: expression,
90791 startLabel: startLabel,
90792 endLabel: endLabel
90793 });
90794 }
90795 /**
90796 * Ends a code block for a generated `with` statement.
90797 */
90798 function endWithBlock() {
90799 ts.Debug.assert(peekBlockKind() === 1 /* With */);
90800 var block = endBlock();
90801 markLabel(block.endLabel);
90802 }
90803 /**
90804 * Begins a code block for a generated `try` statement.
90805 */
90806 function beginExceptionBlock() {
90807 var startLabel = defineLabel();
90808 var endLabel = defineLabel();
90809 markLabel(startLabel);
90810 beginBlock({
90811 kind: 0 /* Exception */,
90812 state: 0 /* Try */,
90813 startLabel: startLabel,
90814 endLabel: endLabel
90815 });
90816 emitNop();
90817 return endLabel;
90818 }
90819 /**
90820 * Enters the `catch` clause of a generated `try` statement.
90821 *
90822 * @param variable The catch variable.
90823 */
90824 function beginCatchBlock(variable) {
90825 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
90826 // generated identifiers should already be unique within a file
90827 var name;
90828 if (ts.isGeneratedIdentifier(variable.name)) {
90829 name = variable.name;
90830 hoistVariableDeclaration(variable.name);
90831 }
90832 else {
90833 var text = ts.idText(variable.name);
90834 name = declareLocal(text);
90835 if (!renamedCatchVariables) {
90836 renamedCatchVariables = new ts.Map();
90837 renamedCatchVariableDeclarations = [];
90838 context.enableSubstitution(78 /* Identifier */);
90839 }
90840 renamedCatchVariables.set(text, true);
90841 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
90842 }
90843 var exception = peekBlock();
90844 ts.Debug.assert(exception.state < 1 /* Catch */);
90845 var endLabel = exception.endLabel;
90846 emitBreak(endLabel);
90847 var catchLabel = defineLabel();
90848 markLabel(catchLabel);
90849 exception.state = 1 /* Catch */;
90850 exception.catchVariable = name;
90851 exception.catchLabel = catchLabel;
90852 emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, []));
90853 emitNop();
90854 }
90855 /**
90856 * Enters the `finally` block of a generated `try` statement.
90857 */
90858 function beginFinallyBlock() {
90859 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
90860 var exception = peekBlock();
90861 ts.Debug.assert(exception.state < 2 /* Finally */);
90862 var endLabel = exception.endLabel;
90863 emitBreak(endLabel);
90864 var finallyLabel = defineLabel();
90865 markLabel(finallyLabel);
90866 exception.state = 2 /* Finally */;
90867 exception.finallyLabel = finallyLabel;
90868 }
90869 /**
90870 * Ends the code block for a generated `try` statement.
90871 */
90872 function endExceptionBlock() {
90873 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
90874 var exception = endBlock();
90875 var state = exception.state;
90876 if (state < 2 /* Finally */) {
90877 emitBreak(exception.endLabel);
90878 }
90879 else {
90880 emitEndfinally();
90881 }
90882 markLabel(exception.endLabel);
90883 emitNop();
90884 exception.state = 3 /* Done */;
90885 }
90886 /**
90887 * Begins a code block that supports `break` or `continue` statements that are defined in
90888 * the source tree and not from generated code.
90889 *
90890 * @param labelText Names from containing labeled statements.
90891 */
90892 function beginScriptLoopBlock() {
90893 beginBlock({
90894 kind: 3 /* Loop */,
90895 isScript: true,
90896 breakLabel: -1,
90897 continueLabel: -1
90898 });
90899 }
90900 /**
90901 * Begins a code block that supports `break` or `continue` statements that are defined in
90902 * generated code. Returns a label used to mark the operation to which to jump when a
90903 * `break` statement targets this block.
90904 *
90905 * @param continueLabel A Label used to mark the operation to which to jump when a
90906 * `continue` statement targets this block.
90907 */
90908 function beginLoopBlock(continueLabel) {
90909 var breakLabel = defineLabel();
90910 beginBlock({
90911 kind: 3 /* Loop */,
90912 isScript: false,
90913 breakLabel: breakLabel,
90914 continueLabel: continueLabel,
90915 });
90916 return breakLabel;
90917 }
90918 /**
90919 * Ends a code block that supports `break` or `continue` statements that are defined in
90920 * generated code or in the source tree.
90921 */
90922 function endLoopBlock() {
90923 ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
90924 var block = endBlock();
90925 var breakLabel = block.breakLabel;
90926 if (!block.isScript) {
90927 markLabel(breakLabel);
90928 }
90929 }
90930 /**
90931 * Begins a code block that supports `break` statements that are defined in the source
90932 * tree and not from generated code.
90933 *
90934 */
90935 function beginScriptSwitchBlock() {
90936 beginBlock({
90937 kind: 2 /* Switch */,
90938 isScript: true,
90939 breakLabel: -1
90940 });
90941 }
90942 /**
90943 * Begins a code block that supports `break` statements that are defined in generated code.
90944 * Returns a label used to mark the operation to which to jump when a `break` statement
90945 * targets this block.
90946 */
90947 function beginSwitchBlock() {
90948 var breakLabel = defineLabel();
90949 beginBlock({
90950 kind: 2 /* Switch */,
90951 isScript: false,
90952 breakLabel: breakLabel,
90953 });
90954 return breakLabel;
90955 }
90956 /**
90957 * Ends a code block that supports `break` statements that are defined in generated code.
90958 */
90959 function endSwitchBlock() {
90960 ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
90961 var block = endBlock();
90962 var breakLabel = block.breakLabel;
90963 if (!block.isScript) {
90964 markLabel(breakLabel);
90965 }
90966 }
90967 function beginScriptLabeledBlock(labelText) {
90968 beginBlock({
90969 kind: 4 /* Labeled */,
90970 isScript: true,
90971 labelText: labelText,
90972 breakLabel: -1
90973 });
90974 }
90975 function beginLabeledBlock(labelText) {
90976 var breakLabel = defineLabel();
90977 beginBlock({
90978 kind: 4 /* Labeled */,
90979 isScript: false,
90980 labelText: labelText,
90981 breakLabel: breakLabel
90982 });
90983 }
90984 function endLabeledBlock() {
90985 ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
90986 var block = endBlock();
90987 if (!block.isScript) {
90988 markLabel(block.breakLabel);
90989 }
90990 }
90991 /**
90992 * Indicates whether the provided block supports `break` statements.
90993 *
90994 * @param block A code block.
90995 */
90996 function supportsUnlabeledBreak(block) {
90997 return block.kind === 2 /* Switch */
90998 || block.kind === 3 /* Loop */;
90999 }
91000 /**
91001 * Indicates whether the provided block supports `break` statements with labels.
91002 *
91003 * @param block A code block.
91004 */
91005 function supportsLabeledBreakOrContinue(block) {
91006 return block.kind === 4 /* Labeled */;
91007 }
91008 /**
91009 * Indicates whether the provided block supports `continue` statements.
91010 *
91011 * @param block A code block.
91012 */
91013 function supportsUnlabeledContinue(block) {
91014 return block.kind === 3 /* Loop */;
91015 }
91016 function hasImmediateContainingLabeledBlock(labelText, start) {
91017 for (var j = start; j >= 0; j--) {
91018 var containingBlock = blockStack[j];
91019 if (supportsLabeledBreakOrContinue(containingBlock)) {
91020 if (containingBlock.labelText === labelText) {
91021 return true;
91022 }
91023 }
91024 else {
91025 break;
91026 }
91027 }
91028 return false;
91029 }
91030 /**
91031 * Finds the label that is the target for a `break` statement.
91032 *
91033 * @param labelText An optional name of a containing labeled statement.
91034 */
91035 function findBreakTarget(labelText) {
91036 if (blockStack) {
91037 if (labelText) {
91038 for (var i = blockStack.length - 1; i >= 0; i--) {
91039 var block = blockStack[i];
91040 if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
91041 return block.breakLabel;
91042 }
91043 else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
91044 return block.breakLabel;
91045 }
91046 }
91047 }
91048 else {
91049 for (var i = blockStack.length - 1; i >= 0; i--) {
91050 var block = blockStack[i];
91051 if (supportsUnlabeledBreak(block)) {
91052 return block.breakLabel;
91053 }
91054 }
91055 }
91056 }
91057 return 0;
91058 }
91059 /**
91060 * Finds the label that is the target for a `continue` statement.
91061 *
91062 * @param labelText An optional name of a containing labeled statement.
91063 */
91064 function findContinueTarget(labelText) {
91065 if (blockStack) {
91066 if (labelText) {
91067 for (var i = blockStack.length - 1; i >= 0; i--) {
91068 var block = blockStack[i];
91069 if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
91070 return block.continueLabel;
91071 }
91072 }
91073 }
91074 else {
91075 for (var i = blockStack.length - 1; i >= 0; i--) {
91076 var block = blockStack[i];
91077 if (supportsUnlabeledContinue(block)) {
91078 return block.continueLabel;
91079 }
91080 }
91081 }
91082 }
91083 return 0;
91084 }
91085 /**
91086 * Creates an expression that can be used to indicate the value for a label.
91087 *
91088 * @param label A label.
91089 */
91090 function createLabel(label) {
91091 if (label !== undefined && label > 0) {
91092 if (labelExpressions === undefined) {
91093 labelExpressions = [];
91094 }
91095 var expression = factory.createNumericLiteral(-1);
91096 if (labelExpressions[label] === undefined) {
91097 labelExpressions[label] = [expression];
91098 }
91099 else {
91100 labelExpressions[label].push(expression);
91101 }
91102 return expression;
91103 }
91104 return factory.createOmittedExpression();
91105 }
91106 /**
91107 * Creates a numeric literal for the provided instruction.
91108 */
91109 function createInstruction(instruction) {
91110 var literal = factory.createNumericLiteral(instruction);
91111 ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
91112 return literal;
91113 }
91114 /**
91115 * Creates a statement that can be used indicate a Break operation to the provided label.
91116 *
91117 * @param label A label.
91118 * @param location An optional source map location for the statement.
91119 */
91120 function createInlineBreak(label, location) {
91121 ts.Debug.assertLessThan(0, label, "Invalid label");
91122 return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
91123 createInstruction(3 /* Break */),
91124 createLabel(label)
91125 ])), location);
91126 }
91127 /**
91128 * Creates a statement that can be used indicate a Return operation.
91129 *
91130 * @param expression The expression for the return statement.
91131 * @param location An optional source map location for the statement.
91132 */
91133 function createInlineReturn(expression, location) {
91134 return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
91135 ? [createInstruction(2 /* Return */), expression]
91136 : [createInstruction(2 /* Return */)])), location);
91137 }
91138 /**
91139 * Creates an expression that can be used to resume from a Yield operation.
91140 */
91141 function createGeneratorResume(location) {
91142 return ts.setTextRange(factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"),
91143 /*typeArguments*/ undefined, []), location);
91144 }
91145 /**
91146 * Emits an empty instruction.
91147 */
91148 function emitNop() {
91149 emitWorker(0 /* Nop */);
91150 }
91151 /**
91152 * Emits a Statement.
91153 *
91154 * @param node A statement.
91155 */
91156 function emitStatement(node) {
91157 if (node) {
91158 emitWorker(1 /* Statement */, [node]);
91159 }
91160 else {
91161 emitNop();
91162 }
91163 }
91164 /**
91165 * Emits an Assignment operation.
91166 *
91167 * @param left The left-hand side of the assignment.
91168 * @param right The right-hand side of the assignment.
91169 * @param location An optional source map location for the assignment.
91170 */
91171 function emitAssignment(left, right, location) {
91172 emitWorker(2 /* Assign */, [left, right], location);
91173 }
91174 /**
91175 * Emits a Break operation to the specified label.
91176 *
91177 * @param label A label.
91178 * @param location An optional source map location for the assignment.
91179 */
91180 function emitBreak(label, location) {
91181 emitWorker(3 /* Break */, [label], location);
91182 }
91183 /**
91184 * Emits a Break operation to the specified label when a condition evaluates to a truthy
91185 * value at runtime.
91186 *
91187 * @param label A label.
91188 * @param condition The condition.
91189 * @param location An optional source map location for the assignment.
91190 */
91191 function emitBreakWhenTrue(label, condition, location) {
91192 emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
91193 }
91194 /**
91195 * Emits a Break to the specified label when a condition evaluates to a falsey value at
91196 * runtime.
91197 *
91198 * @param label A label.
91199 * @param condition The condition.
91200 * @param location An optional source map location for the assignment.
91201 */
91202 function emitBreakWhenFalse(label, condition, location) {
91203 emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
91204 }
91205 /**
91206 * Emits a YieldStar operation for the provided expression.
91207 *
91208 * @param expression An optional value for the yield operation.
91209 * @param location An optional source map location for the assignment.
91210 */
91211 function emitYieldStar(expression, location) {
91212 emitWorker(7 /* YieldStar */, [expression], location);
91213 }
91214 /**
91215 * Emits a Yield operation for the provided expression.
91216 *
91217 * @param expression An optional value for the yield operation.
91218 * @param location An optional source map location for the assignment.
91219 */
91220 function emitYield(expression, location) {
91221 emitWorker(6 /* Yield */, [expression], location);
91222 }
91223 /**
91224 * Emits a Return operation for the provided expression.
91225 *
91226 * @param expression An optional value for the operation.
91227 * @param location An optional source map location for the assignment.
91228 */
91229 function emitReturn(expression, location) {
91230 emitWorker(8 /* Return */, [expression], location);
91231 }
91232 /**
91233 * Emits a Throw operation for the provided expression.
91234 *
91235 * @param expression A value for the operation.
91236 * @param location An optional source map location for the assignment.
91237 */
91238 function emitThrow(expression, location) {
91239 emitWorker(9 /* Throw */, [expression], location);
91240 }
91241 /**
91242 * Emits an Endfinally operation. This is used to handle `finally` block semantics.
91243 */
91244 function emitEndfinally() {
91245 emitWorker(10 /* Endfinally */);
91246 }
91247 /**
91248 * Emits an operation.
91249 *
91250 * @param code The OpCode for the operation.
91251 * @param args The optional arguments for the operation.
91252 */
91253 function emitWorker(code, args, location) {
91254 if (operations === undefined) {
91255 operations = [];
91256 operationArguments = [];
91257 operationLocations = [];
91258 }
91259 if (labelOffsets === undefined) {
91260 // mark entry point
91261 markLabel(defineLabel());
91262 }
91263 var operationIndex = operations.length;
91264 operations[operationIndex] = code;
91265 operationArguments[operationIndex] = args;
91266 operationLocations[operationIndex] = location;
91267 }
91268 /**
91269 * Builds the generator function body.
91270 */
91271 function build() {
91272 blockIndex = 0;
91273 labelNumber = 0;
91274 labelNumbers = undefined;
91275 lastOperationWasAbrupt = false;
91276 lastOperationWasCompletion = false;
91277 clauses = undefined;
91278 statements = undefined;
91279 exceptionBlockStack = undefined;
91280 currentExceptionBlock = undefined;
91281 withBlockStack = undefined;
91282 var buildResult = buildStatements();
91283 return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(
91284 /*modifiers*/ undefined,
91285 /*asteriskToken*/ undefined,
91286 /*name*/ undefined,
91287 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
91288 /*type*/ undefined, factory.createBlock(buildResult,
91289 /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
91290 }
91291 /**
91292 * Builds the statements for the generator function body.
91293 */
91294 function buildStatements() {
91295 if (operations) {
91296 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
91297 writeOperation(operationIndex);
91298 }
91299 flushFinalLabel(operations.length);
91300 }
91301 else {
91302 flushFinalLabel(0);
91303 }
91304 if (clauses) {
91305 var labelExpression = factory.createPropertyAccessExpression(state, "label");
91306 var switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
91307 return [ts.startOnNewLine(switchStatement)];
91308 }
91309 if (statements) {
91310 return statements;
91311 }
91312 return [];
91313 }
91314 /**
91315 * Flush the current label and advance to a new label.
91316 */
91317 function flushLabel() {
91318 if (!statements) {
91319 return;
91320 }
91321 appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
91322 lastOperationWasAbrupt = false;
91323 lastOperationWasCompletion = false;
91324 labelNumber++;
91325 }
91326 /**
91327 * Flush the final label of the generator function body.
91328 */
91329 function flushFinalLabel(operationIndex) {
91330 if (isFinalLabelReachable(operationIndex)) {
91331 tryEnterLabel(operationIndex);
91332 withBlockStack = undefined;
91333 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
91334 }
91335 if (statements && clauses) {
91336 appendLabel(/*markLabelEnd*/ false);
91337 }
91338 updateLabelExpressions();
91339 }
91340 /**
91341 * Tests whether the final label of the generator function body
91342 * is reachable by user code.
91343 */
91344 function isFinalLabelReachable(operationIndex) {
91345 // if the last operation was *not* a completion (return/throw) then
91346 // the final label is reachable.
91347 if (!lastOperationWasCompletion) {
91348 return true;
91349 }
91350 // if there are no labels defined or referenced, then the final label is
91351 // not reachable.
91352 if (!labelOffsets || !labelExpressions) {
91353 return false;
91354 }
91355 // if the label for this offset is referenced, then the final label
91356 // is reachable.
91357 for (var label = 0; label < labelOffsets.length; label++) {
91358 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
91359 return true;
91360 }
91361 }
91362 return false;
91363 }
91364 /**
91365 * Appends a case clause for the last label and sets the new label.
91366 *
91367 * @param markLabelEnd Indicates that the transition between labels was a fall-through
91368 * from a previous case clause and the change in labels should be
91369 * reflected on the `state` object.
91370 */
91371 function appendLabel(markLabelEnd) {
91372 if (!clauses) {
91373 clauses = [];
91374 }
91375 if (statements) {
91376 if (withBlockStack) {
91377 // The previous label was nested inside one or more `with` blocks, so we
91378 // surround the statements in generated `with` blocks to create the same environment.
91379 for (var i = withBlockStack.length - 1; i >= 0; i--) {
91380 var withBlock = withBlockStack[i];
91381 statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))];
91382 }
91383 }
91384 if (currentExceptionBlock) {
91385 // The previous label was nested inside of an exception block, so we must
91386 // indicate entry into a protected region by pushing the label numbers
91387 // for each block in the protected region.
91388 var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
91389 statements.unshift(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"),
91390 /*typeArguments*/ undefined, [
91391 factory.createArrayLiteralExpression([
91392 createLabel(startLabel),
91393 createLabel(catchLabel),
91394 createLabel(finallyLabel),
91395 createLabel(endLabel)
91396 ])
91397 ])));
91398 currentExceptionBlock = undefined;
91399 }
91400 if (markLabelEnd) {
91401 // The case clause for the last label falls through to this label, so we
91402 // add an assignment statement to reflect the change in labels.
91403 statements.push(factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(state, "label"), factory.createNumericLiteral(labelNumber + 1))));
91404 }
91405 }
91406 clauses.push(factory.createCaseClause(factory.createNumericLiteral(labelNumber), statements || []));
91407 statements = undefined;
91408 }
91409 /**
91410 * Tries to enter into a new label at the current operation index.
91411 */
91412 function tryEnterLabel(operationIndex) {
91413 if (!labelOffsets) {
91414 return;
91415 }
91416 for (var label = 0; label < labelOffsets.length; label++) {
91417 if (labelOffsets[label] === operationIndex) {
91418 flushLabel();
91419 if (labelNumbers === undefined) {
91420 labelNumbers = [];
91421 }
91422 if (labelNumbers[labelNumber] === undefined) {
91423 labelNumbers[labelNumber] = [label];
91424 }
91425 else {
91426 labelNumbers[labelNumber].push(label);
91427 }
91428 }
91429 }
91430 }
91431 /**
91432 * Updates literal expressions for labels with actual label numbers.
91433 */
91434 function updateLabelExpressions() {
91435 if (labelExpressions !== undefined && labelNumbers !== undefined) {
91436 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
91437 var labels = labelNumbers[labelNumber_1];
91438 if (labels !== undefined) {
91439 for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
91440 var label = labels_1[_i];
91441 var expressions = labelExpressions[label];
91442 if (expressions !== undefined) {
91443 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
91444 var expression = expressions_1[_a];
91445 expression.text = String(labelNumber_1);
91446 }
91447 }
91448 }
91449 }
91450 }
91451 }
91452 }
91453 /**
91454 * Tries to enter or leave a code block.
91455 */
91456 function tryEnterOrLeaveBlock(operationIndex) {
91457 if (blocks) {
91458 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
91459 var block = blocks[blockIndex];
91460 var blockAction = blockActions[blockIndex];
91461 switch (block.kind) {
91462 case 0 /* Exception */:
91463 if (blockAction === 0 /* Open */) {
91464 if (!exceptionBlockStack) {
91465 exceptionBlockStack = [];
91466 }
91467 if (!statements) {
91468 statements = [];
91469 }
91470 exceptionBlockStack.push(currentExceptionBlock);
91471 currentExceptionBlock = block;
91472 }
91473 else if (blockAction === 1 /* Close */) {
91474 currentExceptionBlock = exceptionBlockStack.pop();
91475 }
91476 break;
91477 case 1 /* With */:
91478 if (blockAction === 0 /* Open */) {
91479 if (!withBlockStack) {
91480 withBlockStack = [];
91481 }
91482 withBlockStack.push(block);
91483 }
91484 else if (blockAction === 1 /* Close */) {
91485 withBlockStack.pop();
91486 }
91487 break;
91488 // default: do nothing
91489 }
91490 }
91491 }
91492 }
91493 /**
91494 * Writes an operation as a statement to the current label's statement list.
91495 *
91496 * @param operation The OpCode of the operation
91497 */
91498 function writeOperation(operationIndex) {
91499 tryEnterLabel(operationIndex);
91500 tryEnterOrLeaveBlock(operationIndex);
91501 // early termination, nothing else to process in this label
91502 if (lastOperationWasAbrupt) {
91503 return;
91504 }
91505 lastOperationWasAbrupt = false;
91506 lastOperationWasCompletion = false;
91507 var opcode = operations[operationIndex];
91508 if (opcode === 0 /* Nop */) {
91509 return;
91510 }
91511 else if (opcode === 10 /* Endfinally */) {
91512 return writeEndfinally();
91513 }
91514 var args = operationArguments[operationIndex];
91515 if (opcode === 1 /* Statement */) {
91516 return writeStatement(args[0]);
91517 }
91518 var location = operationLocations[operationIndex];
91519 switch (opcode) {
91520 case 2 /* Assign */:
91521 return writeAssign(args[0], args[1], location);
91522 case 3 /* Break */:
91523 return writeBreak(args[0], location);
91524 case 4 /* BreakWhenTrue */:
91525 return writeBreakWhenTrue(args[0], args[1], location);
91526 case 5 /* BreakWhenFalse */:
91527 return writeBreakWhenFalse(args[0], args[1], location);
91528 case 6 /* Yield */:
91529 return writeYield(args[0], location);
91530 case 7 /* YieldStar */:
91531 return writeYieldStar(args[0], location);
91532 case 8 /* Return */:
91533 return writeReturn(args[0], location);
91534 case 9 /* Throw */:
91535 return writeThrow(args[0], location);
91536 }
91537 }
91538 /**
91539 * Writes a statement to the current label's statement list.
91540 *
91541 * @param statement A statement to write.
91542 */
91543 function writeStatement(statement) {
91544 if (statement) {
91545 if (!statements) {
91546 statements = [statement];
91547 }
91548 else {
91549 statements.push(statement);
91550 }
91551 }
91552 }
91553 /**
91554 * Writes an Assign operation to the current label's statement list.
91555 *
91556 * @param left The left-hand side of the assignment.
91557 * @param right The right-hand side of the assignment.
91558 * @param operationLocation The source map location for the operation.
91559 */
91560 function writeAssign(left, right, operationLocation) {
91561 writeStatement(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation));
91562 }
91563 /**
91564 * Writes a Throw operation to the current label's statement list.
91565 *
91566 * @param expression The value to throw.
91567 * @param operationLocation The source map location for the operation.
91568 */
91569 function writeThrow(expression, operationLocation) {
91570 lastOperationWasAbrupt = true;
91571 lastOperationWasCompletion = true;
91572 writeStatement(ts.setTextRange(factory.createThrowStatement(expression), operationLocation));
91573 }
91574 /**
91575 * Writes a Return operation to the current label's statement list.
91576 *
91577 * @param expression The value to return.
91578 * @param operationLocation The source map location for the operation.
91579 */
91580 function writeReturn(expression, operationLocation) {
91581 lastOperationWasAbrupt = true;
91582 lastOperationWasCompletion = true;
91583 writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
91584 ? [createInstruction(2 /* Return */), expression]
91585 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
91586 }
91587 /**
91588 * Writes a Break operation to the current label's statement list.
91589 *
91590 * @param label The label for the Break.
91591 * @param operationLocation The source map location for the operation.
91592 */
91593 function writeBreak(label, operationLocation) {
91594 lastOperationWasAbrupt = true;
91595 writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
91596 createInstruction(3 /* Break */),
91597 createLabel(label)
91598 ])), operationLocation), 384 /* NoTokenSourceMaps */));
91599 }
91600 /**
91601 * Writes a BreakWhenTrue operation to the current label's statement list.
91602 *
91603 * @param label The label for the Break.
91604 * @param condition The condition for the Break.
91605 * @param operationLocation The source map location for the operation.
91606 */
91607 function writeBreakWhenTrue(label, condition, operationLocation) {
91608 writeStatement(ts.setEmitFlags(factory.createIfStatement(condition, ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
91609 createInstruction(3 /* Break */),
91610 createLabel(label)
91611 ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
91612 }
91613 /**
91614 * Writes a BreakWhenFalse operation to the current label's statement list.
91615 *
91616 * @param label The label for the Break.
91617 * @param condition The condition for the Break.
91618 * @param operationLocation The source map location for the operation.
91619 */
91620 function writeBreakWhenFalse(label, condition, operationLocation) {
91621 writeStatement(ts.setEmitFlags(factory.createIfStatement(factory.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
91622 createInstruction(3 /* Break */),
91623 createLabel(label)
91624 ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
91625 }
91626 /**
91627 * Writes a Yield operation to the current label's statement list.
91628 *
91629 * @param expression The expression to yield.
91630 * @param operationLocation The source map location for the operation.
91631 */
91632 function writeYield(expression, operationLocation) {
91633 lastOperationWasAbrupt = true;
91634 writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
91635 ? [createInstruction(4 /* Yield */), expression]
91636 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
91637 }
91638 /**
91639 * Writes a YieldStar instruction to the current label's statement list.
91640 *
91641 * @param expression The expression to yield.
91642 * @param operationLocation The source map location for the operation.
91643 */
91644 function writeYieldStar(expression, operationLocation) {
91645 lastOperationWasAbrupt = true;
91646 writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
91647 createInstruction(5 /* YieldStar */),
91648 expression
91649 ])), operationLocation), 384 /* NoTokenSourceMaps */));
91650 }
91651 /**
91652 * Writes an Endfinally instruction to the current label's statement list.
91653 */
91654 function writeEndfinally() {
91655 lastOperationWasAbrupt = true;
91656 writeStatement(factory.createReturnStatement(factory.createArrayLiteralExpression([
91657 createInstruction(7 /* Endfinally */)
91658 ])));
91659 }
91660 }
91661 ts.transformGenerators = transformGenerators;
91662})(ts || (ts = {}));
91663/*@internal*/
91664var ts;
91665(function (ts) {
91666 function transformModule(context) {
91667 function getTransformModuleDelegate(moduleKind) {
91668 switch (moduleKind) {
91669 case ts.ModuleKind.AMD: return transformAMDModule;
91670 case ts.ModuleKind.UMD: return transformUMDModule;
91671 default: return transformCommonJSModule;
91672 }
91673 }
91674 var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
91675 var compilerOptions = context.getCompilerOptions();
91676 var resolver = context.getEmitResolver();
91677 var host = context.getEmitHost();
91678 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
91679 var moduleKind = ts.getEmitModuleKind(compilerOptions);
91680 var previousOnSubstituteNode = context.onSubstituteNode;
91681 var previousOnEmitNode = context.onEmitNode;
91682 context.onSubstituteNode = onSubstituteNode;
91683 context.onEmitNode = onEmitNode;
91684 context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
91685 context.enableSubstitution(213 /* BinaryExpression */); // Substitutes assignments to exported symbols.
91686 context.enableSubstitution(211 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
91687 context.enableSubstitution(212 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
91688 context.enableSubstitution(286 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
91689 context.enableEmitNotification(294 /* SourceFile */); // Restore state when substituting nodes in a file.
91690 var moduleInfoMap = []; // The ExternalModuleInfo for each file.
91691 var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
91692 var currentSourceFile; // The current file.
91693 var currentModuleInfo; // The ExternalModuleInfo for the current file.
91694 var noSubstitution; // Set of nodes for which substitution rules should be ignored.
91695 var needUMDDynamicImportHelper;
91696 return ts.chainBundle(context, transformSourceFile);
91697 /**
91698 * Transforms the module aspects of a SourceFile.
91699 *
91700 * @param node The SourceFile node.
91701 */
91702 function transformSourceFile(node) {
91703 if (node.isDeclarationFile ||
91704 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
91705 node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
91706 (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) {
91707 return node;
91708 }
91709 currentSourceFile = node;
91710 currentModuleInfo = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
91711 moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
91712 // Perform the transformation.
91713 var transformModule = getTransformModuleDelegate(moduleKind);
91714 var updated = transformModule(node);
91715 currentSourceFile = undefined;
91716 currentModuleInfo = undefined;
91717 needUMDDynamicImportHelper = false;
91718 return updated;
91719 }
91720 function shouldEmitUnderscoreUnderscoreESModule() {
91721 if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
91722 return true;
91723 }
91724 return false;
91725 }
91726 /**
91727 * Transforms a SourceFile into a CommonJS module.
91728 *
91729 * @param node The SourceFile node.
91730 */
91731 function transformCommonJSModule(node) {
91732 startLexicalEnvironment();
91733 var statements = [];
91734 var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
91735 var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
91736 if (shouldEmitUnderscoreUnderscoreESModule()) {
91737 ts.append(statements, createUnderscoreUnderscoreESModule());
91738 }
91739 if (ts.length(currentModuleInfo.exportedNames)) {
91740 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())));
91741 }
91742 ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
91743 ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
91744 addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
91745 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
91746 var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
91747 ts.addEmitHelpers(updated, context.readEmitHelpers());
91748 return updated;
91749 }
91750 /**
91751 * Transforms a SourceFile into an AMD module.
91752 *
91753 * @param node The SourceFile node.
91754 */
91755 function transformAMDModule(node) {
91756 var define = factory.createIdentifier("define");
91757 var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
91758 var jsonSourceFile = ts.isJsonSourceFile(node) && node;
91759 // An AMD define function has the following shape:
91760 //
91761 // define(id?, dependencies?, factory);
91762 //
91763 // This has the shape of the following:
91764 //
91765 // define(name, ["module1", "module2"], function (module1Alias) { ... }
91766 //
91767 // The location of the alias in the parameter list in the factory function needs to
91768 // match the position of the module name in the dependency list.
91769 //
91770 // To ensure this is true in cases of modules with no aliases, e.g.:
91771 //
91772 // import "module"
91773 //
91774 // or
91775 //
91776 // /// <amd-dependency path= "a.css" />
91777 //
91778 // we need to add modules without alias names to the end of the dependencies list
91779 var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
91780 // Create an updated SourceFile:
91781 //
91782 // define(mofactory.updateSourceFile", "module2"], function ...
91783 var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
91784 factory.createExpressionStatement(factory.createCallExpression(define,
91785 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
91786 // Add the dependency array argument:
91787 //
91788 // ["require", "exports", module1", "module2", ...]
91789 factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArrays([
91790 factory.createStringLiteral("require"),
91791 factory.createStringLiteral("exports")
91792 ], aliasedModuleNames, unaliasedModuleNames)),
91793 // Add the module body function argument:
91794 //
91795 // function (require, exports, module1, module2) ...
91796 jsonSourceFile ?
91797 jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
91798 factory.createFunctionExpression(
91799 /*modifiers*/ undefined,
91800 /*asteriskToken*/ undefined,
91801 /*name*/ undefined,
91802 /*typeParameters*/ undefined, __spreadArrays([
91803 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
91804 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
91805 ], importAliasNames),
91806 /*type*/ undefined, transformAsynchronousModuleBody(node))
91807 ])))
91808 ]),
91809 /*location*/ node.statements));
91810 ts.addEmitHelpers(updated, context.readEmitHelpers());
91811 return updated;
91812 }
91813 /**
91814 * Transforms a SourceFile into a UMD module.
91815 *
91816 * @param node The SourceFile node.
91817 */
91818 function transformUMDModule(node) {
91819 var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
91820 var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
91821 var umdHeader = factory.createFunctionExpression(
91822 /*modifiers*/ undefined,
91823 /*asteriskToken*/ undefined,
91824 /*name*/ undefined,
91825 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")],
91826 /*type*/ undefined, ts.setTextRange(factory.createBlock([
91827 factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([
91828 factory.createVariableStatement(
91829 /*modifiers*/ undefined, [
91830 factory.createVariableDeclaration("v",
91831 /*exclamationToken*/ undefined,
91832 /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("factory"),
91833 /*typeArguments*/ undefined, [
91834 factory.createIdentifier("require"),
91835 factory.createIdentifier("exports")
91836 ]))
91837 ]),
91838 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 */)
91839 ]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
91840 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"),
91841 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
91842 factory.createArrayLiteralExpression(__spreadArrays([
91843 factory.createStringLiteral("require"),
91844 factory.createStringLiteral("exports")
91845 ], aliasedModuleNames, unaliasedModuleNames)),
91846 factory.createIdentifier("factory")
91847 ])))
91848 ])))
91849 ],
91850 /*multiLine*/ true),
91851 /*location*/ undefined));
91852 // Create an updated SourceFile:
91853 //
91854 // (function (factory) {
91855 // if (typeof module === "object" && typeof module.exports === "object") {
91856 // var v = factory(require, exports);
91857 // if (v !== undefined) module.exports = v;
91858 // }
91859 // else if (typeof define === 'function' && define.amd) {
91860 // define(["require", "exports"], factory);
91861 // }
91862 // })(function ...)
91863 var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
91864 factory.createExpressionStatement(factory.createCallExpression(umdHeader,
91865 /*typeArguments*/ undefined, [
91866 // Add the module body function argument:
91867 //
91868 // function (require, exports) ...
91869 factory.createFunctionExpression(
91870 /*modifiers*/ undefined,
91871 /*asteriskToken*/ undefined,
91872 /*name*/ undefined,
91873 /*typeParameters*/ undefined, __spreadArrays([
91874 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
91875 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
91876 ], importAliasNames),
91877 /*type*/ undefined, transformAsynchronousModuleBody(node))
91878 ]))
91879 ]),
91880 /*location*/ node.statements));
91881 ts.addEmitHelpers(updated, context.readEmitHelpers());
91882 return updated;
91883 }
91884 /**
91885 * Collect the additional asynchronous dependencies for the module.
91886 *
91887 * @param node The source file.
91888 * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
91889 */
91890 function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
91891 // names of modules with corresponding parameter in the factory function
91892 var aliasedModuleNames = [];
91893 // names of modules with no corresponding parameters in factory function
91894 var unaliasedModuleNames = [];
91895 // names of the parameters in the factory function; these
91896 // parameters need to match the indexes of the corresponding
91897 // module names in aliasedModuleNames.
91898 var importAliasNames = [];
91899 // Fill in amd-dependency tags
91900 for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
91901 var amdDependency = _a[_i];
91902 if (amdDependency.name) {
91903 aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
91904 importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
91905 }
91906 else {
91907 unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
91908 }
91909 }
91910 for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
91911 var importNode = _c[_b];
91912 // Find the name of the external module
91913 var externalModuleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
91914 // Find the name of the module alias, if there is one
91915 var importAliasName = ts.getLocalNameForExternalImport(factory, importNode, currentSourceFile);
91916 // It is possible that externalModuleName is undefined if it is not string literal.
91917 // This can happen in the invalid import syntax.
91918 // E.g : "import * from alias from 'someLib';"
91919 if (externalModuleName) {
91920 if (includeNonAmdDependencies && importAliasName) {
91921 // Set emitFlags on the name of the classDeclaration
91922 // This is so that when printer will not substitute the identifier
91923 ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
91924 aliasedModuleNames.push(externalModuleName);
91925 importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
91926 }
91927 else {
91928 unaliasedModuleNames.push(externalModuleName);
91929 }
91930 }
91931 }
91932 return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
91933 }
91934 function getAMDImportExpressionForImport(node) {
91935 if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
91936 return undefined;
91937 }
91938 var name = ts.getLocalNameForExternalImport(factory, node, currentSourceFile); // TODO: GH#18217
91939 var expr = getHelperExpressionForImport(node, name);
91940 if (expr === name) {
91941 return undefined;
91942 }
91943 return factory.createExpressionStatement(factory.createAssignment(name, expr));
91944 }
91945 /**
91946 * Transforms a SourceFile into an AMD or UMD module body.
91947 *
91948 * @param node The SourceFile node.
91949 */
91950 function transformAsynchronousModuleBody(node) {
91951 startLexicalEnvironment();
91952 var statements = [];
91953 var statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
91954 if (shouldEmitUnderscoreUnderscoreESModule()) {
91955 ts.append(statements, createUnderscoreUnderscoreESModule());
91956 }
91957 if (ts.length(currentModuleInfo.exportedNames)) {
91958 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())));
91959 }
91960 // Visit each statement of the module body.
91961 ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
91962 if (moduleKind === ts.ModuleKind.AMD) {
91963 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
91964 }
91965 ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
91966 // Append the 'export =' statement if provided.
91967 addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
91968 // End the lexical environment for the module body
91969 // and merge any new lexical declarations.
91970 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
91971 var body = factory.createBlock(statements, /*multiLine*/ true);
91972 if (needUMDDynamicImportHelper) {
91973 ts.addEmitHelper(body, dynamicImportUMDHelper);
91974 }
91975 return body;
91976 }
91977 /**
91978 * Adds the down-level representation of `export=` to the statement list if one exists
91979 * in the source file.
91980 *
91981 * @param statements The Statement list to modify.
91982 * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
91983 * return statement.
91984 */
91985 function addExportEqualsIfNeeded(statements, emitAsReturn) {
91986 if (currentModuleInfo.exportEquals) {
91987 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
91988 if (expressionResult) {
91989 if (emitAsReturn) {
91990 var statement = factory.createReturnStatement(expressionResult);
91991 ts.setTextRange(statement, currentModuleInfo.exportEquals);
91992 ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
91993 statements.push(statement);
91994 }
91995 else {
91996 var statement = factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), expressionResult));
91997 ts.setTextRange(statement, currentModuleInfo.exportEquals);
91998 ts.setEmitFlags(statement, 1536 /* NoComments */);
91999 statements.push(statement);
92000 }
92001 }
92002 }
92003 }
92004 //
92005 // Top-Level Source Element Visitors
92006 //
92007 /**
92008 * Visits a node at the top level of the source file.
92009 *
92010 * @param node The node to visit.
92011 */
92012 function sourceElementVisitor(node) {
92013 switch (node.kind) {
92014 case 258 /* ImportDeclaration */:
92015 return visitImportDeclaration(node);
92016 case 257 /* ImportEqualsDeclaration */:
92017 return visitImportEqualsDeclaration(node);
92018 case 264 /* ExportDeclaration */:
92019 return visitExportDeclaration(node);
92020 case 263 /* ExportAssignment */:
92021 return visitExportAssignment(node);
92022 case 229 /* VariableStatement */:
92023 return visitVariableStatement(node);
92024 case 248 /* FunctionDeclaration */:
92025 return visitFunctionDeclaration(node);
92026 case 249 /* ClassDeclaration */:
92027 return visitClassDeclaration(node);
92028 case 333 /* MergeDeclarationMarker */:
92029 return visitMergeDeclarationMarker(node);
92030 case 334 /* EndOfDeclarationMarker */:
92031 return visitEndOfDeclarationMarker(node);
92032 default:
92033 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
92034 }
92035 }
92036 function moduleExpressionElementVisitor(node) {
92037 // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
92038 // as export/import statements are only transformed at the top level of a file.
92039 if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
92040 return node;
92041 }
92042 if (ts.isImportCall(node)) {
92043 return visitImportCallExpression(node);
92044 }
92045 else if (ts.isDestructuringAssignment(node)) {
92046 return visitDestructuringAssignment(node);
92047 }
92048 else {
92049 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
92050 }
92051 }
92052 function destructuringNeedsFlattening(node) {
92053 if (ts.isObjectLiteralExpression(node)) {
92054 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
92055 var elem = _a[_i];
92056 switch (elem.kind) {
92057 case 285 /* PropertyAssignment */:
92058 if (destructuringNeedsFlattening(elem.initializer)) {
92059 return true;
92060 }
92061 break;
92062 case 286 /* ShorthandPropertyAssignment */:
92063 if (destructuringNeedsFlattening(elem.name)) {
92064 return true;
92065 }
92066 break;
92067 case 287 /* SpreadAssignment */:
92068 if (destructuringNeedsFlattening(elem.expression)) {
92069 return true;
92070 }
92071 break;
92072 case 164 /* MethodDeclaration */:
92073 case 166 /* GetAccessor */:
92074 case 167 /* SetAccessor */:
92075 return false;
92076 default: ts.Debug.assertNever(elem, "Unhandled object member kind");
92077 }
92078 }
92079 }
92080 else if (ts.isArrayLiteralExpression(node)) {
92081 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
92082 var elem = _c[_b];
92083 if (ts.isSpreadElement(elem)) {
92084 if (destructuringNeedsFlattening(elem.expression)) {
92085 return true;
92086 }
92087 }
92088 else if (destructuringNeedsFlattening(elem)) {
92089 return true;
92090 }
92091 }
92092 }
92093 else if (ts.isIdentifier(node)) {
92094 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
92095 }
92096 return false;
92097 }
92098 function visitDestructuringAssignment(node) {
92099 if (destructuringNeedsFlattening(node.left)) {
92100 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
92101 }
92102 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
92103 }
92104 function visitImportCallExpression(node) {
92105 var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
92106 var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
92107 switch (compilerOptions.module) {
92108 case ts.ModuleKind.AMD:
92109 return createImportCallExpressionAMD(argument, containsLexicalThis);
92110 case ts.ModuleKind.UMD:
92111 return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis);
92112 case ts.ModuleKind.CommonJS:
92113 default:
92114 return createImportCallExpressionCommonJS(argument, containsLexicalThis);
92115 }
92116 }
92117 function createImportCallExpressionUMD(arg, containsLexicalThis) {
92118 // (function (factory) {
92119 // ... (regular UMD)
92120 // }
92121 // })(function (require, exports, useSyncRequire) {
92122 // "use strict";
92123 // Object.defineProperty(exports, "__esModule", { value: true });
92124 // var __syncRequire = typeof module === "object" && typeof module.exports === "object";
92125 // var __resolved = new Promise(function (resolve) { resolve(); });
92126 // .....
92127 // __syncRequire
92128 // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
92129 // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
92130 // });
92131 needUMDDynamicImportHelper = true;
92132 if (ts.isSimpleCopiableExpression(arg)) {
92133 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536 /* NoComments */);
92134 return factory.createConditionalExpression(
92135 /*condition*/ factory.createIdentifier("__syncRequire"),
92136 /*questionToken*/ undefined,
92137 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis),
92138 /*colonToken*/ undefined,
92139 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
92140 }
92141 else {
92142 var temp = factory.createTempVariable(hoistVariableDeclaration);
92143 return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
92144 /*condition*/ factory.createIdentifier("__syncRequire"),
92145 /*questionToken*/ undefined,
92146 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis),
92147 /*colonToken*/ undefined,
92148 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
92149 }
92150 }
92151 function createImportCallExpressionAMD(arg, containsLexicalThis) {
92152 // improt("./blah")
92153 // emit as
92154 // define(["require", "exports", "blah"], function (require, exports) {
92155 // ...
92156 // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
92157 // });
92158 var resolve = factory.createUniqueName("resolve");
92159 var reject = factory.createUniqueName("reject");
92160 var parameters = [
92161 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
92162 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
92163 ];
92164 var body = factory.createBlock([
92165 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"),
92166 /*typeArguments*/ undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]))
92167 ]);
92168 var func;
92169 if (languageVersion >= 2 /* ES2015 */) {
92170 func = factory.createArrowFunction(
92171 /*modifiers*/ undefined,
92172 /*typeParameters*/ undefined, parameters,
92173 /*type*/ undefined,
92174 /*equalsGreaterThanToken*/ undefined, body);
92175 }
92176 else {
92177 func = factory.createFunctionExpression(
92178 /*modifiers*/ undefined,
92179 /*asteriskToken*/ undefined,
92180 /*name*/ undefined,
92181 /*typeParameters*/ undefined, parameters,
92182 /*type*/ undefined, body);
92183 // if there is a lexical 'this' in the import call arguments, ensure we indicate
92184 // that this new function expression indicates it captures 'this' so that the
92185 // es2015 transformer will properly substitute 'this' with '_this'.
92186 if (containsLexicalThis) {
92187 ts.setEmitFlags(func, 8 /* CapturesThis */);
92188 }
92189 }
92190 var promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
92191 if (compilerOptions.esModuleInterop) {
92192 return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
92193 }
92194 return promise;
92195 }
92196 function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
92197 // import("./blah")
92198 // emit as
92199 // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
92200 // We have to wrap require in then callback so that require is done in asynchronously
92201 // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
92202 var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
92203 var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
92204 if (compilerOptions.esModuleInterop) {
92205 requireCall = emitHelpers().createImportStarHelper(requireCall);
92206 }
92207 var func;
92208 if (languageVersion >= 2 /* ES2015 */) {
92209 func = factory.createArrowFunction(
92210 /*modifiers*/ undefined,
92211 /*typeParameters*/ undefined,
92212 /*parameters*/ [],
92213 /*type*/ undefined,
92214 /*equalsGreaterThanToken*/ undefined, requireCall);
92215 }
92216 else {
92217 func = factory.createFunctionExpression(
92218 /*modifiers*/ undefined,
92219 /*asteriskToken*/ undefined,
92220 /*name*/ undefined,
92221 /*typeParameters*/ undefined,
92222 /*parameters*/ [],
92223 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]));
92224 // if there is a lexical 'this' in the import call arguments, ensure we indicate
92225 // that this new function expression indicates it captures 'this' so that the
92226 // es2015 transformer will properly substitute 'this' with '_this'.
92227 if (containsLexicalThis) {
92228 ts.setEmitFlags(func, 8 /* CapturesThis */);
92229 }
92230 }
92231 return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
92232 }
92233 function getHelperExpressionForExport(node, innerExpr) {
92234 if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
92235 return innerExpr;
92236 }
92237 if (ts.getExportNeedsImportStarHelper(node)) {
92238 return emitHelpers().createImportStarHelper(innerExpr);
92239 }
92240 return innerExpr;
92241 }
92242 function getHelperExpressionForImport(node, innerExpr) {
92243 if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
92244 return innerExpr;
92245 }
92246 if (ts.getImportNeedsImportStarHelper(node)) {
92247 return emitHelpers().createImportStarHelper(innerExpr);
92248 }
92249 if (ts.getImportNeedsImportDefaultHelper(node)) {
92250 return emitHelpers().createImportDefaultHelper(innerExpr);
92251 }
92252 return innerExpr;
92253 }
92254 /**
92255 * Visits an ImportDeclaration node.
92256 *
92257 * @param node The node to visit.
92258 */
92259 function visitImportDeclaration(node) {
92260 var statements;
92261 var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
92262 if (moduleKind !== ts.ModuleKind.AMD) {
92263 if (!node.importClause) {
92264 // import "mod";
92265 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
92266 }
92267 else {
92268 var variables = [];
92269 if (namespaceDeclaration && !ts.isDefaultImport(node)) {
92270 // import * as n from "mod";
92271 variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name),
92272 /*exclamationToken*/ undefined,
92273 /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
92274 }
92275 else {
92276 // import d from "mod";
92277 // import { x, y } from "mod";
92278 // import d, { x, y } from "mod";
92279 // import d, * as n from "mod";
92280 variables.push(factory.createVariableDeclaration(factory.getGeneratedNameForNode(node),
92281 /*exclamationToken*/ undefined,
92282 /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
92283 if (namespaceDeclaration && ts.isDefaultImport(node)) {
92284 variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name),
92285 /*exclamationToken*/ undefined,
92286 /*type*/ undefined, factory.getGeneratedNameForNode(node)));
92287 }
92288 }
92289 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
92290 /*modifiers*/ undefined, factory.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)),
92291 /*location*/ node),
92292 /*original*/ node));
92293 }
92294 }
92295 else if (namespaceDeclaration && ts.isDefaultImport(node)) {
92296 // import d, * as n from "mod";
92297 statements = ts.append(statements, factory.createVariableStatement(
92298 /*modifiers*/ undefined, factory.createVariableDeclarationList([
92299 ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name),
92300 /*exclamationToken*/ undefined,
92301 /*type*/ undefined, factory.getGeneratedNameForNode(node)),
92302 /*location*/ node),
92303 /*original*/ node)
92304 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
92305 }
92306 if (hasAssociatedEndOfDeclarationMarker(node)) {
92307 // Defer exports until we encounter an EndOfDeclarationMarker node
92308 var id = ts.getOriginalNodeId(node);
92309 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
92310 }
92311 else {
92312 statements = appendExportsOfImportDeclaration(statements, node);
92313 }
92314 return ts.singleOrMany(statements);
92315 }
92316 /**
92317 * Creates a `require()` call to import an external module.
92318 *
92319 * @param importNode The declararation to import.
92320 */
92321 function createRequireCall(importNode) {
92322 var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
92323 var args = [];
92324 if (moduleName) {
92325 args.push(moduleName);
92326 }
92327 return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, args);
92328 }
92329 /**
92330 * Visits an ImportEqualsDeclaration node.
92331 *
92332 * @param node The node to visit.
92333 */
92334 function visitImportEqualsDeclaration(node) {
92335 ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
92336 var statements;
92337 if (moduleKind !== ts.ModuleKind.AMD) {
92338 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
92339 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
92340 }
92341 else {
92342 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
92343 /*modifiers*/ undefined, factory.createVariableDeclarationList([
92344 factory.createVariableDeclaration(factory.cloneNode(node.name),
92345 /*exclamationToken*/ undefined,
92346 /*type*/ undefined, createRequireCall(node))
92347 ],
92348 /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
92349 }
92350 }
92351 else {
92352 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
92353 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(node), factory.getLocalName(node))), node), node));
92354 }
92355 }
92356 if (hasAssociatedEndOfDeclarationMarker(node)) {
92357 // Defer exports until we encounter an EndOfDeclarationMarker node
92358 var id = ts.getOriginalNodeId(node);
92359 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
92360 }
92361 else {
92362 statements = appendExportsOfImportEqualsDeclaration(statements, node);
92363 }
92364 return ts.singleOrMany(statements);
92365 }
92366 /**
92367 * Visits an ExportDeclaration node.
92368 *
92369 * @param The node to visit.
92370 */
92371 function visitExportDeclaration(node) {
92372 if (!node.moduleSpecifier) {
92373 // Elide export declarations with no module specifier as they are handled
92374 // elsewhere.
92375 return undefined;
92376 }
92377 var generatedName = factory.getGeneratedNameForNode(node);
92378 if (node.exportClause && ts.isNamedExports(node.exportClause)) {
92379 var statements = [];
92380 // export { x, y } from "mod";
92381 if (moduleKind !== ts.ModuleKind.AMD) {
92382 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
92383 /*modifiers*/ undefined, factory.createVariableDeclarationList([
92384 factory.createVariableDeclaration(generatedName,
92385 /*exclamationToken*/ undefined,
92386 /*type*/ undefined, createRequireCall(node))
92387 ])),
92388 /*location*/ node),
92389 /* original */ node));
92390 }
92391 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
92392 var specifier = _a[_i];
92393 if (languageVersion === 0 /* ES3 */) {
92394 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));
92395 }
92396 else {
92397 var exportNeedsImportDefault = !!compilerOptions.esModuleInterop &&
92398 !(ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) &&
92399 ts.idText(specifier.propertyName || specifier.name) === "default";
92400 var exportedValue = factory.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name);
92401 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
92402 }
92403 }
92404 return ts.singleOrMany(statements);
92405 }
92406 else if (node.exportClause) {
92407 var statements = [];
92408 // export * as ns from "mod";
92409 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== ts.ModuleKind.AMD ?
92410 createRequireCall(node) :
92411 factory.createIdentifier(ts.idText(node.exportClause.name))))), node), node));
92412 return ts.singleOrMany(statements);
92413 }
92414 else {
92415 // export * from "mod";
92416 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
92417 }
92418 }
92419 /**
92420 * Visits an ExportAssignment node.
92421 *
92422 * @param node The node to visit.
92423 */
92424 function visitExportAssignment(node) {
92425 if (node.isExportEquals) {
92426 return undefined;
92427 }
92428 var statements;
92429 var original = node.original;
92430 if (original && hasAssociatedEndOfDeclarationMarker(original)) {
92431 // Defer exports until we encounter an EndOfDeclarationMarker node
92432 var id = ts.getOriginalNodeId(node);
92433 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
92434 }
92435 else {
92436 statements = appendExportStatement(statements, factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
92437 }
92438 return ts.singleOrMany(statements);
92439 }
92440 /**
92441 * Visits a FunctionDeclaration node.
92442 *
92443 * @param node The node to visit.
92444 */
92445 function visitFunctionDeclaration(node) {
92446 var statements;
92447 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
92448 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
92449 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
92450 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
92451 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
92452 /*location*/ node),
92453 /*original*/ node));
92454 }
92455 else {
92456 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
92457 }
92458 if (hasAssociatedEndOfDeclarationMarker(node)) {
92459 // Defer exports until we encounter an EndOfDeclarationMarker node
92460 var id = ts.getOriginalNodeId(node);
92461 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
92462 }
92463 else {
92464 statements = appendExportsOfHoistedDeclaration(statements, node);
92465 }
92466 return ts.singleOrMany(statements);
92467 }
92468 /**
92469 * Visits a ClassDeclaration node.
92470 *
92471 * @param node The node to visit.
92472 */
92473 function visitClassDeclaration(node) {
92474 var statements;
92475 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
92476 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(
92477 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
92478 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
92479 }
92480 else {
92481 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
92482 }
92483 if (hasAssociatedEndOfDeclarationMarker(node)) {
92484 // Defer exports until we encounter an EndOfDeclarationMarker node
92485 var id = ts.getOriginalNodeId(node);
92486 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
92487 }
92488 else {
92489 statements = appendExportsOfHoistedDeclaration(statements, node);
92490 }
92491 return ts.singleOrMany(statements);
92492 }
92493 /**
92494 * Visits a VariableStatement node.
92495 *
92496 * @param node The node to visit.
92497 */
92498 function visitVariableStatement(node) {
92499 var statements;
92500 var variables;
92501 var expressions;
92502 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
92503 var modifiers = void 0;
92504 // If we're exporting these variables, then these just become assignments to 'exports.x'.
92505 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
92506 var variable = _a[_i];
92507 if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
92508 if (!modifiers) {
92509 modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
92510 }
92511 variables = ts.append(variables, variable);
92512 }
92513 else if (variable.initializer) {
92514 expressions = ts.append(expressions, transformInitializedVariable(variable));
92515 }
92516 }
92517 if (variables) {
92518 statements = ts.append(statements, factory.updateVariableStatement(node, modifiers, factory.updateVariableDeclarationList(node.declarationList, variables)));
92519 }
92520 if (expressions) {
92521 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node));
92522 }
92523 }
92524 else {
92525 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
92526 }
92527 if (hasAssociatedEndOfDeclarationMarker(node)) {
92528 // Defer exports until we encounter an EndOfDeclarationMarker node
92529 var id = ts.getOriginalNodeId(node);
92530 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
92531 }
92532 else {
92533 statements = appendExportsOfVariableStatement(statements, node);
92534 }
92535 return ts.singleOrMany(statements);
92536 }
92537 function createAllExportExpressions(name, value, location) {
92538 var exportedNames = getExports(name);
92539 if (exportedNames) {
92540 // For each additional export of the declaration, apply an export assignment.
92541 var expression = ts.isExportName(name) ? value : factory.createAssignment(name, value);
92542 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
92543 var exportName = exportedNames_1[_i];
92544 // Mark the node to prevent triggering substitution.
92545 ts.setEmitFlags(expression, 4 /* NoSubstitution */);
92546 expression = createExportExpression(exportName, expression, /*location*/ location);
92547 }
92548 return expression;
92549 }
92550 return factory.createAssignment(name, value);
92551 }
92552 /**
92553 * Transforms an exported variable with an initializer into an expression.
92554 *
92555 * @param node The node to transform.
92556 */
92557 function transformInitializedVariable(node) {
92558 if (ts.isBindingPattern(node.name)) {
92559 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
92560 /*visitor*/ undefined, context, 0 /* All */,
92561 /*needsValue*/ false, createAllExportExpressions);
92562 }
92563 else {
92564 return factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), node.name),
92565 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : factory.createVoidZero());
92566 }
92567 }
92568 /**
92569 * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
92570 * and transformed declaration.
92571 *
92572 * @param node The node to visit.
92573 */
92574 function visitMergeDeclarationMarker(node) {
92575 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
92576 // declaration we do not emit a leading variable declaration. To preserve the
92577 // begin/end semantics of the declararation and to properly handle exports
92578 // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
92579 //
92580 // To balance the declaration, add the exports of the elided variable
92581 // statement.
92582 if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 229 /* VariableStatement */) {
92583 var id = ts.getOriginalNodeId(node);
92584 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
92585 }
92586 return node;
92587 }
92588 /**
92589 * Determines whether a node has an associated EndOfDeclarationMarker.
92590 *
92591 * @param node The node to test.
92592 */
92593 function hasAssociatedEndOfDeclarationMarker(node) {
92594 return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
92595 }
92596 /**
92597 * Visits a DeclarationMarker used as a placeholder for the end of a transformed
92598 * declaration.
92599 *
92600 * @param node The node to visit.
92601 */
92602 function visitEndOfDeclarationMarker(node) {
92603 // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
92604 // end of the transformed declaration. We use this marker to emit any deferred exports
92605 // of the declaration.
92606 var id = ts.getOriginalNodeId(node);
92607 var statements = deferredExports[id];
92608 if (statements) {
92609 delete deferredExports[id];
92610 return ts.append(statements, node);
92611 }
92612 return node;
92613 }
92614 /**
92615 * Appends the exports of an ImportDeclaration to a statement list, returning the
92616 * statement list.
92617 *
92618 * @param statements A statement list to which the down-level export statements are to be
92619 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92620 * appended.
92621 * @param decl The declaration whose exports are to be recorded.
92622 */
92623 function appendExportsOfImportDeclaration(statements, decl) {
92624 if (currentModuleInfo.exportEquals) {
92625 return statements;
92626 }
92627 var importClause = decl.importClause;
92628 if (!importClause) {
92629 return statements;
92630 }
92631 if (importClause.name) {
92632 statements = appendExportsOfDeclaration(statements, importClause);
92633 }
92634 var namedBindings = importClause.namedBindings;
92635 if (namedBindings) {
92636 switch (namedBindings.kind) {
92637 case 260 /* NamespaceImport */:
92638 statements = appendExportsOfDeclaration(statements, namedBindings);
92639 break;
92640 case 261 /* NamedImports */:
92641 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
92642 var importBinding = _a[_i];
92643 statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
92644 }
92645 break;
92646 }
92647 }
92648 return statements;
92649 }
92650 /**
92651 * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
92652 * statement list.
92653 *
92654 * @param statements A statement list to which the down-level export statements are to be
92655 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92656 * appended.
92657 * @param decl The declaration whose exports are to be recorded.
92658 */
92659 function appendExportsOfImportEqualsDeclaration(statements, decl) {
92660 if (currentModuleInfo.exportEquals) {
92661 return statements;
92662 }
92663 return appendExportsOfDeclaration(statements, decl);
92664 }
92665 /**
92666 * Appends the exports of a VariableStatement to a statement list, returning the statement
92667 * list.
92668 *
92669 * @param statements A statement list to which the down-level export statements are to be
92670 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92671 * appended.
92672 * @param node The VariableStatement whose exports are to be recorded.
92673 */
92674 function appendExportsOfVariableStatement(statements, node) {
92675 if (currentModuleInfo.exportEquals) {
92676 return statements;
92677 }
92678 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
92679 var decl = _a[_i];
92680 statements = appendExportsOfBindingElement(statements, decl);
92681 }
92682 return statements;
92683 }
92684 /**
92685 * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
92686 * returning the statement list.
92687 *
92688 * @param statements A statement list to which the down-level export statements are to be
92689 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92690 * appended.
92691 * @param decl The declaration whose exports are to be recorded.
92692 */
92693 function appendExportsOfBindingElement(statements, decl) {
92694 if (currentModuleInfo.exportEquals) {
92695 return statements;
92696 }
92697 if (ts.isBindingPattern(decl.name)) {
92698 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
92699 var element = _a[_i];
92700 if (!ts.isOmittedExpression(element)) {
92701 statements = appendExportsOfBindingElement(statements, element);
92702 }
92703 }
92704 }
92705 else if (!ts.isGeneratedIdentifier(decl.name)) {
92706 statements = appendExportsOfDeclaration(statements, decl);
92707 }
92708 return statements;
92709 }
92710 /**
92711 * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
92712 * returning the statement list.
92713 *
92714 * @param statements A statement list to which the down-level export statements are to be
92715 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92716 * appended.
92717 * @param decl The declaration whose exports are to be recorded.
92718 */
92719 function appendExportsOfHoistedDeclaration(statements, decl) {
92720 if (currentModuleInfo.exportEquals) {
92721 return statements;
92722 }
92723 if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
92724 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl);
92725 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl);
92726 }
92727 if (decl.name) {
92728 statements = appendExportsOfDeclaration(statements, decl);
92729 }
92730 return statements;
92731 }
92732 /**
92733 * Appends the exports of a declaration to a statement list, returning the statement list.
92734 *
92735 * @param statements A statement list to which the down-level export statements are to be
92736 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92737 * appended.
92738 * @param decl The declaration to export.
92739 */
92740 function appendExportsOfDeclaration(statements, decl, liveBinding) {
92741 var name = factory.getDeclarationName(decl);
92742 var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
92743 if (exportSpecifiers) {
92744 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
92745 var exportSpecifier = exportSpecifiers_1[_i];
92746 statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
92747 }
92748 }
92749 return statements;
92750 }
92751 /**
92752 * Appends the down-level representation of an export to a statement list, returning the
92753 * statement list.
92754 *
92755 * @param statements A statement list to which the down-level export statements are to be
92756 * appended. If `statements` is `undefined`, a new array is allocated if statements are
92757 * appended.
92758 * @param exportName The name of the export.
92759 * @param expression The expression to export.
92760 * @param location The location to use for source maps and comments for the export.
92761 * @param allowComments Whether to allow comments on the export.
92762 */
92763 function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
92764 statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
92765 return statements;
92766 }
92767 function createUnderscoreUnderscoreESModule() {
92768 var statement;
92769 if (languageVersion === 0 /* ES3 */) {
92770 statement = factory.createExpressionStatement(createExportExpression(factory.createIdentifier("__esModule"), factory.createTrue()));
92771 }
92772 else {
92773 statement = factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"),
92774 /*typeArguments*/ undefined, [
92775 factory.createIdentifier("exports"),
92776 factory.createStringLiteral("__esModule"),
92777 factory.createObjectLiteralExpression([
92778 factory.createPropertyAssignment("value", factory.createTrue())
92779 ])
92780 ]));
92781 }
92782 ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
92783 return statement;
92784 }
92785 /**
92786 * Creates a call to the current file's export function to export a value.
92787 *
92788 * @param name The bound name of the export.
92789 * @param value The exported value.
92790 * @param location The location to use for source maps and comments for the export.
92791 * @param allowComments An optional value indicating whether to emit comments for the statement.
92792 */
92793 function createExportStatement(name, value, location, allowComments, liveBinding) {
92794 var statement = ts.setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
92795 ts.startOnNewLine(statement);
92796 if (!allowComments) {
92797 ts.setEmitFlags(statement, 1536 /* NoComments */);
92798 }
92799 return statement;
92800 }
92801 /**
92802 * Creates a call to the current file's export function to export a value.
92803 *
92804 * @param name The bound name of the export.
92805 * @param value The exported value.
92806 * @param location The location to use for source maps and comments for the export.
92807 */
92808 function createExportExpression(name, value, location, liveBinding) {
92809 return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"),
92810 /*typeArguments*/ undefined, [
92811 factory.createIdentifier("exports"),
92812 factory.createStringLiteralFromNode(name),
92813 factory.createObjectLiteralExpression([
92814 factory.createPropertyAssignment("enumerable", factory.createTrue()),
92815 factory.createPropertyAssignment("get", factory.createFunctionExpression(
92816 /*modifiers*/ undefined,
92817 /*asteriskToken*/ undefined,
92818 /*name*/ undefined,
92819 /*typeParameters*/ undefined,
92820 /*parameters*/ [],
92821 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(value)])))
92822 ])
92823 ]) : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(name)), value), location);
92824 }
92825 //
92826 // Modifier Visitors
92827 //
92828 /**
92829 * Visit nodes to elide module-specific modifiers.
92830 *
92831 * @param node The node to visit.
92832 */
92833 function modifierVisitor(node) {
92834 // Elide module-specific modifiers.
92835 switch (node.kind) {
92836 case 92 /* ExportKeyword */:
92837 case 87 /* DefaultKeyword */:
92838 return undefined;
92839 }
92840 return node;
92841 }
92842 //
92843 // Emit Notification
92844 //
92845 /**
92846 * Hook for node emit notifications.
92847 *
92848 * @param hint A hint as to the intended usage of the node.
92849 * @param node The node to emit.
92850 * @param emit A callback used to emit the node in the printer.
92851 */
92852 function onEmitNode(hint, node, emitCallback) {
92853 if (node.kind === 294 /* SourceFile */) {
92854 currentSourceFile = node;
92855 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
92856 noSubstitution = [];
92857 previousOnEmitNode(hint, node, emitCallback);
92858 currentSourceFile = undefined;
92859 currentModuleInfo = undefined;
92860 noSubstitution = undefined;
92861 }
92862 else {
92863 previousOnEmitNode(hint, node, emitCallback);
92864 }
92865 }
92866 //
92867 // Substitutions
92868 //
92869 /**
92870 * Hooks node substitutions.
92871 *
92872 * @param hint A hint as to the intended usage of the node.
92873 * @param node The node to substitute.
92874 */
92875 function onSubstituteNode(hint, node) {
92876 node = previousOnSubstituteNode(hint, node);
92877 if (node.id && noSubstitution[node.id]) {
92878 return node;
92879 }
92880 if (hint === 1 /* Expression */) {
92881 return substituteExpression(node);
92882 }
92883 else if (ts.isShorthandPropertyAssignment(node)) {
92884 return substituteShorthandPropertyAssignment(node);
92885 }
92886 return node;
92887 }
92888 /**
92889 * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
92890 * or exported symbol.
92891 *
92892 * @param node The node to substitute.
92893 */
92894 function substituteShorthandPropertyAssignment(node) {
92895 var name = node.name;
92896 var exportedOrImportedName = substituteExpressionIdentifier(name);
92897 if (exportedOrImportedName !== name) {
92898 // A shorthand property with an assignment initializer is probably part of a
92899 // destructuring assignment
92900 if (node.objectAssignmentInitializer) {
92901 var initializer = factory.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
92902 return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
92903 }
92904 return ts.setTextRange(factory.createPropertyAssignment(name, exportedOrImportedName), node);
92905 }
92906 return node;
92907 }
92908 /**
92909 * Substitution for an Expression that may contain an imported or exported symbol.
92910 *
92911 * @param node The node to substitute.
92912 */
92913 function substituteExpression(node) {
92914 switch (node.kind) {
92915 case 78 /* Identifier */:
92916 return substituteExpressionIdentifier(node);
92917 case 213 /* BinaryExpression */:
92918 return substituteBinaryExpression(node);
92919 case 212 /* PostfixUnaryExpression */:
92920 case 211 /* PrefixUnaryExpression */:
92921 return substituteUnaryExpression(node);
92922 }
92923 return node;
92924 }
92925 /**
92926 * Substitution for an Identifier expression that may contain an imported or exported
92927 * symbol.
92928 *
92929 * @param node The node to substitute.
92930 */
92931 function substituteExpressionIdentifier(node) {
92932 if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
92933 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
92934 if (externalHelpersModuleName) {
92935 return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
92936 }
92937 return node;
92938 }
92939 if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
92940 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
92941 if (exportContainer && exportContainer.kind === 294 /* SourceFile */) {
92942 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)),
92943 /*location*/ node);
92944 }
92945 var importDeclaration = resolver.getReferencedImportDeclaration(node);
92946 if (importDeclaration) {
92947 if (ts.isImportClause(importDeclaration)) {
92948 return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")),
92949 /*location*/ node);
92950 }
92951 else if (ts.isImportSpecifier(importDeclaration)) {
92952 var name = importDeclaration.propertyName || importDeclaration.name;
92953 return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(name)),
92954 /*location*/ node);
92955 }
92956 }
92957 }
92958 return node;
92959 }
92960 /**
92961 * Substitution for a BinaryExpression that may contain an imported or exported symbol.
92962 *
92963 * @param node The node to substitute.
92964 */
92965 function substituteBinaryExpression(node) {
92966 // When we see an assignment expression whose left-hand side is an exported symbol,
92967 // we should ensure all exports of that symbol are updated with the correct value.
92968 //
92969 // - We do not substitute generated identifiers for any reason.
92970 // - We do not substitute identifiers tagged with the LocalName flag.
92971 // - We do not substitute identifiers that were originally the name of an enum or
92972 // namespace due to how they are transformed in TypeScript.
92973 // - We only substitute identifiers that are exported at the top level.
92974 if (ts.isAssignmentOperator(node.operatorToken.kind)
92975 && ts.isIdentifier(node.left)
92976 && !ts.isGeneratedIdentifier(node.left)
92977 && !ts.isLocalName(node.left)
92978 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
92979 var exportedNames = getExports(node.left);
92980 if (exportedNames) {
92981 // For each additional export of the declaration, apply an export assignment.
92982 var expression = node;
92983 for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
92984 var exportName = exportedNames_2[_i];
92985 // Mark the node to prevent triggering this rule again.
92986 noSubstitution[ts.getNodeId(expression)] = true;
92987 expression = createExportExpression(exportName, expression, /*location*/ node);
92988 }
92989 return expression;
92990 }
92991 }
92992 return node;
92993 }
92994 /**
92995 * Substitution for a UnaryExpression that may contain an imported or exported symbol.
92996 *
92997 * @param node The node to substitute.
92998 */
92999 function substituteUnaryExpression(node) {
93000 // When we see a prefix or postfix increment expression whose operand is an exported
93001 // symbol, we should ensure all exports of that symbol are updated with the correct
93002 // value.
93003 //
93004 // - We do not substitute generated identifiers for any reason.
93005 // - We do not substitute identifiers tagged with the LocalName flag.
93006 // - We do not substitute identifiers that were originally the name of an enum or
93007 // namespace due to how they are transformed in TypeScript.
93008 // - We only substitute identifiers that are exported at the top level.
93009 if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
93010 && ts.isIdentifier(node.operand)
93011 && !ts.isGeneratedIdentifier(node.operand)
93012 && !ts.isLocalName(node.operand)
93013 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
93014 var exportedNames = getExports(node.operand);
93015 if (exportedNames) {
93016 var expression = node.kind === 212 /* PostfixUnaryExpression */
93017 ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)),
93018 /*location*/ node)
93019 : node;
93020 for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
93021 var exportName = exportedNames_3[_i];
93022 // Mark the node to prevent triggering this rule again.
93023 noSubstitution[ts.getNodeId(expression)] = true;
93024 expression = createExportExpression(exportName, expression);
93025 }
93026 return expression;
93027 }
93028 }
93029 return node;
93030 }
93031 /**
93032 * Gets the additional exports of a name.
93033 *
93034 * @param name The name.
93035 */
93036 function getExports(name) {
93037 if (!ts.isGeneratedIdentifier(name)) {
93038 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
93039 || resolver.getReferencedValueDeclaration(name);
93040 if (valueDeclaration) {
93041 return currentModuleInfo
93042 && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
93043 }
93044 }
93045 }
93046 }
93047 ts.transformModule = transformModule;
93048 // emit helper for dynamic import
93049 var dynamicImportUMDHelper = {
93050 name: "typescript:dynamicimport-sync-require",
93051 scoped: true,
93052 text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
93053 };
93054})(ts || (ts = {}));
93055/*@internal*/
93056var ts;
93057(function (ts) {
93058 function transformSystemModule(context) {
93059 var factory = context.factory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
93060 var compilerOptions = context.getCompilerOptions();
93061 var resolver = context.getEmitResolver();
93062 var host = context.getEmitHost();
93063 var previousOnSubstituteNode = context.onSubstituteNode;
93064 var previousOnEmitNode = context.onEmitNode;
93065 context.onSubstituteNode = onSubstituteNode;
93066 context.onEmitNode = onEmitNode;
93067 context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols.
93068 context.enableSubstitution(286 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
93069 context.enableSubstitution(213 /* BinaryExpression */); // Substitutes assignments to exported symbols.
93070 context.enableSubstitution(211 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
93071 context.enableSubstitution(212 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
93072 context.enableSubstitution(223 /* MetaProperty */); // Substitutes 'import.meta'
93073 context.enableEmitNotification(294 /* SourceFile */); // Restore state when substituting nodes in a file.
93074 var moduleInfoMap = []; // The ExternalModuleInfo for each file.
93075 var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
93076 var exportFunctionsMap = []; // The export function associated with a source file.
93077 var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
93078 var contextObjectMap = []; // The context object associated with a source file.
93079 var currentSourceFile; // The current file.
93080 var moduleInfo; // ExternalModuleInfo for the current file.
93081 var exportFunction; // The export function for the current file.
93082 var contextObject; // The context object for the current file.
93083 var hoistedStatements;
93084 var enclosingBlockScopedContainer;
93085 var noSubstitution; // Set of nodes for which substitution rules should be ignored.
93086 return ts.chainBundle(context, transformSourceFile);
93087 /**
93088 * Transforms the module aspects of a SourceFile.
93089 *
93090 * @param node The SourceFile node.
93091 */
93092 function transformSourceFile(node) {
93093 if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
93094 return node;
93095 }
93096 var id = ts.getOriginalNodeId(node);
93097 currentSourceFile = node;
93098 enclosingBlockScopedContainer = node;
93099 // System modules have the following shape:
93100 //
93101 // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
93102 //
93103 // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
93104 // is used to publish exported values. 'exports' returns its 'value' argument so in
93105 // most cases expressions that mutate exported values can be rewritten as:
93106 //
93107 // expr -> exports('name', expr)
93108 //
93109 // The only exception in this rule is postfix unary operators,
93110 // see comment to 'substitutePostfixUnaryExpression' for more details
93111 // Collect information about the external module and dependency groups.
93112 moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
93113 // Make sure that the name of the 'exports' function does not conflict with
93114 // existing identifiers.
93115 exportFunction = factory.createUniqueName("exports");
93116 exportFunctionsMap[id] = exportFunction;
93117 contextObject = contextObjectMap[id] = factory.createUniqueName("context");
93118 // Add the body of the module.
93119 var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
93120 var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
93121 var moduleBodyFunction = factory.createFunctionExpression(
93122 /*modifiers*/ undefined,
93123 /*asteriskToken*/ undefined,
93124 /*name*/ undefined,
93125 /*typeParameters*/ undefined, [
93126 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
93127 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
93128 ],
93129 /*type*/ undefined, moduleBodyBlock);
93130 // Write the call to `System.register`
93131 // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
93132 // So the helper will be emit at the correct position instead of at the top of the source-file
93133 var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
93134 var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
93135 var updated = ts.setEmitFlags(factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
93136 factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"),
93137 /*typeArguments*/ undefined, moduleName
93138 ? [moduleName, dependencies, moduleBodyFunction]
93139 : [dependencies, moduleBodyFunction]))
93140 ]), node.statements)), 1024 /* NoTrailingComments */);
93141 if (!ts.outFile(compilerOptions)) {
93142 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
93143 }
93144 if (noSubstitution) {
93145 noSubstitutionMap[id] = noSubstitution;
93146 noSubstitution = undefined;
93147 }
93148 currentSourceFile = undefined;
93149 moduleInfo = undefined;
93150 exportFunction = undefined;
93151 contextObject = undefined;
93152 hoistedStatements = undefined;
93153 enclosingBlockScopedContainer = undefined;
93154 return updated;
93155 }
93156 /**
93157 * Collects the dependency groups for this files imports.
93158 *
93159 * @param externalImports The imports for the file.
93160 */
93161 function collectDependencyGroups(externalImports) {
93162 var groupIndices = new ts.Map();
93163 var dependencyGroups = [];
93164 for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
93165 var externalImport = externalImports_1[_i];
93166 var externalModuleName = ts.getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
93167 if (externalModuleName) {
93168 var text = externalModuleName.text;
93169 var groupIndex = groupIndices.get(text);
93170 if (groupIndex !== undefined) {
93171 // deduplicate/group entries in dependency list by the dependency name
93172 dependencyGroups[groupIndex].externalImports.push(externalImport);
93173 }
93174 else {
93175 groupIndices.set(text, dependencyGroups.length);
93176 dependencyGroups.push({
93177 name: externalModuleName,
93178 externalImports: [externalImport]
93179 });
93180 }
93181 }
93182 }
93183 return dependencyGroups;
93184 }
93185 /**
93186 * Adds the statements for the module body function for the source file.
93187 *
93188 * @param node The source file for the module.
93189 * @param dependencyGroups The grouped dependencies of the module.
93190 */
93191 function createSystemModuleBody(node, dependencyGroups) {
93192 // Shape of the body in system modules:
93193 //
93194 // function (exports) {
93195 // <list of local aliases for imports>
93196 // <hoisted variable declarations>
93197 // <hoisted function declarations>
93198 // return {
93199 // setters: [
93200 // <list of setter function for imports>
93201 // ],
93202 // execute: function() {
93203 // <module statements>
93204 // }
93205 // }
93206 // <temp declarations>
93207 // }
93208 //
93209 // i.e:
93210 //
93211 // import {x} from 'file1'
93212 // var y = 1;
93213 // export function foo() { return y + x(); }
93214 // console.log(y);
93215 //
93216 // Will be transformed to:
93217 //
93218 // function(exports) {
93219 // function foo() { return y + file_1.x(); }
93220 // exports("foo", foo);
93221 // var file_1, y;
93222 // return {
93223 // setters: [
93224 // function(v) { file_1 = v }
93225 // ],
93226 // execute(): function() {
93227 // y = 1;
93228 // console.log(y);
93229 // }
93230 // };
93231 // }
93232 var statements = [];
93233 // We start a new lexical environment in this function body, but *not* in the
93234 // body of the execute function. This allows us to emit temporary declarations
93235 // only in the outer module body and not in the inner one.
93236 startLexicalEnvironment();
93237 // Add any prologue directives.
93238 var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
93239 var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, sourceElementVisitor);
93240 // var __moduleName = context_1 && context_1.id;
93241 statements.push(factory.createVariableStatement(
93242 /*modifiers*/ undefined, factory.createVariableDeclarationList([
93243 factory.createVariableDeclaration("__moduleName",
93244 /*exclamationToken*/ undefined,
93245 /*type*/ undefined, factory.createLogicalAnd(contextObject, factory.createPropertyAccessExpression(contextObject, "id")))
93246 ])));
93247 // Visit the synthetic external helpers import declaration if present
93248 ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
93249 // Visit the statements of the source file, emitting any transformations into
93250 // the `executeStatements` array. We do this *before* we fill the `setters` array
93251 // as we both emit transformations as well as aggregate some data used when creating
93252 // setters. This allows us to reduce the number of times we need to loop through the
93253 // statements of the source file.
93254 var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
93255 // Emit early exports for function declarations.
93256 ts.addRange(statements, hoistedStatements);
93257 // We emit hoisted variables early to align roughly with our previous emit output.
93258 // Two key differences in this approach are:
93259 // - Temporary variables will appear at the top rather than at the bottom of the file
93260 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
93261 var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
93262 var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
93263 factory.createModifiersFromModifierFlags(256 /* Async */) :
93264 undefined;
93265 var moduleObject = factory.createObjectLiteralExpression([
93266 factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
93267 factory.createPropertyAssignment("execute", factory.createFunctionExpression(modifiers,
93268 /*asteriskToken*/ undefined,
93269 /*name*/ undefined,
93270 /*typeParameters*/ undefined,
93271 /*parameters*/ [],
93272 /*type*/ undefined, factory.createBlock(executeStatements, /*multiLine*/ true)))
93273 ], /*multiLine*/ true);
93274 statements.push(factory.createReturnStatement(moduleObject));
93275 return factory.createBlock(statements, /*multiLine*/ true);
93276 }
93277 /**
93278 * Adds an exportStar function to a statement list if it is needed for the file.
93279 *
93280 * @param statements A statement list.
93281 */
93282 function addExportStarIfNeeded(statements) {
93283 if (!moduleInfo.hasExportStarsToExportValues) {
93284 return;
93285 }
93286 // when resolving exports local exported entries/indirect exported entries in the module
93287 // should always win over entries with similar names that were added via star exports
93288 // to support this we store names of local/indirect exported entries in a set.
93289 // this set is used to filter names brought by star expors.
93290 // local names set should only be added if we have anything exported
93291 if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
93292 // no exported declarations (export var ...) or export specifiers (export {x})
93293 // check if we have any non star export declarations.
93294 var hasExportDeclarationWithExportClause = false;
93295 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
93296 var externalImport = _a[_i];
93297 if (externalImport.kind === 264 /* ExportDeclaration */ && externalImport.exportClause) {
93298 hasExportDeclarationWithExportClause = true;
93299 break;
93300 }
93301 }
93302 if (!hasExportDeclarationWithExportClause) {
93303 // we still need to emit exportStar helper
93304 var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
93305 statements.push(exportStarFunction_1);
93306 return exportStarFunction_1.name;
93307 }
93308 }
93309 var exportedNames = [];
93310 if (moduleInfo.exportedNames) {
93311 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
93312 var exportedLocalName = _c[_b];
93313 if (exportedLocalName.escapedText === "default") {
93314 continue;
93315 }
93316 // write name of exported declaration, i.e 'export var x...'
93317 exportedNames.push(factory.createPropertyAssignment(factory.createStringLiteralFromNode(exportedLocalName), factory.createTrue()));
93318 }
93319 }
93320 var exportedNamesStorageRef = factory.createUniqueName("exportedNames");
93321 statements.push(factory.createVariableStatement(
93322 /*modifiers*/ undefined, factory.createVariableDeclarationList([
93323 factory.createVariableDeclaration(exportedNamesStorageRef,
93324 /*exclamationToken*/ undefined,
93325 /*type*/ undefined, factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true))
93326 ])));
93327 var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
93328 statements.push(exportStarFunction);
93329 return exportStarFunction.name;
93330 }
93331 /**
93332 * Creates an exportStar function for the file, with an optional set of excluded local
93333 * names.
93334 *
93335 * @param localNames An optional reference to an object containing a set of excluded local
93336 * names.
93337 */
93338 function createExportStarFunction(localNames) {
93339 var exportStarFunction = factory.createUniqueName("exportStar");
93340 var m = factory.createIdentifier("m");
93341 var n = factory.createIdentifier("n");
93342 var exports = factory.createIdentifier("exports");
93343 var condition = factory.createStrictInequality(n, factory.createStringLiteral("default"));
93344 if (localNames) {
93345 condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"),
93346 /*typeArguments*/ undefined, [n])));
93347 }
93348 return factory.createFunctionDeclaration(
93349 /*decorators*/ undefined,
93350 /*modifiers*/ undefined,
93351 /*asteriskToken*/ undefined, exportStarFunction,
93352 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
93353 /*type*/ undefined, factory.createBlock([
93354 factory.createVariableStatement(
93355 /*modifiers*/ undefined, factory.createVariableDeclarationList([
93356 factory.createVariableDeclaration(exports,
93357 /*exclamationToken*/ undefined,
93358 /*type*/ undefined, factory.createObjectLiteralExpression([]))
93359 ])),
93360 factory.createForInStatement(factory.createVariableDeclarationList([
93361 factory.createVariableDeclaration(n)
93362 ]), m, factory.createBlock([
93363 ts.setEmitFlags(factory.createIfStatement(condition, factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(exports, n), factory.createElementAccessExpression(m, n)))), 1 /* SingleLine */)
93364 ])),
93365 factory.createExpressionStatement(factory.createCallExpression(exportFunction,
93366 /*typeArguments*/ undefined, [exports]))
93367 ], /*multiline*/ true));
93368 }
93369 /**
93370 * Creates an array setter callbacks for each dependency group.
93371 *
93372 * @param exportStarFunction A reference to an exportStarFunction for the file.
93373 * @param dependencyGroups An array of grouped dependencies.
93374 */
93375 function createSettersArray(exportStarFunction, dependencyGroups) {
93376 var setters = [];
93377 for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
93378 var group_2 = dependencyGroups_1[_i];
93379 // derive a unique name for parameter from the first named entry in the group
93380 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(factory, i, currentSourceFile); });
93381 var parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
93382 var statements = [];
93383 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
93384 var entry = _b[_a];
93385 var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217
93386 switch (entry.kind) {
93387 case 258 /* ImportDeclaration */:
93388 if (!entry.importClause) {
93389 // 'import "..."' case
93390 // module is imported only for side-effects, no emit required
93391 break;
93392 }
93393 // falls through
93394 case 257 /* ImportEqualsDeclaration */:
93395 ts.Debug.assert(importVariableName !== undefined);
93396 // save import into the local
93397 statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName)));
93398 break;
93399 case 264 /* ExportDeclaration */:
93400 ts.Debug.assert(importVariableName !== undefined);
93401 if (entry.exportClause) {
93402 if (ts.isNamedExports(entry.exportClause)) {
93403 // export {a, b as c} from 'foo'
93404 //
93405 // emit as:
93406 //
93407 // exports_({
93408 // "a": _["a"],
93409 // "c": _["b"]
93410 // });
93411 var properties = [];
93412 for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
93413 var e = _d[_c];
93414 properties.push(factory.createPropertyAssignment(factory.createStringLiteral(ts.idText(e.name)), factory.createElementAccessExpression(parameterName, factory.createStringLiteral(ts.idText(e.propertyName || e.name)))));
93415 }
93416 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction,
93417 /*typeArguments*/ undefined, [factory.createObjectLiteralExpression(properties, /*multiline*/ true)])));
93418 }
93419 else {
93420 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction,
93421 /*typeArguments*/ undefined, [
93422 factory.createStringLiteral(ts.idText(entry.exportClause.name)),
93423 parameterName
93424 ])));
93425 }
93426 }
93427 else {
93428 // export * from 'foo'
93429 //
93430 // emit as:
93431 //
93432 // exportStar(foo_1_1);
93433 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportStarFunction,
93434 /*typeArguments*/ undefined, [parameterName])));
93435 }
93436 break;
93437 }
93438 }
93439 setters.push(factory.createFunctionExpression(
93440 /*modifiers*/ undefined,
93441 /*asteriskToken*/ undefined,
93442 /*name*/ undefined,
93443 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
93444 /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true)));
93445 }
93446 return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
93447 }
93448 //
93449 // Top-level Source Element Visitors
93450 //
93451 /**
93452 * Visit source elements at the top-level of a module.
93453 *
93454 * @param node The node to visit.
93455 */
93456 function sourceElementVisitor(node) {
93457 switch (node.kind) {
93458 case 258 /* ImportDeclaration */:
93459 return visitImportDeclaration(node);
93460 case 257 /* ImportEqualsDeclaration */:
93461 return visitImportEqualsDeclaration(node);
93462 case 264 /* ExportDeclaration */:
93463 return visitExportDeclaration(node);
93464 case 263 /* ExportAssignment */:
93465 return visitExportAssignment(node);
93466 default:
93467 return nestedElementVisitor(node);
93468 }
93469 }
93470 /**
93471 * Visits an ImportDeclaration node.
93472 *
93473 * @param node The node to visit.
93474 */
93475 function visitImportDeclaration(node) {
93476 var statements;
93477 if (node.importClause) {
93478 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
93479 }
93480 if (hasAssociatedEndOfDeclarationMarker(node)) {
93481 // Defer exports until we encounter an EndOfDeclarationMarker node
93482 var id = ts.getOriginalNodeId(node);
93483 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
93484 }
93485 else {
93486 statements = appendExportsOfImportDeclaration(statements, node);
93487 }
93488 return ts.singleOrMany(statements);
93489 }
93490 function visitExportDeclaration(node) {
93491 ts.Debug.assertIsDefined(node);
93492 return undefined;
93493 }
93494 /**
93495 * Visits an ImportEqualsDeclaration node.
93496 *
93497 * @param node The node to visit.
93498 */
93499 function visitImportEqualsDeclaration(node) {
93500 ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
93501 var statements;
93502 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
93503 if (hasAssociatedEndOfDeclarationMarker(node)) {
93504 // Defer exports until we encounter an EndOfDeclarationMarker node
93505 var id = ts.getOriginalNodeId(node);
93506 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
93507 }
93508 else {
93509 statements = appendExportsOfImportEqualsDeclaration(statements, node);
93510 }
93511 return ts.singleOrMany(statements);
93512 }
93513 /**
93514 * Visits an ExportAssignment node.
93515 *
93516 * @param node The node to visit.
93517 */
93518 function visitExportAssignment(node) {
93519 if (node.isExportEquals) {
93520 // Elide `export=` as it is illegal in a SystemJS module.
93521 return undefined;
93522 }
93523 var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
93524 var original = node.original;
93525 if (original && hasAssociatedEndOfDeclarationMarker(original)) {
93526 // Defer exports until we encounter an EndOfDeclarationMarker node
93527 var id = ts.getOriginalNodeId(node);
93528 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
93529 }
93530 else {
93531 return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
93532 }
93533 }
93534 /**
93535 * Visits a FunctionDeclaration, hoisting it to the outer module body function.
93536 *
93537 * @param node The node to visit.
93538 */
93539 function visitFunctionDeclaration(node) {
93540 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
93541 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),
93542 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration),
93543 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
93544 }
93545 else {
93546 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
93547 }
93548 if (hasAssociatedEndOfDeclarationMarker(node)) {
93549 // Defer exports until we encounter an EndOfDeclarationMarker node
93550 var id = ts.getOriginalNodeId(node);
93551 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
93552 }
93553 else {
93554 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
93555 }
93556 return undefined;
93557 }
93558 /**
93559 * Visits a ClassDeclaration, hoisting its name to the outer module body function.
93560 *
93561 * @param node The node to visit.
93562 */
93563 function visitClassDeclaration(node) {
93564 var statements;
93565 // Hoist the name of the class declaration to the outer module body function.
93566 var name = factory.getLocalName(node);
93567 hoistVariableDeclaration(name);
93568 // Rewrite the class declaration into an assignment of a class expression.
93569 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, destructuringAndImportCallVisitor, ts.isDecorator),
93570 /*modifiers*/ undefined, node.name,
93571 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
93572 if (hasAssociatedEndOfDeclarationMarker(node)) {
93573 // Defer exports until we encounter an EndOfDeclarationMarker node
93574 var id = ts.getOriginalNodeId(node);
93575 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
93576 }
93577 else {
93578 statements = appendExportsOfHoistedDeclaration(statements, node);
93579 }
93580 return ts.singleOrMany(statements);
93581 }
93582 /**
93583 * Visits a variable statement, hoisting declared names to the top-level module body.
93584 * Each declaration is rewritten into an assignment expression.
93585 *
93586 * @param node The node to visit.
93587 */
93588 function visitVariableStatement(node) {
93589 if (!shouldHoistVariableDeclarationList(node.declarationList)) {
93590 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
93591 }
93592 var expressions;
93593 var isExportedDeclaration = ts.hasSyntacticModifier(node, 1 /* Export */);
93594 var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
93595 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
93596 var variable = _a[_i];
93597 if (variable.initializer) {
93598 expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
93599 }
93600 else {
93601 hoistBindingElement(variable);
93602 }
93603 }
93604 var statements;
93605 if (expressions) {
93606 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
93607 }
93608 if (isMarkedDeclaration) {
93609 // Defer exports until we encounter an EndOfDeclarationMarker node
93610 var id = ts.getOriginalNodeId(node);
93611 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
93612 }
93613 else {
93614 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
93615 }
93616 return ts.singleOrMany(statements);
93617 }
93618 /**
93619 * Hoists the declared names of a VariableDeclaration or BindingElement.
93620 *
93621 * @param node The declaration to hoist.
93622 */
93623 function hoistBindingElement(node) {
93624 if (ts.isBindingPattern(node.name)) {
93625 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
93626 var element = _a[_i];
93627 if (!ts.isOmittedExpression(element)) {
93628 hoistBindingElement(element);
93629 }
93630 }
93631 }
93632 else {
93633 hoistVariableDeclaration(factory.cloneNode(node.name));
93634 }
93635 }
93636 /**
93637 * Determines whether a VariableDeclarationList should be hoisted.
93638 *
93639 * @param node The node to test.
93640 */
93641 function shouldHoistVariableDeclarationList(node) {
93642 // hoist only non-block scoped declarations or block scoped declarations parented by source file
93643 return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
93644 && (enclosingBlockScopedContainer.kind === 294 /* SourceFile */
93645 || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
93646 }
93647 /**
93648 * Transform an initialized variable declaration into an expression.
93649 *
93650 * @param node The node to transform.
93651 * @param isExportedDeclaration A value indicating whether the variable is exported.
93652 */
93653 function transformInitializedVariable(node, isExportedDeclaration) {
93654 var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
93655 return ts.isBindingPattern(node.name)
93656 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
93657 /*needsValue*/ false, createAssignment)
93658 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
93659 }
93660 /**
93661 * Creates an assignment expression for an exported variable declaration.
93662 *
93663 * @param name The name of the variable.
93664 * @param value The value of the variable's initializer.
93665 * @param location The source map location for the assignment.
93666 */
93667 function createExportedVariableAssignment(name, value, location) {
93668 return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
93669 }
93670 /**
93671 * Creates an assignment expression for a non-exported variable declaration.
93672 *
93673 * @param name The name of the variable.
93674 * @param value The value of the variable's initializer.
93675 * @param location The source map location for the assignment.
93676 */
93677 function createNonExportedVariableAssignment(name, value, location) {
93678 return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
93679 }
93680 /**
93681 * Creates an assignment expression for a variable declaration.
93682 *
93683 * @param name The name of the variable.
93684 * @param value The value of the variable's initializer.
93685 * @param location The source map location for the assignment.
93686 * @param isExportedDeclaration A value indicating whether the variable is exported.
93687 */
93688 function createVariableAssignment(name, value, location, isExportedDeclaration) {
93689 hoistVariableDeclaration(factory.cloneNode(name));
93690 return isExportedDeclaration
93691 ? createExportExpression(name, preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)))
93692 : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location));
93693 }
93694 /**
93695 * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
93696 * and transformed declaration.
93697 *
93698 * @param node The node to visit.
93699 */
93700 function visitMergeDeclarationMarker(node) {
93701 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
93702 // declaration we do not emit a leading variable declaration. To preserve the
93703 // begin/end semantics of the declararation and to properly handle exports
93704 // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
93705 //
93706 // To balance the declaration, we defer the exports of the elided variable
93707 // statement until we visit this declaration's `EndOfDeclarationMarker`.
93708 if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 229 /* VariableStatement */) {
93709 var id = ts.getOriginalNodeId(node);
93710 var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */);
93711 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
93712 }
93713 return node;
93714 }
93715 /**
93716 * Determines whether a node has an associated EndOfDeclarationMarker.
93717 *
93718 * @param node The node to test.
93719 */
93720 function hasAssociatedEndOfDeclarationMarker(node) {
93721 return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
93722 }
93723 /**
93724 * Visits a DeclarationMarker used as a placeholder for the end of a transformed
93725 * declaration.
93726 *
93727 * @param node The node to visit.
93728 */
93729 function visitEndOfDeclarationMarker(node) {
93730 // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
93731 // end of the transformed declaration. We use this marker to emit any deferred exports
93732 // of the declaration.
93733 var id = ts.getOriginalNodeId(node);
93734 var statements = deferredExports[id];
93735 if (statements) {
93736 delete deferredExports[id];
93737 return ts.append(statements, node);
93738 }
93739 else {
93740 var original = ts.getOriginalNode(node);
93741 if (ts.isModuleOrEnumDeclaration(original)) {
93742 return ts.append(appendExportsOfDeclaration(statements, original), node);
93743 }
93744 }
93745 return node;
93746 }
93747 /**
93748 * Appends the exports of an ImportDeclaration to a statement list, returning the
93749 * statement list.
93750 *
93751 * @param statements A statement list to which the down-level export statements are to be
93752 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93753 * appended.
93754 * @param decl The declaration whose exports are to be recorded.
93755 */
93756 function appendExportsOfImportDeclaration(statements, decl) {
93757 if (moduleInfo.exportEquals) {
93758 return statements;
93759 }
93760 var importClause = decl.importClause;
93761 if (!importClause) {
93762 return statements;
93763 }
93764 if (importClause.name) {
93765 statements = appendExportsOfDeclaration(statements, importClause);
93766 }
93767 var namedBindings = importClause.namedBindings;
93768 if (namedBindings) {
93769 switch (namedBindings.kind) {
93770 case 260 /* NamespaceImport */:
93771 statements = appendExportsOfDeclaration(statements, namedBindings);
93772 break;
93773 case 261 /* NamedImports */:
93774 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
93775 var importBinding = _a[_i];
93776 statements = appendExportsOfDeclaration(statements, importBinding);
93777 }
93778 break;
93779 }
93780 }
93781 return statements;
93782 }
93783 /**
93784 * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
93785 * statement list.
93786 *
93787 * @param statements A statement list to which the down-level export statements are to be
93788 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93789 * appended.
93790 * @param decl The declaration whose exports are to be recorded.
93791 */
93792 function appendExportsOfImportEqualsDeclaration(statements, decl) {
93793 if (moduleInfo.exportEquals) {
93794 return statements;
93795 }
93796 return appendExportsOfDeclaration(statements, decl);
93797 }
93798 /**
93799 * Appends the exports of a VariableStatement to a statement list, returning the statement
93800 * list.
93801 *
93802 * @param statements A statement list to which the down-level export statements are to be
93803 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93804 * appended.
93805 * @param node The VariableStatement whose exports are to be recorded.
93806 * @param exportSelf A value indicating whether to also export each VariableDeclaration of
93807 * `nodes` declaration list.
93808 */
93809 function appendExportsOfVariableStatement(statements, node, exportSelf) {
93810 if (moduleInfo.exportEquals) {
93811 return statements;
93812 }
93813 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
93814 var decl = _a[_i];
93815 if (decl.initializer || exportSelf) {
93816 statements = appendExportsOfBindingElement(statements, decl, exportSelf);
93817 }
93818 }
93819 return statements;
93820 }
93821 /**
93822 * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
93823 * returning the statement list.
93824 *
93825 * @param statements A statement list to which the down-level export statements are to be
93826 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93827 * appended.
93828 * @param decl The declaration whose exports are to be recorded.
93829 * @param exportSelf A value indicating whether to also export the declaration itself.
93830 */
93831 function appendExportsOfBindingElement(statements, decl, exportSelf) {
93832 if (moduleInfo.exportEquals) {
93833 return statements;
93834 }
93835 if (ts.isBindingPattern(decl.name)) {
93836 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
93837 var element = _a[_i];
93838 if (!ts.isOmittedExpression(element)) {
93839 statements = appendExportsOfBindingElement(statements, element, exportSelf);
93840 }
93841 }
93842 }
93843 else if (!ts.isGeneratedIdentifier(decl.name)) {
93844 var excludeName = void 0;
93845 if (exportSelf) {
93846 statements = appendExportStatement(statements, decl.name, factory.getLocalName(decl));
93847 excludeName = ts.idText(decl.name);
93848 }
93849 statements = appendExportsOfDeclaration(statements, decl, excludeName);
93850 }
93851 return statements;
93852 }
93853 /**
93854 * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
93855 * returning the statement list.
93856 *
93857 * @param statements A statement list to which the down-level export statements are to be
93858 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93859 * appended.
93860 * @param decl The declaration whose exports are to be recorded.
93861 */
93862 function appendExportsOfHoistedDeclaration(statements, decl) {
93863 if (moduleInfo.exportEquals) {
93864 return statements;
93865 }
93866 var excludeName;
93867 if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
93868 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createStringLiteral("default") : decl.name;
93869 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl));
93870 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
93871 }
93872 if (decl.name) {
93873 statements = appendExportsOfDeclaration(statements, decl, excludeName);
93874 }
93875 return statements;
93876 }
93877 /**
93878 * Appends the exports of a declaration to a statement list, returning the statement list.
93879 *
93880 * @param statements A statement list to which the down-level export statements are to be
93881 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93882 * appended.
93883 * @param decl The declaration to export.
93884 * @param excludeName An optional name to exclude from exports.
93885 */
93886 function appendExportsOfDeclaration(statements, decl, excludeName) {
93887 if (moduleInfo.exportEquals) {
93888 return statements;
93889 }
93890 var name = factory.getDeclarationName(decl);
93891 var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
93892 if (exportSpecifiers) {
93893 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
93894 var exportSpecifier = exportSpecifiers_2[_i];
93895 if (exportSpecifier.name.escapedText !== excludeName) {
93896 statements = appendExportStatement(statements, exportSpecifier.name, name);
93897 }
93898 }
93899 }
93900 return statements;
93901 }
93902 /**
93903 * Appends the down-level representation of an export to a statement list, returning the
93904 * statement list.
93905 *
93906 * @param statements A statement list to which the down-level export statements are to be
93907 * appended. If `statements` is `undefined`, a new array is allocated if statements are
93908 * appended.
93909 * @param exportName The name of the export.
93910 * @param expression The expression to export.
93911 * @param allowComments Whether to allow comments on the export.
93912 */
93913 function appendExportStatement(statements, exportName, expression, allowComments) {
93914 statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
93915 return statements;
93916 }
93917 /**
93918 * Creates a call to the current file's export function to export a value.
93919 *
93920 * @param name The bound name of the export.
93921 * @param value The exported value.
93922 * @param allowComments An optional value indicating whether to emit comments for the statement.
93923 */
93924 function createExportStatement(name, value, allowComments) {
93925 var statement = factory.createExpressionStatement(createExportExpression(name, value));
93926 ts.startOnNewLine(statement);
93927 if (!allowComments) {
93928 ts.setEmitFlags(statement, 1536 /* NoComments */);
93929 }
93930 return statement;
93931 }
93932 /**
93933 * Creates a call to the current file's export function to export a value.
93934 *
93935 * @param name The bound name of the export.
93936 * @param value The exported value.
93937 */
93938 function createExportExpression(name, value) {
93939 var exportName = ts.isIdentifier(name) ? factory.createStringLiteralFromNode(name) : name;
93940 ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
93941 return ts.setCommentRange(factory.createCallExpression(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
93942 }
93943 //
93944 // Top-Level or Nested Source Element Visitors
93945 //
93946 /**
93947 * Visit nested elements at the top-level of a module.
93948 *
93949 * @param node The node to visit.
93950 */
93951 function nestedElementVisitor(node) {
93952 switch (node.kind) {
93953 case 229 /* VariableStatement */:
93954 return visitVariableStatement(node);
93955 case 248 /* FunctionDeclaration */:
93956 return visitFunctionDeclaration(node);
93957 case 249 /* ClassDeclaration */:
93958 return visitClassDeclaration(node);
93959 case 234 /* ForStatement */:
93960 return visitForStatement(node);
93961 case 235 /* ForInStatement */:
93962 return visitForInStatement(node);
93963 case 236 /* ForOfStatement */:
93964 return visitForOfStatement(node);
93965 case 232 /* DoStatement */:
93966 return visitDoStatement(node);
93967 case 233 /* WhileStatement */:
93968 return visitWhileStatement(node);
93969 case 242 /* LabeledStatement */:
93970 return visitLabeledStatement(node);
93971 case 240 /* WithStatement */:
93972 return visitWithStatement(node);
93973 case 241 /* SwitchStatement */:
93974 return visitSwitchStatement(node);
93975 case 255 /* CaseBlock */:
93976 return visitCaseBlock(node);
93977 case 281 /* CaseClause */:
93978 return visitCaseClause(node);
93979 case 282 /* DefaultClause */:
93980 return visitDefaultClause(node);
93981 case 244 /* TryStatement */:
93982 return visitTryStatement(node);
93983 case 284 /* CatchClause */:
93984 return visitCatchClause(node);
93985 case 227 /* Block */:
93986 return visitBlock(node);
93987 case 333 /* MergeDeclarationMarker */:
93988 return visitMergeDeclarationMarker(node);
93989 case 334 /* EndOfDeclarationMarker */:
93990 return visitEndOfDeclarationMarker(node);
93991 default:
93992 return destructuringAndImportCallVisitor(node);
93993 }
93994 }
93995 /**
93996 * Visits the body of a ForStatement to hoist declarations.
93997 *
93998 * @param node The node to visit.
93999 */
94000 function visitForStatement(node) {
94001 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94002 enclosingBlockScopedContainer = node;
94003 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));
94004 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94005 return node;
94006 }
94007 /**
94008 * Visits the body of a ForInStatement to hoist declarations.
94009 *
94010 * @param node The node to visit.
94011 */
94012 function visitForInStatement(node) {
94013 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94014 enclosingBlockScopedContainer = node;
94015 node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
94016 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94017 return node;
94018 }
94019 /**
94020 * Visits the body of a ForOfStatement to hoist declarations.
94021 *
94022 * @param node The node to visit.
94023 */
94024 function visitForOfStatement(node) {
94025 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94026 enclosingBlockScopedContainer = node;
94027 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));
94028 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94029 return node;
94030 }
94031 /**
94032 * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
94033 * ForOfStatement.
94034 *
94035 * @param node The node to test.
94036 */
94037 function shouldHoistForInitializer(node) {
94038 return ts.isVariableDeclarationList(node)
94039 && shouldHoistVariableDeclarationList(node);
94040 }
94041 /**
94042 * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
94043 *
94044 * @param node The node to visit.
94045 */
94046 function visitForInitializer(node) {
94047 if (shouldHoistForInitializer(node)) {
94048 var expressions = void 0;
94049 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
94050 var variable = _a[_i];
94051 expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
94052 if (!variable.initializer) {
94053 hoistBindingElement(variable);
94054 }
94055 }
94056 return expressions ? factory.inlineExpressions(expressions) : factory.createOmittedExpression();
94057 }
94058 else {
94059 return ts.visitEachChild(node, nestedElementVisitor, context);
94060 }
94061 }
94062 /**
94063 * Visits the body of a DoStatement to hoist declarations.
94064 *
94065 * @param node The node to visit.
94066 */
94067 function visitDoStatement(node) {
94068 return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
94069 }
94070 /**
94071 * Visits the body of a WhileStatement to hoist declarations.
94072 *
94073 * @param node The node to visit.
94074 */
94075 function visitWhileStatement(node) {
94076 return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
94077 }
94078 /**
94079 * Visits the body of a LabeledStatement to hoist declarations.
94080 *
94081 * @param node The node to visit.
94082 */
94083 function visitLabeledStatement(node) {
94084 return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
94085 }
94086 /**
94087 * Visits the body of a WithStatement to hoist declarations.
94088 *
94089 * @param node The node to visit.
94090 */
94091 function visitWithStatement(node) {
94092 return factory.updateWithStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
94093 }
94094 /**
94095 * Visits the body of a SwitchStatement to hoist declarations.
94096 *
94097 * @param node The node to visit.
94098 */
94099 function visitSwitchStatement(node) {
94100 return factory.updateSwitchStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
94101 }
94102 /**
94103 * Visits the body of a CaseBlock to hoist declarations.
94104 *
94105 * @param node The node to visit.
94106 */
94107 function visitCaseBlock(node) {
94108 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94109 enclosingBlockScopedContainer = node;
94110 node = factory.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
94111 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94112 return node;
94113 }
94114 /**
94115 * Visits the body of a CaseClause to hoist declarations.
94116 *
94117 * @param node The node to visit.
94118 */
94119 function visitCaseClause(node) {
94120 return factory.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
94121 }
94122 /**
94123 * Visits the body of a DefaultClause to hoist declarations.
94124 *
94125 * @param node The node to visit.
94126 */
94127 function visitDefaultClause(node) {
94128 return ts.visitEachChild(node, nestedElementVisitor, context);
94129 }
94130 /**
94131 * Visits the body of a TryStatement to hoist declarations.
94132 *
94133 * @param node The node to visit.
94134 */
94135 function visitTryStatement(node) {
94136 return ts.visitEachChild(node, nestedElementVisitor, context);
94137 }
94138 /**
94139 * Visits the body of a CatchClause to hoist declarations.
94140 *
94141 * @param node The node to visit.
94142 */
94143 function visitCatchClause(node) {
94144 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94145 enclosingBlockScopedContainer = node;
94146 node = factory.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
94147 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94148 return node;
94149 }
94150 /**
94151 * Visits the body of a Block to hoist declarations.
94152 *
94153 * @param node The node to visit.
94154 */
94155 function visitBlock(node) {
94156 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
94157 enclosingBlockScopedContainer = node;
94158 node = ts.visitEachChild(node, nestedElementVisitor, context);
94159 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
94160 return node;
94161 }
94162 //
94163 // Destructuring Assignment Visitors
94164 //
94165 /**
94166 * Visit nodes to flatten destructuring assignments to exported symbols.
94167 *
94168 * @param node The node to visit.
94169 */
94170 function destructuringAndImportCallVisitor(node) {
94171 if (ts.isDestructuringAssignment(node)) {
94172 return visitDestructuringAssignment(node);
94173 }
94174 else if (ts.isImportCall(node)) {
94175 return visitImportCallExpression(node);
94176 }
94177 else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
94178 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
94179 }
94180 else {
94181 return node;
94182 }
94183 }
94184 function visitImportCallExpression(node) {
94185 // import("./blah")
94186 // emit as
94187 // System.register([], function (_export, _context) {
94188 // return {
94189 // setters: [],
94190 // execute: () => {
94191 // _context.import('./blah');
94192 // }
94193 // };
94194 // });
94195 return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")),
94196 /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
94197 }
94198 /**
94199 * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
94200 *
94201 * @param node The node to visit.
94202 */
94203 function visitDestructuringAssignment(node) {
94204 if (hasExportedReferenceInDestructuringTarget(node.left)) {
94205 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
94206 /*needsValue*/ true);
94207 }
94208 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
94209 }
94210 /**
94211 * Determines whether the target of a destructuring assigment refers to an exported symbol.
94212 *
94213 * @param node The destructuring target.
94214 */
94215 function hasExportedReferenceInDestructuringTarget(node) {
94216 if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
94217 return hasExportedReferenceInDestructuringTarget(node.left);
94218 }
94219 else if (ts.isSpreadElement(node)) {
94220 return hasExportedReferenceInDestructuringTarget(node.expression);
94221 }
94222 else if (ts.isObjectLiteralExpression(node)) {
94223 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
94224 }
94225 else if (ts.isArrayLiteralExpression(node)) {
94226 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
94227 }
94228 else if (ts.isShorthandPropertyAssignment(node)) {
94229 return hasExportedReferenceInDestructuringTarget(node.name);
94230 }
94231 else if (ts.isPropertyAssignment(node)) {
94232 return hasExportedReferenceInDestructuringTarget(node.initializer);
94233 }
94234 else if (ts.isIdentifier(node)) {
94235 var container = resolver.getReferencedExportContainer(node);
94236 return container !== undefined && container.kind === 294 /* SourceFile */;
94237 }
94238 else {
94239 return false;
94240 }
94241 }
94242 //
94243 // Modifier Visitors
94244 //
94245 /**
94246 * Visit nodes to elide module-specific modifiers.
94247 *
94248 * @param node The node to visit.
94249 */
94250 function modifierVisitor(node) {
94251 switch (node.kind) {
94252 case 92 /* ExportKeyword */:
94253 case 87 /* DefaultKeyword */:
94254 return undefined;
94255 }
94256 return node;
94257 }
94258 //
94259 // Emit Notification
94260 //
94261 /**
94262 * Hook for node emit notifications.
94263 *
94264 * @param hint A hint as to the intended usage of the node.
94265 * @param node The node to emit.
94266 * @param emitCallback A callback used to emit the node in the printer.
94267 */
94268 function onEmitNode(hint, node, emitCallback) {
94269 if (node.kind === 294 /* SourceFile */) {
94270 var id = ts.getOriginalNodeId(node);
94271 currentSourceFile = node;
94272 moduleInfo = moduleInfoMap[id];
94273 exportFunction = exportFunctionsMap[id];
94274 noSubstitution = noSubstitutionMap[id];
94275 contextObject = contextObjectMap[id];
94276 if (noSubstitution) {
94277 delete noSubstitutionMap[id];
94278 }
94279 previousOnEmitNode(hint, node, emitCallback);
94280 currentSourceFile = undefined;
94281 moduleInfo = undefined;
94282 exportFunction = undefined;
94283 contextObject = undefined;
94284 noSubstitution = undefined;
94285 }
94286 else {
94287 previousOnEmitNode(hint, node, emitCallback);
94288 }
94289 }
94290 //
94291 // Substitutions
94292 //
94293 /**
94294 * Hooks node substitutions.
94295 *
94296 * @param hint A hint as to the intended usage of the node.
94297 * @param node The node to substitute.
94298 */
94299 function onSubstituteNode(hint, node) {
94300 node = previousOnSubstituteNode(hint, node);
94301 if (isSubstitutionPrevented(node)) {
94302 return node;
94303 }
94304 if (hint === 1 /* Expression */) {
94305 return substituteExpression(node);
94306 }
94307 else if (hint === 4 /* Unspecified */) {
94308 return substituteUnspecified(node);
94309 }
94310 return node;
94311 }
94312 /**
94313 * Substitute the node, if necessary.
94314 *
94315 * @param node The node to substitute.
94316 */
94317 function substituteUnspecified(node) {
94318 switch (node.kind) {
94319 case 286 /* ShorthandPropertyAssignment */:
94320 return substituteShorthandPropertyAssignment(node);
94321 }
94322 return node;
94323 }
94324 /**
94325 * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
94326 *
94327 * @param node The node to substitute.
94328 */
94329 function substituteShorthandPropertyAssignment(node) {
94330 var name = node.name;
94331 if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
94332 var importDeclaration = resolver.getReferencedImportDeclaration(name);
94333 if (importDeclaration) {
94334 if (ts.isImportClause(importDeclaration)) {
94335 return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default"))),
94336 /*location*/ node);
94337 }
94338 else if (ts.isImportSpecifier(importDeclaration)) {
94339 return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))),
94340 /*location*/ node);
94341 }
94342 }
94343 }
94344 return node;
94345 }
94346 /**
94347 * Substitute the expression, if necessary.
94348 *
94349 * @param node The node to substitute.
94350 */
94351 function substituteExpression(node) {
94352 switch (node.kind) {
94353 case 78 /* Identifier */:
94354 return substituteExpressionIdentifier(node);
94355 case 213 /* BinaryExpression */:
94356 return substituteBinaryExpression(node);
94357 case 211 /* PrefixUnaryExpression */:
94358 case 212 /* PostfixUnaryExpression */:
94359 return substituteUnaryExpression(node);
94360 case 223 /* MetaProperty */:
94361 return substituteMetaProperty(node);
94362 }
94363 return node;
94364 }
94365 /**
94366 * Substitution for an Identifier expression that may contain an imported or exported symbol.
94367 *
94368 * @param node The node to substitute.
94369 */
94370 function substituteExpressionIdentifier(node) {
94371 if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
94372 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
94373 if (externalHelpersModuleName) {
94374 return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
94375 }
94376 return node;
94377 }
94378 // When we see an identifier in an expression position that
94379 // points to an imported symbol, we should substitute a qualified
94380 // reference to the imported symbol if one is needed.
94381 //
94382 // - We do not substitute generated identifiers for any reason.
94383 // - We do not substitute identifiers tagged with the LocalName flag.
94384 if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
94385 var importDeclaration = resolver.getReferencedImportDeclaration(node);
94386 if (importDeclaration) {
94387 if (ts.isImportClause(importDeclaration)) {
94388 return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")),
94389 /*location*/ node);
94390 }
94391 else if (ts.isImportSpecifier(importDeclaration)) {
94392 return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)),
94393 /*location*/ node);
94394 }
94395 }
94396 }
94397 return node;
94398 }
94399 /**
94400 * Substitution for a BinaryExpression that may contain an imported or exported symbol.
94401 *
94402 * @param node The node to substitute.
94403 */
94404 function substituteBinaryExpression(node) {
94405 // When we see an assignment expression whose left-hand side is an exported symbol,
94406 // we should ensure all exports of that symbol are updated with the correct value.
94407 //
94408 // - We do not substitute generated identifiers for any reason.
94409 // - We do not substitute identifiers tagged with the LocalName flag.
94410 // - We do not substitute identifiers that were originally the name of an enum or
94411 // namespace due to how they are transformed in TypeScript.
94412 // - We only substitute identifiers that are exported at the top level.
94413 if (ts.isAssignmentOperator(node.operatorToken.kind)
94414 && ts.isIdentifier(node.left)
94415 && !ts.isGeneratedIdentifier(node.left)
94416 && !ts.isLocalName(node.left)
94417 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
94418 var exportedNames = getExports(node.left);
94419 if (exportedNames) {
94420 // For each additional export of the declaration, apply an export assignment.
94421 var expression = node;
94422 for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
94423 var exportName = exportedNames_4[_i];
94424 expression = createExportExpression(exportName, preventSubstitution(expression));
94425 }
94426 return expression;
94427 }
94428 }
94429 return node;
94430 }
94431 /**
94432 * Substitution for a UnaryExpression that may contain an imported or exported symbol.
94433 *
94434 * @param node The node to substitute.
94435 */
94436 function substituteUnaryExpression(node) {
94437 // When we see a prefix or postfix increment expression whose operand is an exported
94438 // symbol, we should ensure all exports of that symbol are updated with the correct
94439 // value.
94440 //
94441 // - We do not substitute generated identifiers for any reason.
94442 // - We do not substitute identifiers tagged with the LocalName flag.
94443 // - We do not substitute identifiers that were originally the name of an enum or
94444 // namespace due to how they are transformed in TypeScript.
94445 // - We only substitute identifiers that are exported at the top level.
94446 if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
94447 && ts.isIdentifier(node.operand)
94448 && !ts.isGeneratedIdentifier(node.operand)
94449 && !ts.isLocalName(node.operand)
94450 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
94451 var exportedNames = getExports(node.operand);
94452 if (exportedNames) {
94453 var expression = node.kind === 212 /* PostfixUnaryExpression */
94454 ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node)
94455 : node;
94456 for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
94457 var exportName = exportedNames_5[_i];
94458 expression = createExportExpression(exportName, preventSubstitution(expression));
94459 }
94460 if (node.kind === 212 /* PostfixUnaryExpression */) {
94461 expression = node.operator === 45 /* PlusPlusToken */
94462 ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1))
94463 : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1));
94464 }
94465 return expression;
94466 }
94467 }
94468 return node;
94469 }
94470 function substituteMetaProperty(node) {
94471 if (ts.isImportMeta(node)) {
94472 return factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("meta"));
94473 }
94474 return node;
94475 }
94476 /**
94477 * Gets the exports of a name.
94478 *
94479 * @param name The name.
94480 */
94481 function getExports(name) {
94482 var exportedNames;
94483 if (!ts.isGeneratedIdentifier(name)) {
94484 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
94485 || resolver.getReferencedValueDeclaration(name);
94486 if (valueDeclaration) {
94487 var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
94488 if (exportContainer && exportContainer.kind === 294 /* SourceFile */) {
94489 exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration));
94490 }
94491 exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
94492 }
94493 }
94494 return exportedNames;
94495 }
94496 /**
94497 * Prevent substitution of a node for this transformer.
94498 *
94499 * @param node The node which should not be substituted.
94500 */
94501 function preventSubstitution(node) {
94502 if (noSubstitution === undefined)
94503 noSubstitution = [];
94504 noSubstitution[ts.getNodeId(node)] = true;
94505 return node;
94506 }
94507 /**
94508 * Determines whether a node should not be substituted.
94509 *
94510 * @param node The node to test.
94511 */
94512 function isSubstitutionPrevented(node) {
94513 return noSubstitution && node.id && noSubstitution[node.id];
94514 }
94515 }
94516 ts.transformSystemModule = transformSystemModule;
94517})(ts || (ts = {}));
94518/*@internal*/
94519var ts;
94520(function (ts) {
94521 function transformECMAScriptModule(context) {
94522 var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
94523 var compilerOptions = context.getCompilerOptions();
94524 var previousOnEmitNode = context.onEmitNode;
94525 var previousOnSubstituteNode = context.onSubstituteNode;
94526 context.onEmitNode = onEmitNode;
94527 context.onSubstituteNode = onSubstituteNode;
94528 context.enableEmitNotification(294 /* SourceFile */);
94529 context.enableSubstitution(78 /* Identifier */);
94530 var helperNameSubstitutions;
94531 return ts.chainBundle(context, transformSourceFile);
94532 function transformSourceFile(node) {
94533 if (node.isDeclarationFile) {
94534 return node;
94535 }
94536 if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
94537 var result = updateExternalModule(node);
94538 if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
94539 return result;
94540 }
94541 return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArrays(result.statements, [ts.createEmptyExports(factory)])), result.statements));
94542 }
94543 return node;
94544 }
94545 function updateExternalModule(node) {
94546 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
94547 if (externalHelpersImportDeclaration) {
94548 var statements = [];
94549 var statementOffset = factory.copyPrologue(node.statements, statements);
94550 ts.append(statements, externalHelpersImportDeclaration);
94551 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
94552 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
94553 }
94554 else {
94555 return ts.visitEachChild(node, visitor, context);
94556 }
94557 }
94558 function visitor(node) {
94559 switch (node.kind) {
94560 case 257 /* ImportEqualsDeclaration */:
94561 // Elide `import=` as it is not legal with --module ES6
94562 return undefined;
94563 case 263 /* ExportAssignment */:
94564 return visitExportAssignment(node);
94565 case 264 /* ExportDeclaration */:
94566 var exportDecl = node;
94567 return visitExportDeclaration(exportDecl);
94568 }
94569 return node;
94570 }
94571 function visitExportAssignment(node) {
94572 // Elide `export=` as it is not legal with --module ES6
94573 return node.isExportEquals ? undefined : node;
94574 }
94575 function visitExportDeclaration(node) {
94576 // `export * as ns` only needs to be transformed in ES2015
94577 if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
94578 return node;
94579 }
94580 // Either ill-formed or don't need to be tranformed.
94581 if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
94582 return node;
94583 }
94584 var oldIdentifier = node.exportClause.name;
94585 var synthName = factory.getGeneratedNameForNode(oldIdentifier);
94586 var importDecl = factory.createImportDeclaration(
94587 /*decorators*/ undefined,
94588 /*modifiers*/ undefined, factory.createImportClause(
94589 /*isTypeOnly*/ false,
94590 /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier);
94591 ts.setOriginalNode(importDecl, node.exportClause);
94592 var exportDecl = factory.createExportDeclaration(
94593 /*decorators*/ undefined,
94594 /*modifiers*/ undefined,
94595 /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(synthName, oldIdentifier)]));
94596 ts.setOriginalNode(exportDecl, node);
94597 return [importDecl, exportDecl];
94598 }
94599 //
94600 // Emit Notification
94601 //
94602 /**
94603 * Hook for node emit.
94604 *
94605 * @param hint A hint as to the intended usage of the node.
94606 * @param node The node to emit.
94607 * @param emit A callback used to emit the node in the printer.
94608 */
94609 function onEmitNode(hint, node, emitCallback) {
94610 if (ts.isSourceFile(node)) {
94611 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
94612 helperNameSubstitutions = new ts.Map();
94613 }
94614 previousOnEmitNode(hint, node, emitCallback);
94615 helperNameSubstitutions = undefined;
94616 }
94617 else {
94618 previousOnEmitNode(hint, node, emitCallback);
94619 }
94620 }
94621 //
94622 // Substitutions
94623 //
94624 /**
94625 * Hooks node substitutions.
94626 *
94627 * @param hint A hint as to the intended usage of the node.
94628 * @param node The node to substitute.
94629 */
94630 function onSubstituteNode(hint, node) {
94631 node = previousOnSubstituteNode(hint, node);
94632 if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
94633 return substituteHelperName(node);
94634 }
94635 return node;
94636 }
94637 function substituteHelperName(node) {
94638 var name = ts.idText(node);
94639 var substitution = helperNameSubstitutions.get(name);
94640 if (!substitution) {
94641 helperNameSubstitutions.set(name, substitution = factory.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
94642 }
94643 return substitution;
94644 }
94645 }
94646 ts.transformECMAScriptModule = transformECMAScriptModule;
94647})(ts || (ts = {}));
94648/* @internal */
94649var ts;
94650(function (ts) {
94651 function canProduceDiagnostics(node) {
94652 return ts.isVariableDeclaration(node) ||
94653 ts.isPropertyDeclaration(node) ||
94654 ts.isPropertySignature(node) ||
94655 ts.isBindingElement(node) ||
94656 ts.isSetAccessor(node) ||
94657 ts.isGetAccessor(node) ||
94658 ts.isConstructSignatureDeclaration(node) ||
94659 ts.isCallSignatureDeclaration(node) ||
94660 ts.isMethodDeclaration(node) ||
94661 ts.isMethodSignature(node) ||
94662 ts.isFunctionDeclaration(node) ||
94663 ts.isParameter(node) ||
94664 ts.isTypeParameterDeclaration(node) ||
94665 ts.isExpressionWithTypeArguments(node) ||
94666 ts.isImportEqualsDeclaration(node) ||
94667 ts.isTypeAliasDeclaration(node) ||
94668 ts.isConstructorDeclaration(node) ||
94669 ts.isIndexSignatureDeclaration(node) ||
94670 ts.isPropertyAccessExpression(node);
94671 }
94672 ts.canProduceDiagnostics = canProduceDiagnostics;
94673 function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
94674 if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
94675 return getAccessorNameVisibilityError;
94676 }
94677 else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
94678 return getMethodNameVisibilityError;
94679 }
94680 else {
94681 return createGetSymbolAccessibilityDiagnosticForNode(node);
94682 }
94683 function getAccessorNameVisibilityError(symbolAccessibilityResult) {
94684 var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
94685 return diagnosticMessage !== undefined ? {
94686 diagnosticMessage: diagnosticMessage,
94687 errorNode: node,
94688 typeName: node.name
94689 } : undefined;
94690 }
94691 function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
94692 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94693 return symbolAccessibilityResult.errorModuleName ?
94694 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94695 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94696 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94697 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
94698 }
94699 else if (node.parent.kind === 249 /* ClassDeclaration */) {
94700 return symbolAccessibilityResult.errorModuleName ?
94701 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94702 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94703 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94704 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
94705 }
94706 else {
94707 return symbolAccessibilityResult.errorModuleName ?
94708 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94709 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
94710 }
94711 }
94712 function getMethodNameVisibilityError(symbolAccessibilityResult) {
94713 var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
94714 return diagnosticMessage !== undefined ? {
94715 diagnosticMessage: diagnosticMessage,
94716 errorNode: node,
94717 typeName: node.name
94718 } : undefined;
94719 }
94720 function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
94721 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94722 return symbolAccessibilityResult.errorModuleName ?
94723 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94724 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94725 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94726 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
94727 }
94728 else if (node.parent.kind === 249 /* ClassDeclaration */) {
94729 return symbolAccessibilityResult.errorModuleName ?
94730 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94731 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94732 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94733 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
94734 }
94735 else {
94736 return symbolAccessibilityResult.errorModuleName ?
94737 ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94738 ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
94739 }
94740 }
94741 }
94742 ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
94743 function createGetSymbolAccessibilityDiagnosticForNode(node) {
94744 if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
94745 return getVariableDeclarationTypeVisibilityError;
94746 }
94747 else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
94748 return getAccessorDeclarationTypeVisibilityError;
94749 }
94750 else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
94751 return getReturnTypeVisibilityError;
94752 }
94753 else if (ts.isParameter(node)) {
94754 if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasSyntacticModifier(node.parent, 8 /* Private */)) {
94755 return getVariableDeclarationTypeVisibilityError;
94756 }
94757 return getParameterDeclarationTypeVisibilityError;
94758 }
94759 else if (ts.isTypeParameterDeclaration(node)) {
94760 return getTypeParameterConstraintVisibilityError;
94761 }
94762 else if (ts.isExpressionWithTypeArguments(node)) {
94763 return getHeritageClauseVisibilityError;
94764 }
94765 else if (ts.isImportEqualsDeclaration(node)) {
94766 return getImportEntityNameVisibilityError;
94767 }
94768 else if (ts.isTypeAliasDeclaration(node)) {
94769 return getTypeAliasDeclarationVisibilityError;
94770 }
94771 else {
94772 return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
94773 }
94774 function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
94775 if (node.kind === 246 /* VariableDeclaration */ || node.kind === 195 /* BindingElement */) {
94776 return symbolAccessibilityResult.errorModuleName ?
94777 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94778 ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94779 ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
94780 ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
94781 }
94782 // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
94783 // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
94784 else if (node.kind === 162 /* PropertyDeclaration */ || node.kind === 198 /* PropertyAccessExpression */ || node.kind === 161 /* PropertySignature */ ||
94785 (node.kind === 159 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) {
94786 // TODO(jfreeman): Deal with computed properties in error reporting.
94787 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94788 return symbolAccessibilityResult.errorModuleName ?
94789 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94790 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94791 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94792 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
94793 }
94794 else if (node.parent.kind === 249 /* ClassDeclaration */ || node.kind === 159 /* Parameter */) {
94795 return symbolAccessibilityResult.errorModuleName ?
94796 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94797 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94798 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
94799 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
94800 }
94801 else {
94802 // Interfaces cannot have types that cannot be named
94803 return symbolAccessibilityResult.errorModuleName ?
94804 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94805 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
94806 }
94807 }
94808 }
94809 function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
94810 var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
94811 return diagnosticMessage !== undefined ? {
94812 diagnosticMessage: diagnosticMessage,
94813 errorNode: node,
94814 typeName: node.name
94815 } : undefined;
94816 }
94817 function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
94818 var diagnosticMessage;
94819 if (node.kind === 167 /* SetAccessor */) {
94820 // Getters can infer the return type from the returned expression, but setters cannot, so the
94821 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
94822 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94823 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94824 ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94825 ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
94826 }
94827 else {
94828 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94829 ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94830 ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
94831 }
94832 }
94833 else {
94834 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94835 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94836 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94837 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 :
94838 ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94839 ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
94840 }
94841 else {
94842 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94843 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94844 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 :
94845 ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94846 ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
94847 }
94848 }
94849 return {
94850 diagnosticMessage: diagnosticMessage,
94851 errorNode: node.name,
94852 typeName: node.name
94853 };
94854 }
94855 function getReturnTypeVisibilityError(symbolAccessibilityResult) {
94856 var diagnosticMessage;
94857 switch (node.kind) {
94858 case 169 /* ConstructSignature */:
94859 // Interfaces cannot have return types that cannot be named
94860 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94861 ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
94862 ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
94863 break;
94864 case 168 /* CallSignature */:
94865 // Interfaces cannot have return types that cannot be named
94866 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94867 ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
94868 ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
94869 break;
94870 case 170 /* IndexSignature */:
94871 // Interfaces cannot have return types that cannot be named
94872 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94873 ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
94874 ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
94875 break;
94876 case 164 /* MethodDeclaration */:
94877 case 163 /* MethodSignature */:
94878 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
94879 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94880 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94881 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 :
94882 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
94883 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
94884 }
94885 else if (node.parent.kind === 249 /* ClassDeclaration */) {
94886 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94887 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94888 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
94889 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
94890 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
94891 }
94892 else {
94893 // Interfaces cannot have return types that cannot be named
94894 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94895 ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
94896 ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
94897 }
94898 break;
94899 case 248 /* FunctionDeclaration */:
94900 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
94901 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94902 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
94903 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
94904 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
94905 break;
94906 default:
94907 return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
94908 }
94909 return {
94910 diagnosticMessage: diagnosticMessage,
94911 errorNode: node.name || node
94912 };
94913 }
94914 function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
94915 var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
94916 return diagnosticMessage !== undefined ? {
94917 diagnosticMessage: diagnosticMessage,
94918 errorNode: node,
94919 typeName: node.name
94920 } : undefined;
94921 }
94922 function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
94923 switch (node.parent.kind) {
94924 case 165 /* Constructor */:
94925 return symbolAccessibilityResult.errorModuleName ?
94926 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94927 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94928 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94929 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
94930 case 169 /* ConstructSignature */:
94931 case 174 /* ConstructorType */:
94932 // Interfaces cannot have parameter types that cannot be named
94933 return symbolAccessibilityResult.errorModuleName ?
94934 ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94935 ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
94936 case 168 /* CallSignature */:
94937 // Interfaces cannot have parameter types that cannot be named
94938 return symbolAccessibilityResult.errorModuleName ?
94939 ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94940 ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
94941 case 170 /* IndexSignature */:
94942 // Interfaces cannot have parameter types that cannot be named
94943 return symbolAccessibilityResult.errorModuleName ?
94944 ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94945 ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
94946 case 164 /* MethodDeclaration */:
94947 case 163 /* MethodSignature */:
94948 if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
94949 return symbolAccessibilityResult.errorModuleName ?
94950 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94951 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 :
94952 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94953 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
94954 }
94955 else if (node.parent.parent.kind === 249 /* ClassDeclaration */) {
94956 return symbolAccessibilityResult.errorModuleName ?
94957 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94958 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94959 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
94960 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
94961 }
94962 else {
94963 // Interfaces cannot have parameter types that cannot be named
94964 return symbolAccessibilityResult.errorModuleName ?
94965 ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
94966 ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
94967 }
94968 case 248 /* FunctionDeclaration */:
94969 case 173 /* FunctionType */:
94970 return symbolAccessibilityResult.errorModuleName ?
94971 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94972 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94973 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
94974 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
94975 case 167 /* SetAccessor */:
94976 case 166 /* GetAccessor */:
94977 return symbolAccessibilityResult.errorModuleName ?
94978 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
94979 ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
94980 ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
94981 ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
94982 default:
94983 return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
94984 }
94985 }
94986 function getTypeParameterConstraintVisibilityError() {
94987 // Type parameter constraints are named by user so we should always be able to name it
94988 var diagnosticMessage;
94989 switch (node.parent.kind) {
94990 case 249 /* ClassDeclaration */:
94991 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
94992 break;
94993 case 250 /* InterfaceDeclaration */:
94994 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
94995 break;
94996 case 189 /* MappedType */:
94997 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
94998 break;
94999 case 174 /* ConstructorType */:
95000 case 169 /* ConstructSignature */:
95001 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
95002 break;
95003 case 168 /* CallSignature */:
95004 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
95005 break;
95006 case 164 /* MethodDeclaration */:
95007 case 163 /* MethodSignature */:
95008 if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
95009 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
95010 }
95011 else if (node.parent.parent.kind === 249 /* ClassDeclaration */) {
95012 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
95013 }
95014 else {
95015 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
95016 }
95017 break;
95018 case 173 /* FunctionType */:
95019 case 248 /* FunctionDeclaration */:
95020 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
95021 break;
95022 case 251 /* TypeAliasDeclaration */:
95023 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
95024 break;
95025 default:
95026 return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
95027 }
95028 return {
95029 diagnosticMessage: diagnosticMessage,
95030 errorNode: node,
95031 typeName: node.name
95032 };
95033 }
95034 function getHeritageClauseVisibilityError() {
95035 var diagnosticMessage;
95036 // Heritage clause is written by user so it can always be named
95037 if (ts.isClassDeclaration(node.parent.parent)) {
95038 // Class or Interface implemented/extended is inaccessible
95039 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 116 /* ImplementsKeyword */ ?
95040 ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
95041 node.parent.parent.name ? ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 :
95042 ts.Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
95043 }
95044 else {
95045 // interface is inaccessible
95046 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
95047 }
95048 return {
95049 diagnosticMessage: diagnosticMessage,
95050 errorNode: node,
95051 typeName: ts.getNameOfDeclaration(node.parent.parent)
95052 };
95053 }
95054 function getImportEntityNameVisibilityError() {
95055 return {
95056 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
95057 errorNode: node,
95058 typeName: node.name
95059 };
95060 }
95061 function getTypeAliasDeclarationVisibilityError() {
95062 return {
95063 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
95064 errorNode: node.type,
95065 typeName: node.name
95066 };
95067 }
95068 }
95069 ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
95070})(ts || (ts = {}));
95071/*@internal*/
95072var ts;
95073(function (ts) {
95074 function getDeclarationDiagnostics(host, resolver, file) {
95075 var compilerOptions = host.getCompilerOptions();
95076 var result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
95077 return result.diagnostics;
95078 }
95079 ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
95080 function hasInternalAnnotation(range, currentSourceFile) {
95081 var comment = currentSourceFile.text.substring(range.pos, range.end);
95082 return ts.stringContains(comment, "@internal");
95083 }
95084 function isInternalDeclaration(node, currentSourceFile) {
95085 var parseTreeNode = ts.getParseTreeNode(node);
95086 if (parseTreeNode && parseTreeNode.kind === 159 /* Parameter */) {
95087 var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
95088 var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
95089 var text = currentSourceFile.text;
95090 var commentRanges = previousSibling
95091 ? ts.concatenate(
95092 // to handle
95093 // ... parameters, /* @internal */
95094 // public param: string
95095 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
95096 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
95097 return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
95098 }
95099 var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
95100 return !!ts.forEach(leadingCommentRanges, function (range) {
95101 return hasInternalAnnotation(range, currentSourceFile);
95102 });
95103 }
95104 ts.isInternalDeclaration = isInternalDeclaration;
95105 var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
95106 2048 /* WriteClassExpressionAsTypeLiteral */ |
95107 4096 /* UseTypeOfFunction */ |
95108 8 /* UseStructuralFallback */ |
95109 524288 /* AllowEmptyTuple */ |
95110 4 /* GenerateNamesForShadowedTypeParams */ |
95111 1 /* NoTruncation */;
95112 /**
95113 * Transforms a ts file into a .d.ts file
95114 * This process requires type information, which is retrieved through the emit resolver. Because of this,
95115 * in many places this transformer assumes it will be operating on parse tree nodes directly.
95116 * This means that _no transforms should be allowed to occur before this one_.
95117 */
95118 function transformDeclarations(context) {
95119 var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
95120 var getSymbolAccessibilityDiagnostic = throwDiagnostic;
95121 var needsDeclare = true;
95122 var isBundledEmit = false;
95123 var resultHasExternalModuleIndicator = false;
95124 var needsScopeFixMarker = false;
95125 var resultHasScopeMarker = false;
95126 var enclosingDeclaration;
95127 var necessaryTypeReferences;
95128 var lateMarkedStatements;
95129 var lateStatementReplacementMap;
95130 var suppressNewDiagnosticContexts;
95131 var exportedModulesFromDeclarationEmit;
95132 var factory = context.factory;
95133 var host = context.getEmitHost();
95134 var symbolTracker = {
95135 trackSymbol: trackSymbol,
95136 reportInaccessibleThisError: reportInaccessibleThisError,
95137 reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
95138 reportCyclicStructureError: reportCyclicStructureError,
95139 reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
95140 reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
95141 moduleResolverHost: host,
95142 trackReferencedAmbientModule: trackReferencedAmbientModule,
95143 trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
95144 reportNonlocalAugmentation: reportNonlocalAugmentation
95145 };
95146 var errorNameNode;
95147 var currentSourceFile;
95148 var refs;
95149 var libs;
95150 var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
95151 var resolver = context.getEmitResolver();
95152 var options = context.getCompilerOptions();
95153 var noResolve = options.noResolve, stripInternal = options.stripInternal;
95154 return transformRoot;
95155 function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
95156 if (!typeReferenceDirectives) {
95157 return;
95158 }
95159 necessaryTypeReferences = necessaryTypeReferences || new ts.Set();
95160 for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
95161 var ref = typeReferenceDirectives_2[_i];
95162 necessaryTypeReferences.add(ref);
95163 }
95164 }
95165 function trackReferencedAmbientModule(node, symbol) {
95166 // If it is visible via `// <reference types="..."/>`, then we should just use that
95167 var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
95168 if (ts.length(directives)) {
95169 return recordTypeReferenceDirectivesIfNecessary(directives);
95170 }
95171 // Otherwise we should emit a path-based reference
95172 var container = ts.getSourceFileOfNode(node);
95173 refs.set(ts.getOriginalNodeId(container), container);
95174 }
95175 function handleSymbolAccessibilityError(symbolAccessibilityResult) {
95176 if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
95177 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
95178 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
95179 if (!lateMarkedStatements) {
95180 lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
95181 }
95182 else {
95183 for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
95184 var ref = _a[_i];
95185 ts.pushIfUnique(lateMarkedStatements, ref);
95186 }
95187 }
95188 }
95189 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
95190 }
95191 else {
95192 // Report error
95193 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
95194 if (errorInfo) {
95195 if (errorInfo.typeName) {
95196 context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
95197 }
95198 else {
95199 context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
95200 }
95201 }
95202 }
95203 }
95204 function trackExternalModuleSymbolOfImportTypeNode(symbol) {
95205 if (!isBundledEmit) {
95206 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
95207 }
95208 }
95209 function trackSymbol(symbol, enclosingDeclaration, meaning) {
95210 if (symbol.flags & 262144 /* TypeParameter */)
95211 return;
95212 handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
95213 recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
95214 }
95215 function reportPrivateInBaseOfClassExpression(propertyName) {
95216 if (errorNameNode) {
95217 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
95218 }
95219 }
95220 function reportInaccessibleUniqueSymbolError() {
95221 if (errorNameNode) {
95222 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"));
95223 }
95224 }
95225 function reportCyclicStructureError() {
95226 if (errorNameNode) {
95227 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)));
95228 }
95229 }
95230 function reportInaccessibleThisError() {
95231 if (errorNameNode) {
95232 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"));
95233 }
95234 }
95235 function reportLikelyUnsafeImportRequiredError(specifier) {
95236 if (errorNameNode) {
95237 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));
95238 }
95239 }
95240 function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
95241 var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
95242 var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
95243 for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
95244 var augmentations = augmentingDeclarations_1[_i];
95245 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)));
95246 }
95247 }
95248 function transformDeclarationsForJS(sourceFile, bundled) {
95249 var oldDiag = getSymbolAccessibilityDiagnostic;
95250 getSymbolAccessibilityDiagnostic = function (s) { return ({
95251 diagnosticMessage: s.errorModuleName
95252 ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
95253 : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
95254 errorNode: s.errorNode || sourceFile
95255 }); };
95256 var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
95257 getSymbolAccessibilityDiagnostic = oldDiag;
95258 return result;
95259 }
95260 function transformRoot(node) {
95261 if (node.kind === 294 /* SourceFile */ && node.isDeclarationFile) {
95262 return node;
95263 }
95264 if (node.kind === 295 /* Bundle */) {
95265 isBundledEmit = true;
95266 refs = new ts.Map();
95267 libs = new ts.Map();
95268 var hasNoDefaultLib_1 = false;
95269 var bundle = factory.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
95270 if (sourceFile.isDeclarationFile)
95271 return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
95272 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
95273 currentSourceFile = sourceFile;
95274 enclosingDeclaration = sourceFile;
95275 lateMarkedStatements = undefined;
95276 suppressNewDiagnosticContexts = false;
95277 lateStatementReplacementMap = new ts.Map();
95278 getSymbolAccessibilityDiagnostic = throwDiagnostic;
95279 needsScopeFixMarker = false;
95280 resultHasScopeMarker = false;
95281 collectReferences(sourceFile, refs);
95282 collectLibs(sourceFile, libs);
95283 if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
95284 resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
95285 needsDeclare = false;
95286 var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
95287 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*/ []);
95288 return newFile;
95289 }
95290 needsDeclare = true;
95291 var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
95292 return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
95293 }), ts.mapDefined(node.prepends, function (prepend) {
95294 if (prepend.kind === 297 /* InputFiles */) {
95295 var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
95296 hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
95297 collectReferences(sourceFile, refs);
95298 recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
95299 collectLibs(sourceFile, libs);
95300 return sourceFile;
95301 }
95302 return prepend;
95303 }));
95304 bundle.syntheticFileReferences = [];
95305 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
95306 bundle.syntheticLibReferences = getLibReferences();
95307 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
95308 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
95309 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
95310 refs.forEach(referenceVisitor_1);
95311 return bundle;
95312 }
95313 // Single source file
95314 needsDeclare = true;
95315 needsScopeFixMarker = false;
95316 resultHasScopeMarker = false;
95317 enclosingDeclaration = node;
95318 currentSourceFile = node;
95319 getSymbolAccessibilityDiagnostic = throwDiagnostic;
95320 isBundledEmit = false;
95321 resultHasExternalModuleIndicator = false;
95322 suppressNewDiagnosticContexts = false;
95323 lateMarkedStatements = undefined;
95324 lateStatementReplacementMap = new ts.Map();
95325 necessaryTypeReferences = undefined;
95326 refs = collectReferences(currentSourceFile, new ts.Map());
95327 libs = collectLibs(currentSourceFile, new ts.Map());
95328 var references = [];
95329 var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
95330 var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
95331 var combinedStatements;
95332 if (ts.isSourceFileJS(currentSourceFile)) {
95333 combinedStatements = factory.createNodeArray(transformDeclarationsForJS(node));
95334 refs.forEach(referenceVisitor);
95335 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
95336 }
95337 else {
95338 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
95339 combinedStatements = ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
95340 refs.forEach(referenceVisitor);
95341 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
95342 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
95343 combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports(factory)])), combinedStatements);
95344 }
95345 }
95346 var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
95347 updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
95348 return updated;
95349 function getLibReferences() {
95350 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
95351 }
95352 function getFileReferencesForUsedTypeReferences() {
95353 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
95354 }
95355 function getFileReferenceForTypeName(typeName) {
95356 // Elide type references for which we have imports
95357 if (emittedImports) {
95358 for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
95359 var importStatement = emittedImports_1[_i];
95360 if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
95361 var expr = importStatement.moduleReference.expression;
95362 if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
95363 return undefined;
95364 }
95365 }
95366 else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
95367 return undefined;
95368 }
95369 }
95370 }
95371 return { fileName: typeName, pos: -1, end: -1 };
95372 }
95373 function mapReferencesIntoArray(references, outputFilePath) {
95374 return function (file) {
95375 var declFileName;
95376 if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
95377 declFileName = file.fileName;
95378 }
95379 else {
95380 if (isBundledEmit && ts.contains(node.sourceFiles, file))
95381 return; // Omit references to files which are being merged
95382 var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
95383 declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
95384 }
95385 if (declFileName) {
95386 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,
95387 /*preferences*/ undefined);
95388 if (!ts.pathIsRelative(specifier)) {
95389 // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
95390 // via a non-relative name, emit a type reference directive to that non-relative name, rather than
95391 // a relative path to the declaration file
95392 recordTypeReferenceDirectivesIfNecessary([specifier]);
95393 return;
95394 }
95395 var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
95396 /*isAbsolutePathAnUrl*/ false);
95397 if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
95398 fileName = fileName.substring(2);
95399 }
95400 // omit references to files from node_modules (npm may disambiguate module
95401 // references when installing this package, making the path is unreliable).
95402 if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
95403 return;
95404 }
95405 references.push({ pos: -1, end: -1, fileName: fileName });
95406 }
95407 };
95408 }
95409 }
95410 function collectReferences(sourceFile, ret) {
95411 if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
95412 return ret;
95413 ts.forEach(sourceFile.referencedFiles, function (f) {
95414 var elem = host.getSourceFileFromReference(sourceFile, f);
95415 if (elem) {
95416 ret.set(ts.getOriginalNodeId(elem), elem);
95417 }
95418 });
95419 return ret;
95420 }
95421 function collectLibs(sourceFile, ret) {
95422 ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
95423 var lib = host.getLibFileFromReference(ref);
95424 if (lib) {
95425 ret.set(ts.toFileNameLowerCase(ref.fileName), true);
95426 }
95427 });
95428 return ret;
95429 }
95430 function filterBindingPatternInitializers(name) {
95431 if (name.kind === 78 /* Identifier */) {
95432 return name;
95433 }
95434 else {
95435 if (name.kind === 194 /* ArrayBindingPattern */) {
95436 return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
95437 }
95438 else {
95439 return factory.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
95440 }
95441 }
95442 function visitBindingElement(elem) {
95443 if (elem.kind === 219 /* OmittedExpression */) {
95444 return elem;
95445 }
95446 return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
95447 }
95448 }
95449 function ensureParameter(p, modifierMask, type) {
95450 var oldDiag;
95451 if (!suppressNewDiagnosticContexts) {
95452 oldDiag = getSymbolAccessibilityDiagnostic;
95453 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
95454 }
95455 var newParam = factory.updateParameterDeclaration(p,
95456 /*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
95457 ensureNoInitializer(p));
95458 if (!suppressNewDiagnosticContexts) {
95459 getSymbolAccessibilityDiagnostic = oldDiag;
95460 }
95461 return newParam;
95462 }
95463 function shouldPrintWithInitializer(node) {
95464 return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
95465 }
95466 function ensureNoInitializer(node) {
95467 if (shouldPrintWithInitializer(node)) {
95468 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
95469 }
95470 return undefined;
95471 }
95472 function ensureType(node, type, ignorePrivate) {
95473 if (!ignorePrivate && ts.hasEffectiveModifier(node, 8 /* Private */)) {
95474 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
95475 return;
95476 }
95477 if (shouldPrintWithInitializer(node)) {
95478 // Literal const declarations will have an initializer ensured rather than a type
95479 return;
95480 }
95481 var shouldUseResolverType = node.kind === 159 /* Parameter */ &&
95482 (resolver.isRequiredInitializedParameter(node) ||
95483 resolver.isOptionalUninitializedParameterProperty(node));
95484 if (type && !shouldUseResolverType) {
95485 return ts.visitNode(type, visitDeclarationSubtree);
95486 }
95487 if (!ts.getParseTreeNode(node)) {
95488 return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */);
95489 }
95490 if (node.kind === 167 /* SetAccessor */) {
95491 // 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
95492 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
95493 return factory.createKeywordTypeNode(128 /* AnyKeyword */);
95494 }
95495 errorNameNode = node.name;
95496 var oldDiag;
95497 if (!suppressNewDiagnosticContexts) {
95498 oldDiag = getSymbolAccessibilityDiagnostic;
95499 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
95500 }
95501 if (node.kind === 246 /* VariableDeclaration */ || node.kind === 195 /* BindingElement */) {
95502 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
95503 }
95504 if (node.kind === 159 /* Parameter */
95505 || node.kind === 162 /* PropertyDeclaration */
95506 || node.kind === 161 /* PropertySignature */) {
95507 if (!node.initializer)
95508 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
95509 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
95510 }
95511 return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
95512 function cleanup(returnValue) {
95513 errorNameNode = undefined;
95514 if (!suppressNewDiagnosticContexts) {
95515 getSymbolAccessibilityDiagnostic = oldDiag;
95516 }
95517 return returnValue || factory.createKeywordTypeNode(128 /* AnyKeyword */);
95518 }
95519 }
95520 function isDeclarationAndNotVisible(node) {
95521 node = ts.getParseTreeNode(node);
95522 switch (node.kind) {
95523 case 248 /* FunctionDeclaration */:
95524 case 253 /* ModuleDeclaration */:
95525 case 250 /* InterfaceDeclaration */:
95526 case 249 /* ClassDeclaration */:
95527 case 251 /* TypeAliasDeclaration */:
95528 case 252 /* EnumDeclaration */:
95529 return !resolver.isDeclarationVisible(node);
95530 // The following should be doing their own visibility checks based on filtering their members
95531 case 246 /* VariableDeclaration */:
95532 return !getBindingNameVisible(node);
95533 case 257 /* ImportEqualsDeclaration */:
95534 case 258 /* ImportDeclaration */:
95535 case 264 /* ExportDeclaration */:
95536 case 263 /* ExportAssignment */:
95537 return false;
95538 }
95539 return false;
95540 }
95541 function getBindingNameVisible(elem) {
95542 if (ts.isOmittedExpression(elem)) {
95543 return false;
95544 }
95545 if (ts.isBindingPattern(elem.name)) {
95546 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
95547 return ts.some(elem.name.elements, getBindingNameVisible);
95548 }
95549 else {
95550 return resolver.isDeclarationVisible(elem);
95551 }
95552 }
95553 function updateParamsList(node, params, modifierMask) {
95554 if (ts.hasEffectiveModifier(node, 8 /* Private */)) {
95555 return undefined; // TODO: GH#18217
95556 }
95557 var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
95558 if (!newParams) {
95559 return undefined; // TODO: GH#18217
95560 }
95561 return factory.createNodeArray(newParams, params.hasTrailingComma);
95562 }
95563 function updateAccessorParamsList(input, isPrivate) {
95564 var newParams;
95565 if (!isPrivate) {
95566 var thisParameter = ts.getThisParameter(input);
95567 if (thisParameter) {
95568 newParams = [ensureParameter(thisParameter)];
95569 }
95570 }
95571 if (ts.isSetAccessorDeclaration(input)) {
95572 var newValueParameter = void 0;
95573 if (!isPrivate) {
95574 var valueParameter = ts.getSetAccessorValueParameter(input);
95575 if (valueParameter) {
95576 var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
95577 newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
95578 }
95579 }
95580 if (!newValueParameter) {
95581 newValueParameter = factory.createParameterDeclaration(
95582 /*decorators*/ undefined,
95583 /*modifiers*/ undefined,
95584 /*dotDotDotToken*/ undefined, "value");
95585 }
95586 newParams = ts.append(newParams, newValueParameter);
95587 }
95588 return factory.createNodeArray(newParams || ts.emptyArray);
95589 }
95590 function ensureTypeParams(node, params) {
95591 return ts.hasEffectiveModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
95592 }
95593 function isEnclosingDeclaration(node) {
95594 return ts.isSourceFile(node)
95595 || ts.isTypeAliasDeclaration(node)
95596 || ts.isModuleDeclaration(node)
95597 || ts.isClassDeclaration(node)
95598 || ts.isInterfaceDeclaration(node)
95599 || ts.isFunctionLike(node)
95600 || ts.isIndexSignatureDeclaration(node)
95601 || ts.isMappedTypeNode(node);
95602 }
95603 function checkEntityNameVisibility(entityName, enclosingDeclaration) {
95604 var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
95605 handleSymbolAccessibilityError(visibilityResult);
95606 recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
95607 }
95608 function preserveJsDoc(updated, original) {
95609 if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
95610 updated.jsDoc = original.jsDoc;
95611 }
95612 return ts.setCommentRange(updated, ts.getCommentRange(original));
95613 }
95614 function rewriteModuleSpecifier(parent, input) {
95615 if (!input)
95616 return undefined; // TODO: GH#18217
95617 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 253 /* ModuleDeclaration */ && parent.kind !== 192 /* ImportType */);
95618 if (ts.isStringLiteralLike(input)) {
95619 if (isBundledEmit) {
95620 var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
95621 if (newName) {
95622 return factory.createStringLiteral(newName);
95623 }
95624 }
95625 else {
95626 var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
95627 if (symbol) {
95628 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
95629 }
95630 }
95631 }
95632 return input;
95633 }
95634 function transformImportEqualsDeclaration(decl) {
95635 if (!resolver.isDeclarationVisible(decl))
95636 return;
95637 if (decl.moduleReference.kind === 269 /* ExternalModuleReference */) {
95638 // Rewrite external module names if necessary
95639 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
95640 return factory.updateImportEqualsDeclaration(decl,
95641 /*decorators*/ undefined, decl.modifiers, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
95642 }
95643 else {
95644 var oldDiag = getSymbolAccessibilityDiagnostic;
95645 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
95646 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
95647 getSymbolAccessibilityDiagnostic = oldDiag;
95648 return decl;
95649 }
95650 }
95651 function transformImportDeclaration(decl) {
95652 if (!decl.importClause) {
95653 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
95654 return factory.updateImportDeclaration(decl,
95655 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
95656 }
95657 // The `importClause` visibility corresponds to the default's visibility.
95658 var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
95659 if (!decl.importClause.namedBindings) {
95660 // No named bindings (either namespace or list), meaning the import is just default or should be elided
95661 return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding,
95662 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
95663 }
95664 if (decl.importClause.namedBindings.kind === 260 /* NamespaceImport */) {
95665 // Namespace import (optionally with visible default)
95666 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
95667 return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
95668 }
95669 // Named imports (optionally with visible default)
95670 var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
95671 if ((bindingList && bindingList.length) || visibleDefaultBinding) {
95672 return factory.updateImportDeclaration(decl,
95673 /*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));
95674 }
95675 // Augmentation of export depends on import
95676 if (resolver.isImportRequiredByAugmentation(decl)) {
95677 return factory.updateImportDeclaration(decl,
95678 /*decorators*/ undefined, decl.modifiers,
95679 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
95680 }
95681 // Nothing visible
95682 }
95683 function transformAndReplaceLatePaintedStatements(statements) {
95684 // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
95685 // error handling which must now be included in the output and themselves checked for errors.
95686 // For example:
95687 // ```
95688 // module A {
95689 // export module Q {}
95690 // import B = Q;
95691 // import C = B;
95692 // export import D = C;
95693 // }
95694 // ```
95695 // 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
95696 // 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
95697 // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
95698 while (ts.length(lateMarkedStatements)) {
95699 var i = lateMarkedStatements.shift();
95700 if (!ts.isLateVisibilityPaintedStatement(i)) {
95701 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));
95702 }
95703 var priorNeedsDeclare = needsDeclare;
95704 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
95705 var result = transformTopLevelDeclaration(i);
95706 needsDeclare = priorNeedsDeclare;
95707 lateStatementReplacementMap.set(ts.getOriginalNodeId(i), result);
95708 }
95709 // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
95710 // (and remove them from the set to examine for outter declarations)
95711 return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
95712 function visitLateVisibilityMarkedStatements(statement) {
95713 if (ts.isLateVisibilityPaintedStatement(statement)) {
95714 var key = ts.getOriginalNodeId(statement);
95715 if (lateStatementReplacementMap.has(key)) {
95716 var result = lateStatementReplacementMap.get(key);
95717 lateStatementReplacementMap.delete(key);
95718 if (result) {
95719 if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
95720 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
95721 needsScopeFixMarker = true;
95722 }
95723 if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
95724 resultHasExternalModuleIndicator = true;
95725 }
95726 }
95727 return result;
95728 }
95729 }
95730 return statement;
95731 }
95732 }
95733 function visitDeclarationSubtree(input) {
95734 if (shouldStripInternal(input))
95735 return;
95736 if (ts.isDeclaration(input)) {
95737 if (isDeclarationAndNotVisible(input))
95738 return;
95739 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
95740 return;
95741 }
95742 }
95743 // Elide implementation signatures from overload sets
95744 if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
95745 return;
95746 // Elide semicolon class statements
95747 if (ts.isSemicolonClassElement(input))
95748 return;
95749 var previousEnclosingDeclaration;
95750 if (isEnclosingDeclaration(input)) {
95751 previousEnclosingDeclaration = enclosingDeclaration;
95752 enclosingDeclaration = input;
95753 }
95754 var oldDiag = getSymbolAccessibilityDiagnostic;
95755 // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
95756 // We'd see a TDZ violation at runtime
95757 var canProduceDiagnostic = ts.canProduceDiagnostics(input);
95758 var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
95759 var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 176 /* TypeLiteral */ || input.kind === 189 /* MappedType */) && input.parent.kind !== 251 /* TypeAliasDeclaration */);
95760 // Emit methods which are private as properties with no type information
95761 if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
95762 if (ts.hasEffectiveModifier(input, 8 /* Private */)) {
95763 if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
95764 return; // Elide all but the first overload
95765 return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
95766 }
95767 }
95768 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
95769 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
95770 }
95771 if (ts.isTypeQueryNode(input)) {
95772 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
95773 }
95774 if (shouldEnterSuppressNewDiagnosticsContextContext) {
95775 // 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.
95776 suppressNewDiagnosticContexts = true;
95777 }
95778 if (isProcessedComponent(input)) {
95779 switch (input.kind) {
95780 case 220 /* ExpressionWithTypeArguments */: {
95781 if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
95782 checkEntityNameVisibility(input.expression, enclosingDeclaration);
95783 }
95784 var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
95785 return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
95786 }
95787 case 172 /* TypeReference */: {
95788 checkEntityNameVisibility(input.typeName, enclosingDeclaration);
95789 var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
95790 return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
95791 }
95792 case 169 /* ConstructSignature */:
95793 return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
95794 case 165 /* Constructor */: {
95795 // A constructor declaration may not have a type annotation
95796 var ctor = factory.createConstructorDeclaration(
95797 /*decorators*/ undefined,
95798 /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */),
95799 /*body*/ undefined);
95800 return cleanup(ctor);
95801 }
95802 case 164 /* MethodDeclaration */: {
95803 if (ts.isPrivateIdentifier(input.name)) {
95804 return cleanup(/*returnValue*/ undefined);
95805 }
95806 var sig = factory.createMethodDeclaration(
95807 /*decorators*/ undefined, ensureModifiers(input),
95808 /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
95809 /*body*/ undefined);
95810 return cleanup(sig);
95811 }
95812 case 166 /* GetAccessor */: {
95813 if (ts.isPrivateIdentifier(input.name)) {
95814 return cleanup(/*returnValue*/ undefined);
95815 }
95816 var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
95817 return cleanup(factory.updateGetAccessorDeclaration(input,
95818 /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType),
95819 /*body*/ undefined));
95820 }
95821 case 167 /* SetAccessor */: {
95822 if (ts.isPrivateIdentifier(input.name)) {
95823 return cleanup(/*returnValue*/ undefined);
95824 }
95825 return cleanup(factory.updateSetAccessorDeclaration(input,
95826 /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)),
95827 /*body*/ undefined));
95828 }
95829 case 162 /* PropertyDeclaration */:
95830 if (ts.isPrivateIdentifier(input.name)) {
95831 return cleanup(/*returnValue*/ undefined);
95832 }
95833 return cleanup(factory.updatePropertyDeclaration(input,
95834 /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
95835 case 161 /* PropertySignature */:
95836 if (ts.isPrivateIdentifier(input.name)) {
95837 return cleanup(/*returnValue*/ undefined);
95838 }
95839 return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type)));
95840 case 163 /* MethodSignature */: {
95841 if (ts.isPrivateIdentifier(input.name)) {
95842 return cleanup(/*returnValue*/ undefined);
95843 }
95844 return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
95845 }
95846 case 168 /* CallSignature */: {
95847 return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
95848 }
95849 case 170 /* IndexSignature */: {
95850 return cleanup(factory.updateIndexSignature(input,
95851 /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */)));
95852 }
95853 case 246 /* VariableDeclaration */: {
95854 if (ts.isBindingPattern(input.name)) {
95855 return recreateBindingPattern(input.name);
95856 }
95857 shouldEnterSuppressNewDiagnosticsContextContext = true;
95858 suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
95859 return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
95860 }
95861 case 158 /* TypeParameter */: {
95862 if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
95863 return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
95864 }
95865 return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
95866 }
95867 case 183 /* ConditionalType */: {
95868 // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
95869 // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
95870 var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
95871 var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
95872 var oldEnclosingDecl = enclosingDeclaration;
95873 enclosingDeclaration = input.trueType;
95874 var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
95875 enclosingDeclaration = oldEnclosingDecl;
95876 var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
95877 return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
95878 }
95879 case 173 /* FunctionType */: {
95880 return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
95881 }
95882 case 174 /* ConstructorType */: {
95883 return cleanup(factory.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
95884 }
95885 case 192 /* ImportType */: {
95886 if (!ts.isLiteralImportTypeNode(input))
95887 return cleanup(input);
95888 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));
95889 }
95890 default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
95891 }
95892 }
95893 if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) {
95894 ts.setEmitFlags(input, 1 /* SingleLine */);
95895 }
95896 return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
95897 function cleanup(returnValue) {
95898 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
95899 checkName(input);
95900 }
95901 if (isEnclosingDeclaration(input)) {
95902 enclosingDeclaration = previousEnclosingDeclaration;
95903 }
95904 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
95905 getSymbolAccessibilityDiagnostic = oldDiag;
95906 }
95907 if (shouldEnterSuppressNewDiagnosticsContextContext) {
95908 suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
95909 }
95910 if (returnValue === input) {
95911 return returnValue;
95912 }
95913 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
95914 }
95915 }
95916 function isPrivateMethodTypeParameter(node) {
95917 return node.parent.kind === 164 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */);
95918 }
95919 function visitDeclarationStatements(input) {
95920 if (!isPreservedDeclarationStatement(input)) {
95921 // return undefined for unmatched kinds to omit them from the tree
95922 return;
95923 }
95924 if (shouldStripInternal(input))
95925 return;
95926 switch (input.kind) {
95927 case 264 /* ExportDeclaration */: {
95928 if (ts.isSourceFile(input.parent)) {
95929 resultHasExternalModuleIndicator = true;
95930 }
95931 resultHasScopeMarker = true;
95932 // Always visible if the parent node isn't dropped for being not visible
95933 // Rewrite external module names if necessary
95934 return factory.updateExportDeclaration(input,
95935 /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
95936 }
95937 case 263 /* ExportAssignment */: {
95938 // Always visible if the parent node isn't dropped for being not visible
95939 if (ts.isSourceFile(input.parent)) {
95940 resultHasExternalModuleIndicator = true;
95941 }
95942 resultHasScopeMarker = true;
95943 if (input.expression.kind === 78 /* Identifier */) {
95944 return input;
95945 }
95946 else {
95947 var newId = factory.createUniqueName("_default", 16 /* Optimistic */);
95948 getSymbolAccessibilityDiagnostic = function () { return ({
95949 diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
95950 errorNode: input
95951 }); };
95952 var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
95953 var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
95954 return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
95955 }
95956 }
95957 }
95958 var result = transformTopLevelDeclaration(input);
95959 // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
95960 lateStatementReplacementMap.set(ts.getOriginalNodeId(input), result);
95961 return input;
95962 }
95963 function stripExportModifiers(statement) {
95964 if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* Default */) || !ts.canHaveModifiers(statement)) {
95965 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
95966 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
95967 return statement;
95968 }
95969 var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */));
95970 return factory.updateModifiers(statement, modifiers);
95971 }
95972 function transformTopLevelDeclaration(input) {
95973 if (shouldStripInternal(input))
95974 return;
95975 switch (input.kind) {
95976 case 257 /* ImportEqualsDeclaration */: {
95977 return transformImportEqualsDeclaration(input);
95978 }
95979 case 258 /* ImportDeclaration */: {
95980 return transformImportDeclaration(input);
95981 }
95982 }
95983 if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
95984 return;
95985 // Elide implementation signatures from overload sets
95986 if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
95987 return;
95988 var previousEnclosingDeclaration;
95989 if (isEnclosingDeclaration(input)) {
95990 previousEnclosingDeclaration = enclosingDeclaration;
95991 enclosingDeclaration = input;
95992 }
95993 var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
95994 var oldDiag = getSymbolAccessibilityDiagnostic;
95995 if (canProdiceDiagnostic) {
95996 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
95997 }
95998 var previousNeedsDeclare = needsDeclare;
95999 switch (input.kind) {
96000 case 251 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
96001 return cleanup(factory.updateTypeAliasDeclaration(input,
96002 /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
96003 case 250 /* InterfaceDeclaration */: {
96004 return cleanup(factory.updateInterfaceDeclaration(input,
96005 /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
96006 }
96007 case 248 /* FunctionDeclaration */: {
96008 // Generators lose their generator-ness, excepting their return type
96009 var clean = cleanup(factory.updateFunctionDeclaration(input,
96010 /*decorators*/ undefined, ensureModifiers(input),
96011 /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
96012 /*body*/ undefined));
96013 if (clean && resolver.isExpandoFunctionDeclaration(input)) {
96014 var props = resolver.getPropertiesOfContainerFunction(input);
96015 // Use parseNodeFactory so it is usable as an enclosing declaration
96016 var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* Namespace */);
96017 ts.setParent(fakespace_1, enclosingDeclaration);
96018 fakespace_1.locals = ts.createSymbolTable(props);
96019 fakespace_1.symbol = props[0].parent;
96020 var exportMappings_1 = [];
96021 var declarations = ts.mapDefined(props, function (p) {
96022 if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
96023 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
96024 }
96025 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
96026 var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
96027 getSymbolAccessibilityDiagnostic = oldDiag;
96028 var nameStr = ts.unescapeLeadingUnderscores(p.escapedName);
96029 var isNonContextualKeywordName = ts.isStringANonContextualKeyword(nameStr);
96030 var name = isNonContextualKeywordName ? factory.getGeneratedNameForNode(p.valueDeclaration) : factory.createIdentifier(nameStr);
96031 if (isNonContextualKeywordName) {
96032 exportMappings_1.push([name, nameStr]);
96033 }
96034 var varDecl = factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, type, /*initializer*/ undefined);
96035 return factory.createVariableStatement(isNonContextualKeywordName ? undefined : [factory.createToken(92 /* ExportKeyword */)], factory.createVariableDeclarationList([varDecl]));
96036 });
96037 if (!exportMappings_1.length) {
96038 declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0 /* None */); });
96039 }
96040 else {
96041 declarations.push(factory.createExportDeclaration(
96042 /*decorators*/ undefined,
96043 /*modifiers*/ undefined,
96044 /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) {
96045 var gen = _a[0], exp = _a[1];
96046 return factory.createExportSpecifier(gen, exp);
96047 }))));
96048 }
96049 var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* Namespace */);
96050 if (!ts.hasEffectiveModifier(clean, 512 /* Default */)) {
96051 return [clean, namespaceDecl];
96052 }
96053 var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
96054 var cleanDeclaration = factory.updateFunctionDeclaration(clean,
96055 /*decorators*/ undefined, modifiers,
96056 /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type,
96057 /*body*/ undefined);
96058 var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl,
96059 /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
96060 var exportDefaultDeclaration = factory.createExportAssignment(
96061 /*decorators*/ undefined,
96062 /*modifiers*/ undefined,
96063 /*isExportEquals*/ false, namespaceDecl.name);
96064 if (ts.isSourceFile(input.parent)) {
96065 resultHasExternalModuleIndicator = true;
96066 }
96067 resultHasScopeMarker = true;
96068 return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
96069 }
96070 else {
96071 return clean;
96072 }
96073 }
96074 case 253 /* ModuleDeclaration */: {
96075 needsDeclare = false;
96076 var inner = input.body;
96077 if (inner && inner.kind === 254 /* ModuleBlock */) {
96078 var oldNeedsScopeFix = needsScopeFixMarker;
96079 var oldHasScopeFix = resultHasScopeMarker;
96080 resultHasScopeMarker = false;
96081 needsScopeFixMarker = false;
96082 var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
96083 var lateStatements = transformAndReplaceLatePaintedStatements(statements);
96084 if (input.flags & 8388608 /* Ambient */) {
96085 needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
96086 }
96087 // With the final list of statements, there are 3 possibilities:
96088 // 1. There's an export assignment or export declaration in the namespace - do nothing
96089 // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
96090 // 3. Some things are exported, some are not, and there's no marker - add an empty marker
96091 if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
96092 if (needsScopeFixMarker) {
96093 lateStatements = factory.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports(factory)]));
96094 }
96095 else {
96096 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
96097 }
96098 }
96099 var body = factory.updateModuleBlock(inner, lateStatements);
96100 needsDeclare = previousNeedsDeclare;
96101 needsScopeFixMarker = oldNeedsScopeFix;
96102 resultHasScopeMarker = oldHasScopeFix;
96103 var mods = ensureModifiers(input);
96104 return cleanup(factory.updateModuleDeclaration(input,
96105 /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
96106 }
96107 else {
96108 needsDeclare = previousNeedsDeclare;
96109 var mods = ensureModifiers(input);
96110 needsDeclare = false;
96111 ts.visitNode(inner, visitDeclarationStatements);
96112 // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
96113 var id = ts.getOriginalNodeId(inner); // TODO: GH#18217
96114 var body = lateStatementReplacementMap.get(id);
96115 lateStatementReplacementMap.delete(id);
96116 return cleanup(factory.updateModuleDeclaration(input,
96117 /*decorators*/ undefined, mods, input.name, body));
96118 }
96119 }
96120 case 249 /* ClassDeclaration */: {
96121 var modifiers = factory.createNodeArray(ensureModifiers(input));
96122 var typeParameters = ensureTypeParams(input, input.typeParameters);
96123 var ctor = ts.getFirstConstructorWithBody(input);
96124 var parameterProperties = void 0;
96125 if (ctor) {
96126 var oldDiag_1 = getSymbolAccessibilityDiagnostic;
96127 parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
96128 if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
96129 return;
96130 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
96131 if (param.name.kind === 78 /* Identifier */) {
96132 return preserveJsDoc(factory.createPropertyDeclaration(
96133 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
96134 }
96135 else {
96136 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
96137 return walkBindingPattern(param.name);
96138 }
96139 function walkBindingPattern(pattern) {
96140 var elems;
96141 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
96142 var elem = _a[_i];
96143 if (ts.isOmittedExpression(elem))
96144 continue;
96145 if (ts.isBindingPattern(elem.name)) {
96146 elems = ts.concatenate(elems, walkBindingPattern(elem.name));
96147 }
96148 elems = elems || [];
96149 elems.push(factory.createPropertyDeclaration(
96150 /*decorators*/ undefined, ensureModifiers(param), elem.name,
96151 /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined),
96152 /*initializer*/ undefined));
96153 }
96154 return elems;
96155 }
96156 }));
96157 getSymbolAccessibilityDiagnostic = oldDiag_1;
96158 }
96159 var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
96160 var privateIdentifier = hasPrivateIdentifier ? [
96161 factory.createPropertyDeclaration(
96162 /*decorators*/ undefined,
96163 /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"),
96164 /*questionToken*/ undefined,
96165 /*type*/ undefined,
96166 /*initializer*/ undefined)
96167 ] : undefined;
96168 var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
96169 var members = factory.createNodeArray(memberNodes);
96170 var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
96171 if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 103 /* NullKeyword */) {
96172 // We must add a temporary declaration for the extends clause expression
96173 var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
96174 var newId_1 = factory.createUniqueName(oldId + "_base", 16 /* Optimistic */);
96175 getSymbolAccessibilityDiagnostic = function () { return ({
96176 diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
96177 errorNode: extendsClause_1,
96178 typeName: input.name
96179 }); };
96180 var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
96181 var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
96182 var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) {
96183 if (clause.token === 93 /* ExtendsKeyword */) {
96184 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
96185 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
96186 var newClause = factory.updateHeritageClause(clause, ts.map(clause.types, function (t) { return factory.updateExpressionWithTypeArguments(t, newId_1, ts.visitNodes(t.typeArguments, visitDeclarationSubtree)); }));
96187 getSymbolAccessibilityDiagnostic = oldDiag_2;
96188 return newClause;
96189 }
96190 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));
96191 }));
96192 return [statement, cleanup(factory.updateClassDeclaration(input,
96193 /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
96194 }
96195 else {
96196 var heritageClauses = transformHeritageClauses(input.heritageClauses);
96197 return cleanup(factory.updateClassDeclaration(input,
96198 /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
96199 }
96200 }
96201 case 229 /* VariableStatement */: {
96202 return cleanup(transformVariableStatement(input));
96203 }
96204 case 252 /* EnumDeclaration */: {
96205 return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) {
96206 if (shouldStripInternal(m))
96207 return;
96208 // Rewrite enum values to their constants, if available
96209 var constValue = resolver.getConstantValue(m);
96210 return preserveJsDoc(factory.updateEnumMember(m, m.name, constValue !== undefined ? typeof constValue === "string" ? factory.createStringLiteral(constValue) : factory.createNumericLiteral(constValue) : undefined), m);
96211 }))));
96212 }
96213 }
96214 // Anything left unhandled is an error, so this should be unreachable
96215 return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
96216 function cleanup(node) {
96217 if (isEnclosingDeclaration(input)) {
96218 enclosingDeclaration = previousEnclosingDeclaration;
96219 }
96220 if (canProdiceDiagnostic) {
96221 getSymbolAccessibilityDiagnostic = oldDiag;
96222 }
96223 if (input.kind === 253 /* ModuleDeclaration */) {
96224 needsDeclare = previousNeedsDeclare;
96225 }
96226 if (node === input) {
96227 return node;
96228 }
96229 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
96230 }
96231 }
96232 function transformVariableStatement(input) {
96233 if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
96234 return;
96235 var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
96236 if (!ts.length(nodes))
96237 return;
96238 return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes));
96239 }
96240 function recreateBindingPattern(d) {
96241 return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
96242 }
96243 function recreateBindingElement(e) {
96244 if (e.kind === 219 /* OmittedExpression */) {
96245 return;
96246 }
96247 if (e.name) {
96248 if (!getBindingNameVisible(e))
96249 return;
96250 if (ts.isBindingPattern(e.name)) {
96251 return recreateBindingPattern(e.name);
96252 }
96253 else {
96254 return factory.createVariableDeclaration(e.name, /*exclamationToken*/ undefined, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
96255 }
96256 }
96257 }
96258 function checkName(node) {
96259 var oldDiag;
96260 if (!suppressNewDiagnosticContexts) {
96261 oldDiag = getSymbolAccessibilityDiagnostic;
96262 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
96263 }
96264 errorNameNode = node.name;
96265 ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
96266 var decl = node;
96267 var entityName = decl.name.expression;
96268 checkEntityNameVisibility(entityName, enclosingDeclaration);
96269 if (!suppressNewDiagnosticContexts) {
96270 getSymbolAccessibilityDiagnostic = oldDiag;
96271 }
96272 errorNameNode = undefined;
96273 }
96274 function shouldStripInternal(node) {
96275 return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
96276 }
96277 function isScopeMarker(node) {
96278 return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
96279 }
96280 function hasScopeMarker(statements) {
96281 return ts.some(statements, isScopeMarker);
96282 }
96283 function ensureModifiers(node) {
96284 var currentFlags = ts.getEffectiveModifierFlags(node);
96285 var newFlags = ensureModifierFlags(node);
96286 if (currentFlags === newFlags) {
96287 return node.modifiers;
96288 }
96289 return factory.createModifiersFromModifierFlags(newFlags);
96290 }
96291 function ensureModifierFlags(node) {
96292 var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
96293 var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
96294 var parentIsFile = node.parent.kind === 294 /* SourceFile */;
96295 if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
96296 mask ^= 2 /* Ambient */;
96297 additions = 0 /* None */;
96298 }
96299 return maskModifierFlags(node, mask, additions);
96300 }
96301 function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
96302 var accessorType = getTypeAnnotationFromAccessor(node);
96303 if (!accessorType && node !== accessors.firstAccessor) {
96304 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
96305 // 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
96306 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
96307 }
96308 if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
96309 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
96310 // 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
96311 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
96312 }
96313 return accessorType;
96314 }
96315 function transformHeritageClauses(nodes) {
96316 return factory.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) {
96317 return ts.isEntityNameExpression(t.expression) || (clause.token === 93 /* ExtendsKeyword */ && t.expression.kind === 103 /* NullKeyword */);
96318 })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
96319 }
96320 }
96321 ts.transformDeclarations = transformDeclarations;
96322 function isAlwaysType(node) {
96323 if (node.kind === 250 /* InterfaceDeclaration */) {
96324 return true;
96325 }
96326 return false;
96327 }
96328 // Elide "public" modifier, as it is the default
96329 function maskModifiers(node, modifierMask, modifierAdditions) {
96330 return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
96331 }
96332 function maskModifierFlags(node, modifierMask, modifierAdditions) {
96333 if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; }
96334 if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
96335 var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions;
96336 if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
96337 // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
96338 // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
96339 flags ^= 1 /* Export */;
96340 }
96341 if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
96342 flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
96343 }
96344 return flags;
96345 }
96346 function getTypeAnnotationFromAccessor(accessor) {
96347 if (accessor) {
96348 return accessor.kind === 166 /* GetAccessor */
96349 ? accessor.type // Getter - return type
96350 : accessor.parameters.length > 0
96351 ? accessor.parameters[0].type // Setter parameter type
96352 : undefined;
96353 }
96354 }
96355 function canHaveLiteralInitializer(node) {
96356 switch (node.kind) {
96357 case 162 /* PropertyDeclaration */:
96358 case 161 /* PropertySignature */:
96359 return !ts.hasEffectiveModifier(node, 8 /* Private */);
96360 case 159 /* Parameter */:
96361 case 246 /* VariableDeclaration */:
96362 return true;
96363 }
96364 return false;
96365 }
96366 function isPreservedDeclarationStatement(node) {
96367 switch (node.kind) {
96368 case 248 /* FunctionDeclaration */:
96369 case 253 /* ModuleDeclaration */:
96370 case 257 /* ImportEqualsDeclaration */:
96371 case 250 /* InterfaceDeclaration */:
96372 case 249 /* ClassDeclaration */:
96373 case 251 /* TypeAliasDeclaration */:
96374 case 252 /* EnumDeclaration */:
96375 case 229 /* VariableStatement */:
96376 case 258 /* ImportDeclaration */:
96377 case 264 /* ExportDeclaration */:
96378 case 263 /* ExportAssignment */:
96379 return true;
96380 }
96381 return false;
96382 }
96383 function isProcessedComponent(node) {
96384 switch (node.kind) {
96385 case 169 /* ConstructSignature */:
96386 case 165 /* Constructor */:
96387 case 164 /* MethodDeclaration */:
96388 case 166 /* GetAccessor */:
96389 case 167 /* SetAccessor */:
96390 case 162 /* PropertyDeclaration */:
96391 case 161 /* PropertySignature */:
96392 case 163 /* MethodSignature */:
96393 case 168 /* CallSignature */:
96394 case 170 /* IndexSignature */:
96395 case 246 /* VariableDeclaration */:
96396 case 158 /* TypeParameter */:
96397 case 220 /* ExpressionWithTypeArguments */:
96398 case 172 /* TypeReference */:
96399 case 183 /* ConditionalType */:
96400 case 173 /* FunctionType */:
96401 case 174 /* ConstructorType */:
96402 case 192 /* ImportType */:
96403 return true;
96404 }
96405 return false;
96406 }
96407})(ts || (ts = {}));
96408/* @internal */
96409var ts;
96410(function (ts) {
96411 function getModuleTransformer(moduleKind) {
96412 switch (moduleKind) {
96413 case ts.ModuleKind.ESNext:
96414 case ts.ModuleKind.ES2020:
96415 case ts.ModuleKind.ES2015:
96416 return ts.transformECMAScriptModule;
96417 case ts.ModuleKind.System:
96418 return ts.transformSystemModule;
96419 default:
96420 return ts.transformModule;
96421 }
96422 }
96423 var TransformationState;
96424 (function (TransformationState) {
96425 TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
96426 TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
96427 TransformationState[TransformationState["Completed"] = 2] = "Completed";
96428 TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
96429 })(TransformationState || (TransformationState = {}));
96430 var SyntaxKindFeatureFlags;
96431 (function (SyntaxKindFeatureFlags) {
96432 SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
96433 SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
96434 })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
96435 ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
96436 function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
96437 return {
96438 scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
96439 declarationTransformers: getDeclarationTransformers(customTransformers),
96440 };
96441 }
96442 ts.getTransformers = getTransformers;
96443 function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
96444 if (emitOnlyDtsFiles)
96445 return ts.emptyArray;
96446 var jsx = compilerOptions.jsx;
96447 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
96448 var moduleKind = ts.getEmitModuleKind(compilerOptions);
96449 var transformers = [];
96450 ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
96451 transformers.push(ts.transformTypeScript);
96452 transformers.push(ts.transformClassFields);
96453 if (jsx === 2 /* React */) {
96454 transformers.push(ts.transformJsx);
96455 }
96456 if (languageVersion < 99 /* ESNext */) {
96457 transformers.push(ts.transformESNext);
96458 }
96459 if (languageVersion < 7 /* ES2020 */) {
96460 transformers.push(ts.transformES2020);
96461 }
96462 if (languageVersion < 6 /* ES2019 */) {
96463 transformers.push(ts.transformES2019);
96464 }
96465 if (languageVersion < 5 /* ES2018 */) {
96466 transformers.push(ts.transformES2018);
96467 }
96468 if (languageVersion < 4 /* ES2017 */) {
96469 transformers.push(ts.transformES2017);
96470 }
96471 if (languageVersion < 3 /* ES2016 */) {
96472 transformers.push(ts.transformES2016);
96473 }
96474 if (languageVersion < 2 /* ES2015 */) {
96475 transformers.push(ts.transformES2015);
96476 transformers.push(ts.transformGenerators);
96477 }
96478 transformers.push(getModuleTransformer(moduleKind));
96479 // The ES5 transformer is last so that it can substitute expressions like `exports.default`
96480 // for ES3.
96481 if (languageVersion < 1 /* ES5 */) {
96482 transformers.push(ts.transformES5);
96483 }
96484 ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
96485 return transformers;
96486 }
96487 function getDeclarationTransformers(customTransformers) {
96488 var transformers = [];
96489 transformers.push(ts.transformDeclarations);
96490 ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
96491 return transformers;
96492 }
96493 /**
96494 * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
96495 */
96496 function wrapCustomTransformer(transformer) {
96497 return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
96498 }
96499 /**
96500 * Wrap a transformer factory that may return a custom script or declaration transformer object.
96501 */
96502 function wrapCustomTransformerFactory(transformer, handleDefault) {
96503 return function (context) {
96504 var customTransformer = transformer(context);
96505 return typeof customTransformer === "function"
96506 ? handleDefault(context, customTransformer)
96507 : wrapCustomTransformer(customTransformer);
96508 };
96509 }
96510 function wrapScriptTransformerFactory(transformer) {
96511 return wrapCustomTransformerFactory(transformer, ts.chainBundle);
96512 }
96513 function wrapDeclarationTransformerFactory(transformer) {
96514 return wrapCustomTransformerFactory(transformer, function (_, node) { return node; });
96515 }
96516 function noEmitSubstitution(_hint, node) {
96517 return node;
96518 }
96519 ts.noEmitSubstitution = noEmitSubstitution;
96520 function noEmitNotification(hint, node, callback) {
96521 callback(hint, node);
96522 }
96523 ts.noEmitNotification = noEmitNotification;
96524 /**
96525 * Transforms an array of SourceFiles by passing them through each transformer.
96526 *
96527 * @param resolver The emit resolver provided by the checker.
96528 * @param host The emit host object used to interact with the file system.
96529 * @param options Compiler options to surface in the `TransformationContext`.
96530 * @param nodes An array of nodes to transform.
96531 * @param transforms An array of `TransformerFactory` callbacks.
96532 * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
96533 */
96534 function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) {
96535 var enabledSyntaxKindFeatures = new Array(336 /* Count */);
96536 var lexicalEnvironmentVariableDeclarations;
96537 var lexicalEnvironmentFunctionDeclarations;
96538 var lexicalEnvironmentStatements;
96539 var lexicalEnvironmentFlags = 0 /* None */;
96540 var lexicalEnvironmentVariableDeclarationsStack = [];
96541 var lexicalEnvironmentFunctionDeclarationsStack = [];
96542 var lexicalEnvironmentStatementsStack = [];
96543 var lexicalEnvironmentFlagsStack = [];
96544 var lexicalEnvironmentStackOffset = 0;
96545 var lexicalEnvironmentSuspended = false;
96546 var emitHelpers;
96547 var onSubstituteNode = noEmitSubstitution;
96548 var onEmitNode = noEmitNotification;
96549 var state = 0 /* Uninitialized */;
96550 var diagnostics = [];
96551 // The transformation context is provided to each transformer as part of transformer
96552 // initialization.
96553 var context = {
96554 factory: factory,
96555 getCompilerOptions: function () { return options; },
96556 getEmitResolver: function () { return resolver; },
96557 getEmitHost: function () { return host; },
96558 getEmitHelperFactory: ts.memoize(function () { return ts.createEmitHelperFactory(context); }),
96559 startLexicalEnvironment: startLexicalEnvironment,
96560 suspendLexicalEnvironment: suspendLexicalEnvironment,
96561 resumeLexicalEnvironment: resumeLexicalEnvironment,
96562 endLexicalEnvironment: endLexicalEnvironment,
96563 setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
96564 getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
96565 hoistVariableDeclaration: hoistVariableDeclaration,
96566 hoistFunctionDeclaration: hoistFunctionDeclaration,
96567 addInitializationStatement: addInitializationStatement,
96568 requestEmitHelper: requestEmitHelper,
96569 readEmitHelpers: readEmitHelpers,
96570 enableSubstitution: enableSubstitution,
96571 enableEmitNotification: enableEmitNotification,
96572 isSubstitutionEnabled: isSubstitutionEnabled,
96573 isEmitNotificationEnabled: isEmitNotificationEnabled,
96574 get onSubstituteNode() { return onSubstituteNode; },
96575 set onSubstituteNode(value) {
96576 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
96577 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
96578 onSubstituteNode = value;
96579 },
96580 get onEmitNode() { return onEmitNode; },
96581 set onEmitNode(value) {
96582 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
96583 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
96584 onEmitNode = value;
96585 },
96586 addDiagnostic: function (diag) {
96587 diagnostics.push(diag);
96588 }
96589 };
96590 // Ensure the parse tree is clean before applying transformations
96591 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
96592 var node = nodes_2[_i];
96593 ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
96594 }
96595 ts.performance.mark("beforeTransform");
96596 // Chain together and initialize each transformer.
96597 var transformersWithContext = transformers.map(function (t) { return t(context); });
96598 var transformation = function (node) {
96599 for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
96600 var transform = transformersWithContext_1[_i];
96601 node = transform(node);
96602 }
96603 return node;
96604 };
96605 // prevent modification of transformation hooks.
96606 state = 1 /* Initialized */;
96607 // Transform each node.
96608 var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
96609 // prevent modification of the lexical environment.
96610 state = 2 /* Completed */;
96611 ts.performance.mark("afterTransform");
96612 ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
96613 return {
96614 transformed: transformed,
96615 substituteNode: substituteNode,
96616 emitNodeWithNotification: emitNodeWithNotification,
96617 isEmitNotificationEnabled: isEmitNotificationEnabled,
96618 dispose: dispose,
96619 diagnostics: diagnostics
96620 };
96621 function transformRoot(node) {
96622 return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
96623 }
96624 /**
96625 * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
96626 */
96627 function enableSubstitution(kind) {
96628 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
96629 enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
96630 }
96631 /**
96632 * Determines whether expression substitutions are enabled for the provided node.
96633 */
96634 function isSubstitutionEnabled(node) {
96635 return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
96636 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
96637 }
96638 /**
96639 * Emits a node with possible substitution.
96640 *
96641 * @param hint A hint as to the intended usage of the node.
96642 * @param node The node to emit.
96643 * @param emitCallback The callback used to emit the node or its substitute.
96644 */
96645 function substituteNode(hint, node) {
96646 ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
96647 return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
96648 }
96649 /**
96650 * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
96651 */
96652 function enableEmitNotification(kind) {
96653 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
96654 enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
96655 }
96656 /**
96657 * Determines whether before/after emit notifications should be raised in the pretty
96658 * printer when it emits a node.
96659 */
96660 function isEmitNotificationEnabled(node) {
96661 return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
96662 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
96663 }
96664 /**
96665 * Emits a node with possible emit notification.
96666 *
96667 * @param hint A hint as to the intended usage of the node.
96668 * @param node The node to emit.
96669 * @param emitCallback The callback used to emit the node.
96670 */
96671 function emitNodeWithNotification(hint, node, emitCallback) {
96672 ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
96673 if (node) {
96674 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
96675 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
96676 if (isEmitNotificationEnabled(node)) {
96677 onEmitNode(hint, node, emitCallback);
96678 }
96679 else {
96680 emitCallback(hint, node);
96681 }
96682 }
96683 }
96684 /**
96685 * Records a hoisted variable declaration for the provided name within a lexical environment.
96686 */
96687 function hoistVariableDeclaration(name) {
96688 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96689 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96690 var decl = ts.setEmitFlags(factory.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
96691 if (!lexicalEnvironmentVariableDeclarations) {
96692 lexicalEnvironmentVariableDeclarations = [decl];
96693 }
96694 else {
96695 lexicalEnvironmentVariableDeclarations.push(decl);
96696 }
96697 if (lexicalEnvironmentFlags & 1 /* InParameters */) {
96698 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
96699 }
96700 }
96701 /**
96702 * Records a hoisted function declaration within a lexical environment.
96703 */
96704 function hoistFunctionDeclaration(func) {
96705 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96706 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96707 ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
96708 if (!lexicalEnvironmentFunctionDeclarations) {
96709 lexicalEnvironmentFunctionDeclarations = [func];
96710 }
96711 else {
96712 lexicalEnvironmentFunctionDeclarations.push(func);
96713 }
96714 }
96715 /**
96716 * Adds an initialization statement to the top of the lexical environment.
96717 */
96718 function addInitializationStatement(node) {
96719 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96720 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96721 ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
96722 if (!lexicalEnvironmentStatements) {
96723 lexicalEnvironmentStatements = [node];
96724 }
96725 else {
96726 lexicalEnvironmentStatements.push(node);
96727 }
96728 }
96729 /**
96730 * Starts a new lexical environment. Any existing hoisted variable or function declarations
96731 * are pushed onto a stack, and the related storage variables are reset.
96732 */
96733 function startLexicalEnvironment() {
96734 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96735 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96736 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
96737 // Save the current lexical environment. Rather than resizing the array we adjust the
96738 // stack size variable. This allows us to reuse existing array slots we've
96739 // already allocated between transformations to avoid allocation and GC overhead during
96740 // transformation.
96741 lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
96742 lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
96743 lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
96744 lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
96745 lexicalEnvironmentStackOffset++;
96746 lexicalEnvironmentVariableDeclarations = undefined;
96747 lexicalEnvironmentFunctionDeclarations = undefined;
96748 lexicalEnvironmentStatements = undefined;
96749 lexicalEnvironmentFlags = 0 /* None */;
96750 }
96751 /** Suspends the current lexical environment, usually after visiting a parameter list. */
96752 function suspendLexicalEnvironment() {
96753 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96754 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96755 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
96756 lexicalEnvironmentSuspended = true;
96757 }
96758 /** Resumes a suspended lexical environment, usually before visiting a function body. */
96759 function resumeLexicalEnvironment() {
96760 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96761 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96762 ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
96763 lexicalEnvironmentSuspended = false;
96764 }
96765 /**
96766 * Ends a lexical environment. The previous set of hoisted declarations are restored and
96767 * any hoisted declarations added in this environment are returned.
96768 */
96769 function endLexicalEnvironment() {
96770 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
96771 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
96772 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
96773 var statements;
96774 if (lexicalEnvironmentVariableDeclarations ||
96775 lexicalEnvironmentFunctionDeclarations ||
96776 lexicalEnvironmentStatements) {
96777 if (lexicalEnvironmentFunctionDeclarations) {
96778 statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
96779 }
96780 if (lexicalEnvironmentVariableDeclarations) {
96781 var statement = factory.createVariableStatement(
96782 /*modifiers*/ undefined, factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
96783 ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
96784 if (!statements) {
96785 statements = [statement];
96786 }
96787 else {
96788 statements.push(statement);
96789 }
96790 }
96791 if (lexicalEnvironmentStatements) {
96792 if (!statements) {
96793 statements = __spreadArrays(lexicalEnvironmentStatements);
96794 }
96795 else {
96796 statements = __spreadArrays(statements, lexicalEnvironmentStatements);
96797 }
96798 }
96799 }
96800 // Restore the previous lexical environment.
96801 lexicalEnvironmentStackOffset--;
96802 lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
96803 lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
96804 lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
96805 lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
96806 if (lexicalEnvironmentStackOffset === 0) {
96807 lexicalEnvironmentVariableDeclarationsStack = [];
96808 lexicalEnvironmentFunctionDeclarationsStack = [];
96809 lexicalEnvironmentStatementsStack = [];
96810 lexicalEnvironmentFlagsStack = [];
96811 }
96812 return statements;
96813 }
96814 function setLexicalEnvironmentFlags(flags, value) {
96815 lexicalEnvironmentFlags = value ?
96816 lexicalEnvironmentFlags | flags :
96817 lexicalEnvironmentFlags & ~flags;
96818 }
96819 function getLexicalEnvironmentFlags() {
96820 return lexicalEnvironmentFlags;
96821 }
96822 function requestEmitHelper(helper) {
96823 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
96824 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
96825 ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
96826 if (helper.dependencies) {
96827 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
96828 var h = _a[_i];
96829 requestEmitHelper(h);
96830 }
96831 }
96832 emitHelpers = ts.append(emitHelpers, helper);
96833 }
96834 function readEmitHelpers() {
96835 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
96836 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
96837 var helpers = emitHelpers;
96838 emitHelpers = undefined;
96839 return helpers;
96840 }
96841 function dispose() {
96842 if (state < 3 /* Disposed */) {
96843 // Clean up emit nodes on parse tree
96844 for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
96845 var node = nodes_3[_i];
96846 ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
96847 }
96848 // Release references to external entries for GC purposes.
96849 lexicalEnvironmentVariableDeclarations = undefined;
96850 lexicalEnvironmentVariableDeclarationsStack = undefined;
96851 lexicalEnvironmentFunctionDeclarations = undefined;
96852 lexicalEnvironmentFunctionDeclarationsStack = undefined;
96853 onSubstituteNode = undefined;
96854 onEmitNode = undefined;
96855 emitHelpers = undefined;
96856 // Prevent further use of the transformation result.
96857 state = 3 /* Disposed */;
96858 }
96859 }
96860 }
96861 ts.transformNodes = transformNodes;
96862 ts.nullTransformationContext = {
96863 get factory() { return ts.factory; },
96864 enableEmitNotification: ts.noop,
96865 enableSubstitution: ts.noop,
96866 endLexicalEnvironment: ts.returnUndefined,
96867 getCompilerOptions: function () { return ({}); },
96868 getEmitHost: ts.notImplemented,
96869 getEmitResolver: ts.notImplemented,
96870 getEmitHelperFactory: ts.notImplemented,
96871 setLexicalEnvironmentFlags: ts.noop,
96872 getLexicalEnvironmentFlags: function () { return 0; },
96873 hoistFunctionDeclaration: ts.noop,
96874 hoistVariableDeclaration: ts.noop,
96875 addInitializationStatement: ts.noop,
96876 isEmitNotificationEnabled: ts.notImplemented,
96877 isSubstitutionEnabled: ts.notImplemented,
96878 onEmitNode: ts.noop,
96879 onSubstituteNode: ts.notImplemented,
96880 readEmitHelpers: ts.notImplemented,
96881 requestEmitHelper: ts.noop,
96882 resumeLexicalEnvironment: ts.noop,
96883 startLexicalEnvironment: ts.noop,
96884 suspendLexicalEnvironment: ts.noop,
96885 addDiagnostic: ts.noop,
96886 };
96887})(ts || (ts = {}));
96888var ts;
96889(function (ts) {
96890 var brackets = createBracketsMap();
96891 var syntheticParent = { pos: -1, end: -1 };
96892 /*@internal*/
96893 function isBuildInfoFile(file) {
96894 return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
96895 }
96896 ts.isBuildInfoFile = isBuildInfoFile;
96897 /*@internal*/
96898 /**
96899 * Iterates over the source files that are expected to have an emit output.
96900 *
96901 * @param host An EmitHost.
96902 * @param action The action to execute.
96903 * @param sourceFilesOrTargetSourceFile
96904 * If an array, the full list of source files to emit.
96905 * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
96906 */
96907 function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
96908 if (forceDtsEmit === void 0) { forceDtsEmit = false; }
96909 var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
96910 var options = host.getCompilerOptions();
96911 if (ts.outFile(options)) {
96912 var prepends = host.getPrependNodes();
96913 if (sourceFiles.length || prepends.length) {
96914 var bundle = ts.factory.createBundle(sourceFiles, prepends);
96915 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
96916 if (result) {
96917 return result;
96918 }
96919 }
96920 }
96921 else {
96922 if (!onlyBuildInfo) {
96923 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
96924 var sourceFile = sourceFiles_1[_a];
96925 var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
96926 if (result) {
96927 return result;
96928 }
96929 }
96930 }
96931 if (includeBuildInfo) {
96932 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
96933 if (buildInfoPath)
96934 return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
96935 }
96936 }
96937 }
96938 ts.forEachEmittedFile = forEachEmittedFile;
96939 function getTsBuildInfoEmitOutputFilePath(options) {
96940 var configFile = options.configFilePath;
96941 if (!ts.isIncrementalCompilation(options))
96942 return undefined;
96943 if (options.tsBuildInfoFile)
96944 return options.tsBuildInfoFile;
96945 var outPath = ts.outFile(options);
96946 var buildInfoExtensionLess;
96947 if (outPath) {
96948 buildInfoExtensionLess = ts.removeFileExtension(outPath);
96949 }
96950 else {
96951 if (!configFile)
96952 return undefined;
96953 var configFileExtensionLess = ts.removeFileExtension(configFile);
96954 buildInfoExtensionLess = options.outDir ?
96955 options.rootDir ?
96956 ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
96957 ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
96958 configFileExtensionLess;
96959 }
96960 return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
96961 }
96962 ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
96963 /*@internal*/
96964 function getOutputPathsForBundle(options, forceDtsPaths) {
96965 var outPath = ts.outFile(options);
96966 var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
96967 var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
96968 var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
96969 var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
96970 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
96971 return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
96972 }
96973 ts.getOutputPathsForBundle = getOutputPathsForBundle;
96974 /*@internal*/
96975 function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
96976 var options = host.getCompilerOptions();
96977 if (sourceFile.kind === 295 /* Bundle */) {
96978 return getOutputPathsForBundle(options, forceDtsPaths);
96979 }
96980 else {
96981 var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
96982 var isJsonFile = ts.isJsonSourceFile(sourceFile);
96983 // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
96984 var isJsonEmittedToSameLocation = isJsonFile &&
96985 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
96986 var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
96987 var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
96988 var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
96989 var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
96990 return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
96991 }
96992 }
96993 ts.getOutputPathsFor = getOutputPathsFor;
96994 function getSourceMapFilePath(jsFilePath, options) {
96995 return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
96996 }
96997 // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
96998 // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
96999 // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
97000 /* @internal */
97001 function getOutputExtension(sourceFile, options) {
97002 if (ts.isJsonSourceFile(sourceFile)) {
97003 return ".json" /* Json */;
97004 }
97005 if (options.jsx === 1 /* Preserve */) {
97006 if (ts.isSourceFileJS(sourceFile)) {
97007 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
97008 return ".jsx" /* Jsx */;
97009 }
97010 }
97011 else if (sourceFile.languageVariant === 1 /* JSX */) {
97012 // TypeScript source file preserving JSX syntax
97013 return ".jsx" /* Jsx */;
97014 }
97015 }
97016 return ".js" /* Js */;
97017 }
97018 ts.getOutputExtension = getOutputExtension;
97019 function rootDirOfOptions(configFile) {
97020 return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
97021 }
97022 function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
97023 return outputDir ?
97024 ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
97025 inputFileName;
97026 }
97027 /* @internal */
97028 function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
97029 ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
97030 return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
97031 }
97032 ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
97033 function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
97034 if (configFile.options.emitDeclarationOnly)
97035 return undefined;
97036 var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
97037 var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
97038 ".json" /* Json */ :
97039 ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
97040 ".jsx" /* Jsx */ :
97041 ".js" /* Js */);
97042 return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
97043 outputFileName :
97044 undefined;
97045 }
97046 function createAddOutput() {
97047 var outputs;
97048 return { addOutput: addOutput, getOutputs: getOutputs };
97049 function addOutput(path) {
97050 if (path) {
97051 (outputs || (outputs = [])).push(path);
97052 }
97053 }
97054 function getOutputs() {
97055 return outputs || ts.emptyArray;
97056 }
97057 }
97058 function getSingleOutputFileNames(configFile, addOutput) {
97059 var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
97060 addOutput(jsFilePath);
97061 addOutput(sourceMapFilePath);
97062 addOutput(declarationFilePath);
97063 addOutput(declarationMapPath);
97064 addOutput(buildInfoPath);
97065 }
97066 function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
97067 if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
97068 return;
97069 var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
97070 addOutput(js);
97071 if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
97072 return;
97073 if (js && configFile.options.sourceMap) {
97074 addOutput(js + ".map");
97075 }
97076 if (ts.getEmitDeclarations(configFile.options)) {
97077 var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
97078 addOutput(dts);
97079 if (configFile.options.declarationMap) {
97080 addOutput(dts + ".map");
97081 }
97082 }
97083 }
97084 /*@internal*/
97085 function getAllProjectOutputs(configFile, ignoreCase) {
97086 var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
97087 if (ts.outFile(configFile.options)) {
97088 getSingleOutputFileNames(configFile, addOutput);
97089 }
97090 else {
97091 for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
97092 var inputFileName = _c[_b];
97093 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
97094 }
97095 addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
97096 }
97097 return getOutputs();
97098 }
97099 ts.getAllProjectOutputs = getAllProjectOutputs;
97100 function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
97101 inputFileName = ts.normalizePath(inputFileName);
97102 ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
97103 var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
97104 if (ts.outFile(commandLine.options)) {
97105 getSingleOutputFileNames(commandLine, addOutput);
97106 }
97107 else {
97108 getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
97109 }
97110 return getOutputs();
97111 }
97112 ts.getOutputFileNames = getOutputFileNames;
97113 /*@internal*/
97114 function getFirstProjectOutput(configFile, ignoreCase) {
97115 if (ts.outFile(configFile.options)) {
97116 var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
97117 return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
97118 }
97119 for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
97120 var inputFileName = _b[_a];
97121 if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
97122 continue;
97123 var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
97124 if (jsFilePath)
97125 return jsFilePath;
97126 if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
97127 continue;
97128 if (ts.getEmitDeclarations(configFile.options)) {
97129 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
97130 }
97131 }
97132 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
97133 if (buildInfoPath)
97134 return buildInfoPath;
97135 return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
97136 }
97137 ts.getFirstProjectOutput = getFirstProjectOutput;
97138 /*@internal*/
97139 // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
97140 function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
97141 var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
97142 var compilerOptions = host.getCompilerOptions();
97143 var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
97144 var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
97145 var emitterDiagnostics = ts.createDiagnosticCollection();
97146 var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
97147 var writer = ts.createTextWriter(newLine);
97148 var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
97149 var bundleBuildInfo;
97150 var emitSkipped = false;
97151 var exportedModulesFromDeclarationEmit;
97152 // Emit each output file
97153 enter();
97154 forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
97155 exit();
97156 return {
97157 emitSkipped: emitSkipped,
97158 diagnostics: emitterDiagnostics.getDiagnostics(),
97159 emittedFiles: emittedFilesList,
97160 sourceMaps: sourceMapDataList,
97161 exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
97162 };
97163 function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
97164 var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
97165 var buildInfoDirectory;
97166 if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
97167 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
97168 bundleBuildInfo = {
97169 commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
97170 sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
97171 };
97172 }
97173 emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
97174 emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
97175 emitBuildInfo(bundleBuildInfo, buildInfoPath);
97176 if (!emitSkipped && emittedFilesList) {
97177 if (!emitOnlyDtsFiles) {
97178 if (jsFilePath) {
97179 emittedFilesList.push(jsFilePath);
97180 }
97181 if (sourceMapFilePath) {
97182 emittedFilesList.push(sourceMapFilePath);
97183 }
97184 if (buildInfoPath) {
97185 emittedFilesList.push(buildInfoPath);
97186 }
97187 }
97188 if (declarationFilePath) {
97189 emittedFilesList.push(declarationFilePath);
97190 }
97191 if (declarationMapPath) {
97192 emittedFilesList.push(declarationMapPath);
97193 }
97194 }
97195 function relativeToBuildInfo(path) {
97196 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
97197 }
97198 }
97199 function emitBuildInfo(bundle, buildInfoPath) {
97200 // Write build information if applicable
97201 if (!buildInfoPath || targetSourceFile || emitSkipped)
97202 return;
97203 var program = host.getProgramBuildInfo();
97204 if (host.isEmitBlocked(buildInfoPath)) {
97205 emitSkipped = true;
97206 return;
97207 }
97208 var version = ts.version; // Extracted into a const so the form is stable between namespace and module
97209 ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
97210 }
97211 function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
97212 if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
97213 return;
97214 }
97215 // Make sure not to write js file and source map file if any of them cannot be written
97216 if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
97217 emitSkipped = true;
97218 return;
97219 }
97220 // Transform the source files
97221 var transform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
97222 var printerOptions = {
97223 removeComments: compilerOptions.removeComments,
97224 newLine: compilerOptions.newLine,
97225 noEmitHelpers: compilerOptions.noEmitHelpers,
97226 module: compilerOptions.module,
97227 target: compilerOptions.target,
97228 sourceMap: compilerOptions.sourceMap,
97229 inlineSourceMap: compilerOptions.inlineSourceMap,
97230 inlineSources: compilerOptions.inlineSources,
97231 extendedDiagnostics: compilerOptions.extendedDiagnostics,
97232 writeBundleFileInfo: !!bundleBuildInfo,
97233 relativeToBuildInfo: relativeToBuildInfo
97234 };
97235 // Create a printer to print the nodes
97236 var printer = createPrinter(printerOptions, {
97237 // resolver hooks
97238 hasGlobalName: resolver.hasGlobalName,
97239 // transform hooks
97240 onEmitNode: transform.emitNodeWithNotification,
97241 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
97242 substituteNode: transform.substituteNode,
97243 });
97244 ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
97245 printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
97246 // Clean up emit nodes on parse tree
97247 transform.dispose();
97248 if (bundleBuildInfo)
97249 bundleBuildInfo.js = printer.bundleFileInfo;
97250 }
97251 function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
97252 if (!sourceFileOrBundle)
97253 return;
97254 if (!declarationFilePath) {
97255 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
97256 emitSkipped = true;
97257 return;
97258 }
97259 var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
97260 var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
97261 // Setup and perform the transformation to retrieve declarations from the input files
97262 var inputListOrBundle = ts.outFile(compilerOptions) ? [ts.factory.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
97263 if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
97264 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
97265 // Do that here when emitting only dts files
97266 filesForEmit.forEach(collectLinkedAliases);
97267 }
97268 var declarationTransform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
97269 if (ts.length(declarationTransform.diagnostics)) {
97270 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
97271 var diagnostic = _b[_a];
97272 emitterDiagnostics.add(diagnostic);
97273 }
97274 }
97275 var printerOptions = {
97276 removeComments: compilerOptions.removeComments,
97277 newLine: compilerOptions.newLine,
97278 noEmitHelpers: true,
97279 module: compilerOptions.module,
97280 target: compilerOptions.target,
97281 sourceMap: compilerOptions.sourceMap,
97282 inlineSourceMap: compilerOptions.inlineSourceMap,
97283 extendedDiagnostics: compilerOptions.extendedDiagnostics,
97284 onlyPrintJsDocStyle: true,
97285 writeBundleFileInfo: !!bundleBuildInfo,
97286 recordInternalSection: !!bundleBuildInfo,
97287 relativeToBuildInfo: relativeToBuildInfo
97288 };
97289 var declarationPrinter = createPrinter(printerOptions, {
97290 // resolver hooks
97291 hasGlobalName: resolver.hasGlobalName,
97292 // transform hooks
97293 onEmitNode: declarationTransform.emitNodeWithNotification,
97294 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
97295 substituteNode: declarationTransform.substituteNode,
97296 });
97297 var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
97298 emitSkipped = emitSkipped || declBlocked;
97299 if (!declBlocked || forceDtsEmit) {
97300 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
97301 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
97302 sourceMap: compilerOptions.declarationMap,
97303 sourceRoot: compilerOptions.sourceRoot,
97304 mapRoot: compilerOptions.mapRoot,
97305 extendedDiagnostics: compilerOptions.extendedDiagnostics,
97306 });
97307 if (forceDtsEmit && declarationTransform.transformed[0].kind === 294 /* SourceFile */) {
97308 var sourceFile = declarationTransform.transformed[0];
97309 exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
97310 }
97311 }
97312 declarationTransform.dispose();
97313 if (bundleBuildInfo)
97314 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
97315 }
97316 function collectLinkedAliases(node) {
97317 if (ts.isExportAssignment(node)) {
97318 if (node.expression.kind === 78 /* Identifier */) {
97319 resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
97320 }
97321 return;
97322 }
97323 else if (ts.isExportSpecifier(node)) {
97324 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
97325 return;
97326 }
97327 ts.forEachChild(node, collectLinkedAliases);
97328 }
97329 function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
97330 var bundle = sourceFileOrBundle.kind === 295 /* Bundle */ ? sourceFileOrBundle : undefined;
97331 var sourceFile = sourceFileOrBundle.kind === 294 /* SourceFile */ ? sourceFileOrBundle : undefined;
97332 var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
97333 var sourceMapGenerator;
97334 if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
97335 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
97336 }
97337 if (bundle) {
97338 printer.writeBundle(bundle, writer, sourceMapGenerator);
97339 }
97340 else {
97341 printer.writeFile(sourceFile, writer, sourceMapGenerator);
97342 }
97343 if (sourceMapGenerator) {
97344 if (sourceMapDataList) {
97345 sourceMapDataList.push({
97346 inputSourceFileNames: sourceMapGenerator.getSources(),
97347 sourceMap: sourceMapGenerator.toJSON()
97348 });
97349 }
97350 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
97351 if (sourceMappingURL) {
97352 if (!writer.isAtStartOfLine())
97353 writer.rawWrite(newLine);
97354 writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
97355 }
97356 // Write the source map
97357 if (sourceMapFilePath) {
97358 var sourceMap = sourceMapGenerator.toString();
97359 ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
97360 }
97361 }
97362 else {
97363 writer.writeLine();
97364 }
97365 // Write the output file
97366 ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
97367 // Reset state
97368 writer.clear();
97369 }
97370 function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
97371 return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
97372 && (sourceFileOrBundle.kind !== 294 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
97373 }
97374 function getSourceRoot(mapOptions) {
97375 // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
97376 // relative paths of the sources list in the sourcemap
97377 var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
97378 return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
97379 }
97380 function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
97381 if (mapOptions.sourceRoot)
97382 return host.getCommonSourceDirectory();
97383 if (mapOptions.mapRoot) {
97384 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
97385 if (sourceFile) {
97386 // For modules or multiple emit files the mapRoot will have directory structure like the sources
97387 // 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
97388 sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
97389 }
97390 if (ts.getRootLength(sourceMapDir) === 0) {
97391 // The relative paths are relative to the common directory
97392 sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
97393 }
97394 return sourceMapDir;
97395 }
97396 return ts.getDirectoryPath(ts.normalizePath(filePath));
97397 }
97398 function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
97399 if (mapOptions.inlineSourceMap) {
97400 // Encode the sourceMap into the sourceMap url
97401 var sourceMapText = sourceMapGenerator.toString();
97402 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
97403 return "data:application/json;base64," + base64SourceMapText;
97404 }
97405 var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
97406 if (mapOptions.mapRoot) {
97407 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
97408 if (sourceFile) {
97409 // For modules or multiple emit files the mapRoot will have directory structure like the sources
97410 // 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
97411 sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
97412 }
97413 if (ts.getRootLength(sourceMapDir) === 0) {
97414 // The relative paths are relative to the common directory
97415 sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
97416 return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
97417 ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
97418 host.getCurrentDirectory(), host.getCanonicalFileName,
97419 /*isAbsolutePathAnUrl*/ true);
97420 }
97421 else {
97422 return ts.combinePaths(sourceMapDir, sourceMapFile);
97423 }
97424 }
97425 return sourceMapFile;
97426 }
97427 }
97428 ts.emitFiles = emitFiles;
97429 /*@internal*/
97430 function getBuildInfoText(buildInfo) {
97431 return JSON.stringify(buildInfo, undefined, 2);
97432 }
97433 ts.getBuildInfoText = getBuildInfoText;
97434 /*@internal*/
97435 function getBuildInfo(buildInfoText) {
97436 return JSON.parse(buildInfoText);
97437 }
97438 ts.getBuildInfo = getBuildInfo;
97439 /*@internal*/
97440 ts.notImplementedResolver = {
97441 hasGlobalName: ts.notImplemented,
97442 getReferencedExportContainer: ts.notImplemented,
97443 getReferencedImportDeclaration: ts.notImplemented,
97444 getReferencedDeclarationWithCollidingName: ts.notImplemented,
97445 isDeclarationWithCollidingName: ts.notImplemented,
97446 isValueAliasDeclaration: ts.notImplemented,
97447 isReferencedAliasDeclaration: ts.notImplemented,
97448 isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
97449 getNodeCheckFlags: ts.notImplemented,
97450 isDeclarationVisible: ts.notImplemented,
97451 isLateBound: function (_node) { return false; },
97452 collectLinkedAliases: ts.notImplemented,
97453 isImplementationOfOverload: ts.notImplemented,
97454 isRequiredInitializedParameter: ts.notImplemented,
97455 isOptionalUninitializedParameterProperty: ts.notImplemented,
97456 isExpandoFunctionDeclaration: ts.notImplemented,
97457 getPropertiesOfContainerFunction: ts.notImplemented,
97458 createTypeOfDeclaration: ts.notImplemented,
97459 createReturnTypeOfSignatureDeclaration: ts.notImplemented,
97460 createTypeOfExpression: ts.notImplemented,
97461 createLiteralConstValue: ts.notImplemented,
97462 isSymbolAccessible: ts.notImplemented,
97463 isEntityNameVisible: ts.notImplemented,
97464 // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
97465 getConstantValue: ts.notImplemented,
97466 getReferencedValueDeclaration: ts.notImplemented,
97467 getTypeReferenceSerializationKind: ts.notImplemented,
97468 isOptionalParameter: ts.notImplemented,
97469 moduleExportsSomeValue: ts.notImplemented,
97470 isArgumentsLocalBinding: ts.notImplemented,
97471 getExternalModuleFileFromDeclaration: ts.notImplemented,
97472 getTypeReferenceDirectivesForEntityName: ts.notImplemented,
97473 getTypeReferenceDirectivesForSymbol: ts.notImplemented,
97474 isLiteralConstDeclaration: ts.notImplemented,
97475 getJsxFactoryEntity: ts.notImplemented,
97476 getJsxFragmentFactoryEntity: ts.notImplemented,
97477 getAllAccessorDeclarations: ts.notImplemented,
97478 getSymbolOfExternalModuleSpecifier: ts.notImplemented,
97479 isBindingCapturedByNode: ts.notImplemented,
97480 getDeclarationStatementsForSourceFile: ts.notImplemented,
97481 isImportRequiredByAugmentation: ts.notImplemented,
97482 };
97483 function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
97484 var _a;
97485 var jsBundle = ts.Debug.checkDefined(bundle.js);
97486 var prologueMap = ((_a = jsBundle.sources) === null || _a === void 0 ? void 0 : _a.prologues) && ts.arrayToMap(jsBundle.sources.prologues, function (prologueInfo) { return prologueInfo.file; });
97487 return bundle.sourceFiles.map(function (fileName, index) {
97488 var _a, _b;
97489 var prologueInfo = prologueMap === null || prologueMap === void 0 ? void 0 : prologueMap.get(index);
97490 var statements = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.directives.map(function (directive) {
97491 var literal = ts.setTextRange(ts.factory.createStringLiteral(directive.expression.text), directive.expression);
97492 var statement = ts.setTextRange(ts.factory.createExpressionStatement(literal), directive);
97493 ts.setParent(literal, statement);
97494 return statement;
97495 });
97496 var eofToken = ts.factory.createToken(1 /* EndOfFileToken */);
97497 var sourceFile = ts.factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */);
97498 sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
97499 sourceFile.text = (_a = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text) !== null && _a !== void 0 ? _a : "";
97500 ts.setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text.length) !== null && _b !== void 0 ? _b : 0);
97501 ts.setEachParent(sourceFile.statements, sourceFile);
97502 ts.setTextRangePosWidth(eofToken, sourceFile.end, 0);
97503 ts.setParent(eofToken, sourceFile);
97504 return sourceFile;
97505 });
97506 }
97507 /*@internal*/
97508 function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
97509 var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
97510 var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
97511 if (!buildInfoText)
97512 return buildInfoPath;
97513 var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
97514 if (!jsFileText)
97515 return jsFilePath;
97516 var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
97517 // error if no source map or for now if inline sourcemap
97518 if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
97519 return sourceMapFilePath || "inline sourcemap decoding";
97520 // read declaration text
97521 var declarationText = declarationFilePath && host.readFile(declarationFilePath);
97522 if (declarationFilePath && !declarationText)
97523 return declarationFilePath;
97524 var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
97525 // error if no source map or for now if inline sourcemap
97526 if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
97527 return declarationMapPath || "inline sourcemap decoding";
97528 var buildInfo = getBuildInfo(buildInfoText);
97529 if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
97530 return buildInfoPath;
97531 var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
97532 var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
97533 /*onlyOwnText*/ true);
97534 var outputFiles = [];
97535 var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
97536 var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
97537 var emitHost = {
97538 getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
97539 getCanonicalFileName: host.getCanonicalFileName,
97540 getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
97541 getCompilerOptions: function () { return config.options; },
97542 getCurrentDirectory: function () { return host.getCurrentDirectory(); },
97543 getNewLine: function () { return host.getNewLine(); },
97544 getSourceFile: ts.returnUndefined,
97545 getSourceFileByPath: ts.returnUndefined,
97546 getSourceFiles: function () { return sourceFilesForJsEmit; },
97547 getLibFileFromReference: ts.notImplemented,
97548 isSourceFileFromExternalLibrary: ts.returnFalse,
97549 getResolvedProjectReferenceToRedirect: ts.returnUndefined,
97550 getProjectReferenceRedirect: ts.returnUndefined,
97551 isSourceOfProjectReferenceRedirect: ts.returnFalse,
97552 writeFile: function (name, text, writeByteOrderMark) {
97553 switch (name) {
97554 case jsFilePath:
97555 if (jsFileText === text)
97556 return;
97557 break;
97558 case sourceMapFilePath:
97559 if (sourceMapText === text)
97560 return;
97561 break;
97562 case buildInfoPath:
97563 var newBuildInfo = getBuildInfo(text);
97564 newBuildInfo.program = buildInfo.program;
97565 // Update sourceFileInfo
97566 var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
97567 newBuildInfo.bundle.js.sources = js.sources;
97568 if (dts) {
97569 newBuildInfo.bundle.dts.sources = dts.sources;
97570 }
97571 newBuildInfo.bundle.sourceFiles = sourceFiles;
97572 outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
97573 return;
97574 case declarationFilePath:
97575 if (declarationText === text)
97576 return;
97577 break;
97578 case declarationMapPath:
97579 if (declarationMapText === text)
97580 return;
97581 break;
97582 default:
97583 ts.Debug.fail("Unexpected path: " + name);
97584 }
97585 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
97586 },
97587 isEmitBlocked: ts.returnFalse,
97588 readFile: function (f) { return host.readFile(f); },
97589 fileExists: function (f) { return host.fileExists(f); },
97590 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
97591 getProgramBuildInfo: ts.returnUndefined,
97592 getSourceFileFromReference: ts.returnUndefined,
97593 redirectTargetsMap: ts.createMultiMap()
97594 };
97595 emitFiles(ts.notImplementedResolver, emitHost,
97596 /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
97597 return outputFiles;
97598 }
97599 ts.emitUsingBuildInfo = emitUsingBuildInfo;
97600 var PipelinePhase;
97601 (function (PipelinePhase) {
97602 PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
97603 PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
97604 PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
97605 PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
97606 PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
97607 })(PipelinePhase || (PipelinePhase = {}));
97608 function createPrinter(printerOptions, handlers) {
97609 if (printerOptions === void 0) { printerOptions = {}; }
97610 if (handlers === void 0) { handlers = {}; }
97611 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;
97612 var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
97613 var newLine = ts.getNewLineCharacter(printerOptions);
97614 var moduleKind = ts.getEmitModuleKind(printerOptions);
97615 var bundledHelpers = new ts.Map();
97616 var currentSourceFile;
97617 var nodeIdToGeneratedName; // Map of generated names for specific nodes.
97618 var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
97619 var generatedNames; // Set of names generated by the NameGenerator.
97620 var tempFlagsStack; // Stack of enclosing name generation scopes.
97621 var tempFlags; // TempFlags for the current name generation scope.
97622 var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
97623 var reservedNames; // TempFlags to reserve in nested name generation scopes.
97624 var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
97625 var nextListElementPos; // See comment in `getLeadingLineTerminatorCount`.
97626 var writer;
97627 var ownWriter; // Reusable `EmitTextWriter` for basic printing.
97628 var write = writeBase;
97629 var isOwnFileEmit;
97630 var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
97631 var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
97632 var recordInternalSection = printerOptions.recordInternalSection;
97633 var sourceFileTextPos = 0;
97634 var sourceFileTextKind = "text" /* Text */;
97635 // Source Maps
97636 var sourceMapsDisabled = true;
97637 var sourceMapGenerator;
97638 var sourceMapSource;
97639 var sourceMapSourceIndex = -1;
97640 // Comments
97641 var containerPos = -1;
97642 var containerEnd = -1;
97643 var declarationListContainerEnd = -1;
97644 var currentLineMap;
97645 var detachedCommentsInfo;
97646 var hasWrittenComment = false;
97647 var commentsDisabled = !!printerOptions.removeComments;
97648 var lastNode;
97649 var lastSubstitution;
97650 var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
97651 reset();
97652 return {
97653 // public API
97654 printNode: printNode,
97655 printList: printList,
97656 printFile: printFile,
97657 printBundle: printBundle,
97658 // internal API
97659 writeNode: writeNode,
97660 writeList: writeList,
97661 writeFile: writeFile,
97662 writeBundle: writeBundle,
97663 bundleFileInfo: bundleFileInfo
97664 };
97665 function printNode(hint, node, sourceFile) {
97666 switch (hint) {
97667 case 0 /* SourceFile */:
97668 ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
97669 break;
97670 case 2 /* IdentifierName */:
97671 ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
97672 break;
97673 case 1 /* Expression */:
97674 ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
97675 break;
97676 }
97677 switch (node.kind) {
97678 case 294 /* SourceFile */: return printFile(node);
97679 case 295 /* Bundle */: return printBundle(node);
97680 case 296 /* UnparsedSource */: return printUnparsedSource(node);
97681 }
97682 writeNode(hint, node, sourceFile, beginPrint());
97683 return endPrint();
97684 }
97685 function printList(format, nodes, sourceFile) {
97686 writeList(format, nodes, sourceFile, beginPrint());
97687 return endPrint();
97688 }
97689 function printBundle(bundle) {
97690 writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
97691 return endPrint();
97692 }
97693 function printFile(sourceFile) {
97694 writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
97695 return endPrint();
97696 }
97697 function printUnparsedSource(unparsed) {
97698 writeUnparsedSource(unparsed, beginPrint());
97699 return endPrint();
97700 }
97701 function writeNode(hint, node, sourceFile, output) {
97702 var previousWriter = writer;
97703 setWriter(output, /*_sourceMapGenerator*/ undefined);
97704 print(hint, node, sourceFile);
97705 reset();
97706 writer = previousWriter;
97707 }
97708 function writeList(format, nodes, sourceFile, output) {
97709 var previousWriter = writer;
97710 setWriter(output, /*_sourceMapGenerator*/ undefined);
97711 if (sourceFile) {
97712 setSourceFile(sourceFile);
97713 }
97714 emitList(syntheticParent, nodes, format);
97715 reset();
97716 writer = previousWriter;
97717 }
97718 function getTextPosWithWriteLine() {
97719 return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
97720 }
97721 function updateOrPushBundleFileTextLike(pos, end, kind) {
97722 var last = ts.lastOrUndefined(bundleFileInfo.sections);
97723 if (last && last.kind === kind) {
97724 last.end = end;
97725 }
97726 else {
97727 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
97728 }
97729 }
97730 function recordBundleFileInternalSectionStart(node) {
97731 if (recordInternalSection &&
97732 bundleFileInfo &&
97733 currentSourceFile &&
97734 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
97735 ts.isInternalDeclaration(node, currentSourceFile) &&
97736 sourceFileTextKind !== "internal" /* Internal */) {
97737 var prevSourceFileTextKind = sourceFileTextKind;
97738 recordBundleFileTextLikeSection(writer.getTextPos());
97739 sourceFileTextPos = getTextPosWithWriteLine();
97740 sourceFileTextKind = "internal" /* Internal */;
97741 return prevSourceFileTextKind;
97742 }
97743 return undefined;
97744 }
97745 function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
97746 if (prevSourceFileTextKind) {
97747 recordBundleFileTextLikeSection(writer.getTextPos());
97748 sourceFileTextPos = getTextPosWithWriteLine();
97749 sourceFileTextKind = prevSourceFileTextKind;
97750 }
97751 }
97752 function recordBundleFileTextLikeSection(end) {
97753 if (sourceFileTextPos < end) {
97754 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
97755 return true;
97756 }
97757 return false;
97758 }
97759 function writeBundle(bundle, output, sourceMapGenerator) {
97760 var _a;
97761 isOwnFileEmit = false;
97762 var previousWriter = writer;
97763 setWriter(output, sourceMapGenerator);
97764 emitShebangIfNeeded(bundle);
97765 emitPrologueDirectivesIfNeeded(bundle);
97766 emitHelpers(bundle);
97767 emitSyntheticTripleSlashReferencesIfNeeded(bundle);
97768 for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
97769 var prepend = _c[_b];
97770 writeLine();
97771 var pos = writer.getTextPos();
97772 var savedSections = bundleFileInfo && bundleFileInfo.sections;
97773 if (savedSections)
97774 bundleFileInfo.sections = [];
97775 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
97776 if (bundleFileInfo) {
97777 var newSections = bundleFileInfo.sections;
97778 bundleFileInfo.sections = savedSections;
97779 if (prepend.oldFileOfCurrentEmit)
97780 (_a = bundleFileInfo.sections).push.apply(_a, newSections);
97781 else {
97782 newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
97783 bundleFileInfo.sections.push({
97784 pos: pos,
97785 end: writer.getTextPos(),
97786 kind: "prepend" /* Prepend */,
97787 data: relativeToBuildInfo(prepend.fileName),
97788 texts: newSections
97789 });
97790 }
97791 }
97792 }
97793 sourceFileTextPos = getTextPosWithWriteLine();
97794 for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
97795 var sourceFile = _e[_d];
97796 print(0 /* SourceFile */, sourceFile, sourceFile);
97797 }
97798 if (bundleFileInfo && bundle.sourceFiles.length) {
97799 var end = writer.getTextPos();
97800 if (recordBundleFileTextLikeSection(end)) {
97801 // Store prologues
97802 var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
97803 if (prologues) {
97804 if (!bundleFileInfo.sources)
97805 bundleFileInfo.sources = {};
97806 bundleFileInfo.sources.prologues = prologues;
97807 }
97808 // Store helpes
97809 var helpers = getHelpersFromBundledSourceFiles(bundle);
97810 if (helpers) {
97811 if (!bundleFileInfo.sources)
97812 bundleFileInfo.sources = {};
97813 bundleFileInfo.sources.helpers = helpers;
97814 }
97815 }
97816 }
97817 reset();
97818 writer = previousWriter;
97819 }
97820 function writeUnparsedSource(unparsed, output) {
97821 var previousWriter = writer;
97822 setWriter(output, /*_sourceMapGenerator*/ undefined);
97823 print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
97824 reset();
97825 writer = previousWriter;
97826 }
97827 function writeFile(sourceFile, output, sourceMapGenerator) {
97828 isOwnFileEmit = true;
97829 var previousWriter = writer;
97830 setWriter(output, sourceMapGenerator);
97831 emitShebangIfNeeded(sourceFile);
97832 emitPrologueDirectivesIfNeeded(sourceFile);
97833 print(0 /* SourceFile */, sourceFile, sourceFile);
97834 reset();
97835 writer = previousWriter;
97836 }
97837 function beginPrint() {
97838 return ownWriter || (ownWriter = ts.createTextWriter(newLine));
97839 }
97840 function endPrint() {
97841 var text = ownWriter.getText();
97842 ownWriter.clear();
97843 return text;
97844 }
97845 function print(hint, node, sourceFile) {
97846 if (sourceFile) {
97847 setSourceFile(sourceFile);
97848 }
97849 pipelineEmit(hint, node);
97850 }
97851 function setSourceFile(sourceFile) {
97852 currentSourceFile = sourceFile;
97853 currentLineMap = undefined;
97854 detachedCommentsInfo = undefined;
97855 if (sourceFile) {
97856 setSourceMapSource(sourceFile);
97857 }
97858 }
97859 function setWriter(_writer, _sourceMapGenerator) {
97860 if (_writer && printerOptions.omitTrailingSemicolon) {
97861 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
97862 }
97863 writer = _writer; // TODO: GH#18217
97864 sourceMapGenerator = _sourceMapGenerator;
97865 sourceMapsDisabled = !writer || !sourceMapGenerator;
97866 }
97867 function reset() {
97868 nodeIdToGeneratedName = [];
97869 autoGeneratedIdToGeneratedName = [];
97870 generatedNames = new ts.Set();
97871 tempFlagsStack = [];
97872 tempFlags = 0 /* Auto */;
97873 reservedNamesStack = [];
97874 currentSourceFile = undefined;
97875 currentLineMap = undefined;
97876 detachedCommentsInfo = undefined;
97877 lastNode = undefined;
97878 lastSubstitution = undefined;
97879 setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
97880 }
97881 function getCurrentLineMap() {
97882 return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
97883 }
97884 function emit(node) {
97885 if (node === undefined)
97886 return;
97887 var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
97888 var substitute = pipelineEmit(4 /* Unspecified */, node);
97889 recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
97890 return substitute;
97891 }
97892 function emitIdentifierName(node) {
97893 if (node === undefined)
97894 return;
97895 return pipelineEmit(2 /* IdentifierName */, node);
97896 }
97897 function emitExpression(node) {
97898 if (node === undefined)
97899 return;
97900 return pipelineEmit(1 /* Expression */, node);
97901 }
97902 function emitJsxAttributeValue(node) {
97903 return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
97904 }
97905 function pipelineEmit(emitHint, node) {
97906 var savedLastNode = lastNode;
97907 var savedLastSubstitution = lastSubstitution;
97908 var savedPreserveSourceNewlines = preserveSourceNewlines;
97909 lastNode = node;
97910 lastSubstitution = undefined;
97911 if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
97912 preserveSourceNewlines = false;
97913 }
97914 var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
97915 pipelinePhase(emitHint, node);
97916 ts.Debug.assert(lastNode === node);
97917 var substitute = lastSubstitution;
97918 lastNode = savedLastNode;
97919 lastSubstitution = savedLastSubstitution;
97920 preserveSourceNewlines = savedPreserveSourceNewlines;
97921 return substitute || node;
97922 }
97923 function getPipelinePhase(phase, emitHint, node) {
97924 switch (phase) {
97925 case 0 /* Notification */:
97926 if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
97927 return pipelineEmitWithNotification;
97928 }
97929 // falls through
97930 case 1 /* Substitution */:
97931 if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
97932 return pipelineEmitWithSubstitution;
97933 }
97934 // falls through
97935 case 2 /* Comments */:
97936 if (!commentsDisabled && node.kind !== 294 /* SourceFile */) {
97937 return pipelineEmitWithComments;
97938 }
97939 // falls through
97940 case 3 /* SourceMaps */:
97941 if (!sourceMapsDisabled && node.kind !== 294 /* SourceFile */ && !ts.isInJsonFile(node)) {
97942 return pipelineEmitWithSourceMap;
97943 }
97944 // falls through
97945 case 4 /* Emit */:
97946 return pipelineEmitWithHint;
97947 default:
97948 return ts.Debug.assertNever(phase);
97949 }
97950 }
97951 function getNextPipelinePhase(currentPhase, emitHint, node) {
97952 return getPipelinePhase(currentPhase + 1, emitHint, node);
97953 }
97954 function pipelineEmitWithNotification(hint, node) {
97955 ts.Debug.assert(lastNode === node);
97956 var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
97957 onEmitNode(hint, node, pipelinePhase);
97958 ts.Debug.assert(lastNode === node);
97959 }
97960 function pipelineEmitWithHint(hint, node) {
97961 ts.Debug.assert(lastNode === node || lastSubstitution === node);
97962 if (hint === 0 /* SourceFile */)
97963 return emitSourceFile(ts.cast(node, ts.isSourceFile));
97964 if (hint === 2 /* IdentifierName */)
97965 return emitIdentifier(ts.cast(node, ts.isIdentifier));
97966 if (hint === 6 /* JsxAttributeValue */)
97967 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
97968 if (hint === 3 /* MappedTypeParameter */)
97969 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
97970 if (hint === 5 /* EmbeddedStatement */) {
97971 ts.Debug.assertNode(node, ts.isEmptyStatement);
97972 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
97973 }
97974 if (hint === 4 /* Unspecified */) {
97975 if (ts.isKeyword(node.kind))
97976 return writeTokenNode(node, writeKeyword);
97977 switch (node.kind) {
97978 // Pseudo-literals
97979 case 15 /* TemplateHead */:
97980 case 16 /* TemplateMiddle */:
97981 case 17 /* TemplateTail */:
97982 return emitLiteral(node, /*jsxAttributeEscape*/ false);
97983 case 296 /* UnparsedSource */:
97984 case 290 /* UnparsedPrepend */:
97985 return emitUnparsedSourceOrPrepend(node);
97986 case 289 /* UnparsedPrologue */:
97987 return writeUnparsedNode(node);
97988 case 291 /* UnparsedText */:
97989 case 292 /* UnparsedInternalText */:
97990 return emitUnparsedTextLike(node);
97991 case 293 /* UnparsedSyntheticReference */:
97992 return emitUnparsedSyntheticReference(node);
97993 // Identifiers
97994 case 78 /* Identifier */:
97995 return emitIdentifier(node);
97996 // PrivateIdentifiers
97997 case 79 /* PrivateIdentifier */:
97998 return emitPrivateIdentifier(node);
97999 // Parse tree nodes
98000 // Names
98001 case 156 /* QualifiedName */:
98002 return emitQualifiedName(node);
98003 case 157 /* ComputedPropertyName */:
98004 return emitComputedPropertyName(node);
98005 // Signature elements
98006 case 158 /* TypeParameter */:
98007 return emitTypeParameter(node);
98008 case 159 /* Parameter */:
98009 return emitParameter(node);
98010 case 160 /* Decorator */:
98011 return emitDecorator(node);
98012 // Type members
98013 case 161 /* PropertySignature */:
98014 return emitPropertySignature(node);
98015 case 162 /* PropertyDeclaration */:
98016 return emitPropertyDeclaration(node);
98017 case 163 /* MethodSignature */:
98018 return emitMethodSignature(node);
98019 case 164 /* MethodDeclaration */:
98020 return emitMethodDeclaration(node);
98021 case 165 /* Constructor */:
98022 return emitConstructor(node);
98023 case 166 /* GetAccessor */:
98024 case 167 /* SetAccessor */:
98025 return emitAccessorDeclaration(node);
98026 case 168 /* CallSignature */:
98027 return emitCallSignature(node);
98028 case 169 /* ConstructSignature */:
98029 return emitConstructSignature(node);
98030 case 170 /* IndexSignature */:
98031 return emitIndexSignature(node);
98032 // Types
98033 case 171 /* TypePredicate */:
98034 return emitTypePredicate(node);
98035 case 172 /* TypeReference */:
98036 return emitTypeReference(node);
98037 case 173 /* FunctionType */:
98038 return emitFunctionType(node);
98039 case 304 /* JSDocFunctionType */:
98040 return emitJSDocFunctionType(node);
98041 case 174 /* ConstructorType */:
98042 return emitConstructorType(node);
98043 case 175 /* TypeQuery */:
98044 return emitTypeQuery(node);
98045 case 176 /* TypeLiteral */:
98046 return emitTypeLiteral(node);
98047 case 177 /* ArrayType */:
98048 return emitArrayType(node);
98049 case 178 /* TupleType */:
98050 return emitTupleType(node);
98051 case 179 /* OptionalType */:
98052 return emitOptionalType(node);
98053 case 181 /* UnionType */:
98054 return emitUnionType(node);
98055 case 182 /* IntersectionType */:
98056 return emitIntersectionType(node);
98057 case 183 /* ConditionalType */:
98058 return emitConditionalType(node);
98059 case 184 /* InferType */:
98060 return emitInferType(node);
98061 case 185 /* ParenthesizedType */:
98062 return emitParenthesizedType(node);
98063 case 220 /* ExpressionWithTypeArguments */:
98064 return emitExpressionWithTypeArguments(node);
98065 case 186 /* ThisType */:
98066 return emitThisType();
98067 case 187 /* TypeOperator */:
98068 return emitTypeOperator(node);
98069 case 188 /* IndexedAccessType */:
98070 return emitIndexedAccessType(node);
98071 case 189 /* MappedType */:
98072 return emitMappedType(node);
98073 case 190 /* LiteralType */:
98074 return emitLiteralType(node);
98075 case 192 /* ImportType */:
98076 return emitImportTypeNode(node);
98077 case 299 /* JSDocAllType */:
98078 writePunctuation("*");
98079 return;
98080 case 300 /* JSDocUnknownType */:
98081 writePunctuation("?");
98082 return;
98083 case 301 /* JSDocNullableType */:
98084 return emitJSDocNullableType(node);
98085 case 302 /* JSDocNonNullableType */:
98086 return emitJSDocNonNullableType(node);
98087 case 303 /* JSDocOptionalType */:
98088 return emitJSDocOptionalType(node);
98089 case 180 /* RestType */:
98090 case 305 /* JSDocVariadicType */:
98091 return emitRestOrJSDocVariadicType(node);
98092 case 191 /* NamedTupleMember */:
98093 return emitNamedTupleMember(node);
98094 // Binding patterns
98095 case 193 /* ObjectBindingPattern */:
98096 return emitObjectBindingPattern(node);
98097 case 194 /* ArrayBindingPattern */:
98098 return emitArrayBindingPattern(node);
98099 case 195 /* BindingElement */:
98100 return emitBindingElement(node);
98101 // Misc
98102 case 225 /* TemplateSpan */:
98103 return emitTemplateSpan(node);
98104 case 226 /* SemicolonClassElement */:
98105 return emitSemicolonClassElement();
98106 // Statements
98107 case 227 /* Block */:
98108 return emitBlock(node);
98109 case 229 /* VariableStatement */:
98110 return emitVariableStatement(node);
98111 case 228 /* EmptyStatement */:
98112 return emitEmptyStatement(/*isEmbeddedStatement*/ false);
98113 case 230 /* ExpressionStatement */:
98114 return emitExpressionStatement(node);
98115 case 231 /* IfStatement */:
98116 return emitIfStatement(node);
98117 case 232 /* DoStatement */:
98118 return emitDoStatement(node);
98119 case 233 /* WhileStatement */:
98120 return emitWhileStatement(node);
98121 case 234 /* ForStatement */:
98122 return emitForStatement(node);
98123 case 235 /* ForInStatement */:
98124 return emitForInStatement(node);
98125 case 236 /* ForOfStatement */:
98126 return emitForOfStatement(node);
98127 case 237 /* ContinueStatement */:
98128 return emitContinueStatement(node);
98129 case 238 /* BreakStatement */:
98130 return emitBreakStatement(node);
98131 case 239 /* ReturnStatement */:
98132 return emitReturnStatement(node);
98133 case 240 /* WithStatement */:
98134 return emitWithStatement(node);
98135 case 241 /* SwitchStatement */:
98136 return emitSwitchStatement(node);
98137 case 242 /* LabeledStatement */:
98138 return emitLabeledStatement(node);
98139 case 243 /* ThrowStatement */:
98140 return emitThrowStatement(node);
98141 case 244 /* TryStatement */:
98142 return emitTryStatement(node);
98143 case 245 /* DebuggerStatement */:
98144 return emitDebuggerStatement(node);
98145 // Declarations
98146 case 246 /* VariableDeclaration */:
98147 return emitVariableDeclaration(node);
98148 case 247 /* VariableDeclarationList */:
98149 return emitVariableDeclarationList(node);
98150 case 248 /* FunctionDeclaration */:
98151 return emitFunctionDeclaration(node);
98152 case 249 /* ClassDeclaration */:
98153 return emitClassDeclaration(node);
98154 case 250 /* InterfaceDeclaration */:
98155 return emitInterfaceDeclaration(node);
98156 case 251 /* TypeAliasDeclaration */:
98157 return emitTypeAliasDeclaration(node);
98158 case 252 /* EnumDeclaration */:
98159 return emitEnumDeclaration(node);
98160 case 253 /* ModuleDeclaration */:
98161 return emitModuleDeclaration(node);
98162 case 254 /* ModuleBlock */:
98163 return emitModuleBlock(node);
98164 case 255 /* CaseBlock */:
98165 return emitCaseBlock(node);
98166 case 256 /* NamespaceExportDeclaration */:
98167 return emitNamespaceExportDeclaration(node);
98168 case 257 /* ImportEqualsDeclaration */:
98169 return emitImportEqualsDeclaration(node);
98170 case 258 /* ImportDeclaration */:
98171 return emitImportDeclaration(node);
98172 case 259 /* ImportClause */:
98173 return emitImportClause(node);
98174 case 260 /* NamespaceImport */:
98175 return emitNamespaceImport(node);
98176 case 266 /* NamespaceExport */:
98177 return emitNamespaceExport(node);
98178 case 261 /* NamedImports */:
98179 return emitNamedImports(node);
98180 case 262 /* ImportSpecifier */:
98181 return emitImportSpecifier(node);
98182 case 263 /* ExportAssignment */:
98183 return emitExportAssignment(node);
98184 case 264 /* ExportDeclaration */:
98185 return emitExportDeclaration(node);
98186 case 265 /* NamedExports */:
98187 return emitNamedExports(node);
98188 case 267 /* ExportSpecifier */:
98189 return emitExportSpecifier(node);
98190 case 268 /* MissingDeclaration */:
98191 return;
98192 // Module references
98193 case 269 /* ExternalModuleReference */:
98194 return emitExternalModuleReference(node);
98195 // JSX (non-expression)
98196 case 11 /* JsxText */:
98197 return emitJsxText(node);
98198 case 272 /* JsxOpeningElement */:
98199 case 275 /* JsxOpeningFragment */:
98200 return emitJsxOpeningElementOrFragment(node);
98201 case 273 /* JsxClosingElement */:
98202 case 276 /* JsxClosingFragment */:
98203 return emitJsxClosingElementOrFragment(node);
98204 case 277 /* JsxAttribute */:
98205 return emitJsxAttribute(node);
98206 case 278 /* JsxAttributes */:
98207 return emitJsxAttributes(node);
98208 case 279 /* JsxSpreadAttribute */:
98209 return emitJsxSpreadAttribute(node);
98210 case 280 /* JsxExpression */:
98211 return emitJsxExpression(node);
98212 // Clauses
98213 case 281 /* CaseClause */:
98214 return emitCaseClause(node);
98215 case 282 /* DefaultClause */:
98216 return emitDefaultClause(node);
98217 case 283 /* HeritageClause */:
98218 return emitHeritageClause(node);
98219 case 284 /* CatchClause */:
98220 return emitCatchClause(node);
98221 // Property assignments
98222 case 285 /* PropertyAssignment */:
98223 return emitPropertyAssignment(node);
98224 case 286 /* ShorthandPropertyAssignment */:
98225 return emitShorthandPropertyAssignment(node);
98226 case 287 /* SpreadAssignment */:
98227 return emitSpreadAssignment(node);
98228 // Enum
98229 case 288 /* EnumMember */:
98230 return emitEnumMember(node);
98231 // JSDoc nodes (only used in codefixes currently)
98232 case 322 /* JSDocParameterTag */:
98233 case 328 /* JSDocPropertyTag */:
98234 return emitJSDocPropertyLikeTag(node);
98235 case 323 /* JSDocReturnTag */:
98236 case 325 /* JSDocTypeTag */:
98237 case 324 /* JSDocThisTag */:
98238 case 321 /* JSDocEnumTag */:
98239 return emitJSDocSimpleTypedTag(node);
98240 case 312 /* JSDocImplementsTag */:
98241 case 311 /* JSDocAugmentsTag */:
98242 return emitJSDocHeritageTag(node);
98243 case 326 /* JSDocTemplateTag */:
98244 return emitJSDocTemplateTag(node);
98245 case 327 /* JSDocTypedefTag */:
98246 return emitJSDocTypedefTag(node);
98247 case 320 /* JSDocCallbackTag */:
98248 return emitJSDocCallbackTag(node);
98249 case 309 /* JSDocSignature */:
98250 return emitJSDocSignature(node);
98251 case 308 /* JSDocTypeLiteral */:
98252 return emitJSDocTypeLiteral(node);
98253 case 315 /* JSDocClassTag */:
98254 case 310 /* JSDocTag */:
98255 return emitJSDocSimpleTag(node);
98256 case 307 /* JSDocComment */:
98257 return emitJSDoc(node);
98258 // Transformation nodes (ignored)
98259 }
98260 if (ts.isExpression(node)) {
98261 hint = 1 /* Expression */;
98262 if (substituteNode !== ts.noEmitSubstitution) {
98263 lastSubstitution = node = substituteNode(hint, node);
98264 }
98265 }
98266 else if (ts.isToken(node)) {
98267 return writeTokenNode(node, writePunctuation);
98268 }
98269 }
98270 if (hint === 1 /* Expression */) {
98271 switch (node.kind) {
98272 // Literals
98273 case 8 /* NumericLiteral */:
98274 case 9 /* BigIntLiteral */:
98275 return emitNumericOrBigIntLiteral(node);
98276 case 10 /* StringLiteral */:
98277 case 13 /* RegularExpressionLiteral */:
98278 case 14 /* NoSubstitutionTemplateLiteral */:
98279 return emitLiteral(node, /*jsxAttributeEscape*/ false);
98280 // Identifiers
98281 case 78 /* Identifier */:
98282 return emitIdentifier(node);
98283 // Reserved words
98284 case 94 /* FalseKeyword */:
98285 case 103 /* NullKeyword */:
98286 case 105 /* SuperKeyword */:
98287 case 109 /* TrueKeyword */:
98288 case 107 /* ThisKeyword */:
98289 case 99 /* ImportKeyword */:
98290 writeTokenNode(node, writeKeyword);
98291 return;
98292 // Expressions
98293 case 196 /* ArrayLiteralExpression */:
98294 return emitArrayLiteralExpression(node);
98295 case 197 /* ObjectLiteralExpression */:
98296 return emitObjectLiteralExpression(node);
98297 case 198 /* PropertyAccessExpression */:
98298 return emitPropertyAccessExpression(node);
98299 case 199 /* ElementAccessExpression */:
98300 return emitElementAccessExpression(node);
98301 case 200 /* CallExpression */:
98302 return emitCallExpression(node);
98303 case 201 /* NewExpression */:
98304 return emitNewExpression(node);
98305 case 202 /* TaggedTemplateExpression */:
98306 return emitTaggedTemplateExpression(node);
98307 case 203 /* TypeAssertionExpression */:
98308 return emitTypeAssertionExpression(node);
98309 case 204 /* ParenthesizedExpression */:
98310 return emitParenthesizedExpression(node);
98311 case 205 /* FunctionExpression */:
98312 return emitFunctionExpression(node);
98313 case 206 /* ArrowFunction */:
98314 return emitArrowFunction(node);
98315 case 207 /* DeleteExpression */:
98316 return emitDeleteExpression(node);
98317 case 208 /* TypeOfExpression */:
98318 return emitTypeOfExpression(node);
98319 case 209 /* VoidExpression */:
98320 return emitVoidExpression(node);
98321 case 210 /* AwaitExpression */:
98322 return emitAwaitExpression(node);
98323 case 211 /* PrefixUnaryExpression */:
98324 return emitPrefixUnaryExpression(node);
98325 case 212 /* PostfixUnaryExpression */:
98326 return emitPostfixUnaryExpression(node);
98327 case 213 /* BinaryExpression */:
98328 return emitBinaryExpression(node);
98329 case 214 /* ConditionalExpression */:
98330 return emitConditionalExpression(node);
98331 case 215 /* TemplateExpression */:
98332 return emitTemplateExpression(node);
98333 case 216 /* YieldExpression */:
98334 return emitYieldExpression(node);
98335 case 217 /* SpreadElement */:
98336 return emitSpreadExpression(node);
98337 case 218 /* ClassExpression */:
98338 return emitClassExpression(node);
98339 case 219 /* OmittedExpression */:
98340 return;
98341 case 221 /* AsExpression */:
98342 return emitAsExpression(node);
98343 case 222 /* NonNullExpression */:
98344 return emitNonNullExpression(node);
98345 case 223 /* MetaProperty */:
98346 return emitMetaProperty(node);
98347 // JSX
98348 case 270 /* JsxElement */:
98349 return emitJsxElement(node);
98350 case 271 /* JsxSelfClosingElement */:
98351 return emitJsxSelfClosingElement(node);
98352 case 274 /* JsxFragment */:
98353 return emitJsxFragment(node);
98354 // Transformation nodes
98355 case 331 /* PartiallyEmittedExpression */:
98356 return emitPartiallyEmittedExpression(node);
98357 case 332 /* CommaListExpression */:
98358 return emitCommaList(node);
98359 }
98360 }
98361 }
98362 function emitMappedTypeParameter(node) {
98363 emit(node.name);
98364 writeSpace();
98365 writeKeyword("in");
98366 writeSpace();
98367 emit(node.constraint);
98368 }
98369 function pipelineEmitWithSubstitution(hint, node) {
98370 ts.Debug.assert(lastNode === node || lastSubstitution === node);
98371 var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
98372 pipelinePhase(hint, lastSubstitution);
98373 ts.Debug.assert(lastNode === node || lastSubstitution === node);
98374 }
98375 function getHelpersFromBundledSourceFiles(bundle) {
98376 var result;
98377 if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
98378 return undefined;
98379 }
98380 var bundledHelpers = new ts.Map();
98381 for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
98382 var sourceFile = _b[_a];
98383 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
98384 var helpers = getSortedEmitHelpers(sourceFile);
98385 if (!helpers)
98386 continue;
98387 for (var _c = 0, helpers_5 = helpers; _c < helpers_5.length; _c++) {
98388 var helper = helpers_5[_c];
98389 if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
98390 bundledHelpers.set(helper.name, true);
98391 (result || (result = [])).push(helper.name);
98392 }
98393 }
98394 }
98395 return result;
98396 }
98397 function emitHelpers(node) {
98398 var helpersEmitted = false;
98399 var bundle = node.kind === 295 /* Bundle */ ? node : undefined;
98400 if (bundle && moduleKind === ts.ModuleKind.None) {
98401 return;
98402 }
98403 var numPrepends = bundle ? bundle.prepends.length : 0;
98404 var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
98405 for (var i = 0; i < numNodes; i++) {
98406 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
98407 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
98408 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
98409 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
98410 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
98411 if (helpers) {
98412 for (var _a = 0, helpers_6 = helpers; _a < helpers_6.length; _a++) {
98413 var helper = helpers_6[_a];
98414 if (!helper.scoped) {
98415 // Skip the helper if it can be skipped and the noEmitHelpers compiler
98416 // option is set, or if it can be imported and the importHelpers compiler
98417 // option is set.
98418 if (shouldSkip)
98419 continue;
98420 // Skip the helper if it can be bundled but hasn't already been emitted and we
98421 // are emitting a bundled module.
98422 if (shouldBundle) {
98423 if (bundledHelpers.get(helper.name)) {
98424 continue;
98425 }
98426 bundledHelpers.set(helper.name, true);
98427 }
98428 }
98429 else if (bundle) {
98430 // Skip the helper if it is scoped and we are emitting bundled helpers
98431 continue;
98432 }
98433 var pos = getTextPosWithWriteLine();
98434 if (typeof helper.text === "string") {
98435 writeLines(helper.text);
98436 }
98437 else {
98438 writeLines(helper.text(makeFileLevelOptimisticUniqueName));
98439 }
98440 if (bundleFileInfo)
98441 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
98442 helpersEmitted = true;
98443 }
98444 }
98445 }
98446 return helpersEmitted;
98447 }
98448 function getSortedEmitHelpers(node) {
98449 var helpers = ts.getEmitHelpers(node);
98450 return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
98451 }
98452 //
98453 // Literals/Pseudo-literals
98454 //
98455 // SyntaxKind.NumericLiteral
98456 // SyntaxKind.BigIntLiteral
98457 function emitNumericOrBigIntLiteral(node) {
98458 emitLiteral(node, /*jsxAttributeEscape*/ false);
98459 }
98460 // SyntaxKind.StringLiteral
98461 // SyntaxKind.RegularExpressionLiteral
98462 // SyntaxKind.NoSubstitutionTemplateLiteral
98463 // SyntaxKind.TemplateHead
98464 // SyntaxKind.TemplateMiddle
98465 // SyntaxKind.TemplateTail
98466 function emitLiteral(node, jsxAttributeEscape) {
98467 var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
98468 if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
98469 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
98470 writeLiteral(text);
98471 }
98472 else {
98473 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
98474 writeStringLiteral(text);
98475 }
98476 }
98477 // SyntaxKind.UnparsedSource
98478 // SyntaxKind.UnparsedPrepend
98479 function emitUnparsedSourceOrPrepend(unparsed) {
98480 for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
98481 var text = _b[_a];
98482 writeLine();
98483 emit(text);
98484 }
98485 }
98486 // SyntaxKind.UnparsedPrologue
98487 // SyntaxKind.UnparsedText
98488 // SyntaxKind.UnparsedInternal
98489 // SyntaxKind.UnparsedSyntheticReference
98490 function writeUnparsedNode(unparsed) {
98491 writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
98492 }
98493 // SyntaxKind.UnparsedText
98494 // SyntaxKind.UnparsedInternal
98495 function emitUnparsedTextLike(unparsed) {
98496 var pos = getTextPosWithWriteLine();
98497 writeUnparsedNode(unparsed);
98498 if (bundleFileInfo) {
98499 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 291 /* UnparsedText */ ?
98500 "text" /* Text */ :
98501 "internal" /* Internal */);
98502 }
98503 }
98504 // SyntaxKind.UnparsedSyntheticReference
98505 function emitUnparsedSyntheticReference(unparsed) {
98506 var pos = getTextPosWithWriteLine();
98507 writeUnparsedNode(unparsed);
98508 if (bundleFileInfo) {
98509 var section = ts.clone(unparsed.section);
98510 section.pos = pos;
98511 section.end = writer.getTextPos();
98512 bundleFileInfo.sections.push(section);
98513 }
98514 }
98515 //
98516 // Identifiers
98517 //
98518 function emitIdentifier(node) {
98519 var writeText = node.symbol ? writeSymbol : write;
98520 writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
98521 emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
98522 }
98523 //
98524 // Names
98525 //
98526 function emitPrivateIdentifier(node) {
98527 var writeText = node.symbol ? writeSymbol : write;
98528 writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
98529 }
98530 function emitQualifiedName(node) {
98531 emitEntityName(node.left);
98532 writePunctuation(".");
98533 emit(node.right);
98534 }
98535 function emitEntityName(node) {
98536 if (node.kind === 78 /* Identifier */) {
98537 emitExpression(node);
98538 }
98539 else {
98540 emit(node);
98541 }
98542 }
98543 function emitComputedPropertyName(node) {
98544 writePunctuation("[");
98545 emitExpression(node.expression);
98546 writePunctuation("]");
98547 }
98548 //
98549 // Signature elements
98550 //
98551 function emitTypeParameter(node) {
98552 emit(node.name);
98553 if (node.constraint) {
98554 writeSpace();
98555 writeKeyword("extends");
98556 writeSpace();
98557 emit(node.constraint);
98558 }
98559 if (node.default) {
98560 writeSpace();
98561 writeOperator("=");
98562 writeSpace();
98563 emit(node.default);
98564 }
98565 }
98566 function emitParameter(node) {
98567 emitDecorators(node, node.decorators);
98568 emitModifiers(node, node.modifiers);
98569 emit(node.dotDotDotToken);
98570 emitNodeWithWriter(node.name, writeParameter);
98571 emit(node.questionToken);
98572 if (node.parent && node.parent.kind === 304 /* JSDocFunctionType */ && !node.name) {
98573 emit(node.type);
98574 }
98575 else {
98576 emitTypeAnnotation(node.type);
98577 }
98578 // 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.
98579 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);
98580 }
98581 function emitDecorator(decorator) {
98582 writePunctuation("@");
98583 emitExpression(decorator.expression);
98584 }
98585 //
98586 // Type members
98587 //
98588 function emitPropertySignature(node) {
98589 emitDecorators(node, node.decorators);
98590 emitModifiers(node, node.modifiers);
98591 emitNodeWithWriter(node.name, writeProperty);
98592 emit(node.questionToken);
98593 emitTypeAnnotation(node.type);
98594 writeTrailingSemicolon();
98595 }
98596 function emitPropertyDeclaration(node) {
98597 emitDecorators(node, node.decorators);
98598 emitModifiers(node, node.modifiers);
98599 emit(node.name);
98600 emit(node.questionToken);
98601 emit(node.exclamationToken);
98602 emitTypeAnnotation(node.type);
98603 emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
98604 writeTrailingSemicolon();
98605 }
98606 function emitMethodSignature(node) {
98607 pushNameGenerationScope(node);
98608 emitDecorators(node, node.decorators);
98609 emitModifiers(node, node.modifiers);
98610 emit(node.name);
98611 emit(node.questionToken);
98612 emitTypeParameters(node, node.typeParameters);
98613 emitParameters(node, node.parameters);
98614 emitTypeAnnotation(node.type);
98615 writeTrailingSemicolon();
98616 popNameGenerationScope(node);
98617 }
98618 function emitMethodDeclaration(node) {
98619 emitDecorators(node, node.decorators);
98620 emitModifiers(node, node.modifiers);
98621 emit(node.asteriskToken);
98622 emit(node.name);
98623 emit(node.questionToken);
98624 emitSignatureAndBody(node, emitSignatureHead);
98625 }
98626 function emitConstructor(node) {
98627 emitModifiers(node, node.modifiers);
98628 writeKeyword("constructor");
98629 emitSignatureAndBody(node, emitSignatureHead);
98630 }
98631 function emitAccessorDeclaration(node) {
98632 emitDecorators(node, node.decorators);
98633 emitModifiers(node, node.modifiers);
98634 writeKeyword(node.kind === 166 /* GetAccessor */ ? "get" : "set");
98635 writeSpace();
98636 emit(node.name);
98637 emitSignatureAndBody(node, emitSignatureHead);
98638 }
98639 function emitCallSignature(node) {
98640 pushNameGenerationScope(node);
98641 emitDecorators(node, node.decorators);
98642 emitModifiers(node, node.modifiers);
98643 emitTypeParameters(node, node.typeParameters);
98644 emitParameters(node, node.parameters);
98645 emitTypeAnnotation(node.type);
98646 writeTrailingSemicolon();
98647 popNameGenerationScope(node);
98648 }
98649 function emitConstructSignature(node) {
98650 pushNameGenerationScope(node);
98651 emitDecorators(node, node.decorators);
98652 emitModifiers(node, node.modifiers);
98653 writeKeyword("new");
98654 writeSpace();
98655 emitTypeParameters(node, node.typeParameters);
98656 emitParameters(node, node.parameters);
98657 emitTypeAnnotation(node.type);
98658 writeTrailingSemicolon();
98659 popNameGenerationScope(node);
98660 }
98661 function emitIndexSignature(node) {
98662 emitDecorators(node, node.decorators);
98663 emitModifiers(node, node.modifiers);
98664 emitParametersForIndexSignature(node, node.parameters);
98665 emitTypeAnnotation(node.type);
98666 writeTrailingSemicolon();
98667 }
98668 function emitSemicolonClassElement() {
98669 writeTrailingSemicolon();
98670 }
98671 //
98672 // Types
98673 //
98674 function emitTypePredicate(node) {
98675 if (node.assertsModifier) {
98676 emit(node.assertsModifier);
98677 writeSpace();
98678 }
98679 emit(node.parameterName);
98680 if (node.type) {
98681 writeSpace();
98682 writeKeyword("is");
98683 writeSpace();
98684 emit(node.type);
98685 }
98686 }
98687 function emitTypeReference(node) {
98688 emit(node.typeName);
98689 emitTypeArguments(node, node.typeArguments);
98690 }
98691 function emitFunctionType(node) {
98692 pushNameGenerationScope(node);
98693 emitTypeParameters(node, node.typeParameters);
98694 emitParametersForArrow(node, node.parameters);
98695 writeSpace();
98696 writePunctuation("=>");
98697 writeSpace();
98698 emit(node.type);
98699 popNameGenerationScope(node);
98700 }
98701 function emitJSDocFunctionType(node) {
98702 writeKeyword("function");
98703 emitParameters(node, node.parameters);
98704 writePunctuation(":");
98705 emit(node.type);
98706 }
98707 function emitJSDocNullableType(node) {
98708 writePunctuation("?");
98709 emit(node.type);
98710 }
98711 function emitJSDocNonNullableType(node) {
98712 writePunctuation("!");
98713 emit(node.type);
98714 }
98715 function emitJSDocOptionalType(node) {
98716 emit(node.type);
98717 writePunctuation("=");
98718 }
98719 function emitConstructorType(node) {
98720 pushNameGenerationScope(node);
98721 writeKeyword("new");
98722 writeSpace();
98723 emitTypeParameters(node, node.typeParameters);
98724 emitParameters(node, node.parameters);
98725 writeSpace();
98726 writePunctuation("=>");
98727 writeSpace();
98728 emit(node.type);
98729 popNameGenerationScope(node);
98730 }
98731 function emitTypeQuery(node) {
98732 writeKeyword("typeof");
98733 writeSpace();
98734 emit(node.exprName);
98735 }
98736 function emitTypeLiteral(node) {
98737 writePunctuation("{");
98738 var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
98739 emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
98740 writePunctuation("}");
98741 }
98742 function emitArrayType(node) {
98743 emit(node.elementType);
98744 writePunctuation("[");
98745 writePunctuation("]");
98746 }
98747 function emitRestOrJSDocVariadicType(node) {
98748 writePunctuation("...");
98749 emit(node.type);
98750 }
98751 function emitTupleType(node) {
98752 emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node);
98753 var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
98754 emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */);
98755 emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
98756 }
98757 function emitNamedTupleMember(node) {
98758 emit(node.dotDotDotToken);
98759 emit(node.name);
98760 emit(node.questionToken);
98761 emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node);
98762 writeSpace();
98763 emit(node.type);
98764 }
98765 function emitOptionalType(node) {
98766 emit(node.type);
98767 writePunctuation("?");
98768 }
98769 function emitUnionType(node) {
98770 emitList(node, node.types, 516 /* UnionTypeConstituents */);
98771 }
98772 function emitIntersectionType(node) {
98773 emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
98774 }
98775 function emitConditionalType(node) {
98776 emit(node.checkType);
98777 writeSpace();
98778 writeKeyword("extends");
98779 writeSpace();
98780 emit(node.extendsType);
98781 writeSpace();
98782 writePunctuation("?");
98783 writeSpace();
98784 emit(node.trueType);
98785 writeSpace();
98786 writePunctuation(":");
98787 writeSpace();
98788 emit(node.falseType);
98789 }
98790 function emitInferType(node) {
98791 writeKeyword("infer");
98792 writeSpace();
98793 emit(node.typeParameter);
98794 }
98795 function emitParenthesizedType(node) {
98796 writePunctuation("(");
98797 emit(node.type);
98798 writePunctuation(")");
98799 }
98800 function emitThisType() {
98801 writeKeyword("this");
98802 }
98803 function emitTypeOperator(node) {
98804 writeTokenText(node.operator, writeKeyword);
98805 writeSpace();
98806 emit(node.type);
98807 }
98808 function emitIndexedAccessType(node) {
98809 emit(node.objectType);
98810 writePunctuation("[");
98811 emit(node.indexType);
98812 writePunctuation("]");
98813 }
98814 function emitMappedType(node) {
98815 var emitFlags = ts.getEmitFlags(node);
98816 writePunctuation("{");
98817 if (emitFlags & 1 /* SingleLine */) {
98818 writeSpace();
98819 }
98820 else {
98821 writeLine();
98822 increaseIndent();
98823 }
98824 if (node.readonlyToken) {
98825 emit(node.readonlyToken);
98826 if (node.readonlyToken.kind !== 141 /* ReadonlyKeyword */) {
98827 writeKeyword("readonly");
98828 }
98829 writeSpace();
98830 }
98831 writePunctuation("[");
98832 pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
98833 writePunctuation("]");
98834 if (node.questionToken) {
98835 emit(node.questionToken);
98836 if (node.questionToken.kind !== 57 /* QuestionToken */) {
98837 writePunctuation("?");
98838 }
98839 }
98840 writePunctuation(":");
98841 writeSpace();
98842 emit(node.type);
98843 writeTrailingSemicolon();
98844 if (emitFlags & 1 /* SingleLine */) {
98845 writeSpace();
98846 }
98847 else {
98848 writeLine();
98849 decreaseIndent();
98850 }
98851 writePunctuation("}");
98852 }
98853 function emitLiteralType(node) {
98854 emitExpression(node.literal);
98855 }
98856 function emitImportTypeNode(node) {
98857 if (node.isTypeOf) {
98858 writeKeyword("typeof");
98859 writeSpace();
98860 }
98861 writeKeyword("import");
98862 writePunctuation("(");
98863 emit(node.argument);
98864 writePunctuation(")");
98865 if (node.qualifier) {
98866 writePunctuation(".");
98867 emit(node.qualifier);
98868 }
98869 emitTypeArguments(node, node.typeArguments);
98870 }
98871 //
98872 // Binding patterns
98873 //
98874 function emitObjectBindingPattern(node) {
98875 writePunctuation("{");
98876 emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
98877 writePunctuation("}");
98878 }
98879 function emitArrayBindingPattern(node) {
98880 writePunctuation("[");
98881 emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
98882 writePunctuation("]");
98883 }
98884 function emitBindingElement(node) {
98885 emit(node.dotDotDotToken);
98886 if (node.propertyName) {
98887 emit(node.propertyName);
98888 writePunctuation(":");
98889 writeSpace();
98890 }
98891 emit(node.name);
98892 emitInitializer(node.initializer, node.name.end, node);
98893 }
98894 //
98895 // Expressions
98896 //
98897 function emitArrayLiteralExpression(node) {
98898 var elements = node.elements;
98899 var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
98900 emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
98901 }
98902 function emitObjectLiteralExpression(node) {
98903 ts.forEach(node.properties, generateMemberNames);
98904 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
98905 if (indentedFlag) {
98906 increaseIndent();
98907 }
98908 var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
98909 var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
98910 emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
98911 if (indentedFlag) {
98912 decreaseIndent();
98913 }
98914 }
98915 function emitPropertyAccessExpression(node) {
98916 var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
98917 var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos);
98918 var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
98919 var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
98920 writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
98921 var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
98922 mayNeedDotDotForPropertyAccess(expression) &&
98923 !writer.hasTrailingComment() &&
98924 !writer.hasTrailingWhitespace();
98925 if (shouldEmitDotDot) {
98926 writePunctuation(".");
98927 }
98928 if (node.questionDotToken) {
98929 emit(token);
98930 }
98931 else {
98932 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
98933 }
98934 writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
98935 emit(node.name);
98936 decreaseIndentIf(linesBeforeDot, linesAfterDot);
98937 }
98938 // 1..toString is a valid property access, emit a dot after the literal
98939 // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
98940 function mayNeedDotDotForPropertyAccess(expression) {
98941 expression = ts.skipPartiallyEmittedExpressions(expression);
98942 if (ts.isNumericLiteral(expression)) {
98943 // check if numeric literal is a decimal literal that was originally written with a dot
98944 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
98945 // If he number will be printed verbatim and it doesn't already contain a dot, add one
98946 // if the expression doesn't have any comments that will be emitted.
98947 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
98948 }
98949 else if (ts.isAccessExpression(expression)) {
98950 // check if constant enum value is integer
98951 var constantValue = ts.getConstantValue(expression);
98952 // isFinite handles cases when constantValue is undefined
98953 return typeof constantValue === "number" && isFinite(constantValue)
98954 && Math.floor(constantValue) === constantValue;
98955 }
98956 }
98957 function emitElementAccessExpression(node) {
98958 emitExpression(node.expression);
98959 emit(node.questionDotToken);
98960 emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
98961 emitExpression(node.argumentExpression);
98962 emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
98963 }
98964 function emitCallExpression(node) {
98965 emitExpression(node.expression);
98966 emit(node.questionDotToken);
98967 emitTypeArguments(node, node.typeArguments);
98968 emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
98969 }
98970 function emitNewExpression(node) {
98971 emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node);
98972 writeSpace();
98973 emitExpression(node.expression);
98974 emitTypeArguments(node, node.typeArguments);
98975 emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
98976 }
98977 function emitTaggedTemplateExpression(node) {
98978 emitExpression(node.tag);
98979 emitTypeArguments(node, node.typeArguments);
98980 writeSpace();
98981 emitExpression(node.template);
98982 }
98983 function emitTypeAssertionExpression(node) {
98984 writePunctuation("<");
98985 emit(node.type);
98986 writePunctuation(">");
98987 emitExpression(node.expression);
98988 }
98989 function emitParenthesizedExpression(node) {
98990 var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
98991 var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
98992 emitExpression(node.expression);
98993 writeLineSeparatorsAfter(node.expression, node);
98994 decreaseIndentIf(indented);
98995 emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
98996 }
98997 function emitFunctionExpression(node) {
98998 generateNameIfNeeded(node.name);
98999 emitFunctionDeclarationOrExpression(node);
99000 }
99001 function emitArrowFunction(node) {
99002 emitDecorators(node, node.decorators);
99003 emitModifiers(node, node.modifiers);
99004 emitSignatureAndBody(node, emitArrowFunctionHead);
99005 }
99006 function emitArrowFunctionHead(node) {
99007 emitTypeParameters(node, node.typeParameters);
99008 emitParametersForArrow(node, node.parameters);
99009 emitTypeAnnotation(node.type);
99010 writeSpace();
99011 emit(node.equalsGreaterThanToken);
99012 }
99013 function emitDeleteExpression(node) {
99014 emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node);
99015 writeSpace();
99016 emitExpression(node.expression);
99017 }
99018 function emitTypeOfExpression(node) {
99019 emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node);
99020 writeSpace();
99021 emitExpression(node.expression);
99022 }
99023 function emitVoidExpression(node) {
99024 emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node);
99025 writeSpace();
99026 emitExpression(node.expression);
99027 }
99028 function emitAwaitExpression(node) {
99029 emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node);
99030 writeSpace();
99031 emitExpression(node.expression);
99032 }
99033 function emitPrefixUnaryExpression(node) {
99034 writeTokenText(node.operator, writeOperator);
99035 if (shouldEmitWhitespaceBeforeOperand(node)) {
99036 writeSpace();
99037 }
99038 emitExpression(node.operand);
99039 }
99040 function shouldEmitWhitespaceBeforeOperand(node) {
99041 // In some cases, we need to emit a space between the operator and the operand. One obvious case
99042 // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
99043 // and minus expressions in certain cases. Specifically, consider the following two cases (parens
99044 // are just for clarity of exposition, and not part of the source code):
99045 //
99046 // (+(+1))
99047 // (+(++1))
99048 //
99049 // We need to emit a space in both cases. In the first case, the absence of a space will make
99050 // the resulting expression a prefix increment operation. And in the second, it will make the resulting
99051 // expression a prefix increment whose operand is a plus expression - (++(+x))
99052 // The same is true of minus of course.
99053 var operand = node.operand;
99054 return operand.kind === 211 /* PrefixUnaryExpression */
99055 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
99056 || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
99057 }
99058 function emitPostfixUnaryExpression(node) {
99059 emitExpression(node.operand);
99060 writeTokenText(node.operator, writeOperator);
99061 }
99062 var EmitBinaryExpressionState;
99063 (function (EmitBinaryExpressionState) {
99064 EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
99065 EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
99066 EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
99067 })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
99068 /**
99069 * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
99070 * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
99071 * not require notification/substitution/comment/sourcemap decorations.
99072 */
99073 function emitBinaryExpression(node) {
99074 var nodeStack = [node];
99075 var stateStack = [0 /* EmitLeft */];
99076 var stackIndex = 0;
99077 while (stackIndex >= 0) {
99078 node = nodeStack[stackIndex];
99079 switch (stateStack[stackIndex]) {
99080 case 0 /* EmitLeft */: {
99081 maybePipelineEmitExpression(node.left);
99082 break;
99083 }
99084 case 1 /* EmitRight */: {
99085 var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
99086 var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
99087 var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
99088 writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
99089 emitLeadingCommentsOfPosition(node.operatorToken.pos);
99090 writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator);
99091 emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
99092 writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
99093 maybePipelineEmitExpression(node.right);
99094 break;
99095 }
99096 case 2 /* FinishEmit */: {
99097 var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
99098 var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
99099 decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
99100 stackIndex--;
99101 break;
99102 }
99103 default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
99104 }
99105 }
99106 function maybePipelineEmitExpression(next) {
99107 // Advance the state of this unit of work,
99108 stateStack[stackIndex]++;
99109 // Then actually do the work of emitting the node `next` returned by the prior state
99110 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
99111 // binary expression handling, where possible, to the contained work queue
99112 // #region trampolinePipelineEmit
99113 var savedLastNode = lastNode;
99114 var savedLastSubstitution = lastSubstitution;
99115 lastNode = next;
99116 lastSubstitution = undefined;
99117 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
99118 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
99119 // If the target pipeline phase is emit directly, and the next node's also a binary expression,
99120 // skip all the intermediate indirection and push the expression directly onto the work stack
99121 stackIndex++;
99122 stateStack[stackIndex] = 0 /* EmitLeft */;
99123 nodeStack[stackIndex] = next;
99124 }
99125 else {
99126 pipelinePhase(1 /* Expression */, next);
99127 }
99128 ts.Debug.assert(lastNode === next);
99129 lastNode = savedLastNode;
99130 lastSubstitution = savedLastSubstitution;
99131 // #endregion trampolinePipelineEmit
99132 }
99133 }
99134 function emitConditionalExpression(node) {
99135 var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
99136 var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
99137 var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
99138 var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
99139 emitExpression(node.condition);
99140 writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
99141 emit(node.questionToken);
99142 writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
99143 emitExpression(node.whenTrue);
99144 decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
99145 writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
99146 emit(node.colonToken);
99147 writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
99148 emitExpression(node.whenFalse);
99149 decreaseIndentIf(linesBeforeColon, linesAfterColon);
99150 }
99151 function emitTemplateExpression(node) {
99152 emit(node.head);
99153 emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
99154 }
99155 function emitYieldExpression(node) {
99156 emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node);
99157 emit(node.asteriskToken);
99158 emitExpressionWithLeadingSpace(node.expression);
99159 }
99160 function emitSpreadExpression(node) {
99161 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
99162 emitExpression(node.expression);
99163 }
99164 function emitClassExpression(node) {
99165 generateNameIfNeeded(node.name);
99166 emitClassDeclarationOrExpression(node);
99167 }
99168 function emitExpressionWithTypeArguments(node) {
99169 emitExpression(node.expression);
99170 emitTypeArguments(node, node.typeArguments);
99171 }
99172 function emitAsExpression(node) {
99173 emitExpression(node.expression);
99174 if (node.type) {
99175 writeSpace();
99176 writeKeyword("as");
99177 writeSpace();
99178 emit(node.type);
99179 }
99180 }
99181 function emitNonNullExpression(node) {
99182 emitExpression(node.expression);
99183 writeOperator("!");
99184 }
99185 function emitMetaProperty(node) {
99186 writeToken(node.keywordToken, node.pos, writePunctuation);
99187 writePunctuation(".");
99188 emit(node.name);
99189 }
99190 //
99191 // Misc
99192 //
99193 function emitTemplateSpan(node) {
99194 emitExpression(node.expression);
99195 emit(node.literal);
99196 }
99197 //
99198 // Statements
99199 //
99200 function emitBlock(node) {
99201 emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
99202 }
99203 function emitBlockStatements(node, forceSingleLine) {
99204 emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
99205 var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
99206 emitList(node, node.statements, format);
99207 emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
99208 }
99209 function emitVariableStatement(node) {
99210 emitModifiers(node, node.modifiers);
99211 emit(node.declarationList);
99212 writeTrailingSemicolon();
99213 }
99214 function emitEmptyStatement(isEmbeddedStatement) {
99215 // While most trailing semicolons are possibly insignificant, an embedded "empty"
99216 // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
99217 if (isEmbeddedStatement) {
99218 writePunctuation(";");
99219 }
99220 else {
99221 writeTrailingSemicolon();
99222 }
99223 }
99224 function emitExpressionStatement(node) {
99225 emitExpression(node.expression);
99226 // Emit semicolon in non json files
99227 // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
99228 if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
99229 writeTrailingSemicolon();
99230 }
99231 }
99232 function emitIfStatement(node) {
99233 var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node);
99234 writeSpace();
99235 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99236 emitExpression(node.expression);
99237 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99238 emitEmbeddedStatement(node, node.thenStatement);
99239 if (node.elseStatement) {
99240 writeLineOrSpace(node, node.thenStatement, node.elseStatement);
99241 emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
99242 if (node.elseStatement.kind === 231 /* IfStatement */) {
99243 writeSpace();
99244 emit(node.elseStatement);
99245 }
99246 else {
99247 emitEmbeddedStatement(node, node.elseStatement);
99248 }
99249 }
99250 }
99251 function emitWhileClause(node, startPos) {
99252 var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node);
99253 writeSpace();
99254 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99255 emitExpression(node.expression);
99256 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99257 }
99258 function emitDoStatement(node) {
99259 emitTokenWithComment(89 /* DoKeyword */, node.pos, writeKeyword, node);
99260 emitEmbeddedStatement(node, node.statement);
99261 if (ts.isBlock(node.statement) && !preserveSourceNewlines) {
99262 writeSpace();
99263 }
99264 else {
99265 writeLineOrSpace(node, node.statement, node.expression);
99266 }
99267 emitWhileClause(node, node.statement.end);
99268 writeTrailingSemicolon();
99269 }
99270 function emitWhileStatement(node) {
99271 emitWhileClause(node, node.pos);
99272 emitEmbeddedStatement(node, node.statement);
99273 }
99274 function emitForStatement(node) {
99275 var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
99276 writeSpace();
99277 var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
99278 emitForBinding(node.initializer);
99279 pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
99280 emitExpressionWithLeadingSpace(node.condition);
99281 pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
99282 emitExpressionWithLeadingSpace(node.incrementor);
99283 emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
99284 emitEmbeddedStatement(node, node.statement);
99285 }
99286 function emitForInStatement(node) {
99287 var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
99288 writeSpace();
99289 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99290 emitForBinding(node.initializer);
99291 writeSpace();
99292 emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node);
99293 writeSpace();
99294 emitExpression(node.expression);
99295 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99296 emitEmbeddedStatement(node, node.statement);
99297 }
99298 function emitForOfStatement(node) {
99299 var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
99300 writeSpace();
99301 emitWithTrailingSpace(node.awaitModifier);
99302 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99303 emitForBinding(node.initializer);
99304 writeSpace();
99305 emitTokenWithComment(155 /* OfKeyword */, node.initializer.end, writeKeyword, node);
99306 writeSpace();
99307 emitExpression(node.expression);
99308 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99309 emitEmbeddedStatement(node, node.statement);
99310 }
99311 function emitForBinding(node) {
99312 if (node !== undefined) {
99313 if (node.kind === 247 /* VariableDeclarationList */) {
99314 emit(node);
99315 }
99316 else {
99317 emitExpression(node);
99318 }
99319 }
99320 }
99321 function emitContinueStatement(node) {
99322 emitTokenWithComment(85 /* ContinueKeyword */, node.pos, writeKeyword, node);
99323 emitWithLeadingSpace(node.label);
99324 writeTrailingSemicolon();
99325 }
99326 function emitBreakStatement(node) {
99327 emitTokenWithComment(80 /* BreakKeyword */, node.pos, writeKeyword, node);
99328 emitWithLeadingSpace(node.label);
99329 writeTrailingSemicolon();
99330 }
99331 function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
99332 var node = ts.getParseTreeNode(contextNode);
99333 var isSimilarNode = node && node.kind === contextNode.kind;
99334 var startPos = pos;
99335 if (isSimilarNode && currentSourceFile) {
99336 pos = ts.skipTrivia(currentSourceFile.text, pos);
99337 }
99338 if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
99339 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
99340 if (needsIndent) {
99341 increaseIndent();
99342 }
99343 emitLeadingCommentsOfPosition(startPos);
99344 if (needsIndent) {
99345 decreaseIndent();
99346 }
99347 }
99348 pos = writeTokenText(token, writer, pos);
99349 if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
99350 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
99351 }
99352 return pos;
99353 }
99354 function emitReturnStatement(node) {
99355 emitTokenWithComment(104 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
99356 emitExpressionWithLeadingSpace(node.expression);
99357 writeTrailingSemicolon();
99358 }
99359 function emitWithStatement(node) {
99360 var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node);
99361 writeSpace();
99362 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99363 emitExpression(node.expression);
99364 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99365 emitEmbeddedStatement(node, node.statement);
99366 }
99367 function emitSwitchStatement(node) {
99368 var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node);
99369 writeSpace();
99370 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99371 emitExpression(node.expression);
99372 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
99373 writeSpace();
99374 emit(node.caseBlock);
99375 }
99376 function emitLabeledStatement(node) {
99377 emit(node.label);
99378 emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
99379 writeSpace();
99380 emit(node.statement);
99381 }
99382 function emitThrowStatement(node) {
99383 emitTokenWithComment(108 /* ThrowKeyword */, node.pos, writeKeyword, node);
99384 emitExpressionWithLeadingSpace(node.expression);
99385 writeTrailingSemicolon();
99386 }
99387 function emitTryStatement(node) {
99388 emitTokenWithComment(110 /* TryKeyword */, node.pos, writeKeyword, node);
99389 writeSpace();
99390 emit(node.tryBlock);
99391 if (node.catchClause) {
99392 writeLineOrSpace(node, node.tryBlock, node.catchClause);
99393 emit(node.catchClause);
99394 }
99395 if (node.finallyBlock) {
99396 writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
99397 emitTokenWithComment(95 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
99398 writeSpace();
99399 emit(node.finallyBlock);
99400 }
99401 }
99402 function emitDebuggerStatement(node) {
99403 writeToken(86 /* DebuggerKeyword */, node.pos, writeKeyword);
99404 writeTrailingSemicolon();
99405 }
99406 //
99407 // Declarations
99408 //
99409 function emitVariableDeclaration(node) {
99410 emit(node.name);
99411 emit(node.exclamationToken);
99412 emitTypeAnnotation(node.type);
99413 emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
99414 }
99415 function emitVariableDeclarationList(node) {
99416 writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
99417 writeSpace();
99418 emitList(node, node.declarations, 528 /* VariableDeclarationList */);
99419 }
99420 function emitFunctionDeclaration(node) {
99421 emitFunctionDeclarationOrExpression(node);
99422 }
99423 function emitFunctionDeclarationOrExpression(node) {
99424 emitDecorators(node, node.decorators);
99425 emitModifiers(node, node.modifiers);
99426 writeKeyword("function");
99427 emit(node.asteriskToken);
99428 writeSpace();
99429 emitIdentifierName(node.name);
99430 emitSignatureAndBody(node, emitSignatureHead);
99431 }
99432 function emitBlockCallback(_hint, body) {
99433 emitBlockFunctionBody(body);
99434 }
99435 function emitSignatureAndBody(node, emitSignatureHead) {
99436 var body = node.body;
99437 if (body) {
99438 if (ts.isBlock(body)) {
99439 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
99440 if (indentedFlag) {
99441 increaseIndent();
99442 }
99443 pushNameGenerationScope(node);
99444 ts.forEach(node.parameters, generateNames);
99445 generateNames(node.body);
99446 emitSignatureHead(node);
99447 if (onEmitNode) {
99448 onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
99449 }
99450 else {
99451 emitBlockFunctionBody(body);
99452 }
99453 popNameGenerationScope(node);
99454 if (indentedFlag) {
99455 decreaseIndent();
99456 }
99457 }
99458 else {
99459 emitSignatureHead(node);
99460 writeSpace();
99461 emitExpression(body);
99462 }
99463 }
99464 else {
99465 emitSignatureHead(node);
99466 writeTrailingSemicolon();
99467 }
99468 }
99469 function emitSignatureHead(node) {
99470 emitTypeParameters(node, node.typeParameters);
99471 emitParameters(node, node.parameters);
99472 emitTypeAnnotation(node.type);
99473 }
99474 function shouldEmitBlockFunctionBodyOnSingleLine(body) {
99475 // We must emit a function body as a single-line body in the following case:
99476 // * The body has NodeEmitFlags.SingleLine specified.
99477 // We must emit a function body as a multi-line body in the following cases:
99478 // * The body is explicitly marked as multi-line.
99479 // * A non-synthesized body's start and end position are on different lines.
99480 // * Any statement in the body starts on a new line.
99481 if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
99482 return true;
99483 }
99484 if (body.multiLine) {
99485 return false;
99486 }
99487 if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
99488 return false;
99489 }
99490 if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
99491 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
99492 return false;
99493 }
99494 var previousStatement;
99495 for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
99496 var statement = _b[_a];
99497 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
99498 return false;
99499 }
99500 previousStatement = statement;
99501 }
99502 return true;
99503 }
99504 function emitBlockFunctionBody(body) {
99505 writeSpace();
99506 writePunctuation("{");
99507 increaseIndent();
99508 var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
99509 ? emitBlockFunctionBodyOnSingleLine
99510 : emitBlockFunctionBodyWorker;
99511 if (emitBodyWithDetachedComments) {
99512 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
99513 }
99514 else {
99515 emitBlockFunctionBody(body);
99516 }
99517 decreaseIndent();
99518 writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
99519 }
99520 function emitBlockFunctionBodyOnSingleLine(body) {
99521 emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
99522 }
99523 function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
99524 // Emit all the prologue directives (like "use strict").
99525 var statementOffset = emitPrologueDirectives(body.statements);
99526 var pos = writer.getTextPos();
99527 emitHelpers(body);
99528 if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
99529 decreaseIndent();
99530 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
99531 increaseIndent();
99532 }
99533 else {
99534 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
99535 }
99536 }
99537 function emitClassDeclaration(node) {
99538 emitClassDeclarationOrExpression(node);
99539 }
99540 function emitClassDeclarationOrExpression(node) {
99541 ts.forEach(node.members, generateMemberNames);
99542 emitDecorators(node, node.decorators);
99543 emitModifiers(node, node.modifiers);
99544 writeKeyword("class");
99545 if (node.name) {
99546 writeSpace();
99547 emitIdentifierName(node.name);
99548 }
99549 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
99550 if (indentedFlag) {
99551 increaseIndent();
99552 }
99553 emitTypeParameters(node, node.typeParameters);
99554 emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
99555 writeSpace();
99556 writePunctuation("{");
99557 emitList(node, node.members, 129 /* ClassMembers */);
99558 writePunctuation("}");
99559 if (indentedFlag) {
99560 decreaseIndent();
99561 }
99562 }
99563 function emitInterfaceDeclaration(node) {
99564 emitDecorators(node, node.decorators);
99565 emitModifiers(node, node.modifiers);
99566 writeKeyword("interface");
99567 writeSpace();
99568 emit(node.name);
99569 emitTypeParameters(node, node.typeParameters);
99570 emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
99571 writeSpace();
99572 writePunctuation("{");
99573 emitList(node, node.members, 129 /* InterfaceMembers */);
99574 writePunctuation("}");
99575 }
99576 function emitTypeAliasDeclaration(node) {
99577 emitDecorators(node, node.decorators);
99578 emitModifiers(node, node.modifiers);
99579 writeKeyword("type");
99580 writeSpace();
99581 emit(node.name);
99582 emitTypeParameters(node, node.typeParameters);
99583 writeSpace();
99584 writePunctuation("=");
99585 writeSpace();
99586 emit(node.type);
99587 writeTrailingSemicolon();
99588 }
99589 function emitEnumDeclaration(node) {
99590 emitModifiers(node, node.modifiers);
99591 writeKeyword("enum");
99592 writeSpace();
99593 emit(node.name);
99594 writeSpace();
99595 writePunctuation("{");
99596 emitList(node, node.members, 145 /* EnumMembers */);
99597 writePunctuation("}");
99598 }
99599 function emitModuleDeclaration(node) {
99600 emitModifiers(node, node.modifiers);
99601 if (~node.flags & 1024 /* GlobalAugmentation */) {
99602 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
99603 writeSpace();
99604 }
99605 emit(node.name);
99606 var body = node.body;
99607 if (!body)
99608 return writeTrailingSemicolon();
99609 while (body.kind === 253 /* ModuleDeclaration */) {
99610 writePunctuation(".");
99611 emit(body.name);
99612 body = body.body;
99613 }
99614 writeSpace();
99615 emit(body);
99616 }
99617 function emitModuleBlock(node) {
99618 pushNameGenerationScope(node);
99619 ts.forEach(node.statements, generateNames);
99620 emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
99621 popNameGenerationScope(node);
99622 }
99623 function emitCaseBlock(node) {
99624 emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
99625 emitList(node, node.clauses, 129 /* CaseBlockClauses */);
99626 emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
99627 }
99628 function emitImportEqualsDeclaration(node) {
99629 emitModifiers(node, node.modifiers);
99630 emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
99631 writeSpace();
99632 emit(node.name);
99633 writeSpace();
99634 emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
99635 writeSpace();
99636 emitModuleReference(node.moduleReference);
99637 writeTrailingSemicolon();
99638 }
99639 function emitModuleReference(node) {
99640 if (node.kind === 78 /* Identifier */) {
99641 emitExpression(node);
99642 }
99643 else {
99644 emit(node);
99645 }
99646 }
99647 function emitImportDeclaration(node) {
99648 emitModifiers(node, node.modifiers);
99649 emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
99650 writeSpace();
99651 if (node.importClause) {
99652 emit(node.importClause);
99653 writeSpace();
99654 emitTokenWithComment(152 /* FromKeyword */, node.importClause.end, writeKeyword, node);
99655 writeSpace();
99656 }
99657 emitExpression(node.moduleSpecifier);
99658 writeTrailingSemicolon();
99659 }
99660 function emitImportClause(node) {
99661 if (node.isTypeOnly) {
99662 emitTokenWithComment(148 /* TypeKeyword */, node.pos, writeKeyword, node);
99663 writeSpace();
99664 }
99665 emit(node.name);
99666 if (node.name && node.namedBindings) {
99667 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
99668 writeSpace();
99669 }
99670 emit(node.namedBindings);
99671 }
99672 function emitNamespaceImport(node) {
99673 var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
99674 writeSpace();
99675 emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
99676 writeSpace();
99677 emit(node.name);
99678 }
99679 function emitNamedImports(node) {
99680 emitNamedImportsOrExports(node);
99681 }
99682 function emitImportSpecifier(node) {
99683 emitImportOrExportSpecifier(node);
99684 }
99685 function emitExportAssignment(node) {
99686 var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
99687 writeSpace();
99688 if (node.isExportEquals) {
99689 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
99690 }
99691 else {
99692 emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node);
99693 }
99694 writeSpace();
99695 emitExpression(node.expression);
99696 writeTrailingSemicolon();
99697 }
99698 function emitExportDeclaration(node) {
99699 var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
99700 writeSpace();
99701 if (node.isTypeOnly) {
99702 nextPos = emitTokenWithComment(148 /* TypeKeyword */, nextPos, writeKeyword, node);
99703 writeSpace();
99704 }
99705 if (node.exportClause) {
99706 emit(node.exportClause);
99707 }
99708 else {
99709 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
99710 }
99711 if (node.moduleSpecifier) {
99712 writeSpace();
99713 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
99714 emitTokenWithComment(152 /* FromKeyword */, fromPos, writeKeyword, node);
99715 writeSpace();
99716 emitExpression(node.moduleSpecifier);
99717 }
99718 writeTrailingSemicolon();
99719 }
99720 function emitNamespaceExportDeclaration(node) {
99721 var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
99722 writeSpace();
99723 nextPos = emitTokenWithComment(126 /* AsKeyword */, nextPos, writeKeyword, node);
99724 writeSpace();
99725 nextPos = emitTokenWithComment(139 /* NamespaceKeyword */, nextPos, writeKeyword, node);
99726 writeSpace();
99727 emit(node.name);
99728 writeTrailingSemicolon();
99729 }
99730 function emitNamespaceExport(node) {
99731 var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
99732 writeSpace();
99733 emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
99734 writeSpace();
99735 emit(node.name);
99736 }
99737 function emitNamedExports(node) {
99738 emitNamedImportsOrExports(node);
99739 }
99740 function emitExportSpecifier(node) {
99741 emitImportOrExportSpecifier(node);
99742 }
99743 function emitNamedImportsOrExports(node) {
99744 writePunctuation("{");
99745 emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
99746 writePunctuation("}");
99747 }
99748 function emitImportOrExportSpecifier(node) {
99749 if (node.propertyName) {
99750 emit(node.propertyName);
99751 writeSpace();
99752 emitTokenWithComment(126 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
99753 writeSpace();
99754 }
99755 emit(node.name);
99756 }
99757 //
99758 // Module references
99759 //
99760 function emitExternalModuleReference(node) {
99761 writeKeyword("require");
99762 writePunctuation("(");
99763 emitExpression(node.expression);
99764 writePunctuation(")");
99765 }
99766 //
99767 // JSX
99768 //
99769 function emitJsxElement(node) {
99770 emit(node.openingElement);
99771 emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
99772 emit(node.closingElement);
99773 }
99774 function emitJsxSelfClosingElement(node) {
99775 writePunctuation("<");
99776 emitJsxTagName(node.tagName);
99777 emitTypeArguments(node, node.typeArguments);
99778 writeSpace();
99779 emit(node.attributes);
99780 writePunctuation("/>");
99781 }
99782 function emitJsxFragment(node) {
99783 emit(node.openingFragment);
99784 emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
99785 emit(node.closingFragment);
99786 }
99787 function emitJsxOpeningElementOrFragment(node) {
99788 writePunctuation("<");
99789 if (ts.isJsxOpeningElement(node)) {
99790 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
99791 emitJsxTagName(node.tagName);
99792 emitTypeArguments(node, node.typeArguments);
99793 if (node.attributes.properties && node.attributes.properties.length > 0) {
99794 writeSpace();
99795 }
99796 emit(node.attributes);
99797 writeLineSeparatorsAfter(node.attributes, node);
99798 decreaseIndentIf(indented);
99799 }
99800 writePunctuation(">");
99801 }
99802 function emitJsxText(node) {
99803 writer.writeLiteral(node.text);
99804 }
99805 function emitJsxClosingElementOrFragment(node) {
99806 writePunctuation("</");
99807 if (ts.isJsxClosingElement(node)) {
99808 emitJsxTagName(node.tagName);
99809 }
99810 writePunctuation(">");
99811 }
99812 function emitJsxAttributes(node) {
99813 emitList(node, node.properties, 262656 /* JsxElementAttributes */);
99814 }
99815 function emitJsxAttribute(node) {
99816 emit(node.name);
99817 emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
99818 }
99819 function emitJsxSpreadAttribute(node) {
99820 writePunctuation("{...");
99821 emitExpression(node.expression);
99822 writePunctuation("}");
99823 }
99824 function emitJsxExpression(node) {
99825 if (node.expression) {
99826 writePunctuation("{");
99827 emit(node.dotDotDotToken);
99828 emitExpression(node.expression);
99829 writePunctuation("}");
99830 }
99831 }
99832 function emitJsxTagName(node) {
99833 if (node.kind === 78 /* Identifier */) {
99834 emitExpression(node);
99835 }
99836 else {
99837 emit(node);
99838 }
99839 }
99840 //
99841 // Clauses
99842 //
99843 function emitCaseClause(node) {
99844 emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node);
99845 writeSpace();
99846 emitExpression(node.expression);
99847 emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
99848 }
99849 function emitDefaultClause(node) {
99850 var pos = emitTokenWithComment(87 /* DefaultKeyword */, node.pos, writeKeyword, node);
99851 emitCaseOrDefaultClauseRest(node, node.statements, pos);
99852 }
99853 function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
99854 var emitAsSingleStatement = statements.length === 1 &&
99855 (
99856 // treat synthesized nodes as located on the same line for emit purposes
99857 ts.nodeIsSynthesized(parentNode) ||
99858 ts.nodeIsSynthesized(statements[0]) ||
99859 ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
99860 var format = 163969 /* CaseOrDefaultClauseStatements */;
99861 if (emitAsSingleStatement) {
99862 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
99863 writeSpace();
99864 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
99865 }
99866 else {
99867 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
99868 }
99869 emitList(parentNode, statements, format);
99870 }
99871 function emitHeritageClause(node) {
99872 writeSpace();
99873 writeTokenText(node.token, writeKeyword);
99874 writeSpace();
99875 emitList(node, node.types, 528 /* HeritageClauseTypes */);
99876 }
99877 function emitCatchClause(node) {
99878 var openParenPos = emitTokenWithComment(82 /* CatchKeyword */, node.pos, writeKeyword, node);
99879 writeSpace();
99880 if (node.variableDeclaration) {
99881 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
99882 emit(node.variableDeclaration);
99883 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
99884 writeSpace();
99885 }
99886 emit(node.block);
99887 }
99888 //
99889 // Property assignments
99890 //
99891 function emitPropertyAssignment(node) {
99892 emit(node.name);
99893 writePunctuation(":");
99894 writeSpace();
99895 // This is to ensure that we emit comment in the following case:
99896 // For example:
99897 // obj = {
99898 // id: /*comment1*/ ()=>void
99899 // }
99900 // "comment1" is not considered to be leading comment for node.initializer
99901 // but rather a trailing comment on the previous node.
99902 var initializer = node.initializer;
99903 if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
99904 var commentRange = ts.getCommentRange(initializer);
99905 emitTrailingCommentsOfPosition(commentRange.pos);
99906 }
99907 emitExpression(initializer);
99908 }
99909 function emitShorthandPropertyAssignment(node) {
99910 emit(node.name);
99911 if (node.objectAssignmentInitializer) {
99912 writeSpace();
99913 writePunctuation("=");
99914 writeSpace();
99915 emitExpression(node.objectAssignmentInitializer);
99916 }
99917 }
99918 function emitSpreadAssignment(node) {
99919 if (node.expression) {
99920 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
99921 emitExpression(node.expression);
99922 }
99923 }
99924 //
99925 // Enum
99926 //
99927 function emitEnumMember(node) {
99928 emit(node.name);
99929 emitInitializer(node.initializer, node.name.end, node);
99930 }
99931 //
99932 // JSDoc
99933 //
99934 function emitJSDoc(node) {
99935 write("/**");
99936 if (node.comment) {
99937 var lines = node.comment.split(/\r\n?|\n/g);
99938 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
99939 var line = lines_2[_a];
99940 writeLine();
99941 writeSpace();
99942 writePunctuation("*");
99943 writeSpace();
99944 write(line);
99945 }
99946 }
99947 if (node.tags) {
99948 if (node.tags.length === 1 && node.tags[0].kind === 325 /* JSDocTypeTag */ && !node.comment) {
99949 writeSpace();
99950 emit(node.tags[0]);
99951 }
99952 else {
99953 emitList(node, node.tags, 33 /* JSDocComment */);
99954 }
99955 }
99956 writeSpace();
99957 write("*/");
99958 }
99959 function emitJSDocSimpleTypedTag(tag) {
99960 emitJSDocTagName(tag.tagName);
99961 emitJSDocTypeExpression(tag.typeExpression);
99962 emitJSDocComment(tag.comment);
99963 }
99964 function emitJSDocHeritageTag(tag) {
99965 emitJSDocTagName(tag.tagName);
99966 writeSpace();
99967 writePunctuation("{");
99968 emit(tag.class);
99969 writePunctuation("}");
99970 emitJSDocComment(tag.comment);
99971 }
99972 function emitJSDocTemplateTag(tag) {
99973 emitJSDocTagName(tag.tagName);
99974 emitJSDocTypeExpression(tag.constraint);
99975 writeSpace();
99976 emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
99977 emitJSDocComment(tag.comment);
99978 }
99979 function emitJSDocTypedefTag(tag) {
99980 emitJSDocTagName(tag.tagName);
99981 if (tag.typeExpression) {
99982 if (tag.typeExpression.kind === 298 /* JSDocTypeExpression */) {
99983 emitJSDocTypeExpression(tag.typeExpression);
99984 }
99985 else {
99986 writeSpace();
99987 writePunctuation("{");
99988 write("Object");
99989 if (tag.typeExpression.isArrayType) {
99990 writePunctuation("[");
99991 writePunctuation("]");
99992 }
99993 writePunctuation("}");
99994 }
99995 }
99996 if (tag.fullName) {
99997 writeSpace();
99998 emit(tag.fullName);
99999 }
100000 emitJSDocComment(tag.comment);
100001 if (tag.typeExpression && tag.typeExpression.kind === 308 /* JSDocTypeLiteral */) {
100002 emitJSDocTypeLiteral(tag.typeExpression);
100003 }
100004 }
100005 function emitJSDocCallbackTag(tag) {
100006 emitJSDocTagName(tag.tagName);
100007 if (tag.name) {
100008 writeSpace();
100009 emit(tag.name);
100010 }
100011 emitJSDocComment(tag.comment);
100012 emitJSDocSignature(tag.typeExpression);
100013 }
100014 function emitJSDocSimpleTag(tag) {
100015 emitJSDocTagName(tag.tagName);
100016 emitJSDocComment(tag.comment);
100017 }
100018 function emitJSDocTypeLiteral(lit) {
100019 emitList(lit, ts.factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
100020 }
100021 function emitJSDocSignature(sig) {
100022 if (sig.typeParameters) {
100023 emitList(sig, ts.factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
100024 }
100025 if (sig.parameters) {
100026 emitList(sig, ts.factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
100027 }
100028 if (sig.type) {
100029 writeLine();
100030 writeSpace();
100031 writePunctuation("*");
100032 writeSpace();
100033 emit(sig.type);
100034 }
100035 }
100036 function emitJSDocPropertyLikeTag(param) {
100037 emitJSDocTagName(param.tagName);
100038 emitJSDocTypeExpression(param.typeExpression);
100039 writeSpace();
100040 if (param.isBracketed) {
100041 writePunctuation("[");
100042 }
100043 emit(param.name);
100044 if (param.isBracketed) {
100045 writePunctuation("]");
100046 }
100047 emitJSDocComment(param.comment);
100048 }
100049 function emitJSDocTagName(tagName) {
100050 writePunctuation("@");
100051 emit(tagName);
100052 }
100053 function emitJSDocComment(comment) {
100054 if (comment) {
100055 writeSpace();
100056 write(comment);
100057 }
100058 }
100059 function emitJSDocTypeExpression(typeExpression) {
100060 if (typeExpression) {
100061 writeSpace();
100062 writePunctuation("{");
100063 emit(typeExpression.type);
100064 writePunctuation("}");
100065 }
100066 }
100067 //
100068 // Top-level nodes
100069 //
100070 function emitSourceFile(node) {
100071 writeLine();
100072 var statements = node.statements;
100073 if (emitBodyWithDetachedComments) {
100074 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
100075 // The synthesized node will have no leading comment so some comments may be missed.
100076 var shouldEmitDetachedComment = statements.length === 0 ||
100077 !ts.isPrologueDirective(statements[0]) ||
100078 ts.nodeIsSynthesized(statements[0]);
100079 if (shouldEmitDetachedComment) {
100080 emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
100081 return;
100082 }
100083 }
100084 emitSourceFileWorker(node);
100085 }
100086 function emitSyntheticTripleSlashReferencesIfNeeded(node) {
100087 emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
100088 for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
100089 var prepend = _b[_a];
100090 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
100091 for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
100092 var ref = _d[_c];
100093 emit(ref);
100094 writeLine();
100095 }
100096 }
100097 }
100098 }
100099 function emitTripleSlashDirectivesIfNeeded(node) {
100100 if (node.isDeclarationFile)
100101 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
100102 }
100103 function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
100104 if (hasNoDefaultLib) {
100105 var pos = writer.getTextPos();
100106 writeComment("/// <reference no-default-lib=\"true\"/>");
100107 if (bundleFileInfo)
100108 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
100109 writeLine();
100110 }
100111 if (currentSourceFile && currentSourceFile.moduleName) {
100112 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
100113 writeLine();
100114 }
100115 if (currentSourceFile && currentSourceFile.amdDependencies) {
100116 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
100117 var dep = _b[_a];
100118 if (dep.name) {
100119 writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
100120 }
100121 else {
100122 writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
100123 }
100124 writeLine();
100125 }
100126 }
100127 for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
100128 var directive = files_1[_c];
100129 var pos = writer.getTextPos();
100130 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
100131 if (bundleFileInfo)
100132 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
100133 writeLine();
100134 }
100135 for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
100136 var directive = types_22[_d];
100137 var pos = writer.getTextPos();
100138 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
100139 if (bundleFileInfo)
100140 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
100141 writeLine();
100142 }
100143 for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
100144 var directive = libs_1[_e];
100145 var pos = writer.getTextPos();
100146 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
100147 if (bundleFileInfo)
100148 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
100149 writeLine();
100150 }
100151 }
100152 function emitSourceFileWorker(node) {
100153 var statements = node.statements;
100154 pushNameGenerationScope(node);
100155 ts.forEach(node.statements, generateNames);
100156 emitHelpers(node);
100157 var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
100158 emitTripleSlashDirectivesIfNeeded(node);
100159 emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
100160 popNameGenerationScope(node);
100161 }
100162 // Transformation nodes
100163 function emitPartiallyEmittedExpression(node) {
100164 emitExpression(node.expression);
100165 }
100166 function emitCommaList(node) {
100167 emitExpressionList(node, node.elements, 528 /* CommaListElements */);
100168 }
100169 /**
100170 * Emits any prologue directives at the start of a Statement list, returning the
100171 * number of prologue directives written to the output.
100172 */
100173 function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
100174 var needsToSetSourceFile = !!sourceFile;
100175 for (var i = 0; i < statements.length; i++) {
100176 var statement = statements[i];
100177 if (ts.isPrologueDirective(statement)) {
100178 var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
100179 if (shouldEmitPrologueDirective) {
100180 if (needsToSetSourceFile) {
100181 needsToSetSourceFile = false;
100182 setSourceFile(sourceFile);
100183 }
100184 writeLine();
100185 var pos = writer.getTextPos();
100186 emit(statement);
100187 if (recordBundleFileSection && bundleFileInfo)
100188 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
100189 if (seenPrologueDirectives) {
100190 seenPrologueDirectives.add(statement.expression.text);
100191 }
100192 }
100193 }
100194 else {
100195 // return index of the first non prologue directive
100196 return i;
100197 }
100198 }
100199 return statements.length;
100200 }
100201 function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
100202 for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
100203 var prologue = prologues_1[_a];
100204 if (!seenPrologueDirectives.has(prologue.data)) {
100205 writeLine();
100206 var pos = writer.getTextPos();
100207 emit(prologue);
100208 if (bundleFileInfo)
100209 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
100210 if (seenPrologueDirectives) {
100211 seenPrologueDirectives.add(prologue.data);
100212 }
100213 }
100214 }
100215 }
100216 function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
100217 if (ts.isSourceFile(sourceFileOrBundle)) {
100218 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
100219 }
100220 else {
100221 var seenPrologueDirectives = new ts.Set();
100222 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
100223 var prepend = _b[_a];
100224 emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
100225 }
100226 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
100227 var sourceFile = _d[_c];
100228 emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
100229 }
100230 setSourceFile(undefined);
100231 }
100232 }
100233 function getPrologueDirectivesFromBundledSourceFiles(bundle) {
100234 var seenPrologueDirectives = new ts.Set();
100235 var prologues;
100236 for (var index = 0; index < bundle.sourceFiles.length; index++) {
100237 var sourceFile = bundle.sourceFiles[index];
100238 var directives = void 0;
100239 var end = 0;
100240 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
100241 var statement = _b[_a];
100242 if (!ts.isPrologueDirective(statement))
100243 break;
100244 if (seenPrologueDirectives.has(statement.expression.text))
100245 continue;
100246 seenPrologueDirectives.add(statement.expression.text);
100247 (directives || (directives = [])).push({
100248 pos: statement.pos,
100249 end: statement.end,
100250 expression: {
100251 pos: statement.expression.pos,
100252 end: statement.expression.end,
100253 text: statement.expression.text
100254 }
100255 });
100256 end = end < statement.end ? statement.end : end;
100257 }
100258 if (directives)
100259 (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
100260 }
100261 return prologues;
100262 }
100263 function emitShebangIfNeeded(sourceFileOrBundle) {
100264 if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
100265 var shebang = ts.getShebang(sourceFileOrBundle.text);
100266 if (shebang) {
100267 writeComment(shebang);
100268 writeLine();
100269 return true;
100270 }
100271 }
100272 else {
100273 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
100274 var prepend = _b[_a];
100275 ts.Debug.assertNode(prepend, ts.isUnparsedSource);
100276 if (emitShebangIfNeeded(prepend)) {
100277 return true;
100278 }
100279 }
100280 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
100281 var sourceFile = _d[_c];
100282 // Emit only the first encountered shebang
100283 if (emitShebangIfNeeded(sourceFile)) {
100284 return true;
100285 }
100286 }
100287 }
100288 }
100289 //
100290 // Helpers
100291 //
100292 function emitNodeWithWriter(node, writer) {
100293 if (!node)
100294 return;
100295 var savedWrite = write;
100296 write = writer;
100297 emit(node);
100298 write = savedWrite;
100299 }
100300 function emitModifiers(node, modifiers) {
100301 if (modifiers && modifiers.length) {
100302 emitList(node, modifiers, 262656 /* Modifiers */);
100303 writeSpace();
100304 }
100305 }
100306 function emitTypeAnnotation(node) {
100307 if (node) {
100308 writePunctuation(":");
100309 writeSpace();
100310 emit(node);
100311 }
100312 }
100313 function emitInitializer(node, equalCommentStartPos, container) {
100314 if (node) {
100315 writeSpace();
100316 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
100317 writeSpace();
100318 emitExpression(node);
100319 }
100320 }
100321 function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
100322 if (node) {
100323 prefixWriter(prefix);
100324 emit(node);
100325 }
100326 }
100327 function emitWithLeadingSpace(node) {
100328 if (node) {
100329 writeSpace();
100330 emit(node);
100331 }
100332 }
100333 function emitExpressionWithLeadingSpace(node) {
100334 if (node) {
100335 writeSpace();
100336 emitExpression(node);
100337 }
100338 }
100339 function emitWithTrailingSpace(node) {
100340 if (node) {
100341 emit(node);
100342 writeSpace();
100343 }
100344 }
100345 function emitEmbeddedStatement(parent, node) {
100346 if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
100347 writeSpace();
100348 emit(node);
100349 }
100350 else {
100351 writeLine();
100352 increaseIndent();
100353 if (ts.isEmptyStatement(node)) {
100354 pipelineEmit(5 /* EmbeddedStatement */, node);
100355 }
100356 else {
100357 emit(node);
100358 }
100359 decreaseIndent();
100360 }
100361 }
100362 function emitDecorators(parentNode, decorators) {
100363 emitList(parentNode, decorators, 2146305 /* Decorators */);
100364 }
100365 function emitTypeArguments(parentNode, typeArguments) {
100366 emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
100367 }
100368 function emitTypeParameters(parentNode, typeParameters) {
100369 if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
100370 return emitTypeArguments(parentNode, parentNode.typeArguments);
100371 }
100372 emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
100373 }
100374 function emitParameters(parentNode, parameters) {
100375 emitList(parentNode, parameters, 2576 /* Parameters */);
100376 }
100377 function canEmitSimpleArrowHead(parentNode, parameters) {
100378 var parameter = ts.singleOrUndefined(parameters);
100379 return parameter
100380 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
100381 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
100382 && !parentNode.type // arrow function may not have return type annotation
100383 && !ts.some(parentNode.decorators) // parent may not have decorators
100384 && !ts.some(parentNode.modifiers) // parent may not have modifiers
100385 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
100386 && !ts.some(parameter.decorators) // parameter may not have decorators
100387 && !ts.some(parameter.modifiers) // parameter may not have modifiers
100388 && !parameter.dotDotDotToken // parameter may not be rest
100389 && !parameter.questionToken // parameter may not be optional
100390 && !parameter.type // parameter may not have a type annotation
100391 && !parameter.initializer // parameter may not have an initializer
100392 && ts.isIdentifier(parameter.name); // parameter name must be identifier
100393 }
100394 function emitParametersForArrow(parentNode, parameters) {
100395 if (canEmitSimpleArrowHead(parentNode, parameters)) {
100396 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
100397 }
100398 else {
100399 emitParameters(parentNode, parameters);
100400 }
100401 }
100402 function emitParametersForIndexSignature(parentNode, parameters) {
100403 emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
100404 }
100405 function emitList(parentNode, children, format, start, count) {
100406 emitNodeList(emit, parentNode, children, format, start, count);
100407 }
100408 function emitExpressionList(parentNode, children, format, start, count) {
100409 emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
100410 }
100411 function writeDelimiter(format) {
100412 switch (format & 60 /* DelimitersMask */) {
100413 case 0 /* None */:
100414 break;
100415 case 16 /* CommaDelimited */:
100416 writePunctuation(",");
100417 break;
100418 case 4 /* BarDelimited */:
100419 writeSpace();
100420 writePunctuation("|");
100421 break;
100422 case 32 /* AsteriskDelimited */:
100423 writeSpace();
100424 writePunctuation("*");
100425 writeSpace();
100426 break;
100427 case 8 /* AmpersandDelimited */:
100428 writeSpace();
100429 writePunctuation("&");
100430 break;
100431 }
100432 }
100433 function emitNodeList(emit, parentNode, children, format, start, count) {
100434 if (start === void 0) { start = 0; }
100435 if (count === void 0) { count = children ? children.length - start : 0; }
100436 var isUndefined = children === undefined;
100437 if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
100438 return;
100439 }
100440 var isEmpty = children === undefined || start >= children.length || count === 0;
100441 if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
100442 if (onBeforeEmitNodeArray) {
100443 onBeforeEmitNodeArray(children);
100444 }
100445 if (onAfterEmitNodeArray) {
100446 onAfterEmitNodeArray(children);
100447 }
100448 return;
100449 }
100450 if (format & 15360 /* BracketsMask */) {
100451 writePunctuation(getOpeningBracket(format));
100452 if (isEmpty && !isUndefined) {
100453 // TODO: GH#18217
100454 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
100455 }
100456 }
100457 if (onBeforeEmitNodeArray) {
100458 onBeforeEmitNodeArray(children);
100459 }
100460 if (isEmpty) {
100461 // Write a line terminator if the parent node was multi-line
100462 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
100463 writeLine();
100464 }
100465 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
100466 writeSpace();
100467 }
100468 }
100469 else {
100470 // Write the opening line terminator or leading whitespace.
100471 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
100472 var shouldEmitInterveningComments = mayEmitInterveningComments;
100473 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
100474 if (leadingLineTerminatorCount) {
100475 writeLine(leadingLineTerminatorCount);
100476 shouldEmitInterveningComments = false;
100477 }
100478 else if (format & 256 /* SpaceBetweenBraces */) {
100479 writeSpace();
100480 }
100481 // Increase the indent, if requested.
100482 if (format & 128 /* Indented */) {
100483 increaseIndent();
100484 }
100485 // Emit each child.
100486 var previousSibling = void 0;
100487 var previousSourceFileTextKind = void 0;
100488 var shouldDecreaseIndentAfterEmit = false;
100489 for (var i = 0; i < count; i++) {
100490 var child = children[start + i];
100491 // Write the delimiter if this is not the first node.
100492 if (format & 32 /* AsteriskDelimited */) {
100493 // always write JSDoc in the format "\n *"
100494 writeLine();
100495 writeDelimiter(format);
100496 }
100497 else if (previousSibling) {
100498 // i.e
100499 // function commentedParameters(
100500 // /* Parameter a */
100501 // a
100502 // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
100503 // ,
100504 if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
100505 emitLeadingCommentsOfPosition(previousSibling.end);
100506 }
100507 writeDelimiter(format);
100508 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
100509 // Write either a line terminator or whitespace to separate the elements.
100510 var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
100511 if (separatingLineTerminatorCount > 0) {
100512 // If a synthesized node in a single-line list starts on a new
100513 // line, we should increase the indent.
100514 if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
100515 increaseIndent();
100516 shouldDecreaseIndentAfterEmit = true;
100517 }
100518 writeLine(separatingLineTerminatorCount);
100519 shouldEmitInterveningComments = false;
100520 }
100521 else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
100522 writeSpace();
100523 }
100524 }
100525 // Emit this child.
100526 previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
100527 if (shouldEmitInterveningComments) {
100528 if (emitTrailingCommentsOfPosition) {
100529 var commentRange = ts.getCommentRange(child);
100530 emitTrailingCommentsOfPosition(commentRange.pos);
100531 }
100532 }
100533 else {
100534 shouldEmitInterveningComments = mayEmitInterveningComments;
100535 }
100536 nextListElementPos = child.pos;
100537 emit(child);
100538 if (shouldDecreaseIndentAfterEmit) {
100539 decreaseIndent();
100540 shouldDecreaseIndentAfterEmit = false;
100541 }
100542 previousSibling = child;
100543 }
100544 // Write a trailing comma, if requested.
100545 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
100546 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
100547 writePunctuation(",");
100548 }
100549 // Emit any trailing comment of the last element in the list
100550 // i.e
100551 // var array = [...
100552 // 2
100553 // /* end of element 2 */
100554 // ];
100555 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
100556 emitLeadingCommentsOfPosition(previousSibling.end);
100557 }
100558 // Decrease the indent, if requested.
100559 if (format & 128 /* Indented */) {
100560 decreaseIndent();
100561 }
100562 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
100563 // Write the closing line terminator or closing whitespace.
100564 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
100565 if (closingLineTerminatorCount) {
100566 writeLine(closingLineTerminatorCount);
100567 }
100568 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
100569 writeSpace();
100570 }
100571 }
100572 if (onAfterEmitNodeArray) {
100573 onAfterEmitNodeArray(children);
100574 }
100575 if (format & 15360 /* BracketsMask */) {
100576 if (isEmpty && !isUndefined) {
100577 // TODO: GH#18217
100578 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
100579 }
100580 writePunctuation(getClosingBracket(format));
100581 }
100582 }
100583 // Writers
100584 function writeLiteral(s) {
100585 writer.writeLiteral(s);
100586 }
100587 function writeStringLiteral(s) {
100588 writer.writeStringLiteral(s);
100589 }
100590 function writeBase(s) {
100591 writer.write(s);
100592 }
100593 function writeSymbol(s, sym) {
100594 writer.writeSymbol(s, sym);
100595 }
100596 function writePunctuation(s) {
100597 writer.writePunctuation(s);
100598 }
100599 function writeTrailingSemicolon() {
100600 writer.writeTrailingSemicolon(";");
100601 }
100602 function writeKeyword(s) {
100603 writer.writeKeyword(s);
100604 }
100605 function writeOperator(s) {
100606 writer.writeOperator(s);
100607 }
100608 function writeParameter(s) {
100609 writer.writeParameter(s);
100610 }
100611 function writeComment(s) {
100612 writer.writeComment(s);
100613 }
100614 function writeSpace() {
100615 writer.writeSpace(" ");
100616 }
100617 function writeProperty(s) {
100618 writer.writeProperty(s);
100619 }
100620 function writeLine(count) {
100621 if (count === void 0) { count = 1; }
100622 for (var i = 0; i < count; i++) {
100623 writer.writeLine(i > 0);
100624 }
100625 }
100626 function increaseIndent() {
100627 writer.increaseIndent();
100628 }
100629 function decreaseIndent() {
100630 writer.decreaseIndent();
100631 }
100632 function writeToken(token, pos, writer, contextNode) {
100633 return !sourceMapsDisabled
100634 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
100635 : writeTokenText(token, writer, pos);
100636 }
100637 function writeTokenNode(node, writer) {
100638 if (onBeforeEmitToken) {
100639 onBeforeEmitToken(node);
100640 }
100641 writer(ts.tokenToString(node.kind));
100642 if (onAfterEmitToken) {
100643 onAfterEmitToken(node);
100644 }
100645 }
100646 function writeTokenText(token, writer, pos) {
100647 var tokenString = ts.tokenToString(token);
100648 writer(tokenString);
100649 return pos < 0 ? pos : pos + tokenString.length;
100650 }
100651 function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
100652 if (ts.getEmitFlags(parentNode) & 1 /* SingleLine */) {
100653 writeSpace();
100654 }
100655 else if (preserveSourceNewlines) {
100656 var lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
100657 if (lines) {
100658 writeLine(lines);
100659 }
100660 else {
100661 writeSpace();
100662 }
100663 }
100664 else {
100665 writeLine();
100666 }
100667 }
100668 function writeLines(text) {
100669 var lines = text.split(/\r\n?|\n/g);
100670 var indentation = ts.guessIndentation(lines);
100671 for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
100672 var lineText = lines_3[_a];
100673 var line = indentation ? lineText.slice(indentation) : lineText;
100674 if (line.length) {
100675 writeLine();
100676 write(line);
100677 }
100678 }
100679 }
100680 function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
100681 if (lineCount) {
100682 increaseIndent();
100683 writeLine(lineCount);
100684 }
100685 else if (writeSpaceIfNotIndenting) {
100686 writeSpace();
100687 }
100688 }
100689 // Helper function to decrease the indent if we previously indented. Allows multiple
100690 // previous indent values to be considered at a time. This also allows caller to just
100691 // call this once, passing in all their appropriate indent values, instead of needing
100692 // to call this helper function multiple times.
100693 function decreaseIndentIf(value1, value2) {
100694 if (value1) {
100695 decreaseIndent();
100696 }
100697 if (value2) {
100698 decreaseIndent();
100699 }
100700 }
100701 function getLeadingLineTerminatorCount(parentNode, children, format) {
100702 if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
100703 if (format & 65536 /* PreferNewLine */) {
100704 return 1;
100705 }
100706 var firstChild_1 = children[0];
100707 if (firstChild_1 === undefined) {
100708 return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
100709 }
100710 if (firstChild_1.pos === nextListElementPos) {
100711 // If this child starts at the beginning of a list item in a parent list, its leading
100712 // line terminators have already been written as the separating line terminators of the
100713 // parent list. Example:
100714 //
100715 // class Foo {
100716 // constructor() {}
100717 // public foo() {}
100718 // }
100719 //
100720 // The outer list is the list of class members, with one line terminator between the
100721 // constructor and the method. The constructor is written, the separating line terminator
100722 // is written, and then we start emitting the method. Its modifiers ([public]) constitute an inner
100723 // list, so we look for its leading line terminators. If we didn't know that we had already
100724 // written a newline as part of the parent list, it would appear that we need to write a
100725 // leading newline to start the modifiers.
100726 return 0;
100727 }
100728 if (firstChild_1.kind === 11 /* JsxText */) {
100729 // JsxText will be written with its leading whitespace, so don't add more manually.
100730 return 0;
100731 }
100732 if (!ts.positionIsSynthesized(parentNode.pos) &&
100733 !ts.nodeIsSynthesized(firstChild_1) &&
100734 (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) {
100735 if (preserveSourceNewlines) {
100736 return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
100737 }
100738 return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
100739 }
100740 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
100741 return 1;
100742 }
100743 }
100744 return format & 1 /* MultiLine */ ? 1 : 0;
100745 }
100746 function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
100747 if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
100748 if (previousNode === undefined || nextNode === undefined) {
100749 return 0;
100750 }
100751 if (nextNode.kind === 11 /* JsxText */) {
100752 // JsxText will be written with its leading whitespace, so don't add more manually.
100753 return 0;
100754 }
100755 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
100756 if (preserveSourceNewlines) {
100757 return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
100758 }
100759 return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
100760 }
100761 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
100762 return 1;
100763 }
100764 }
100765 else if (ts.getStartsOnNewLine(nextNode)) {
100766 return 1;
100767 }
100768 return format & 1 /* MultiLine */ ? 1 : 0;
100769 }
100770 function getClosingLineTerminatorCount(parentNode, children, format) {
100771 if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
100772 if (format & 65536 /* PreferNewLine */) {
100773 return 1;
100774 }
100775 var lastChild = ts.lastOrUndefined(children);
100776 if (lastChild === undefined) {
100777 return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
100778 }
100779 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
100780 if (preserveSourceNewlines) {
100781 var end_2 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
100782 return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_2, parentNode.end, currentSourceFile, includeComments); });
100783 }
100784 return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
100785 }
100786 if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
100787 return 1;
100788 }
100789 }
100790 if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
100791 return 1;
100792 }
100793 return 0;
100794 }
100795 function getEffectiveLines(getLineDifference) {
100796 // If 'preserveSourceNewlines' is disabled, we should never call this function
100797 // because it could be more expensive than alternative approximations.
100798 ts.Debug.assert(!!preserveSourceNewlines);
100799 // We start by measuring the line difference from a position to its adjacent comments,
100800 // so that this is counted as a one-line difference, not two:
100801 //
100802 // node1;
100803 // // NODE2 COMMENT
100804 // node2;
100805 var lines = getLineDifference(/*includeComments*/ true);
100806 if (lines === 0) {
100807 // However, if the line difference considering comments was 0, we might have this:
100808 //
100809 // node1; // NODE2 COMMENT
100810 // node2;
100811 //
100812 // in which case we should be ignoring node2's comment, so this too is counted as
100813 // a one-line difference, not zero.
100814 return getLineDifference(/*includeComments*/ false);
100815 }
100816 return lines;
100817 }
100818 function writeLineSeparatorsAndIndentBefore(node, parent) {
100819 var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
100820 if (leadingNewlines) {
100821 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
100822 }
100823 return !!leadingNewlines;
100824 }
100825 function writeLineSeparatorsAfter(node, parent) {
100826 var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
100827 if (trailingNewlines) {
100828 writeLine(trailingNewlines);
100829 }
100830 }
100831 function synthesizedNodeStartsOnNewLine(node, format) {
100832 if (ts.nodeIsSynthesized(node)) {
100833 var startsOnNewLine = ts.getStartsOnNewLine(node);
100834 if (startsOnNewLine === undefined) {
100835 return (format & 65536 /* PreferNewLine */) !== 0;
100836 }
100837 return startsOnNewLine;
100838 }
100839 return (format & 65536 /* PreferNewLine */) !== 0;
100840 }
100841 function getLinesBetweenNodes(parent, node1, node2) {
100842 if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
100843 return 0;
100844 }
100845 parent = skipSynthesizedParentheses(parent);
100846 node1 = skipSynthesizedParentheses(node1);
100847 node2 = skipSynthesizedParentheses(node2);
100848 // Always use a newline for synthesized code if the synthesizer desires it.
100849 if (ts.getStartsOnNewLine(node2)) {
100850 return 1;
100851 }
100852 if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
100853 if (preserveSourceNewlines) {
100854 return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
100855 }
100856 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
100857 }
100858 return 0;
100859 }
100860 function isEmptyBlock(block) {
100861 return block.statements.length === 0
100862 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
100863 }
100864 function skipSynthesizedParentheses(node) {
100865 while (node.kind === 204 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
100866 node = node.expression;
100867 }
100868 return node;
100869 }
100870 function getTextOfNode(node, includeTrivia) {
100871 if (ts.isGeneratedIdentifier(node)) {
100872 return generateName(node);
100873 }
100874 else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
100875 return ts.idText(node);
100876 }
100877 else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
100878 return getTextOfNode(node.textSourceNode, includeTrivia);
100879 }
100880 else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
100881 return node.text;
100882 }
100883 return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
100884 }
100885 function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
100886 if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
100887 var textSourceNode = node.textSourceNode;
100888 if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) {
100889 var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
100890 return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(text) + "\"" :
100891 neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(text) + "\"" :
100892 "\"" + ts.escapeNonAsciiString(text) + "\"";
100893 }
100894 else {
100895 return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
100896 }
100897 }
100898 return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
100899 }
100900 /**
100901 * Push a new name generation scope.
100902 */
100903 function pushNameGenerationScope(node) {
100904 if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
100905 return;
100906 }
100907 tempFlagsStack.push(tempFlags);
100908 tempFlags = 0;
100909 reservedNamesStack.push(reservedNames);
100910 }
100911 /**
100912 * Pop the current name generation scope.
100913 */
100914 function popNameGenerationScope(node) {
100915 if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
100916 return;
100917 }
100918 tempFlags = tempFlagsStack.pop();
100919 reservedNames = reservedNamesStack.pop();
100920 }
100921 function reserveNameInNestedScopes(name) {
100922 if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
100923 reservedNames = new ts.Set();
100924 }
100925 reservedNames.add(name);
100926 }
100927 function generateNames(node) {
100928 if (!node)
100929 return;
100930 switch (node.kind) {
100931 case 227 /* Block */:
100932 ts.forEach(node.statements, generateNames);
100933 break;
100934 case 242 /* LabeledStatement */:
100935 case 240 /* WithStatement */:
100936 case 232 /* DoStatement */:
100937 case 233 /* WhileStatement */:
100938 generateNames(node.statement);
100939 break;
100940 case 231 /* IfStatement */:
100941 generateNames(node.thenStatement);
100942 generateNames(node.elseStatement);
100943 break;
100944 case 234 /* ForStatement */:
100945 case 236 /* ForOfStatement */:
100946 case 235 /* ForInStatement */:
100947 generateNames(node.initializer);
100948 generateNames(node.statement);
100949 break;
100950 case 241 /* SwitchStatement */:
100951 generateNames(node.caseBlock);
100952 break;
100953 case 255 /* CaseBlock */:
100954 ts.forEach(node.clauses, generateNames);
100955 break;
100956 case 281 /* CaseClause */:
100957 case 282 /* DefaultClause */:
100958 ts.forEach(node.statements, generateNames);
100959 break;
100960 case 244 /* TryStatement */:
100961 generateNames(node.tryBlock);
100962 generateNames(node.catchClause);
100963 generateNames(node.finallyBlock);
100964 break;
100965 case 284 /* CatchClause */:
100966 generateNames(node.variableDeclaration);
100967 generateNames(node.block);
100968 break;
100969 case 229 /* VariableStatement */:
100970 generateNames(node.declarationList);
100971 break;
100972 case 247 /* VariableDeclarationList */:
100973 ts.forEach(node.declarations, generateNames);
100974 break;
100975 case 246 /* VariableDeclaration */:
100976 case 159 /* Parameter */:
100977 case 195 /* BindingElement */:
100978 case 249 /* ClassDeclaration */:
100979 generateNameIfNeeded(node.name);
100980 break;
100981 case 248 /* FunctionDeclaration */:
100982 generateNameIfNeeded(node.name);
100983 if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
100984 ts.forEach(node.parameters, generateNames);
100985 generateNames(node.body);
100986 }
100987 break;
100988 case 193 /* ObjectBindingPattern */:
100989 case 194 /* ArrayBindingPattern */:
100990 ts.forEach(node.elements, generateNames);
100991 break;
100992 case 258 /* ImportDeclaration */:
100993 generateNames(node.importClause);
100994 break;
100995 case 259 /* ImportClause */:
100996 generateNameIfNeeded(node.name);
100997 generateNames(node.namedBindings);
100998 break;
100999 case 260 /* NamespaceImport */:
101000 generateNameIfNeeded(node.name);
101001 break;
101002 case 266 /* NamespaceExport */:
101003 generateNameIfNeeded(node.name);
101004 break;
101005 case 261 /* NamedImports */:
101006 ts.forEach(node.elements, generateNames);
101007 break;
101008 case 262 /* ImportSpecifier */:
101009 generateNameIfNeeded(node.propertyName || node.name);
101010 break;
101011 }
101012 }
101013 function generateMemberNames(node) {
101014 if (!node)
101015 return;
101016 switch (node.kind) {
101017 case 285 /* PropertyAssignment */:
101018 case 286 /* ShorthandPropertyAssignment */:
101019 case 162 /* PropertyDeclaration */:
101020 case 164 /* MethodDeclaration */:
101021 case 166 /* GetAccessor */:
101022 case 167 /* SetAccessor */:
101023 generateNameIfNeeded(node.name);
101024 break;
101025 }
101026 }
101027 function generateNameIfNeeded(name) {
101028 if (name) {
101029 if (ts.isGeneratedIdentifier(name)) {
101030 generateName(name);
101031 }
101032 else if (ts.isBindingPattern(name)) {
101033 generateNames(name);
101034 }
101035 }
101036 }
101037 /**
101038 * Generate the text for a generated identifier.
101039 */
101040 function generateName(name) {
101041 if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
101042 // Node names generate unique names based on their original node
101043 // and are cached based on that node's id.
101044 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
101045 }
101046 else {
101047 // Auto, Loop, and Unique names are cached based on their unique
101048 // autoGenerateId.
101049 var autoGenerateId = name.autoGenerateId;
101050 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
101051 }
101052 }
101053 function generateNameCached(node, flags) {
101054 var nodeId = ts.getNodeId(node);
101055 return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
101056 }
101057 /**
101058 * Returns a value indicating whether a name is unique globally, within the current file,
101059 * or within the NameGenerator.
101060 */
101061 function isUniqueName(name) {
101062 return isFileLevelUniqueName(name)
101063 && !generatedNames.has(name)
101064 && !(reservedNames && reservedNames.has(name));
101065 }
101066 /**
101067 * Returns a value indicating whether a name is unique globally or within the current file.
101068 */
101069 function isFileLevelUniqueName(name) {
101070 return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
101071 }
101072 /**
101073 * Returns a value indicating whether a name is unique within a container.
101074 */
101075 function isUniqueLocalName(name, container) {
101076 for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
101077 if (node.locals) {
101078 var local = node.locals.get(ts.escapeLeadingUnderscores(name));
101079 // We conservatively include alias symbols to cover cases where they're emitted as locals
101080 if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
101081 return false;
101082 }
101083 }
101084 }
101085 return true;
101086 }
101087 /**
101088 * Return the next available name in the pattern _a ... _z, _0, _1, ...
101089 * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
101090 * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
101091 */
101092 function makeTempVariableName(flags, reservedInNestedScopes) {
101093 if (flags && !(tempFlags & flags)) {
101094 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
101095 if (isUniqueName(name)) {
101096 tempFlags |= flags;
101097 if (reservedInNestedScopes) {
101098 reserveNameInNestedScopes(name);
101099 }
101100 return name;
101101 }
101102 }
101103 while (true) {
101104 var count = tempFlags & 268435455 /* CountMask */;
101105 tempFlags++;
101106 // Skip over 'i' and 'n'
101107 if (count !== 8 && count !== 13) {
101108 var name = count < 26
101109 ? "_" + String.fromCharCode(97 /* a */ + count)
101110 : "_" + (count - 26);
101111 if (isUniqueName(name)) {
101112 if (reservedInNestedScopes) {
101113 reserveNameInNestedScopes(name);
101114 }
101115 return name;
101116 }
101117 }
101118 }
101119 }
101120 /**
101121 * Generate a name that is unique within the current file and doesn't conflict with any names
101122 * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
101123 * where n is a positive integer. Note that names generated by makeTempVariableName and
101124 * makeUniqueName are guaranteed to never conflict.
101125 * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
101126 */
101127 function makeUniqueName(baseName, checkFn, optimistic, scoped) {
101128 if (checkFn === void 0) { checkFn = isUniqueName; }
101129 if (optimistic) {
101130 if (checkFn(baseName)) {
101131 if (scoped) {
101132 reserveNameInNestedScopes(baseName);
101133 }
101134 else {
101135 generatedNames.add(baseName);
101136 }
101137 return baseName;
101138 }
101139 }
101140 // Find the first unique 'name_n', where n is a positive number
101141 if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
101142 baseName += "_";
101143 }
101144 var i = 1;
101145 while (true) {
101146 var generatedName = baseName + i;
101147 if (checkFn(generatedName)) {
101148 if (scoped) {
101149 reserveNameInNestedScopes(generatedName);
101150 }
101151 else {
101152 generatedNames.add(generatedName);
101153 }
101154 return generatedName;
101155 }
101156 i++;
101157 }
101158 }
101159 function makeFileLevelOptimisticUniqueName(name) {
101160 return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
101161 }
101162 /**
101163 * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
101164 */
101165 function generateNameForModuleOrEnum(node) {
101166 var name = getTextOfNode(node.name);
101167 // Use module/enum name itself if it is unique, otherwise make a unique variation
101168 return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
101169 }
101170 /**
101171 * Generates a unique name for an ImportDeclaration or ExportDeclaration.
101172 */
101173 function generateNameForImportOrExportDeclaration(node) {
101174 var expr = ts.getExternalModuleName(node); // TODO: GH#18217
101175 var baseName = ts.isStringLiteral(expr) ?
101176 ts.makeIdentifierFromModuleName(expr.text) : "module";
101177 return makeUniqueName(baseName);
101178 }
101179 /**
101180 * Generates a unique name for a default export.
101181 */
101182 function generateNameForExportDefault() {
101183 return makeUniqueName("default");
101184 }
101185 /**
101186 * Generates a unique name for a class expression.
101187 */
101188 function generateNameForClassExpression() {
101189 return makeUniqueName("class");
101190 }
101191 function generateNameForMethodOrAccessor(node) {
101192 if (ts.isIdentifier(node.name)) {
101193 return generateNameCached(node.name);
101194 }
101195 return makeTempVariableName(0 /* Auto */);
101196 }
101197 /**
101198 * Generates a unique name from a node.
101199 */
101200 function generateNameForNode(node, flags) {
101201 switch (node.kind) {
101202 case 78 /* Identifier */:
101203 return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
101204 case 253 /* ModuleDeclaration */:
101205 case 252 /* EnumDeclaration */:
101206 return generateNameForModuleOrEnum(node);
101207 case 258 /* ImportDeclaration */:
101208 case 264 /* ExportDeclaration */:
101209 return generateNameForImportOrExportDeclaration(node);
101210 case 248 /* FunctionDeclaration */:
101211 case 249 /* ClassDeclaration */:
101212 case 263 /* ExportAssignment */:
101213 return generateNameForExportDefault();
101214 case 218 /* ClassExpression */:
101215 return generateNameForClassExpression();
101216 case 164 /* MethodDeclaration */:
101217 case 166 /* GetAccessor */:
101218 case 167 /* SetAccessor */:
101219 return generateNameForMethodOrAccessor(node);
101220 case 157 /* ComputedPropertyName */:
101221 return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
101222 default:
101223 return makeTempVariableName(0 /* Auto */);
101224 }
101225 }
101226 /**
101227 * Generates a unique identifier for a node.
101228 */
101229 function makeName(name) {
101230 switch (name.autoGenerateFlags & 7 /* KindMask */) {
101231 case 1 /* Auto */:
101232 return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
101233 case 2 /* Loop */:
101234 return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
101235 case 3 /* Unique */:
101236 return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
101237 }
101238 return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
101239 }
101240 /**
101241 * Gets the node from which a name should be generated.
101242 */
101243 function getNodeForGeneratedName(name) {
101244 var autoGenerateId = name.autoGenerateId;
101245 var node = name;
101246 var original = node.original;
101247 while (original) {
101248 node = original;
101249 // if "node" is a different generated name (having a different
101250 // "autoGenerateId"), use it and stop traversing.
101251 if (ts.isIdentifier(node)
101252 && !!(node.autoGenerateFlags & 4 /* Node */)
101253 && node.autoGenerateId !== autoGenerateId) {
101254 break;
101255 }
101256 original = node.original;
101257 }
101258 // otherwise, return the original node for the source;
101259 return node;
101260 }
101261 // Comments
101262 function pipelineEmitWithComments(hint, node) {
101263 ts.Debug.assert(lastNode === node || lastSubstitution === node);
101264 enterComment();
101265 hasWrittenComment = false;
101266 var emitFlags = ts.getEmitFlags(node);
101267 var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
101268 var isEmittedNode = node.kind !== 330 /* NotEmittedStatement */;
101269 // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
101270 // It is expensive to walk entire tree just to set one kind of node to have no comments.
101271 var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
101272 var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
101273 // Save current container state on the stack.
101274 var savedContainerPos = containerPos;
101275 var savedContainerEnd = containerEnd;
101276 var savedDeclarationListContainerEnd = declarationListContainerEnd;
101277 if ((pos > 0 || end > 0) && pos !== end) {
101278 // Emit leading comments if the position is not synthesized and the node
101279 // has not opted out from emitting leading comments.
101280 if (!skipLeadingComments) {
101281 emitLeadingComments(pos, isEmittedNode);
101282 }
101283 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
101284 // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
101285 containerPos = pos;
101286 }
101287 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
101288 // As above.
101289 containerEnd = end;
101290 // To avoid invalid comment emit in a down-level binding pattern, we
101291 // keep track of the last declaration list container's end
101292 if (node.kind === 247 /* VariableDeclarationList */) {
101293 declarationListContainerEnd = end;
101294 }
101295 }
101296 }
101297 ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
101298 exitComment();
101299 var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
101300 if (emitFlags & 2048 /* NoNestedComments */) {
101301 commentsDisabled = true;
101302 pipelinePhase(hint, node);
101303 commentsDisabled = false;
101304 }
101305 else {
101306 pipelinePhase(hint, node);
101307 }
101308 enterComment();
101309 ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
101310 if ((pos > 0 || end > 0) && pos !== end) {
101311 // Restore previous container state.
101312 containerPos = savedContainerPos;
101313 containerEnd = savedContainerEnd;
101314 declarationListContainerEnd = savedDeclarationListContainerEnd;
101315 // Emit trailing comments if the position is not synthesized and the node
101316 // has not opted out from emitting leading comments and is an emitted node.
101317 if (!skipTrailingComments && isEmittedNode) {
101318 emitTrailingComments(end);
101319 }
101320 }
101321 exitComment();
101322 ts.Debug.assert(lastNode === node || lastSubstitution === node);
101323 }
101324 function emitLeadingSynthesizedComment(comment) {
101325 if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
101326 writer.writeLine();
101327 }
101328 writeSynthesizedComment(comment);
101329 if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
101330 writer.writeLine();
101331 }
101332 else {
101333 writer.writeSpace(" ");
101334 }
101335 }
101336 function emitTrailingSynthesizedComment(comment) {
101337 if (!writer.isAtStartOfLine()) {
101338 writer.writeSpace(" ");
101339 }
101340 writeSynthesizedComment(comment);
101341 if (comment.hasTrailingNewLine) {
101342 writer.writeLine();
101343 }
101344 }
101345 function writeSynthesizedComment(comment) {
101346 var text = formatSynthesizedComment(comment);
101347 var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
101348 ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
101349 }
101350 function formatSynthesizedComment(comment) {
101351 return comment.kind === 3 /* MultiLineCommentTrivia */
101352 ? "/*" + comment.text + "*/"
101353 : "//" + comment.text;
101354 }
101355 function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
101356 enterComment();
101357 var pos = detachedRange.pos, end = detachedRange.end;
101358 var emitFlags = ts.getEmitFlags(node);
101359 var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
101360 var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
101361 if (!skipLeadingComments) {
101362 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
101363 }
101364 exitComment();
101365 if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
101366 commentsDisabled = true;
101367 emitCallback(node);
101368 commentsDisabled = false;
101369 }
101370 else {
101371 emitCallback(node);
101372 }
101373 enterComment();
101374 if (!skipTrailingComments) {
101375 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
101376 if (hasWrittenComment && !writer.isAtStartOfLine()) {
101377 writer.writeLine();
101378 }
101379 }
101380 exitComment();
101381 }
101382 function emitLeadingComments(pos, isEmittedNode) {
101383 hasWrittenComment = false;
101384 if (isEmittedNode) {
101385 forEachLeadingCommentToEmit(pos, emitLeadingComment);
101386 }
101387 else if (pos === 0) {
101388 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
101389 // unless it is a triple slash comment at the top of the file.
101390 // For Example:
101391 // /// <reference-path ...>
101392 // declare var x;
101393 // /// <reference-path ...>
101394 // interface F {}
101395 // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
101396 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
101397 }
101398 }
101399 function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
101400 if (isTripleSlashComment(commentPos, commentEnd)) {
101401 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
101402 }
101403 }
101404 function shouldWriteComment(text, pos) {
101405 if (printerOptions.onlyPrintJsDocStyle) {
101406 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
101407 }
101408 return true;
101409 }
101410 function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
101411 if (!shouldWriteComment(currentSourceFile.text, commentPos))
101412 return;
101413 if (!hasWrittenComment) {
101414 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
101415 hasWrittenComment = true;
101416 }
101417 // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
101418 emitPos(commentPos);
101419 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
101420 emitPos(commentEnd);
101421 if (hasTrailingNewLine) {
101422 writer.writeLine();
101423 }
101424 else if (kind === 3 /* MultiLineCommentTrivia */) {
101425 writer.writeSpace(" ");
101426 }
101427 }
101428 function emitLeadingCommentsOfPosition(pos) {
101429 if (commentsDisabled || pos === -1) {
101430 return;
101431 }
101432 emitLeadingComments(pos, /*isEmittedNode*/ true);
101433 }
101434 function emitTrailingComments(pos) {
101435 forEachTrailingCommentToEmit(pos, emitTrailingComment);
101436 }
101437 function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
101438 if (!shouldWriteComment(currentSourceFile.text, commentPos))
101439 return;
101440 // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
101441 if (!writer.isAtStartOfLine()) {
101442 writer.writeSpace(" ");
101443 }
101444 emitPos(commentPos);
101445 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
101446 emitPos(commentEnd);
101447 if (hasTrailingNewLine) {
101448 writer.writeLine();
101449 }
101450 }
101451 function emitTrailingCommentsOfPosition(pos, prefixSpace) {
101452 if (commentsDisabled) {
101453 return;
101454 }
101455 enterComment();
101456 forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
101457 exitComment();
101458 }
101459 function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
101460 // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
101461 emitPos(commentPos);
101462 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
101463 emitPos(commentEnd);
101464 if (hasTrailingNewLine) {
101465 writer.writeLine();
101466 }
101467 else {
101468 writer.writeSpace(" ");
101469 }
101470 }
101471 function forEachLeadingCommentToEmit(pos, cb) {
101472 // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
101473 if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
101474 if (hasDetachedComments(pos)) {
101475 forEachLeadingCommentWithoutDetachedComments(cb);
101476 }
101477 else {
101478 ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
101479 }
101480 }
101481 }
101482 function forEachTrailingCommentToEmit(end, cb) {
101483 // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
101484 if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
101485 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
101486 }
101487 }
101488 function hasDetachedComments(pos) {
101489 return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
101490 }
101491 function forEachLeadingCommentWithoutDetachedComments(cb) {
101492 // get the leading comments from detachedPos
101493 var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
101494 if (detachedCommentsInfo.length - 1) {
101495 detachedCommentsInfo.pop();
101496 }
101497 else {
101498 detachedCommentsInfo = undefined;
101499 }
101500 ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
101501 }
101502 function emitDetachedCommentsAndUpdateCommentsInfo(range) {
101503 var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
101504 if (currentDetachedCommentInfo) {
101505 if (detachedCommentsInfo) {
101506 detachedCommentsInfo.push(currentDetachedCommentInfo);
101507 }
101508 else {
101509 detachedCommentsInfo = [currentDetachedCommentInfo];
101510 }
101511 }
101512 }
101513 function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
101514 if (!shouldWriteComment(currentSourceFile.text, commentPos))
101515 return;
101516 emitPos(commentPos);
101517 ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
101518 emitPos(commentEnd);
101519 }
101520 /**
101521 * Determine if the given comment is a triple-slash
101522 *
101523 * @return true if the comment is a triple-slash comment else false
101524 */
101525 function isTripleSlashComment(commentPos, commentEnd) {
101526 return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
101527 }
101528 // Source Maps
101529 function getParsedSourceMap(node) {
101530 if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
101531 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
101532 }
101533 return node.parsedSourceMap || undefined;
101534 }
101535 function pipelineEmitWithSourceMap(hint, node) {
101536 ts.Debug.assert(lastNode === node || lastSubstitution === node);
101537 var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
101538 if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
101539 pipelinePhase(hint, node);
101540 }
101541 else if (ts.isUnparsedNode(node)) {
101542 var parsed = getParsedSourceMap(node.parent);
101543 if (parsed && sourceMapGenerator) {
101544 sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
101545 }
101546 pipelinePhase(hint, node);
101547 }
101548 else {
101549 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
101550 var emitFlags = ts.getEmitFlags(node);
101551 if (node.kind !== 330 /* NotEmittedStatement */
101552 && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
101553 && pos >= 0) {
101554 emitSourcePos(source, skipSourceTrivia(source, pos));
101555 }
101556 if (emitFlags & 64 /* NoNestedSourceMaps */) {
101557 sourceMapsDisabled = true;
101558 pipelinePhase(hint, node);
101559 sourceMapsDisabled = false;
101560 }
101561 else {
101562 pipelinePhase(hint, node);
101563 }
101564 if (node.kind !== 330 /* NotEmittedStatement */
101565 && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
101566 && end >= 0) {
101567 emitSourcePos(source, end);
101568 }
101569 }
101570 ts.Debug.assert(lastNode === node || lastSubstitution === node);
101571 }
101572 /**
101573 * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
101574 */
101575 function skipSourceTrivia(source, pos) {
101576 return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
101577 }
101578 /**
101579 * Emits a mapping.
101580 *
101581 * If the position is synthetic (undefined or a negative value), no mapping will be
101582 * created.
101583 *
101584 * @param pos The position.
101585 */
101586 function emitPos(pos) {
101587 if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
101588 return;
101589 }
101590 var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
101591 sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter,
101592 /*nameIndex*/ undefined);
101593 }
101594 function emitSourcePos(source, pos) {
101595 if (source !== sourceMapSource) {
101596 var savedSourceMapSource = sourceMapSource;
101597 setSourceMapSource(source);
101598 emitPos(pos);
101599 setSourceMapSource(savedSourceMapSource);
101600 }
101601 else {
101602 emitPos(pos);
101603 }
101604 }
101605 /**
101606 * Emits a token of a node with possible leading and trailing source maps.
101607 *
101608 * @param node The node containing the token.
101609 * @param token The token to emit.
101610 * @param tokenStartPos The start pos of the token.
101611 * @param emitCallback The callback used to emit the token.
101612 */
101613 function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
101614 if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
101615 return emitCallback(token, writer, tokenPos);
101616 }
101617 var emitNode = node && node.emitNode;
101618 var emitFlags = emitNode && emitNode.flags || 0 /* None */;
101619 var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
101620 var source = range && range.source || sourceMapSource;
101621 tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
101622 if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
101623 emitSourcePos(source, tokenPos);
101624 }
101625 tokenPos = emitCallback(token, writer, tokenPos);
101626 if (range)
101627 tokenPos = range.end;
101628 if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
101629 emitSourcePos(source, tokenPos);
101630 }
101631 return tokenPos;
101632 }
101633 function setSourceMapSource(source) {
101634 if (sourceMapsDisabled) {
101635 return;
101636 }
101637 sourceMapSource = source;
101638 if (isJsonSourceMapSource(source)) {
101639 return;
101640 }
101641 sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
101642 if (printerOptions.inlineSources) {
101643 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
101644 }
101645 }
101646 function isJsonSourceMapSource(sourceFile) {
101647 return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
101648 }
101649 }
101650 ts.createPrinter = createPrinter;
101651 function createBracketsMap() {
101652 var brackets = [];
101653 brackets[1024 /* Braces */] = ["{", "}"];
101654 brackets[2048 /* Parenthesis */] = ["(", ")"];
101655 brackets[4096 /* AngleBrackets */] = ["<", ">"];
101656 brackets[8192 /* SquareBrackets */] = ["[", "]"];
101657 return brackets;
101658 }
101659 function getOpeningBracket(format) {
101660 return brackets[format & 15360 /* BracketsMask */][0];
101661 }
101662 function getClosingBracket(format) {
101663 return brackets[format & 15360 /* BracketsMask */][1];
101664 }
101665 // Flags enum to track count of temp variables and a few dedicated names
101666 var TempFlags;
101667 (function (TempFlags) {
101668 TempFlags[TempFlags["Auto"] = 0] = "Auto";
101669 TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
101670 TempFlags[TempFlags["_i"] = 268435456] = "_i";
101671 })(TempFlags || (TempFlags = {}));
101672})(ts || (ts = {}));
101673/* @internal */
101674var ts;
101675(function (ts) {
101676 function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
101677 if (!host.getDirectories || !host.readDirectory) {
101678 return undefined;
101679 }
101680 var cachedReadDirectoryResult = new ts.Map();
101681 var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
101682 return {
101683 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
101684 fileExists: fileExists,
101685 readFile: function (path, encoding) { return host.readFile(path, encoding); },
101686 directoryExists: host.directoryExists && directoryExists,
101687 getDirectories: getDirectories,
101688 readDirectory: readDirectory,
101689 createDirectory: host.createDirectory && createDirectory,
101690 writeFile: host.writeFile && writeFile,
101691 addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
101692 addOrDeleteFile: addOrDeleteFile,
101693 clearCache: clearCache,
101694 realpath: host.realpath && realpath
101695 };
101696 function toPath(fileName) {
101697 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
101698 }
101699 function getCachedFileSystemEntries(rootDirPath) {
101700 return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
101701 }
101702 function getCachedFileSystemEntriesForBaseDir(path) {
101703 return getCachedFileSystemEntries(ts.getDirectoryPath(path));
101704 }
101705 function getBaseNameOfFileName(fileName) {
101706 return ts.getBaseFileName(ts.normalizePath(fileName));
101707 }
101708 function createCachedFileSystemEntries(rootDir, rootDirPath) {
101709 var resultFromHost = {
101710 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
101711 directories: host.getDirectories(rootDir) || []
101712 };
101713 cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
101714 return resultFromHost;
101715 }
101716 /**
101717 * If the readDirectory result was already cached, it returns that
101718 * Otherwise gets result from host and caches it.
101719 * The host request is done under try catch block to avoid caching incorrect result
101720 */
101721 function tryReadDirectory(rootDir, rootDirPath) {
101722 rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
101723 var cachedResult = getCachedFileSystemEntries(rootDirPath);
101724 if (cachedResult) {
101725 return cachedResult;
101726 }
101727 try {
101728 return createCachedFileSystemEntries(rootDir, rootDirPath);
101729 }
101730 catch (_e) {
101731 // If there is exception to read directories, dont cache the result and direct the calls to host
101732 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
101733 return undefined;
101734 }
101735 }
101736 function fileNameEqual(name1, name2) {
101737 return getCanonicalFileName(name1) === getCanonicalFileName(name2);
101738 }
101739 function hasEntry(entries, name) {
101740 return ts.some(entries, function (file) { return fileNameEqual(file, name); });
101741 }
101742 function updateFileSystemEntry(entries, baseName, isValid) {
101743 if (hasEntry(entries, baseName)) {
101744 if (!isValid) {
101745 return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
101746 }
101747 }
101748 else if (isValid) {
101749 return entries.push(baseName);
101750 }
101751 }
101752 function writeFile(fileName, data, writeByteOrderMark) {
101753 var path = toPath(fileName);
101754 var result = getCachedFileSystemEntriesForBaseDir(path);
101755 if (result) {
101756 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
101757 }
101758 return host.writeFile(fileName, data, writeByteOrderMark);
101759 }
101760 function fileExists(fileName) {
101761 var path = toPath(fileName);
101762 var result = getCachedFileSystemEntriesForBaseDir(path);
101763 return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
101764 host.fileExists(fileName);
101765 }
101766 function directoryExists(dirPath) {
101767 var path = toPath(dirPath);
101768 return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
101769 }
101770 function createDirectory(dirPath) {
101771 var path = toPath(dirPath);
101772 var result = getCachedFileSystemEntriesForBaseDir(path);
101773 var baseFileName = getBaseNameOfFileName(dirPath);
101774 if (result) {
101775 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
101776 }
101777 host.createDirectory(dirPath);
101778 }
101779 function getDirectories(rootDir) {
101780 var rootDirPath = toPath(rootDir);
101781 var result = tryReadDirectory(rootDir, rootDirPath);
101782 if (result) {
101783 return result.directories.slice();
101784 }
101785 return host.getDirectories(rootDir);
101786 }
101787 function readDirectory(rootDir, extensions, excludes, includes, depth) {
101788 var rootDirPath = toPath(rootDir);
101789 var result = tryReadDirectory(rootDir, rootDirPath);
101790 if (result) {
101791 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
101792 }
101793 return host.readDirectory(rootDir, extensions, excludes, includes, depth);
101794 function getFileSystemEntries(dir) {
101795 var path = toPath(dir);
101796 if (path === rootDirPath) {
101797 return result;
101798 }
101799 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
101800 }
101801 }
101802 function realpath(s) {
101803 return host.realpath ? host.realpath(s) : s;
101804 }
101805 function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
101806 var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
101807 if (existingResult) {
101808 // Just clear the cache for now
101809 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
101810 clearCache();
101811 return undefined;
101812 }
101813 var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
101814 if (!parentResult) {
101815 return undefined;
101816 }
101817 // This was earlier a file (hence not in cached directory contents)
101818 // or we never cached the directory containing it
101819 if (!host.directoryExists) {
101820 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
101821 clearCache();
101822 return undefined;
101823 }
101824 var baseName = getBaseNameOfFileName(fileOrDirectory);
101825 var fsQueryResult = {
101826 fileExists: host.fileExists(fileOrDirectoryPath),
101827 directoryExists: host.directoryExists(fileOrDirectoryPath)
101828 };
101829 if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
101830 // Folder added or removed, clear the cache instead of updating the folder and its structure
101831 clearCache();
101832 }
101833 else {
101834 // No need to update the directory structure, just files
101835 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
101836 }
101837 return fsQueryResult;
101838 }
101839 function addOrDeleteFile(fileName, filePath, eventKind) {
101840 if (eventKind === ts.FileWatcherEventKind.Changed) {
101841 return;
101842 }
101843 var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
101844 if (parentResult) {
101845 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
101846 }
101847 }
101848 function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
101849 updateFileSystemEntry(parentResult.files, baseName, fileExists);
101850 }
101851 function clearCache() {
101852 cachedReadDirectoryResult.clear();
101853 }
101854 }
101855 ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
101856 var ConfigFileProgramReloadLevel;
101857 (function (ConfigFileProgramReloadLevel) {
101858 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
101859 /** Update the file name list from the disk */
101860 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
101861 /** Reload completely by re-reading contents of config file from disk and updating program */
101862 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
101863 })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
101864 /**
101865 * Updates the existing missing file watches with the new set of missing files after new program is created
101866 */
101867 function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
101868 var missingFilePaths = program.getMissingFilePaths();
101869 // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap`
101870 var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue);
101871 // Update the missing file paths watcher
101872 ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
101873 // Watch the missing files
101874 createNewValue: createMissingFileWatch,
101875 // Files that are no longer missing (e.g. because they are no longer required)
101876 // should no longer be watched.
101877 onDeleteValue: ts.closeFileWatcher
101878 });
101879 }
101880 ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
101881 /**
101882 * Updates the existing wild card directory watches with the new set of wild card directories from the config file
101883 * after new program is created because the config file was reloaded or program was created first time from the config file
101884 * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
101885 * as wildcard directories wont change unless reloading config file
101886 */
101887 function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
101888 ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
101889 // Create new watch and recursive info
101890 createNewValue: createWildcardDirectoryWatcher,
101891 // Close existing watch thats not needed any more
101892 onDeleteValue: closeFileWatcherOf,
101893 // Close existing watch that doesnt match in the flags
101894 onExistingValue: updateWildcardDirectoryWatcher
101895 });
101896 function createWildcardDirectoryWatcher(directory, flags) {
101897 // Create new watch and recursive info
101898 return {
101899 watcher: watchDirectory(directory, flags),
101900 flags: flags
101901 };
101902 }
101903 function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
101904 // Watcher needs to be updated if the recursive flags dont match
101905 if (existingWatcher.flags === flags) {
101906 return;
101907 }
101908 existingWatcher.watcher.close();
101909 existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
101910 }
101911 }
101912 ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
101913 /* @internal */
101914 function isIgnoredFileFromWildCardWatching(_a) {
101915 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;
101916 var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
101917 if (!newPath) {
101918 writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory);
101919 return true;
101920 }
101921 fileOrDirectoryPath = newPath;
101922 if (fileOrDirectoryPath === watchedDirPath)
101923 return false;
101924 // If the the added or created file or directory is not supported file name, ignore the file
101925 // But when watched directory is added/removed, we need to reload the file list
101926 if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
101927 writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
101928 return true;
101929 }
101930 if (ts.isExcludedFile(fileOrDirectory, configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
101931 writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory);
101932 return true;
101933 }
101934 if (!program)
101935 return false;
101936 // We want to ignore emit file check if file is not going to be emitted next to source file
101937 // In that case we follow config file inclusion rules
101938 if (options.outFile || options.outDir)
101939 return false;
101940 // File if emitted next to input needs to be ignored
101941 if (ts.fileExtensionIs(fileOrDirectoryPath, ".d.ts" /* Dts */)) {
101942 // If its declaration directory: its not ignored if not excluded by config
101943 if (options.declarationDir)
101944 return false;
101945 }
101946 else if (!ts.fileExtensionIsOneOf(fileOrDirectoryPath, ts.supportedJSExtensions)) {
101947 return false;
101948 }
101949 // just check if sourceFile with the name exists
101950 var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath);
101951 var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
101952 if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) ||
101953 hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) {
101954 writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory);
101955 return true;
101956 }
101957 return false;
101958 function hasSourceFile(file) {
101959 return realProgram ?
101960 !!realProgram.getSourceFileByPath(file) :
101961 program.getState().fileInfos.has(file);
101962 }
101963 }
101964 ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching;
101965 function isBuilderProgram(program) {
101966 return !!program.getState;
101967 }
101968 function isEmittedFileOfProgram(program, file) {
101969 if (!program) {
101970 return false;
101971 }
101972 return program.isEmittedFile(file);
101973 }
101974 ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
101975 var WatchLogLevel;
101976 (function (WatchLogLevel) {
101977 WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
101978 WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
101979 WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
101980 })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
101981 function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
101982 return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
101983 }
101984 ts.getWatchFactory = getWatchFactory;
101985 function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
101986 var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
101987 var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
101988 var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
101989 if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
101990 ts.setSysLog(function (s) { return log(s); });
101991 }
101992 return {
101993 watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
101994 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
101995 },
101996 watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
101997 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
101998 },
101999 watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
102000 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
102001 }
102002 };
102003 }
102004 function watchFile(host, file, callback, pollingInterval, options) {
102005 return host.watchFile(file, callback, pollingInterval, options);
102006 }
102007 function watchFilePath(host, file, callback, pollingInterval, options, path) {
102008 return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
102009 }
102010 function watchDirectory(host, directory, callback, flags, options) {
102011 return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
102012 }
102013 function getCreateFileWatcher(watchLogLevel, addWatch) {
102014 switch (watchLogLevel) {
102015 case WatchLogLevel.None:
102016 return addWatch;
102017 case WatchLogLevel.TriggerOnly:
102018 return createFileWatcherWithTriggerLogging;
102019 case WatchLogLevel.Verbose:
102020 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
102021 }
102022 }
102023 function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
102024 log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
102025 var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
102026 return {
102027 close: function () {
102028 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
102029 watcher.close();
102030 }
102031 };
102032 }
102033 function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
102034 var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
102035 log(watchInfo);
102036 var start = ts.timestamp();
102037 var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
102038 var elapsed = ts.timestamp() - start;
102039 log("Elapsed:: " + elapsed + "ms " + watchInfo);
102040 return {
102041 close: function () {
102042 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
102043 log(watchInfo);
102044 var start = ts.timestamp();
102045 watcher.close();
102046 var elapsed = ts.timestamp() - start;
102047 log("Elapsed:: " + elapsed + "ms " + watchInfo);
102048 }
102049 };
102050 }
102051 function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
102052 return addWatch(host, file, function (fileName, cbOptional) {
102053 var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
102054 log(triggerredInfo);
102055 var start = ts.timestamp();
102056 cb(fileName, cbOptional, passThrough);
102057 var elapsed = ts.timestamp() - start;
102058 log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
102059 }, flags, options);
102060 }
102061 function getFallbackOptions(options) {
102062 var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
102063 return {
102064 watchFile: fallbackPolling !== undefined ?
102065 fallbackPolling :
102066 ts.WatchFileKind.PriorityPollingInterval
102067 };
102068 }
102069 ts.getFallbackOptions = getFallbackOptions;
102070 function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
102071 return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
102072 }
102073 function closeFileWatcherOf(objWithWatcher) {
102074 objWithWatcher.watcher.close();
102075 }
102076 ts.closeFileWatcherOf = closeFileWatcherOf;
102077})(ts || (ts = {}));
102078var ts;
102079(function (ts) {
102080 function findConfigFile(searchPath, fileExists, configName) {
102081 if (configName === void 0) { configName = "tsconfig.json"; }
102082 return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
102083 var fileName = ts.combinePaths(ancestor, configName);
102084 return fileExists(fileName) ? fileName : undefined;
102085 });
102086 }
102087 ts.findConfigFile = findConfigFile;
102088 function resolveTripleslashReference(moduleName, containingFile) {
102089 var basePath = ts.getDirectoryPath(containingFile);
102090 var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
102091 return ts.normalizePath(referencedFileName);
102092 }
102093 ts.resolveTripleslashReference = resolveTripleslashReference;
102094 /* @internal */
102095 function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
102096 var commonPathComponents;
102097 var failed = ts.forEach(fileNames, function (sourceFile) {
102098 // Each file contributes into common source file path
102099 var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
102100 sourcePathComponents.pop(); // The base file name is not part of the common directory path
102101 if (!commonPathComponents) {
102102 // first file
102103 commonPathComponents = sourcePathComponents;
102104 return;
102105 }
102106 var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
102107 for (var i = 0; i < n; i++) {
102108 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
102109 if (i === 0) {
102110 // Failed to find any common path component
102111 return true;
102112 }
102113 // New common path found that is 0 -> i-1
102114 commonPathComponents.length = i;
102115 break;
102116 }
102117 }
102118 // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
102119 if (sourcePathComponents.length < commonPathComponents.length) {
102120 commonPathComponents.length = sourcePathComponents.length;
102121 }
102122 });
102123 // A common path can not be found when paths span multiple drives on windows, for example
102124 if (failed) {
102125 return "";
102126 }
102127 if (!commonPathComponents) { // Can happen when all input files are .d.ts files
102128 return currentDirectory;
102129 }
102130 return ts.getPathFromPathComponents(commonPathComponents);
102131 }
102132 ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
102133 function createCompilerHost(options, setParentNodes) {
102134 return createCompilerHostWorker(options, setParentNodes);
102135 }
102136 ts.createCompilerHost = createCompilerHost;
102137 /*@internal*/
102138 // TODO(shkamat): update this after reworking ts build API
102139 function createCompilerHostWorker(options, setParentNodes, system) {
102140 if (system === void 0) { system = ts.sys; }
102141 var existingDirectories = new ts.Map();
102142 var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
102143 function getSourceFile(fileName, languageVersion, onError) {
102144 var text;
102145 try {
102146 ts.performance.mark("beforeIORead");
102147 text = compilerHost.readFile(fileName);
102148 ts.performance.mark("afterIORead");
102149 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
102150 }
102151 catch (e) {
102152 if (onError) {
102153 onError(e.message);
102154 }
102155 text = "";
102156 }
102157 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
102158 }
102159 function directoryExists(directoryPath) {
102160 if (existingDirectories.has(directoryPath)) {
102161 return true;
102162 }
102163 if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
102164 existingDirectories.set(directoryPath, true);
102165 return true;
102166 }
102167 return false;
102168 }
102169 function writeFile(fileName, data, writeByteOrderMark, onError) {
102170 try {
102171 ts.performance.mark("beforeIOWrite");
102172 // NOTE: If patchWriteFileEnsuringDirectory has been called,
102173 // the system.writeFile will do its own directory creation and
102174 // the ensureDirectoriesExist call will always be redundant.
102175 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); });
102176 ts.performance.mark("afterIOWrite");
102177 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
102178 }
102179 catch (e) {
102180 if (onError) {
102181 onError(e.message);
102182 }
102183 }
102184 }
102185 var outputFingerprints;
102186 function writeFileWorker(fileName, data, writeByteOrderMark) {
102187 if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
102188 system.writeFile(fileName, data, writeByteOrderMark);
102189 return;
102190 }
102191 if (!outputFingerprints) {
102192 outputFingerprints = new ts.Map();
102193 }
102194 var hash = system.createHash(data);
102195 var mtimeBefore = system.getModifiedTime(fileName);
102196 if (mtimeBefore) {
102197 var fingerprint = outputFingerprints.get(fileName);
102198 // If output has not been changed, and the file has no external modification
102199 if (fingerprint &&
102200 fingerprint.byteOrderMark === writeByteOrderMark &&
102201 fingerprint.hash === hash &&
102202 fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
102203 return;
102204 }
102205 }
102206 system.writeFile(fileName, data, writeByteOrderMark);
102207 var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
102208 outputFingerprints.set(fileName, {
102209 hash: hash,
102210 byteOrderMark: writeByteOrderMark,
102211 mtime: mtimeAfter
102212 });
102213 }
102214 function getDefaultLibLocation() {
102215 return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
102216 }
102217 var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
102218 var realpath = system.realpath && (function (path) { return system.realpath(path); });
102219 var compilerHost = {
102220 getSourceFile: getSourceFile,
102221 getDefaultLibLocation: getDefaultLibLocation,
102222 getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
102223 writeFile: writeFile,
102224 getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
102225 useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
102226 getCanonicalFileName: getCanonicalFileName,
102227 getNewLine: function () { return newLine; },
102228 fileExists: function (fileName) { return system.fileExists(fileName); },
102229 readFile: function (fileName) { return system.readFile(fileName); },
102230 trace: function (s) { return system.write(s + newLine); },
102231 directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
102232 getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
102233 getDirectories: function (path) { return system.getDirectories(path); },
102234 realpath: realpath,
102235 readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
102236 createDirectory: function (d) { return system.createDirectory(d); },
102237 createHash: ts.maybeBind(system, system.createHash)
102238 };
102239 return compilerHost;
102240 }
102241 ts.createCompilerHostWorker = createCompilerHostWorker;
102242 /*@internal*/
102243 function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
102244 var originalReadFile = host.readFile;
102245 var originalFileExists = host.fileExists;
102246 var originalDirectoryExists = host.directoryExists;
102247 var originalCreateDirectory = host.createDirectory;
102248 var originalWriteFile = host.writeFile;
102249 var readFileCache = new ts.Map();
102250 var fileExistsCache = new ts.Map();
102251 var directoryExistsCache = new ts.Map();
102252 var sourceFileCache = new ts.Map();
102253 var readFileWithCache = function (fileName) {
102254 var key = toPath(fileName);
102255 var value = readFileCache.get(key);
102256 if (value !== undefined)
102257 return value !== false ? value : undefined;
102258 return setReadFileCache(key, fileName);
102259 };
102260 var setReadFileCache = function (key, fileName) {
102261 var newValue = originalReadFile.call(host, fileName);
102262 readFileCache.set(key, newValue !== undefined ? newValue : false);
102263 return newValue;
102264 };
102265 host.readFile = function (fileName) {
102266 var key = toPath(fileName);
102267 var value = readFileCache.get(key);
102268 if (value !== undefined)
102269 return value !== false ? value : undefined; // could be .d.ts from output
102270 // Cache json or buildInfo
102271 if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
102272 return originalReadFile.call(host, fileName);
102273 }
102274 return setReadFileCache(key, fileName);
102275 };
102276 var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
102277 var key = toPath(fileName);
102278 var value = sourceFileCache.get(key);
102279 if (value)
102280 return value;
102281 var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
102282 if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
102283 sourceFileCache.set(key, sourceFile);
102284 }
102285 return sourceFile;
102286 } : undefined;
102287 // fileExists for any kind of extension
102288 host.fileExists = function (fileName) {
102289 var key = toPath(fileName);
102290 var value = fileExistsCache.get(key);
102291 if (value !== undefined)
102292 return value;
102293 var newValue = originalFileExists.call(host, fileName);
102294 fileExistsCache.set(key, !!newValue);
102295 return newValue;
102296 };
102297 if (originalWriteFile) {
102298 host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
102299 var key = toPath(fileName);
102300 fileExistsCache.delete(key);
102301 var value = readFileCache.get(key);
102302 if (value !== undefined && value !== data) {
102303 readFileCache.delete(key);
102304 sourceFileCache.delete(key);
102305 }
102306 else if (getSourceFileWithCache) {
102307 var sourceFile = sourceFileCache.get(key);
102308 if (sourceFile && sourceFile.text !== data) {
102309 sourceFileCache.delete(key);
102310 }
102311 }
102312 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
102313 };
102314 }
102315 // directoryExists
102316 if (originalDirectoryExists && originalCreateDirectory) {
102317 host.directoryExists = function (directory) {
102318 var key = toPath(directory);
102319 var value = directoryExistsCache.get(key);
102320 if (value !== undefined)
102321 return value;
102322 var newValue = originalDirectoryExists.call(host, directory);
102323 directoryExistsCache.set(key, !!newValue);
102324 return newValue;
102325 };
102326 host.createDirectory = function (directory) {
102327 var key = toPath(directory);
102328 directoryExistsCache.delete(key);
102329 originalCreateDirectory.call(host, directory);
102330 };
102331 }
102332 return {
102333 originalReadFile: originalReadFile,
102334 originalFileExists: originalFileExists,
102335 originalDirectoryExists: originalDirectoryExists,
102336 originalCreateDirectory: originalCreateDirectory,
102337 originalWriteFile: originalWriteFile,
102338 getSourceFileWithCache: getSourceFileWithCache,
102339 readFileWithCache: readFileWithCache
102340 };
102341 }
102342 ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
102343 function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
102344 var diagnostics;
102345 diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
102346 diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
102347 diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
102348 diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
102349 diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
102350 if (ts.getEmitDeclarations(program.getCompilerOptions())) {
102351 diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
102352 }
102353 return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
102354 }
102355 ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
102356 function formatDiagnostics(diagnostics, host) {
102357 var output = "";
102358 for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
102359 var diagnostic = diagnostics_3[_i];
102360 output += formatDiagnostic(diagnostic, host);
102361 }
102362 return output;
102363 }
102364 ts.formatDiagnostics = formatDiagnostics;
102365 function formatDiagnostic(diagnostic, host) {
102366 var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
102367 if (diagnostic.file) {
102368 var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
102369 var fileName = diagnostic.file.fileName;
102370 var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
102371 return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
102372 }
102373 return errorMessage;
102374 }
102375 ts.formatDiagnostic = formatDiagnostic;
102376 /** @internal */
102377 var ForegroundColorEscapeSequences;
102378 (function (ForegroundColorEscapeSequences) {
102379 ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
102380 ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
102381 ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
102382 ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
102383 ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
102384 })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
102385 var gutterStyleSequence = "\u001b[7m";
102386 var gutterSeparator = " ";
102387 var resetEscapeSequence = "\u001b[0m";
102388 var ellipsis = "...";
102389 var halfIndent = " ";
102390 var indent = " ";
102391 function getCategoryFormat(category) {
102392 switch (category) {
102393 case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
102394 case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
102395 case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
102396 case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
102397 }
102398 }
102399 /** @internal */
102400 function formatColorAndReset(text, formatStyle) {
102401 return formatStyle + text + resetEscapeSequence;
102402 }
102403 ts.formatColorAndReset = formatColorAndReset;
102404 function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
102405 var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
102406 var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
102407 var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
102408 var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
102409 var gutterWidth = (lastLine + 1 + "").length;
102410 if (hasMoreThanFiveLines) {
102411 gutterWidth = Math.max(ellipsis.length, gutterWidth);
102412 }
102413 var context = "";
102414 for (var i = firstLine; i <= lastLine; i++) {
102415 context += host.getNewLine();
102416 // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
102417 // so we'll skip ahead to the second-to-last line.
102418 if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
102419 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
102420 i = lastLine - 1;
102421 }
102422 var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
102423 var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
102424 var lineContent = file.text.slice(lineStart, lineEnd);
102425 lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
102426 lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
102427 // Output the gutter and the actual contents of the line.
102428 context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
102429 context += lineContent + host.getNewLine();
102430 // Output the gutter and the error span for the line using tildes.
102431 context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
102432 context += squiggleColor;
102433 if (i === firstLine) {
102434 // If we're on the last line, then limit it to the last character of the last line.
102435 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
102436 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
102437 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
102438 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
102439 }
102440 else if (i === lastLine) {
102441 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
102442 }
102443 else {
102444 // Squiggle the entire line.
102445 context += lineContent.replace(/./g, "~");
102446 }
102447 context += resetEscapeSequence;
102448 }
102449 return context;
102450 }
102451 /* @internal */
102452 function formatLocation(file, start, host, color) {
102453 if (color === void 0) { color = formatColorAndReset; }
102454 var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
102455 var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
102456 var output = "";
102457 output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
102458 output += ":";
102459 output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
102460 output += ":";
102461 output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
102462 return output;
102463 }
102464 ts.formatLocation = formatLocation;
102465 function formatDiagnosticsWithColorAndContext(diagnostics, host) {
102466 var output = "";
102467 for (var _i = 0, diagnostics_4 = diagnostics; _i < diagnostics_4.length; _i++) {
102468 var diagnostic = diagnostics_4[_i];
102469 if (diagnostic.file) {
102470 var file = diagnostic.file, start = diagnostic.start;
102471 output += formatLocation(file, start, host); // TODO: GH#18217
102472 output += " - ";
102473 }
102474 output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
102475 output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
102476 output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
102477 if (diagnostic.file) {
102478 output += host.getNewLine();
102479 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
102480 if (diagnostic.relatedInformation) {
102481 output += host.getNewLine();
102482 for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
102483 var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
102484 if (file) {
102485 output += host.getNewLine();
102486 output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
102487 output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
102488 }
102489 output += host.getNewLine();
102490 output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
102491 }
102492 }
102493 }
102494 output += host.getNewLine();
102495 }
102496 return output;
102497 }
102498 ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
102499 function flattenDiagnosticMessageText(diag, newLine, indent) {
102500 if (indent === void 0) { indent = 0; }
102501 if (ts.isString(diag)) {
102502 return diag;
102503 }
102504 else if (diag === undefined) {
102505 return "";
102506 }
102507 var result = "";
102508 if (indent) {
102509 result += newLine;
102510 for (var i = 0; i < indent; i++) {
102511 result += " ";
102512 }
102513 }
102514 result += diag.messageText;
102515 indent++;
102516 if (diag.next) {
102517 for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
102518 var kid = _a[_i];
102519 result += flattenDiagnosticMessageText(kid, newLine, indent);
102520 }
102521 }
102522 return result;
102523 }
102524 ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
102525 /* @internal */
102526 function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
102527 if (names.length === 0) {
102528 return [];
102529 }
102530 var resolutions = [];
102531 var cache = new ts.Map();
102532 for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
102533 var name = names_2[_i];
102534 var result = void 0;
102535 if (cache.has(name)) {
102536 result = cache.get(name);
102537 }
102538 else {
102539 cache.set(name, result = loader(name, containingFile, redirectedReference));
102540 }
102541 resolutions.push(result);
102542 }
102543 return resolutions;
102544 }
102545 ts.loadWithLocalCache = loadWithLocalCache;
102546 /* @internal */
102547 ts.inferredTypesContainingFile = "__inferred type names__.ts";
102548 /**
102549 * Determines if program structure is upto date or needs to be recreated
102550 */
102551 /* @internal */
102552 function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
102553 // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
102554 if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) {
102555 return false;
102556 }
102557 // If root file names don't match
102558 if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
102559 return false;
102560 }
102561 var seenResolvedRefs;
102562 // If project references don't match
102563 if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
102564 return false;
102565 }
102566 // If any file is not up-to-date, then the whole program is not up-to-date
102567 if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
102568 return false;
102569 }
102570 // If any of the missing file paths are now created
102571 if (program.getMissingFilePaths().some(fileExists)) {
102572 return false;
102573 }
102574 var currentOptions = program.getCompilerOptions();
102575 // If the compilation settings do no match, then the program is not up-to-date
102576 if (!ts.compareDataObjects(currentOptions, newOptions)) {
102577 return false;
102578 }
102579 // If everything matches but the text of config file is changed,
102580 // error locations can change for program options, so update the program
102581 if (currentOptions.configFile && newOptions.configFile) {
102582 return currentOptions.configFile.text === newOptions.configFile.text;
102583 }
102584 return true;
102585 function sourceFileNotUptoDate(sourceFile) {
102586 return !sourceFileVersionUptoDate(sourceFile) ||
102587 hasInvalidatedResolution(sourceFile.path);
102588 }
102589 function sourceFileVersionUptoDate(sourceFile) {
102590 return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
102591 }
102592 function projectReferenceUptoDate(oldRef, newRef, index) {
102593 if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
102594 return false;
102595 }
102596 return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
102597 }
102598 function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
102599 if (oldResolvedRef) {
102600 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
102601 // Assume true
102602 return true;
102603 }
102604 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
102605 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
102606 return false;
102607 }
102608 // Add to seen before checking the referenced paths of this config file
102609 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
102610 // If child project references are upto date, this project reference is uptodate
102611 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
102612 return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
102613 });
102614 }
102615 // In old program, not able to resolve project reference path,
102616 // so if config file doesnt exist, it is uptodate.
102617 return !fileExists(resolveProjectReferencePath(oldRef));
102618 }
102619 }
102620 ts.isProgramUptoDate = isProgramUptoDate;
102621 function getConfigFileParsingDiagnostics(configFileParseResult) {
102622 return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
102623 configFileParseResult.errors;
102624 }
102625 ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
102626 /**
102627 * Determine if source file needs to be re-created even if its text hasn't changed
102628 */
102629 function shouldProgramCreateNewSourceFiles(program, newOptions) {
102630 if (!program)
102631 return false;
102632 // If any compiler options change, we can't reuse old source file even if version match
102633 // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
102634 var oldOptions = program.getCompilerOptions();
102635 return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
102636 return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
102637 });
102638 }
102639 function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
102640 return {
102641 rootNames: rootNames,
102642 options: options,
102643 host: host,
102644 oldProgram: oldProgram,
102645 configFileParsingDiagnostics: configFileParsingDiagnostics
102646 };
102647 }
102648 function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
102649 var _a, _b;
102650 var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
102651 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
102652 var oldProgram = createProgramOptions.oldProgram;
102653 var processingDefaultLibFiles;
102654 var processingOtherFiles;
102655 var files;
102656 var symlinks;
102657 var commonSourceDirectory;
102658 var diagnosticsProducingTypeChecker;
102659 var noDiagnosticsTypeChecker;
102660 var classifiableNames;
102661 var ambientModuleNameToUnmodifiedFileName = new ts.Map();
102662 // Todo:: Use this to report why file was included in --extendedDiagnostics
102663 var refFileMap;
102664 var cachedBindAndCheckDiagnosticsForFile = {};
102665 var cachedDeclarationDiagnosticsForFile = {};
102666 var resolvedTypeReferenceDirectives = new ts.Map();
102667 var fileProcessingDiagnostics = ts.createDiagnosticCollection();
102668 // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
102669 // This works as imported modules are discovered recursively in a depth first manner, specifically:
102670 // - For each root file, findSourceFile is called.
102671 // - This calls processImportedModules for each module imported in the source file.
102672 // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
102673 // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
102674 // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
102675 var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
102676 var currentNodeModulesDepth = 0;
102677 // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
102678 // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
102679 var modulesWithElidedImports = new ts.Map();
102680 // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
102681 var sourceFilesFoundSearchingNodeModules = new ts.Map();
102682 ts.performance.mark("beforeProgram");
102683 var host = createProgramOptions.host || createCompilerHost(options);
102684 var configParsingHost = parseConfigHostFromCompilerHostLike(host);
102685 var skipDefaultLib = options.noLib;
102686 var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
102687 var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
102688 var programDiagnostics = ts.createDiagnosticCollection();
102689 var currentDirectory = host.getCurrentDirectory();
102690 var supportedExtensions = ts.getSupportedExtensions(options);
102691 var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
102692 // Map storing if there is emit blocking diagnostics for given input
102693 var hasEmitBlockingDiagnostics = new ts.Map();
102694 var _compilerOptionsObjectLiteralSyntax;
102695 var moduleResolutionCache;
102696 var actualResolveModuleNamesWorker;
102697 var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
102698 if (host.resolveModuleNames) {
102699 actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
102700 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
102701 if (!resolved || resolved.extension !== undefined) {
102702 return resolved;
102703 }
102704 var withExtension = ts.clone(resolved);
102705 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
102706 return withExtension;
102707 }); };
102708 }
102709 else {
102710 moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
102711 var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
102712 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
102713 }
102714 var actualResolveTypeReferenceDirectiveNamesWorker;
102715 if (host.resolveTypeReferenceDirectives) {
102716 actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
102717 }
102718 else {
102719 var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
102720 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
102721 }
102722 // Map from a stringified PackageId to the source file with that id.
102723 // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
102724 // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
102725 var packageIdToSourceFile = new ts.Map();
102726 // Maps from a SourceFile's `.path` to the name of the package it was imported with.
102727 var sourceFileToPackageName = new ts.Map();
102728 // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
102729 var redirectTargetsMap = ts.createMultiMap();
102730 /**
102731 * map with
102732 * - SourceFile if present
102733 * - false if sourceFile missing for source of project reference redirect
102734 * - undefined otherwise
102735 */
102736 var filesByName = new ts.Map();
102737 var missingFilePaths;
102738 // stores 'filename -> file association' ignoring case
102739 // used to track cases when two file names differ only in casing
102740 var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? new ts.Map() : undefined;
102741 // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
102742 var resolvedProjectReferences;
102743 var projectReferenceRedirects;
102744 var mapFromFileToProjectReferenceRedirects;
102745 var mapFromToProjectReferenceRedirectSource;
102746 var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
102747 !options.disableSourceOfProjectReferenceRedirect;
102748 var _c = updateHostForUseSourceOfProjectReferenceRedirect({
102749 compilerHost: host,
102750 getSymlinkCache: getSymlinkCache,
102751 useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
102752 toPath: toPath,
102753 getResolvedProjectReferences: getResolvedProjectReferences,
102754 getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
102755 forEachResolvedProjectReference: forEachResolvedProjectReference
102756 }), onProgramCreateComplete = _c.onProgramCreateComplete, fileExists = _c.fileExists, directoryExists = _c.directoryExists;
102757 var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
102758 // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
102759 // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
102760 var structuralIsReused;
102761 structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
102762 if (structuralIsReused !== 2 /* Completely */) {
102763 processingDefaultLibFiles = [];
102764 processingOtherFiles = [];
102765 if (projectReferences) {
102766 if (!resolvedProjectReferences) {
102767 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
102768 }
102769 if (rootNames.length) {
102770 for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
102771 var parsedRef = resolvedProjectReferences_1[_i];
102772 if (!parsedRef)
102773 continue;
102774 var out = ts.outFile(parsedRef.commandLine.options);
102775 if (useSourceOfProjectReferenceRedirect) {
102776 if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
102777 for (var _d = 0, _e = parsedRef.commandLine.fileNames; _d < _e.length; _d++) {
102778 var fileName = _e[_d];
102779 processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
102780 }
102781 }
102782 }
102783 else {
102784 if (out) {
102785 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
102786 }
102787 else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
102788 for (var _f = 0, _g = parsedRef.commandLine.fileNames; _f < _g.length; _f++) {
102789 var fileName = _g[_f];
102790 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
102791 processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
102792 }
102793 }
102794 }
102795 }
102796 }
102797 }
102798 }
102799 ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
102800 // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
102801 var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
102802 if (typeReferences.length) {
102803 // This containingFilename needs to match with the one used in managed-side
102804 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
102805 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
102806 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
102807 for (var i = 0; i < typeReferences.length; i++) {
102808 processTypeReferenceDirective(typeReferences[i], resolutions[i]);
102809 }
102810 }
102811 // Do not process the default library if:
102812 // - The '--noLib' flag is used.
102813 // - A 'no-default-lib' reference comment is encountered in
102814 // processing the root files.
102815 if (rootNames.length && !skipDefaultLib) {
102816 // If '--lib' is not specified, include default library file according to '--target'
102817 // otherwise, using options specified in '--lib' instead of '--target' default library file
102818 var defaultLibraryFileName = getDefaultLibraryFileName();
102819 if (!options.lib && defaultLibraryFileName) {
102820 processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
102821 }
102822 else {
102823 ts.forEach(options.lib, function (libFileName) {
102824 processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
102825 });
102826 }
102827 }
102828 missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
102829 var path = _a[0], file = _a[1];
102830 return file === undefined ? path : undefined;
102831 }));
102832 files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
102833 processingDefaultLibFiles = undefined;
102834 processingOtherFiles = undefined;
102835 }
102836 ts.Debug.assert(!!missingFilePaths);
102837 // Release any files we have acquired in the old program but are
102838 // not part of the new program.
102839 if (oldProgram && host.onReleaseOldSourceFile) {
102840 var oldSourceFiles = oldProgram.getSourceFiles();
102841 for (var _h = 0, oldSourceFiles_1 = oldSourceFiles; _h < oldSourceFiles_1.length; _h++) {
102842 var oldSourceFile = oldSourceFiles_1[_h];
102843 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
102844 if (shouldCreateNewSourceFile || !newFile ||
102845 // old file wasnt redirect but new file is
102846 (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
102847 host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
102848 }
102849 }
102850 oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
102851 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
102852 host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
102853 }
102854 });
102855 }
102856 // unconditionally set oldProgram to undefined to prevent it from being captured in closure
102857 oldProgram = undefined;
102858 var program = {
102859 getRootFileNames: function () { return rootNames; },
102860 getSourceFile: getSourceFile,
102861 getSourceFileByPath: getSourceFileByPath,
102862 getSourceFiles: function () { return files; },
102863 getMissingFilePaths: function () { return missingFilePaths; },
102864 getRefFileMap: function () { return refFileMap; },
102865 getFilesByNameMap: function () { return filesByName; },
102866 getCompilerOptions: function () { return options; },
102867 getSyntacticDiagnostics: getSyntacticDiagnostics,
102868 getOptionsDiagnostics: getOptionsDiagnostics,
102869 getGlobalDiagnostics: getGlobalDiagnostics,
102870 getSemanticDiagnostics: getSemanticDiagnostics,
102871 getCachedSemanticDiagnostics: getCachedSemanticDiagnostics,
102872 getSuggestionDiagnostics: getSuggestionDiagnostics,
102873 getDeclarationDiagnostics: getDeclarationDiagnostics,
102874 getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
102875 getProgramDiagnostics: getProgramDiagnostics,
102876 getTypeChecker: getTypeChecker,
102877 getClassifiableNames: getClassifiableNames,
102878 getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
102879 getCommonSourceDirectory: getCommonSourceDirectory,
102880 emit: emit,
102881 getCurrentDirectory: function () { return currentDirectory; },
102882 getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
102883 getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
102884 getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
102885 getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
102886 getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
102887 getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
102888 getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
102889 getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
102890 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
102891 isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
102892 dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
102893 getSourceFileFromReference: getSourceFileFromReference,
102894 getLibFileFromReference: getLibFileFromReference,
102895 sourceFileToPackageName: sourceFileToPackageName,
102896 redirectTargetsMap: redirectTargetsMap,
102897 isEmittedFile: isEmittedFile,
102898 getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
102899 getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
102900 getProjectReferences: getProjectReferences,
102901 getResolvedProjectReferences: getResolvedProjectReferences,
102902 getProjectReferenceRedirect: getProjectReferenceRedirect,
102903 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
102904 getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
102905 forEachResolvedProjectReference: forEachResolvedProjectReference,
102906 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
102907 emitBuildInfo: emitBuildInfo,
102908 fileExists: fileExists,
102909 directoryExists: directoryExists,
102910 getSymlinkCache: getSymlinkCache,
102911 realpath: (_b = host.realpath) === null || _b === void 0 ? void 0 : _b.bind(host),
102912 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
102913 };
102914 onProgramCreateComplete();
102915 verifyCompilerOptions();
102916 ts.performance.mark("afterProgram");
102917 ts.performance.measure("Program", "beforeProgram", "afterProgram");
102918 return program;
102919 function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
102920 ts.performance.mark("beforeResolveModule");
102921 var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
102922 ts.performance.mark("afterResolveModule");
102923 ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
102924 return result;
102925 }
102926 function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
102927 ts.performance.mark("beforeResolveTypeReference");
102928 var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
102929 ts.performance.mark("afterResolveTypeReference");
102930 ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
102931 return result;
102932 }
102933 function compareDefaultLibFiles(a, b) {
102934 return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
102935 }
102936 function getDefaultLibFilePriority(a) {
102937 if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
102938 var basename = ts.getBaseFileName(a.fileName);
102939 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
102940 return 0;
102941 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
102942 var index = ts.libs.indexOf(name);
102943 if (index !== -1)
102944 return index + 1;
102945 }
102946 return ts.libs.length + 2;
102947 }
102948 function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
102949 return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
102950 }
102951 function toPath(fileName) {
102952 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
102953 }
102954 function getCommonSourceDirectory() {
102955 if (commonSourceDirectory === undefined) {
102956 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
102957 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
102958 // If a rootDir is specified use it as the commonSourceDirectory
102959 commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
102960 }
102961 else if (options.composite && options.configFilePath) {
102962 // Project compilations never infer their root from the input source paths
102963 commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
102964 checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
102965 }
102966 else {
102967 commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
102968 }
102969 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
102970 // Make sure directory path ends with directory separator so this string can directly
102971 // used to replace with "" to get the relative path of the source file and the relative path doesn't
102972 // start with / making it rooted path
102973 commonSourceDirectory += ts.directorySeparator;
102974 }
102975 }
102976 return commonSourceDirectory;
102977 }
102978 function getClassifiableNames() {
102979 var _a;
102980 if (!classifiableNames) {
102981 // Initialize a checker so that all our files are bound.
102982 getTypeChecker();
102983 classifiableNames = new ts.Set();
102984 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
102985 var sourceFile = files_2[_i];
102986 (_a = sourceFile.classifiableNames) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return classifiableNames.add(value); });
102987 }
102988 }
102989 return classifiableNames;
102990 }
102991 function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
102992 if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
102993 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
102994 // the best we can do is fallback to the default logic.
102995 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
102996 }
102997 var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
102998 if (oldSourceFile !== file && file.resolvedModules) {
102999 // `file` was created for the new program.
103000 //
103001 // We only set `file.resolvedModules` via work from the current function,
103002 // so it is defined iff we already called the current function on `file`.
103003 // That call happened no later than the creation of the `file` object,
103004 // which per above occurred during the current program creation.
103005 // Since we assume the filesystem does not change during program creation,
103006 // it is safe to reuse resolutions from the earlier call.
103007 var result_12 = [];
103008 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
103009 var moduleName = moduleNames_1[_i];
103010 var resolvedModule = file.resolvedModules.get(moduleName);
103011 result_12.push(resolvedModule);
103012 }
103013 return result_12;
103014 }
103015 // At this point, we know at least one of the following hold:
103016 // - file has local declarations for ambient modules
103017 // - old program state is available
103018 // With this information, we can infer some module resolutions without performing resolution.
103019 /** An ordered list of module names for which we cannot recover the resolution. */
103020 var unknownModuleNames;
103021 /**
103022 * The indexing of elements in this list matches that of `moduleNames`.
103023 *
103024 * Before combining results, result[i] is in one of the following states:
103025 * * undefined: needs to be recomputed,
103026 * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
103027 * Needs to be reset to undefined before returning,
103028 * * ResolvedModuleFull instance: can be reused.
103029 */
103030 var result;
103031 var reusedNames;
103032 /** A transient placeholder used to mark predicted resolution in the result list. */
103033 var predictedToResolveToAmbientModuleMarker = {};
103034 for (var i = 0; i < moduleNames.length; i++) {
103035 var moduleName = moduleNames[i];
103036 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
103037 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
103038 var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName);
103039 if (oldResolvedModule) {
103040 if (ts.isTraceEnabled(options, host)) {
103041 ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
103042 }
103043 (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
103044 (reusedNames || (reusedNames = [])).push(moduleName);
103045 continue;
103046 }
103047 }
103048 // We know moduleName resolves to an ambient module provided that moduleName:
103049 // - is in the list of ambient modules locally declared in the current source file.
103050 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
103051 // (so the same module declaration will land in the new program)
103052 var resolvesToAmbientModuleInNonModifiedFile = false;
103053 if (ts.contains(file.ambientModuleNames, moduleName)) {
103054 resolvesToAmbientModuleInNonModifiedFile = true;
103055 if (ts.isTraceEnabled(options, host)) {
103056 ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
103057 }
103058 }
103059 else {
103060 resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
103061 }
103062 if (resolvesToAmbientModuleInNonModifiedFile) {
103063 (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
103064 }
103065 else {
103066 // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
103067 (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
103068 }
103069 }
103070 var resolutions = unknownModuleNames && unknownModuleNames.length
103071 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
103072 : ts.emptyArray;
103073 // Combine results of resolutions and predicted results
103074 if (!result) {
103075 // There were no unresolved/ambient resolutions.
103076 ts.Debug.assert(resolutions.length === moduleNames.length);
103077 return resolutions;
103078 }
103079 var j = 0;
103080 for (var i = 0; i < result.length; i++) {
103081 if (result[i]) {
103082 // `result[i]` is either a `ResolvedModuleFull` or a marker.
103083 // If it is the former, we can leave it as is.
103084 if (result[i] === predictedToResolveToAmbientModuleMarker) {
103085 result[i] = undefined; // TODO: GH#18217
103086 }
103087 }
103088 else {
103089 result[i] = resolutions[j];
103090 j++;
103091 }
103092 }
103093 ts.Debug.assert(j === resolutions.length);
103094 return result;
103095 // If we change our policy of rechecking failed lookups on each program create,
103096 // we should adjust the value returned here.
103097 function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
103098 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
103099 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
103100 if (resolutionToFile && resolvedFile) {
103101 // In the old program, we resolved to an ambient module that was in the same
103102 // place as we expected to find an actual module file.
103103 // We actually need to return 'false' here even though this seems like a 'true' case
103104 // because the normal module resolution algorithm will find this anyway.
103105 return false;
103106 }
103107 // at least one of declarations should come from non-modified source file
103108 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
103109 if (!unmodifiedFile) {
103110 return false;
103111 }
103112 if (ts.isTraceEnabled(options, host)) {
103113 ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
103114 }
103115 return true;
103116 }
103117 }
103118 function canReuseProjectReferences() {
103119 return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
103120 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
103121 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
103122 if (oldResolvedRef) {
103123 // Resolved project reference has gone missing or changed
103124 return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
103125 }
103126 else {
103127 // A previously-unresolved reference may be resolved now
103128 return newResolvedRef !== undefined;
103129 }
103130 }, function (oldProjectReferences, parent) {
103131 // If array of references is changed, we cant resue old program
103132 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
103133 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
103134 });
103135 }
103136 function tryReuseStructureFromOldProgram() {
103137 var _a;
103138 if (!oldProgram) {
103139 return 0 /* Not */;
103140 }
103141 // check properties that can affect structure of the program or module resolution strategy
103142 // if any of these properties has changed - structure cannot be reused
103143 var oldOptions = oldProgram.getCompilerOptions();
103144 if (ts.changesAffectModuleResolution(oldOptions, options)) {
103145 return oldProgram.structureIsReused = 0 /* Not */;
103146 }
103147 // there is an old program, check if we can reuse its structure
103148 var oldRootNames = oldProgram.getRootFileNames();
103149 if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
103150 return oldProgram.structureIsReused = 0 /* Not */;
103151 }
103152 if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
103153 return oldProgram.structureIsReused = 0 /* Not */;
103154 }
103155 // Check if any referenced project tsconfig files are different
103156 if (!canReuseProjectReferences()) {
103157 return oldProgram.structureIsReused = 0 /* Not */;
103158 }
103159 if (projectReferences) {
103160 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
103161 }
103162 // check if program source files has changed in the way that can affect structure of the program
103163 var newSourceFiles = [];
103164 var modifiedSourceFiles = [];
103165 oldProgram.structureIsReused = 2 /* Completely */;
103166 // If the missing file paths are now present, it can change the progam structure,
103167 // and hence cant reuse the structure.
103168 // This is same as how we dont reuse the structure if one of the file from old program is now missing
103169 if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
103170 return oldProgram.structureIsReused = 0 /* Not */;
103171 }
103172 var oldSourceFiles = oldProgram.getSourceFiles();
103173 var SeenPackageName;
103174 (function (SeenPackageName) {
103175 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
103176 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
103177 })(SeenPackageName || (SeenPackageName = {}));
103178 var seenPackageNames = new ts.Map();
103179 for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
103180 var oldSourceFile = oldSourceFiles_2[_i];
103181 var newSourceFile = host.getSourceFileByPath
103182 ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
103183 : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
103184 if (!newSourceFile) {
103185 return oldProgram.structureIsReused = 0 /* Not */;
103186 }
103187 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
103188 var fileChanged = void 0;
103189 if (oldSourceFile.redirectInfo) {
103190 // We got `newSourceFile` by path, so it is actually for the unredirected file.
103191 // This lets us know if the unredirected file has changed. If it has we should break the redirect.
103192 if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
103193 // Underlying file has changed. Might not redirect anymore. Must rebuild program.
103194 return oldProgram.structureIsReused = 0 /* Not */;
103195 }
103196 fileChanged = false;
103197 newSourceFile = oldSourceFile; // Use the redirect.
103198 }
103199 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
103200 // If a redirected-to source file changes, the redirect may be broken.
103201 if (newSourceFile !== oldSourceFile) {
103202 return oldProgram.structureIsReused = 0 /* Not */;
103203 }
103204 fileChanged = false;
103205 }
103206 else {
103207 fileChanged = newSourceFile !== oldSourceFile;
103208 }
103209 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
103210 newSourceFile.path = oldSourceFile.path;
103211 newSourceFile.originalFileName = oldSourceFile.originalFileName;
103212 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
103213 newSourceFile.fileName = oldSourceFile.fileName;
103214 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
103215 if (packageName !== undefined) {
103216 // If there are 2 different source files for the same package name and at least one of them changes,
103217 // they might become redirects. So we must rebuild the program.
103218 var prevKind = seenPackageNames.get(packageName);
103219 var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
103220 if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
103221 return oldProgram.structureIsReused = 0 /* Not */;
103222 }
103223 seenPackageNames.set(packageName, newKind);
103224 }
103225 if (fileChanged) {
103226 // The `newSourceFile` object was created for the new program.
103227 if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
103228 // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
103229 return oldProgram.structureIsReused = 0 /* Not */;
103230 }
103231 if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
103232 // value of no-default-lib has changed
103233 // this will affect if default library is injected into the list of files
103234 oldProgram.structureIsReused = 1 /* SafeModules */;
103235 }
103236 // check tripleslash references
103237 if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
103238 // tripleslash references has changed
103239 oldProgram.structureIsReused = 1 /* SafeModules */;
103240 }
103241 // check imports and module augmentations
103242 collectExternalModuleReferences(newSourceFile);
103243 if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
103244 // imports has changed
103245 oldProgram.structureIsReused = 1 /* SafeModules */;
103246 }
103247 if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
103248 // moduleAugmentations has changed
103249 oldProgram.structureIsReused = 1 /* SafeModules */;
103250 }
103251 if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
103252 // dynamicImport has changed
103253 oldProgram.structureIsReused = 1 /* SafeModules */;
103254 }
103255 if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
103256 // 'types' references has changed
103257 oldProgram.structureIsReused = 1 /* SafeModules */;
103258 }
103259 // tentatively approve the file
103260 modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
103261 }
103262 else if (hasInvalidatedResolution(oldSourceFile.path)) {
103263 // 'module/types' references could have changed
103264 oldProgram.structureIsReused = 1 /* SafeModules */;
103265 // add file to the modified list so that we will resolve it later
103266 modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
103267 }
103268 // if file has passed all checks it should be safe to reuse it
103269 newSourceFiles.push(newSourceFile);
103270 }
103271 if (oldProgram.structureIsReused !== 2 /* Completely */) {
103272 return oldProgram.structureIsReused;
103273 }
103274 var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
103275 for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) {
103276 var oldFile = oldSourceFiles_3[_b];
103277 if (!ts.contains(modifiedFiles, oldFile)) {
103278 for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) {
103279 var moduleName = _d[_c];
103280 ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
103281 }
103282 }
103283 }
103284 // try to verify results of module resolution
103285 for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) {
103286 var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile;
103287 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
103288 var moduleNames = getModuleNames(newSourceFile);
103289 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
103290 // ensure that module resolution results are still correct
103291 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
103292 if (resolutionsChanged) {
103293 oldProgram.structureIsReused = 1 /* SafeModules */;
103294 newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
103295 }
103296 else {
103297 newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
103298 }
103299 if (resolveTypeReferenceDirectiveNamesWorker) {
103300 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
103301 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
103302 var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
103303 // ensure that types resolutions are still correct
103304 var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
103305 if (resolutionsChanged_1) {
103306 oldProgram.structureIsReused = 1 /* SafeModules */;
103307 newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
103308 }
103309 else {
103310 newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
103311 }
103312 }
103313 }
103314 if (oldProgram.structureIsReused !== 2 /* Completely */) {
103315 return oldProgram.structureIsReused;
103316 }
103317 if ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host)) {
103318 return oldProgram.structureIsReused = 1 /* SafeModules */;
103319 }
103320 missingFilePaths = oldProgram.getMissingFilePaths();
103321 refFileMap = oldProgram.getRefFileMap();
103322 // update fileName -> file mapping
103323 ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
103324 for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
103325 var newSourceFile = newSourceFiles_1[_g];
103326 filesByName.set(newSourceFile.path, newSourceFile);
103327 }
103328 var oldFilesByNameMap = oldProgram.getFilesByNameMap();
103329 oldFilesByNameMap.forEach(function (oldFile, path) {
103330 if (!oldFile) {
103331 filesByName.set(path, oldFile);
103332 return;
103333 }
103334 if (oldFile.path === path) {
103335 // Set the file as found during node modules search if it was found that way in old progra,
103336 if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
103337 sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
103338 }
103339 return;
103340 }
103341 filesByName.set(path, filesByName.get(oldFile.path));
103342 });
103343 files = newSourceFiles;
103344 fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
103345 for (var _h = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _h < modifiedSourceFiles_2.length; _h++) {
103346 var modifiedFile = modifiedSourceFiles_2[_h];
103347 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
103348 }
103349 resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
103350 sourceFileToPackageName = oldProgram.sourceFileToPackageName;
103351 redirectTargetsMap = oldProgram.redirectTargetsMap;
103352 return oldProgram.structureIsReused = 2 /* Completely */;
103353 }
103354 function getEmitHost(writeFileCallback) {
103355 return {
103356 getPrependNodes: getPrependNodes,
103357 getCanonicalFileName: getCanonicalFileName,
103358 getCommonSourceDirectory: program.getCommonSourceDirectory,
103359 getCompilerOptions: program.getCompilerOptions,
103360 getCurrentDirectory: function () { return currentDirectory; },
103361 getNewLine: function () { return host.getNewLine(); },
103362 getSourceFile: program.getSourceFile,
103363 getSourceFileByPath: program.getSourceFileByPath,
103364 getSourceFiles: program.getSourceFiles,
103365 getLibFileFromReference: program.getLibFileFromReference,
103366 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
103367 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
103368 getProjectReferenceRedirect: getProjectReferenceRedirect,
103369 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
103370 getSymlinkCache: getSymlinkCache,
103371 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
103372 isEmitBlocked: isEmitBlocked,
103373 readFile: function (f) { return host.readFile(f); },
103374 fileExists: function (f) {
103375 // Use local caches
103376 var path = toPath(f);
103377 if (getSourceFileByPath(path))
103378 return true;
103379 if (ts.contains(missingFilePaths, path))
103380 return false;
103381 // Before falling back to the host
103382 return host.fileExists(f);
103383 },
103384 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
103385 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
103386 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
103387 redirectTargetsMap: redirectTargetsMap,
103388 };
103389 }
103390 function emitBuildInfo(writeFileCallback) {
103391 ts.Debug.assert(!ts.outFile(options));
103392 ts.performance.mark("beforeEmit");
103393 var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
103394 /*targetSourceFile*/ undefined,
103395 /*transformers*/ ts.noTransformers,
103396 /*emitOnlyDtsFiles*/ false,
103397 /*onlyBuildInfo*/ true);
103398 ts.performance.mark("afterEmit");
103399 ts.performance.measure("Emit", "beforeEmit", "afterEmit");
103400 return emitResult;
103401 }
103402 function getResolvedProjectReferences() {
103403 return resolvedProjectReferences;
103404 }
103405 function getProjectReferences() {
103406 return projectReferences;
103407 }
103408 function getPrependNodes() {
103409 return createPrependNodes(projectReferences, function (_ref, index) { var _a; return (_a = resolvedProjectReferences[index]) === null || _a === void 0 ? void 0 : _a.commandLine; }, function (fileName) {
103410 var path = toPath(fileName);
103411 var sourceFile = getSourceFileByPath(path);
103412 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
103413 });
103414 }
103415 function isSourceFileFromExternalLibrary(file) {
103416 return !!sourceFilesFoundSearchingNodeModules.get(file.path);
103417 }
103418 function isSourceFileDefaultLibrary(file) {
103419 if (file.hasNoDefaultLib) {
103420 return true;
103421 }
103422 if (!options.noLib) {
103423 return false;
103424 }
103425 // If '--lib' is not specified, include default library file according to '--target'
103426 // otherwise, using options specified in '--lib' instead of '--target' default library file
103427 var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
103428 if (!options.lib) {
103429 return equalityComparer(file.fileName, getDefaultLibraryFileName());
103430 }
103431 else {
103432 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
103433 }
103434 }
103435 function getDiagnosticsProducingTypeChecker() {
103436 return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
103437 }
103438 function dropDiagnosticsProducingTypeChecker() {
103439 diagnosticsProducingTypeChecker = undefined;
103440 }
103441 function getTypeChecker() {
103442 return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
103443 }
103444 function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
103445 return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
103446 }
103447 function isEmitBlocked(emitFileName) {
103448 return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
103449 }
103450 function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
103451 if (!forceDtsEmit) {
103452 var result = handleNoEmitOptions(program, sourceFile, writeFileCallback, cancellationToken);
103453 if (result)
103454 return result;
103455 }
103456 // Create the emit resolver outside of the "emitTime" tracking code below. That way
103457 // any cost associated with it (like type checking) are appropriate associated with
103458 // the type-checking counter.
103459 //
103460 // If the -out option is specified, we should not pass the source file to getEmitResolver.
103461 // This is because in the -out scenario all files need to be emitted, and therefore all
103462 // files need to be type checked. And the way to specify that all files need to be type
103463 // checked is to not pass the file to getEmitResolver.
103464 var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(ts.outFile(options) ? undefined : sourceFile, cancellationToken);
103465 ts.performance.mark("beforeEmit");
103466 var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles,
103467 /*onlyBuildInfo*/ false, forceDtsEmit);
103468 ts.performance.mark("afterEmit");
103469 ts.performance.measure("Emit", "beforeEmit", "afterEmit");
103470 return emitResult;
103471 }
103472 function getSourceFile(fileName) {
103473 return getSourceFileByPath(toPath(fileName));
103474 }
103475 function getSourceFileByPath(path) {
103476 return filesByName.get(path) || undefined;
103477 }
103478 function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
103479 if (sourceFile) {
103480 return getDiagnostics(sourceFile, cancellationToken);
103481 }
103482 return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
103483 if (cancellationToken) {
103484 cancellationToken.throwIfCancellationRequested();
103485 }
103486 return getDiagnostics(sourceFile, cancellationToken);
103487 }));
103488 }
103489 function getSyntacticDiagnostics(sourceFile, cancellationToken) {
103490 return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
103491 }
103492 function getSemanticDiagnostics(sourceFile, cancellationToken) {
103493 return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
103494 }
103495 function getCachedSemanticDiagnostics(sourceFile) {
103496 var _a;
103497 return sourceFile
103498 ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
103499 }
103500 function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
103501 return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
103502 }
103503 function getProgramDiagnostics(sourceFile) {
103504 if (ts.skipTypeChecking(sourceFile, options, program)) {
103505 return ts.emptyArray;
103506 }
103507 var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
103508 var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
103509 return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
103510 }
103511 function getMergedProgramDiagnostics(sourceFile) {
103512 var _a;
103513 var allDiagnostics = [];
103514 for (var _i = 1; _i < arguments.length; _i++) {
103515 allDiagnostics[_i - 1] = arguments[_i];
103516 }
103517 var flatDiagnostics = ts.flatten(allDiagnostics);
103518 if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
103519 return flatDiagnostics;
103520 }
103521 return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
103522 }
103523 function getDeclarationDiagnostics(sourceFile, cancellationToken) {
103524 var options = program.getCompilerOptions();
103525 // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
103526 if (!sourceFile || ts.outFile(options)) {
103527 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
103528 }
103529 else {
103530 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
103531 }
103532 }
103533 function getSyntacticDiagnosticsForFile(sourceFile) {
103534 // For JavaScript files, we report semantic errors for using TypeScript-only
103535 // constructs from within a JavaScript file as syntactic errors.
103536 if (ts.isSourceFileJS(sourceFile)) {
103537 if (!sourceFile.additionalSyntacticDiagnostics) {
103538 sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
103539 }
103540 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
103541 }
103542 return sourceFile.parseDiagnostics;
103543 }
103544 function runWithCancellationToken(func) {
103545 try {
103546 return func();
103547 }
103548 catch (e) {
103549 if (e instanceof ts.OperationCanceledException) {
103550 // We were canceled while performing the operation. Because our type checker
103551 // might be a bad state, we need to throw it away.
103552 //
103553 // Note: we are overly aggressive here. We do not actually *have* to throw away
103554 // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
103555 // the lifetimes of these two TypeCheckers the same. Also, we generally only
103556 // cancel when the user has made a change anyways. And, in that case, we (the
103557 // program instance) will get thrown away anyways. So trying to keep one of
103558 // these type checkers alive doesn't serve much purpose.
103559 noDiagnosticsTypeChecker = undefined;
103560 diagnosticsProducingTypeChecker = undefined;
103561 }
103562 throw e;
103563 }
103564 }
103565 function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
103566 return ts.concatenate(filterSemanticDiagnotics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile));
103567 }
103568 function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
103569 return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
103570 }
103571 function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
103572 return runWithCancellationToken(function () {
103573 if (ts.skipTypeChecking(sourceFile, options, program)) {
103574 return ts.emptyArray;
103575 }
103576 var typeChecker = getDiagnosticsProducingTypeChecker();
103577 ts.Debug.assert(!!sourceFile.bindDiagnostics);
103578 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
103579 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
103580 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
103581 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
103582 sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
103583 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
103584 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
103585 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
103586 });
103587 }
103588 function getMergedBindAndCheckDiagnostics(sourceFile) {
103589 var _a;
103590 var allDiagnostics = [];
103591 for (var _i = 1; _i < arguments.length; _i++) {
103592 allDiagnostics[_i - 1] = arguments[_i];
103593 }
103594 var flatDiagnostics = ts.flatten(allDiagnostics);
103595 if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
103596 return flatDiagnostics;
103597 }
103598 var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
103599 for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
103600 var errorExpectation = _d[_c];
103601 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
103602 }
103603 return diagnostics;
103604 }
103605 /**
103606 * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
103607 * Comments that match to any of those diagnostics are marked as used.
103608 */
103609 function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
103610 // Diagnostics are only reported if there is no comment directive preceding them
103611 // This will modify the directives map by marking "used" ones with a corresponding diagnostic
103612 var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
103613 var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
103614 return { diagnostics: diagnostics, directives: directives };
103615 }
103616 function getSuggestionDiagnostics(sourceFile, cancellationToken) {
103617 return runWithCancellationToken(function () {
103618 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
103619 });
103620 }
103621 /**
103622 * @returns The line index marked as preceding the diagnostic, or -1 if none was.
103623 */
103624 function markPrecedingCommentDirectiveLine(diagnostic, directives) {
103625 var file = diagnostic.file, start = diagnostic.start;
103626 if (!file) {
103627 return -1;
103628 }
103629 // Start out with the line just before the text
103630 var lineStarts = ts.getLineStarts(file);
103631 var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
103632 while (line >= 0) {
103633 // As soon as that line is known to have a comment directive, use that
103634 if (directives.markUsed(line)) {
103635 return line;
103636 }
103637 // Stop searching if the line is not empty and not a comment
103638 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
103639 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
103640 return -1;
103641 }
103642 line--;
103643 }
103644 return -1;
103645 }
103646 function getJSSyntacticDiagnosticsForFile(sourceFile) {
103647 return runWithCancellationToken(function () {
103648 var diagnostics = [];
103649 walk(sourceFile, sourceFile);
103650 ts.forEachChildRecursively(sourceFile, walk, walkArray);
103651 return diagnostics;
103652 function walk(node, parent) {
103653 // Return directly from the case if the given node doesnt want to visit each child
103654 // Otherwise break to visit each child
103655 switch (parent.kind) {
103656 case 159 /* Parameter */:
103657 case 162 /* PropertyDeclaration */:
103658 case 164 /* MethodDeclaration */:
103659 if (parent.questionToken === node) {
103660 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
103661 return "skip";
103662 }
103663 // falls through
103664 case 163 /* MethodSignature */:
103665 case 165 /* Constructor */:
103666 case 166 /* GetAccessor */:
103667 case 167 /* SetAccessor */:
103668 case 205 /* FunctionExpression */:
103669 case 248 /* FunctionDeclaration */:
103670 case 206 /* ArrowFunction */:
103671 case 246 /* VariableDeclaration */:
103672 // type annotation
103673 if (parent.type === node) {
103674 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
103675 return "skip";
103676 }
103677 }
103678 switch (node.kind) {
103679 case 259 /* ImportClause */:
103680 if (node.isTypeOnly) {
103681 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
103682 return "skip";
103683 }
103684 break;
103685 case 264 /* ExportDeclaration */:
103686 if (node.isTypeOnly) {
103687 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
103688 return "skip";
103689 }
103690 break;
103691 case 257 /* ImportEqualsDeclaration */:
103692 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
103693 return "skip";
103694 case 263 /* ExportAssignment */:
103695 if (node.isExportEquals) {
103696 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
103697 return "skip";
103698 }
103699 break;
103700 case 283 /* HeritageClause */:
103701 var heritageClause = node;
103702 if (heritageClause.token === 116 /* ImplementsKeyword */) {
103703 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
103704 return "skip";
103705 }
103706 break;
103707 case 250 /* InterfaceDeclaration */:
103708 var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */);
103709 ts.Debug.assertIsDefined(interfaceKeyword);
103710 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
103711 return "skip";
103712 case 253 /* ModuleDeclaration */:
103713 var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(139 /* NamespaceKeyword */) : ts.tokenToString(138 /* ModuleKeyword */);
103714 ts.Debug.assertIsDefined(moduleKeyword);
103715 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
103716 return "skip";
103717 case 251 /* TypeAliasDeclaration */:
103718 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
103719 return "skip";
103720 case 252 /* EnumDeclaration */:
103721 var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */));
103722 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
103723 return "skip";
103724 case 222 /* NonNullExpression */:
103725 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
103726 return "skip";
103727 case 221 /* AsExpression */:
103728 diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
103729 return "skip";
103730 case 203 /* TypeAssertionExpression */:
103731 ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
103732 }
103733 }
103734 function walkArray(nodes, parent) {
103735 if (parent.decorators === nodes && !options.experimentalDecorators) {
103736 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));
103737 }
103738 switch (parent.kind) {
103739 case 249 /* ClassDeclaration */:
103740 case 218 /* ClassExpression */:
103741 case 164 /* MethodDeclaration */:
103742 case 165 /* Constructor */:
103743 case 166 /* GetAccessor */:
103744 case 167 /* SetAccessor */:
103745 case 205 /* FunctionExpression */:
103746 case 248 /* FunctionDeclaration */:
103747 case 206 /* ArrowFunction */:
103748 // Check type parameters
103749 if (nodes === parent.typeParameters) {
103750 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
103751 return "skip";
103752 }
103753 // falls through
103754 case 229 /* VariableStatement */:
103755 // Check modifiers
103756 if (nodes === parent.modifiers) {
103757 checkModifiers(parent.modifiers, parent.kind === 229 /* VariableStatement */);
103758 return "skip";
103759 }
103760 break;
103761 case 162 /* PropertyDeclaration */:
103762 // Check modifiers of property declaration
103763 if (nodes === parent.modifiers) {
103764 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
103765 var modifier = _a[_i];
103766 if (modifier.kind !== 123 /* StaticKeyword */) {
103767 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
103768 }
103769 }
103770 return "skip";
103771 }
103772 break;
103773 case 159 /* Parameter */:
103774 // Check modifiers of parameter declaration
103775 if (nodes === parent.modifiers) {
103776 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
103777 return "skip";
103778 }
103779 break;
103780 case 200 /* CallExpression */:
103781 case 201 /* NewExpression */:
103782 case 220 /* ExpressionWithTypeArguments */:
103783 case 271 /* JsxSelfClosingElement */:
103784 case 272 /* JsxOpeningElement */:
103785 case 202 /* TaggedTemplateExpression */:
103786 // Check type arguments
103787 if (nodes === parent.typeArguments) {
103788 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
103789 return "skip";
103790 }
103791 break;
103792 }
103793 }
103794 function checkModifiers(modifiers, isConstValid) {
103795 for (var _i = 0, modifiers_2 = modifiers; _i < modifiers_2.length; _i++) {
103796 var modifier = modifiers_2[_i];
103797 switch (modifier.kind) {
103798 case 84 /* ConstKeyword */:
103799 if (isConstValid) {
103800 continue;
103801 }
103802 // to report error,
103803 // falls through
103804 case 122 /* PublicKeyword */:
103805 case 120 /* PrivateKeyword */:
103806 case 121 /* ProtectedKeyword */:
103807 case 141 /* ReadonlyKeyword */:
103808 case 133 /* DeclareKeyword */:
103809 case 125 /* AbstractKeyword */:
103810 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
103811 break;
103812 // These are all legal modifiers.
103813 case 123 /* StaticKeyword */:
103814 case 92 /* ExportKeyword */:
103815 case 87 /* DefaultKeyword */:
103816 }
103817 }
103818 }
103819 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
103820 var start = nodes.pos;
103821 return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
103822 }
103823 // Since these are syntactic diagnostics, parent might not have been set
103824 // this means the sourceFile cannot be infered from the node
103825 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
103826 return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
103827 }
103828 });
103829 }
103830 function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
103831 return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
103832 }
103833 function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
103834 return runWithCancellationToken(function () {
103835 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
103836 // Don't actually write any files since we're just getting diagnostics.
103837 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
103838 });
103839 }
103840 function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
103841 var _a;
103842 var cachedResult = sourceFile
103843 ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cache.allDiagnostics;
103844 if (cachedResult) {
103845 return cachedResult;
103846 }
103847 var result = getDiagnostics(sourceFile, cancellationToken);
103848 if (sourceFile) {
103849 (cache.perFile || (cache.perFile = new ts.Map())).set(sourceFile.path, result);
103850 }
103851 else {
103852 cache.allDiagnostics = result;
103853 }
103854 return result;
103855 }
103856 function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
103857 return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
103858 }
103859 function getOptionsDiagnostics() {
103860 return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
103861 }
103862 function getOptionsDiagnosticsOfConfigFile() {
103863 if (!options.configFile) {
103864 return ts.emptyArray;
103865 }
103866 var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
103867 forEachResolvedProjectReference(function (resolvedRef) {
103868 if (resolvedRef) {
103869 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
103870 }
103871 });
103872 return diagnostics;
103873 }
103874 function getGlobalDiagnostics() {
103875 return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
103876 }
103877 function getConfigFileParsingDiagnostics() {
103878 return configFileParsingDiagnostics || ts.emptyArray;
103879 }
103880 function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
103881 processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
103882 }
103883 function fileReferenceIsEqualTo(a, b) {
103884 return a.fileName === b.fileName;
103885 }
103886 function moduleNameIsEqualTo(a, b) {
103887 return a.kind === 78 /* Identifier */
103888 ? b.kind === 78 /* Identifier */ && a.escapedText === b.escapedText
103889 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
103890 }
103891 function collectExternalModuleReferences(file) {
103892 if (file.imports) {
103893 return;
103894 }
103895 var isJavaScriptFile = ts.isSourceFileJS(file);
103896 var isExternalModuleFile = ts.isExternalModule(file);
103897 // file.imports may not be undefined if there exists dynamic import
103898 var imports;
103899 var moduleAugmentations;
103900 var ambientModules;
103901 // If we are importing helpers, we need to add a synthetic reference to resolve the
103902 // helpers library.
103903 if (options.importHelpers
103904 && (options.isolatedModules || isExternalModuleFile)
103905 && !file.isDeclarationFile) {
103906 // synthesize 'import "tslib"' declaration
103907 var externalHelpersModuleReference = ts.factory.createStringLiteral(ts.externalHelpersModuleNameText);
103908 var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
103909 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
103910 ts.setParent(externalHelpersModuleReference, importDecl);
103911 ts.setParent(importDecl, file);
103912 imports = [externalHelpersModuleReference];
103913 }
103914 for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
103915 var node = _a[_i];
103916 collectModuleReferences(node, /*inAmbientModule*/ false);
103917 }
103918 if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
103919 collectDynamicImportOrRequireCalls(file);
103920 }
103921 file.imports = imports || ts.emptyArray;
103922 file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
103923 file.ambientModuleNames = ambientModules || ts.emptyArray;
103924 return;
103925 function collectModuleReferences(node, inAmbientModule) {
103926 if (ts.isAnyImportOrReExport(node)) {
103927 var moduleNameExpr = ts.getExternalModuleName(node);
103928 // TypeScript 1.0 spec (April 2014): 12.1.6
103929 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
103930 // only through top - level external module names. Relative external module names are not permitted.
103931 if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
103932 imports = ts.append(imports, moduleNameExpr);
103933 }
103934 }
103935 else if (ts.isModuleDeclaration(node)) {
103936 if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
103937 var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
103938 // Ambient module declarations can be interpreted as augmentations for some existing external modules.
103939 // This will happen in two cases:
103940 // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
103941 // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
103942 // immediately nested in top level ambient module declaration .
103943 if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
103944 (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
103945 }
103946 else if (!inAmbientModule) {
103947 if (file.isDeclarationFile) {
103948 // for global .d.ts files record name of ambient module
103949 (ambientModules || (ambientModules = [])).push(nameText);
103950 }
103951 // An AmbientExternalModuleDeclaration declares an external module.
103952 // This type of declaration is permitted only in the global module.
103953 // The StringLiteral must specify a top - level external module name.
103954 // Relative external module names are not permitted
103955 // NOTE: body of ambient module is always a module block, if it exists
103956 var body = node.body;
103957 if (body) {
103958 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
103959 var statement = _a[_i];
103960 collectModuleReferences(statement, /*inAmbientModule*/ true);
103961 }
103962 }
103963 }
103964 }
103965 }
103966 }
103967 function collectDynamicImportOrRequireCalls(file) {
103968 var r = /import|require/g;
103969 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
103970 var node = getNodeAtPosition(file, r.lastIndex);
103971 if (isJavaScriptFile && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
103972 imports = ts.append(imports, node.arguments[0]);
103973 }
103974 // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
103975 else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
103976 imports = ts.append(imports, node.arguments[0]);
103977 }
103978 else if (ts.isLiteralImportTypeNode(node)) {
103979 imports = ts.append(imports, node.argument.literal);
103980 }
103981 }
103982 }
103983 /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
103984 function getNodeAtPosition(sourceFile, position) {
103985 var current = sourceFile;
103986 var getContainingChild = function (child) {
103987 if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
103988 return child;
103989 }
103990 };
103991 while (true) {
103992 var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
103993 if (!child) {
103994 return current;
103995 }
103996 current = child;
103997 }
103998 }
103999 }
104000 function getLibFileFromReference(ref) {
104001 var libName = ts.toFileNameLowerCase(ref.fileName);
104002 var libFileName = ts.libMap.get(libName);
104003 if (libFileName) {
104004 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
104005 }
104006 }
104007 /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
104008 function getSourceFileFromReference(referencingFile, ref) {
104009 return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
104010 }
104011 function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
104012 if (ts.hasExtension(fileName)) {
104013 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
104014 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
104015 if (fail) {
104016 if (ts.hasJSFileExtension(canonicalFileName_1)) {
104017 fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
104018 }
104019 else {
104020 fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
104021 }
104022 }
104023 return undefined;
104024 }
104025 var sourceFile = getSourceFile(fileName);
104026 if (fail) {
104027 if (!sourceFile) {
104028 var redirect = getProjectReferenceRedirect(fileName);
104029 if (redirect) {
104030 fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
104031 }
104032 else {
104033 fail(ts.Diagnostics.File_0_not_found, fileName);
104034 }
104035 }
104036 else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
104037 fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
104038 }
104039 }
104040 return sourceFile;
104041 }
104042 else {
104043 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
104044 if (sourceFileNoExtension)
104045 return sourceFileNoExtension;
104046 if (fail && options.allowNonTsExtensions) {
104047 fail(ts.Diagnostics.File_0_not_found, fileName);
104048 return undefined;
104049 }
104050 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
104051 if (fail && !sourceFileWithAddedExtension)
104052 fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
104053 return sourceFileWithAddedExtension;
104054 }
104055 }
104056 /** This has side effects through `findSourceFile`. */
104057 function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
104058 getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
104059 function (diagnostic) {
104060 var args = [];
104061 for (var _i = 1; _i < arguments.length; _i++) {
104062 args[_i - 1] = arguments[_i];
104063 }
104064 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
104065 }, refFile && refFile.file);
104066 }
104067 function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
104068 var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
104069 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
104070 fileProcessingDiagnostics.add(refToReportErrorOn ?
104071 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
104072 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
104073 }
104074 function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
104075 var redirect = Object.create(redirectTarget);
104076 redirect.fileName = fileName;
104077 redirect.path = path;
104078 redirect.resolvedPath = resolvedPath;
104079 redirect.originalFileName = originalFileName;
104080 redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
104081 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
104082 Object.defineProperties(redirect, {
104083 id: {
104084 get: function () { return this.redirectInfo.redirectTarget.id; },
104085 set: function (value) { this.redirectInfo.redirectTarget.id = value; },
104086 },
104087 symbol: {
104088 get: function () { return this.redirectInfo.redirectTarget.symbol; },
104089 set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
104090 },
104091 });
104092 return redirect;
104093 }
104094 // Get source file from normalized fileName
104095 function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
104096 if (useSourceOfProjectReferenceRedirect) {
104097 var source = getSourceOfProjectReferenceRedirect(fileName);
104098 // If preserveSymlinks is true, module resolution wont jump the symlink
104099 // but the resolved real path may be the .d.ts from project reference
104100 // Note:: Currently we try the real path only if the
104101 // file is from node_modules to avoid having to run real path on all file paths
104102 if (!source &&
104103 host.realpath &&
104104 options.preserveSymlinks &&
104105 ts.isDeclarationFileName(fileName) &&
104106 ts.stringContains(fileName, ts.nodeModulesPathPart)) {
104107 var realPath = host.realpath(fileName);
104108 if (realPath !== fileName)
104109 source = getSourceOfProjectReferenceRedirect(realPath);
104110 }
104111 if (source) {
104112 var file_1 = ts.isString(source) ?
104113 findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
104114 undefined;
104115 if (file_1)
104116 addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
104117 return file_1;
104118 }
104119 }
104120 var originalFileName = fileName;
104121 if (filesByName.has(path)) {
104122 var file_2 = filesByName.get(path);
104123 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
104124 // try to check if we've already seen this file but with a different casing in path
104125 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
104126 if (file_2 && options.forceConsistentCasingInFileNames) {
104127 var checkedName = file_2.fileName;
104128 var isRedirect = toPath(checkedName) !== toPath(fileName);
104129 if (isRedirect) {
104130 fileName = getProjectReferenceRedirect(fileName) || fileName;
104131 }
104132 // Check if it differs only in drive letters its ok to ignore that error:
104133 var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
104134 var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
104135 if (checkedAbsolutePath !== inputAbsolutePath) {
104136 reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
104137 }
104138 }
104139 // If the file was previously found via a node_modules search, but is now being processed as a root file,
104140 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
104141 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
104142 sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
104143 if (!options.noResolve) {
104144 processReferencedFiles(file_2, isDefaultLib);
104145 processTypeReferenceDirectives(file_2);
104146 }
104147 if (!options.noLib) {
104148 processLibReferenceDirectives(file_2);
104149 }
104150 modulesWithElidedImports.set(file_2.path, false);
104151 processImportedModules(file_2);
104152 }
104153 // See if we need to reprocess the imports due to prior skipped imports
104154 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
104155 if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
104156 modulesWithElidedImports.set(file_2.path, false);
104157 processImportedModules(file_2);
104158 }
104159 }
104160 return file_2 || undefined;
104161 }
104162 var redirectedPath;
104163 if (refFile && !useSourceOfProjectReferenceRedirect) {
104164 var redirectProject = getProjectReferenceRedirectProject(fileName);
104165 if (redirectProject) {
104166 if (ts.outFile(redirectProject.commandLine.options)) {
104167 // Shouldnt create many to 1 mapping file in --out scenario
104168 return undefined;
104169 }
104170 var redirect = getProjectReferenceOutputName(redirectProject, fileName);
104171 fileName = redirect;
104172 // Once we start redirecting to a file, we can potentially come back to it
104173 // via a back-reference from another file in the .d.ts folder. If that happens we'll
104174 // end up trying to add it to the program *again* because we were tracking it via its
104175 // original (un-redirected) name. So we have to map both the original path and the redirected path
104176 // to the source file we're about to find/create
104177 redirectedPath = toPath(redirect);
104178 }
104179 }
104180 // We haven't looked for this file, do so now and cache result
104181 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);
104182 if (packageId) {
104183 var packageIdKey = ts.packageIdToString(packageId);
104184 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
104185 if (fileFromPackageId) {
104186 // Some other SourceFile already exists with this package name and version.
104187 // Instead of creating a duplicate, just redirect to the existing one.
104188 var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
104189 redirectTargetsMap.add(fileFromPackageId.path, fileName);
104190 addFileToFilesByName(dupFile, path, redirectedPath);
104191 sourceFileToPackageName.set(path, packageId.name);
104192 processingOtherFiles.push(dupFile);
104193 return dupFile;
104194 }
104195 else if (file) {
104196 // This is the first source file to have this packageId.
104197 packageIdToSourceFile.set(packageIdKey, file);
104198 sourceFileToPackageName.set(path, packageId.name);
104199 }
104200 }
104201 addFileToFilesByName(file, path, redirectedPath);
104202 if (file) {
104203 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
104204 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
104205 file.path = path;
104206 file.resolvedPath = toPath(fileName);
104207 file.originalFileName = originalFileName;
104208 addFileToRefFileMap(fileName, file, refFile);
104209 if (host.useCaseSensitiveFileNames()) {
104210 var pathLowerCase = ts.toFileNameLowerCase(path);
104211 // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
104212 var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
104213 if (existingFile) {
104214 reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
104215 }
104216 else {
104217 filesByNameIgnoreCase.set(pathLowerCase, file);
104218 }
104219 }
104220 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
104221 if (!options.noResolve) {
104222 processReferencedFiles(file, isDefaultLib);
104223 processTypeReferenceDirectives(file);
104224 }
104225 if (!options.noLib) {
104226 processLibReferenceDirectives(file);
104227 }
104228 // always process imported modules to record module name resolutions
104229 processImportedModules(file);
104230 if (isDefaultLib) {
104231 processingDefaultLibFiles.push(file);
104232 }
104233 else {
104234 processingOtherFiles.push(file);
104235 }
104236 }
104237 return file;
104238 }
104239 function addFileToRefFileMap(referencedFileName, file, refFile) {
104240 if (refFile && file) {
104241 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
104242 referencedFileName: referencedFileName,
104243 kind: refFile.kind,
104244 index: refFile.index,
104245 file: refFile.file.path
104246 });
104247 }
104248 }
104249 function addFileToFilesByName(file, path, redirectedPath) {
104250 if (redirectedPath) {
104251 filesByName.set(redirectedPath, file);
104252 filesByName.set(path, file || false);
104253 }
104254 else {
104255 filesByName.set(path, file);
104256 }
104257 }
104258 function getProjectReferenceRedirect(fileName) {
104259 var referencedProject = getProjectReferenceRedirectProject(fileName);
104260 return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
104261 }
104262 function getProjectReferenceRedirectProject(fileName) {
104263 // Ignore dts or any json files
104264 if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
104265 return undefined;
104266 }
104267 // If this file is produced by a referenced project, we need to rewrite it to
104268 // look in the output folder of the referenced project rather than the input
104269 return getResolvedProjectReferenceToRedirect(fileName);
104270 }
104271 function getProjectReferenceOutputName(referencedProject, fileName) {
104272 var out = ts.outFile(referencedProject.commandLine.options);
104273 return out ?
104274 ts.changeExtension(out, ".d.ts" /* Dts */) :
104275 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
104276 }
104277 /**
104278 * Get the referenced project if the file is input file from that reference project
104279 */
104280 function getResolvedProjectReferenceToRedirect(fileName) {
104281 if (mapFromFileToProjectReferenceRedirects === undefined) {
104282 mapFromFileToProjectReferenceRedirects = new ts.Map();
104283 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
104284 // not input file from the referenced project, ignore
104285 if (referencedProject &&
104286 toPath(options.configFilePath) !== referenceProjectPath) {
104287 referencedProject.commandLine.fileNames.forEach(function (f) {
104288 return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
104289 });
104290 }
104291 });
104292 }
104293 var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
104294 return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
104295 }
104296 function forEachResolvedProjectReference(cb) {
104297 return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
104298 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
104299 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
104300 return cb(resolvedRef, resolvedRefPath);
104301 });
104302 }
104303 function getSourceOfProjectReferenceRedirect(file) {
104304 if (!ts.isDeclarationFileName(file))
104305 return undefined;
104306 if (mapFromToProjectReferenceRedirectSource === undefined) {
104307 mapFromToProjectReferenceRedirectSource = new ts.Map();
104308 forEachResolvedProjectReference(function (resolvedRef) {
104309 if (resolvedRef) {
104310 var out = ts.outFile(resolvedRef.commandLine.options);
104311 if (out) {
104312 // Dont know which source file it means so return true?
104313 var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
104314 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
104315 }
104316 else {
104317 ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
104318 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
104319 var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
104320 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
104321 }
104322 });
104323 }
104324 }
104325 });
104326 }
104327 return mapFromToProjectReferenceRedirectSource.get(toPath(file));
104328 }
104329 function isSourceOfProjectReferenceRedirect(fileName) {
104330 return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
104331 }
104332 function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
104333 var seenResolvedRefs;
104334 return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
104335 function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
104336 // Visit project references first
104337 if (cbRef) {
104338 var result = cbRef(projectReferences, parent);
104339 if (result) {
104340 return result;
104341 }
104342 }
104343 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
104344 if (ts.contains(seenResolvedRefs, resolvedRef)) {
104345 // ignore recursives
104346 return undefined;
104347 }
104348 var result = cbResolvedRef(resolvedRef, index, parent);
104349 if (result) {
104350 return result;
104351 }
104352 if (!resolvedRef)
104353 return undefined;
104354 (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
104355 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
104356 });
104357 }
104358 }
104359 function getResolvedProjectReferenceByPath(projectReferencePath) {
104360 if (!projectReferenceRedirects) {
104361 return undefined;
104362 }
104363 return projectReferenceRedirects.get(projectReferencePath) || undefined;
104364 }
104365 function processReferencedFiles(file, isDefaultLib) {
104366 ts.forEach(file.referencedFiles, function (ref, index) {
104367 var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
104368 processSourceFile(referencedFileName, isDefaultLib,
104369 /*ignoreNoDefaultLib*/ false,
104370 /*packageId*/ undefined, {
104371 kind: ts.RefFileKind.ReferenceFile,
104372 index: index,
104373 file: file,
104374 pos: ref.pos,
104375 end: ref.end
104376 });
104377 });
104378 }
104379 function processTypeReferenceDirectives(file) {
104380 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
104381 var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
104382 if (!typeDirectives) {
104383 return;
104384 }
104385 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
104386 for (var i = 0; i < typeDirectives.length; i++) {
104387 var ref = file.typeReferenceDirectives[i];
104388 var resolvedTypeReferenceDirective = resolutions[i];
104389 // store resolved type directive on the file
104390 var fileName = ts.toFileNameLowerCase(ref.fileName);
104391 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
104392 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
104393 kind: ts.RefFileKind.TypeReferenceDirective,
104394 index: i,
104395 file: file,
104396 pos: ref.pos,
104397 end: ref.end
104398 });
104399 }
104400 }
104401 function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
104402 // If we already found this library as a primary reference - nothing to do
104403 var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
104404 if (previousResolution && previousResolution.primary) {
104405 return;
104406 }
104407 var saveResolution = true;
104408 if (resolvedTypeReferenceDirective) {
104409 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
104410 currentNodeModulesDepth++;
104411 if (resolvedTypeReferenceDirective.primary) {
104412 // resolved from the primary path
104413 processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
104414 }
104415 else {
104416 // If we already resolved to this file, it must have been a secondary reference. Check file contents
104417 // for sameness and possibly issue an error
104418 if (previousResolution) {
104419 // Don't bother reading the file again if it's the same file.
104420 if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
104421 var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
104422 var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
104423 if (otherFileText !== existingFile_1.text) {
104424 // Try looking up ref for original file
104425 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
104426 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
104427 fileProcessingDiagnostics.add(refToReportErrorOn ?
104428 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) :
104429 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));
104430 }
104431 }
104432 // don't overwrite previous resolution result
104433 saveResolution = false;
104434 }
104435 else {
104436 // First resolution of this library
104437 processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
104438 }
104439 }
104440 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
104441 currentNodeModulesDepth--;
104442 }
104443 else {
104444 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
104445 }
104446 if (saveResolution) {
104447 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
104448 }
104449 }
104450 function processLibReferenceDirectives(file) {
104451 ts.forEach(file.libReferenceDirectives, function (libReference) {
104452 var libName = ts.toFileNameLowerCase(libReference.fileName);
104453 var libFileName = ts.libMap.get(libName);
104454 if (libFileName) {
104455 // we ignore any 'no-default-lib' reference set on this file.
104456 processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
104457 }
104458 else {
104459 var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
104460 var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
104461 var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
104462 fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
104463 }
104464 });
104465 }
104466 function createRefFileDiagnostic(refFile, message) {
104467 var args = [];
104468 for (var _i = 2; _i < arguments.length; _i++) {
104469 args[_i - 2] = arguments[_i];
104470 }
104471 if (!refFile) {
104472 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
104473 }
104474 else {
104475 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
104476 }
104477 }
104478 function getCanonicalFileName(fileName) {
104479 return host.getCanonicalFileName(fileName);
104480 }
104481 function processImportedModules(file) {
104482 collectExternalModuleReferences(file);
104483 if (file.imports.length || file.moduleAugmentations.length) {
104484 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
104485 var moduleNames = getModuleNames(file);
104486 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
104487 ts.Debug.assert(resolutions.length === moduleNames.length);
104488 for (var i = 0; i < moduleNames.length; i++) {
104489 var resolution = resolutions[i];
104490 ts.setResolvedModule(file, moduleNames[i], resolution);
104491 if (!resolution) {
104492 continue;
104493 }
104494 var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
104495 var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
104496 var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
104497 var resolvedFileName = resolution.resolvedFileName;
104498 if (isFromNodeModulesSearch) {
104499 currentNodeModulesDepth++;
104500 }
104501 // add file to program only if:
104502 // - resolution was successful
104503 // - noResolve is falsy
104504 // - module name comes from the list of imports
104505 // - it's not a top level JavaScript module that exceeded the search max
104506 var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
104507 // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
104508 // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
104509 var shouldAddFile = resolvedFileName
104510 && !getResolutionDiagnostic(options, resolution)
104511 && !options.noResolve
104512 && i < file.imports.length
104513 && !elideImport
104514 && !(isJsFile && !options.allowJs)
104515 && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
104516 if (elideImport) {
104517 modulesWithElidedImports.set(file.path, true);
104518 }
104519 else if (shouldAddFile) {
104520 var path = toPath(resolvedFileName);
104521 var pos = ts.skipTrivia(file.text, file.imports[i].pos);
104522 findSourceFile(resolvedFileName, path,
104523 /*isDefaultLib*/ false,
104524 /*ignoreNoDefaultLib*/ false, {
104525 kind: ts.RefFileKind.Import,
104526 index: i,
104527 file: file,
104528 pos: pos,
104529 end: file.imports[i].end
104530 }, resolution.packageId);
104531 }
104532 if (isFromNodeModulesSearch) {
104533 currentNodeModulesDepth--;
104534 }
104535 }
104536 }
104537 else {
104538 // no imports - drop cached module resolutions
104539 file.resolvedModules = undefined;
104540 }
104541 }
104542 function computeCommonSourceDirectory(sourceFiles) {
104543 var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
104544 return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
104545 }
104546 function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
104547 var allFilesBelongToPath = true;
104548 var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
104549 var rootPaths;
104550 for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
104551 var sourceFile = sourceFiles_2[_i];
104552 if (!sourceFile.isDeclarationFile) {
104553 var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
104554 if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
104555 if (!rootPaths)
104556 rootPaths = new ts.Set(rootNames.map(toPath));
104557 addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
104558 allFilesBelongToPath = false;
104559 }
104560 }
104561 }
104562 return allFilesBelongToPath;
104563 }
104564 function parseProjectReferenceConfigFile(ref) {
104565 if (!projectReferenceRedirects) {
104566 projectReferenceRedirects = new ts.Map();
104567 }
104568 // The actual filename (i.e. add "/tsconfig.json" if necessary)
104569 var refPath = resolveProjectReferencePath(ref);
104570 var sourceFilePath = toPath(refPath);
104571 var fromCache = projectReferenceRedirects.get(sourceFilePath);
104572 if (fromCache !== undefined) {
104573 return fromCache || undefined;
104574 }
104575 var commandLine;
104576 var sourceFile;
104577 if (host.getParsedCommandLine) {
104578 commandLine = host.getParsedCommandLine(refPath);
104579 if (!commandLine) {
104580 addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
104581 projectReferenceRedirects.set(sourceFilePath, false);
104582 return undefined;
104583 }
104584 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
104585 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
104586 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
104587 }
104588 else {
104589 // An absolute path pointing to the containing directory of the config file
104590 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
104591 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
104592 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
104593 if (sourceFile === undefined) {
104594 projectReferenceRedirects.set(sourceFilePath, false);
104595 return undefined;
104596 }
104597 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
104598 }
104599 sourceFile.fileName = refPath;
104600 sourceFile.path = sourceFilePath;
104601 sourceFile.resolvedPath = sourceFilePath;
104602 sourceFile.originalFileName = refPath;
104603 var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
104604 projectReferenceRedirects.set(sourceFilePath, resolvedRef);
104605 if (commandLine.projectReferences) {
104606 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
104607 }
104608 return resolvedRef;
104609 }
104610 function verifyCompilerOptions() {
104611 if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
104612 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
104613 }
104614 if (options.isolatedModules) {
104615 if (options.out) {
104616 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
104617 }
104618 if (options.outFile) {
104619 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
104620 }
104621 }
104622 if (options.inlineSourceMap) {
104623 if (options.sourceMap) {
104624 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
104625 }
104626 if (options.mapRoot) {
104627 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
104628 }
104629 }
104630 if (options.paths && options.baseUrl === undefined) {
104631 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
104632 }
104633 if (options.composite) {
104634 if (options.declaration === false) {
104635 createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
104636 }
104637 if (options.incremental === false) {
104638 createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
104639 }
104640 }
104641 var outputFile = ts.outFile(options);
104642 if (options.tsBuildInfoFile) {
104643 if (!ts.isIncrementalCompilation(options)) {
104644 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
104645 }
104646 }
104647 else if (options.incremental && !outputFile && !options.configFilePath) {
104648 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
104649 }
104650 verifyProjectReferences();
104651 // List of collected files is complete; validate exhautiveness if this is a project with a file list
104652 if (options.composite) {
104653 var rootPaths = new ts.Set(rootNames.map(toPath));
104654 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
104655 var file = files_3[_i];
104656 // Ignore file that is not emitted
104657 if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
104658 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 || "");
104659 }
104660 }
104661 }
104662 if (options.paths) {
104663 for (var key in options.paths) {
104664 if (!ts.hasProperty(options.paths, key)) {
104665 continue;
104666 }
104667 if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
104668 createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
104669 }
104670 if (ts.isArray(options.paths[key])) {
104671 var len = options.paths[key].length;
104672 if (len === 0) {
104673 createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
104674 }
104675 for (var i = 0; i < len; i++) {
104676 var subst = options.paths[key][i];
104677 var typeOfSubst = typeof subst;
104678 if (typeOfSubst === "string") {
104679 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
104680 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
104681 }
104682 }
104683 else {
104684 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
104685 }
104686 }
104687 }
104688 else {
104689 createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
104690 }
104691 }
104692 }
104693 if (!options.sourceMap && !options.inlineSourceMap) {
104694 if (options.inlineSources) {
104695 createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
104696 }
104697 if (options.sourceRoot) {
104698 createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
104699 }
104700 }
104701 if (options.out && options.outFile) {
104702 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
104703 }
104704 if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
104705 // Error to specify --mapRoot without --sourcemap
104706 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
104707 }
104708 if (options.declarationDir) {
104709 if (!ts.getEmitDeclarations(options)) {
104710 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
104711 }
104712 if (outputFile) {
104713 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
104714 }
104715 }
104716 if (options.declarationMap && !ts.getEmitDeclarations(options)) {
104717 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
104718 }
104719 if (options.lib && options.noLib) {
104720 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
104721 }
104722 if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
104723 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
104724 }
104725 var languageVersion = options.target || 0 /* ES3 */;
104726 var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
104727 if (options.isolatedModules) {
104728 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
104729 createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
104730 }
104731 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
104732 if (firstNonExternalModuleSourceFile) {
104733 var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
104734 programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
104735 }
104736 }
104737 else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
104738 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
104739 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
104740 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
104741 }
104742 // Cannot specify module gen that isn't amd or system with --out
104743 if (outputFile && !options.emitDeclarationOnly) {
104744 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
104745 createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
104746 }
104747 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
104748 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
104749 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"));
104750 }
104751 }
104752 if (options.resolveJsonModule) {
104753 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
104754 createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
104755 }
104756 // Any emit other than common js, amd, es2015 or esnext is error
104757 else if (!ts.hasJsonModuleEmitEnabled(options)) {
104758 createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
104759 }
104760 }
104761 // there has to be common source directory if user specified --outdir || --sourceRoot
104762 // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
104763 if (options.outDir || // there is --outDir specified
104764 options.sourceRoot || // there is --sourceRoot specified
104765 options.mapRoot) { // there is --mapRoot specified
104766 // Precalculate and cache the common source directory
104767 var dir = getCommonSourceDirectory();
104768 // 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
104769 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
104770 createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
104771 }
104772 }
104773 if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
104774 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
104775 }
104776 if (options.checkJs && !options.allowJs) {
104777 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
104778 }
104779 if (options.emitDeclarationOnly) {
104780 if (!ts.getEmitDeclarations(options)) {
104781 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
104782 }
104783 if (options.noEmit) {
104784 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
104785 }
104786 }
104787 if (options.emitDecoratorMetadata &&
104788 !options.experimentalDecorators) {
104789 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
104790 }
104791 if (options.jsxFactory) {
104792 if (options.reactNamespace) {
104793 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
104794 }
104795 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
104796 createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
104797 }
104798 }
104799 else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
104800 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
104801 }
104802 if (options.jsxFragmentFactory) {
104803 if (!options.jsxFactory) {
104804 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
104805 }
104806 if (!ts.parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
104807 createOptionValueDiagnostic("jsxFragmentFactory", ts.Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
104808 }
104809 }
104810 // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
104811 if (!options.noEmit && !options.suppressOutputPathCheck) {
104812 var emitHost = getEmitHost();
104813 var emitFilesSeen_1 = new ts.Set();
104814 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
104815 if (!options.emitDeclarationOnly) {
104816 verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
104817 }
104818 verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
104819 });
104820 }
104821 // Verify that all the emit files are unique and don't overwrite input files
104822 function verifyEmitFilePath(emitFileName, emitFilesSeen) {
104823 if (emitFileName) {
104824 var emitFilePath = toPath(emitFileName);
104825 // Report error if the output overwrites input file
104826 if (filesByName.has(emitFilePath)) {
104827 var chain = void 0;
104828 if (!options.configFilePath) {
104829 // The program is from either an inferred project or an external project
104830 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);
104831 }
104832 chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
104833 blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
104834 }
104835 var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
104836 // Report error if multiple files write into same file
104837 if (emitFilesSeen.has(emitFileKey)) {
104838 // Already seen the same emit file - report error
104839 blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
104840 }
104841 else {
104842 emitFilesSeen.add(emitFileKey);
104843 }
104844 }
104845 }
104846 }
104847 function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
104848 var _a, _b;
104849 var args = [];
104850 for (var _i = 2; _i < arguments.length; _i++) {
104851 args[_i - 2] = arguments[_i];
104852 }
104853 var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
104854 var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
104855 var pos, end;
104856 switch (kind) {
104857 case ts.RefFileKind.Import:
104858 pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
104859 end = refFile.imports[index].end;
104860 break;
104861 case ts.RefFileKind.ReferenceFile:
104862 (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
104863 break;
104864 case ts.RefFileKind.TypeReferenceDirective:
104865 (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
104866 break;
104867 default:
104868 return ts.Debug.assertNever(kind);
104869 }
104870 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
104871 }
104872 function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
104873 var args = [];
104874 for (var _i = 3; _i < arguments.length; _i++) {
104875 args[_i - 3] = arguments[_i];
104876 }
104877 var refPaths = refFileMap === null || refFileMap === void 0 ? void 0 : refFileMap.get(file.path);
104878 var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
104879 ts.elementAt(refPaths, 0);
104880 programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
104881 }
104882 function verifyProjectReferences() {
104883 var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
104884 forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
104885 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
104886 var parentFile = parent && parent.sourceFile;
104887 if (!resolvedRef) {
104888 createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
104889 return;
104890 }
104891 var options = resolvedRef.commandLine.options;
104892 if (!options.composite || options.noEmit) {
104893 // ok to not have composite if the current program is container only
104894 var inputs = parent ? parent.commandLine.fileNames : rootNames;
104895 if (inputs.length) {
104896 if (!options.composite)
104897 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
104898 if (options.noEmit)
104899 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
104900 }
104901 }
104902 if (ref.prepend) {
104903 var out = ts.outFile(options);
104904 if (out) {
104905 if (!host.fileExists(out)) {
104906 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
104907 }
104908 }
104909 else {
104910 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
104911 }
104912 }
104913 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
104914 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
104915 hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
104916 }
104917 });
104918 }
104919 function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
104920 var needCompilerDiagnostic = true;
104921 var pathsSyntax = getOptionPathsSyntax();
104922 for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
104923 var pathProp = pathsSyntax_1[_i];
104924 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
104925 for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
104926 var keyProps = _b[_a];
104927 var initializer = keyProps.initializer;
104928 if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
104929 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
104930 needCompilerDiagnostic = false;
104931 }
104932 }
104933 }
104934 }
104935 if (needCompilerDiagnostic) {
104936 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
104937 }
104938 }
104939 function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
104940 var needCompilerDiagnostic = true;
104941 var pathsSyntax = getOptionPathsSyntax();
104942 for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
104943 var pathProp = pathsSyntax_2[_i];
104944 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
104945 createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
104946 needCompilerDiagnostic = false;
104947 }
104948 }
104949 if (needCompilerDiagnostic) {
104950 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
104951 }
104952 }
104953 function getOptionsSyntaxByName(name) {
104954 var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
104955 if (compilerOptionsObjectLiteralSyntax) {
104956 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
104957 }
104958 return undefined;
104959 }
104960 function getOptionPathsSyntax() {
104961 return getOptionsSyntaxByName("paths") || ts.emptyArray;
104962 }
104963 function createDiagnosticForOptionName(message, option1, option2, option3) {
104964 createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
104965 }
104966 function createOptionValueDiagnostic(option1, message, arg0) {
104967 createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
104968 }
104969 function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
104970 var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
104971 if (referencesSyntax && referencesSyntax.elements.length > index) {
104972 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
104973 }
104974 else {
104975 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
104976 }
104977 }
104978 function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
104979 var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
104980 var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
104981 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
104982 if (needCompilerDiagnostic) {
104983 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
104984 }
104985 }
104986 function getCompilerOptionsObjectLiteralSyntax() {
104987 if (_compilerOptionsObjectLiteralSyntax === undefined) {
104988 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
104989 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
104990 if (jsonObjectLiteral) {
104991 for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
104992 var prop = _a[_i];
104993 if (ts.isObjectLiteralExpression(prop.initializer)) {
104994 _compilerOptionsObjectLiteralSyntax = prop.initializer;
104995 break;
104996 }
104997 }
104998 }
104999 }
105000 return _compilerOptionsObjectLiteralSyntax;
105001 }
105002 function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
105003 var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
105004 for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
105005 var prop = props_3[_i];
105006 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
105007 }
105008 return !!props.length;
105009 }
105010 function blockEmittingOfFile(emitFileName, diag) {
105011 hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
105012 programDiagnostics.add(diag);
105013 }
105014 function isEmittedFile(file) {
105015 if (options.noEmit) {
105016 return false;
105017 }
105018 // If this is source file, its not emitted file
105019 var filePath = toPath(file);
105020 if (getSourceFileByPath(filePath)) {
105021 return false;
105022 }
105023 // If options have --outFile or --out just check that
105024 var out = ts.outFile(options);
105025 if (out) {
105026 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
105027 }
105028 // If declarationDir is specified, return if its a file in that directory
105029 if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
105030 return true;
105031 }
105032 // If --outDir, check if file is in that directory
105033 if (options.outDir) {
105034 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
105035 }
105036 if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
105037 // Otherwise just check if sourceFile with the name exists
105038 var filePathWithoutExtension = ts.removeFileExtension(filePath);
105039 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
105040 !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
105041 }
105042 return false;
105043 }
105044 function isSameFile(file1, file2) {
105045 return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
105046 }
105047 function getSymlinkCache() {
105048 if (host.getSymlinkCache) {
105049 return host.getSymlinkCache();
105050 }
105051 return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
105052 }
105053 }
105054 ts.createProgram = createProgram;
105055 function updateHostForUseSourceOfProjectReferenceRedirect(host) {
105056 var setOfDeclarationDirectories;
105057 var originalFileExists = host.compilerHost.fileExists;
105058 var originalDirectoryExists = host.compilerHost.directoryExists;
105059 var originalGetDirectories = host.compilerHost.getDirectories;
105060 var originalRealpath = host.compilerHost.realpath;
105061 if (!host.useSourceOfProjectReferenceRedirect)
105062 return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
105063 host.compilerHost.fileExists = fileExists;
105064 var directoryExists;
105065 if (originalDirectoryExists) {
105066 // This implementation of directoryExists checks if the directory being requested is
105067 // directory of .d.ts file for the referenced Project.
105068 // If it is it returns true irrespective of whether that directory exists on host
105069 directoryExists = host.compilerHost.directoryExists = function (path) {
105070 if (originalDirectoryExists.call(host.compilerHost, path)) {
105071 handleDirectoryCouldBeSymlink(path);
105072 return true;
105073 }
105074 if (!host.getResolvedProjectReferences())
105075 return false;
105076 if (!setOfDeclarationDirectories) {
105077 setOfDeclarationDirectories = new ts.Set();
105078 host.forEachResolvedProjectReference(function (ref) {
105079 if (!ref)
105080 return;
105081 var out = ts.outFile(ref.commandLine.options);
105082 if (out) {
105083 setOfDeclarationDirectories.add(ts.getDirectoryPath(host.toPath(out)));
105084 }
105085 else {
105086 // Set declaration's in different locations only, if they are next to source the directory present doesnt change
105087 var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
105088 if (declarationDir) {
105089 setOfDeclarationDirectories.add(host.toPath(declarationDir));
105090 }
105091 }
105092 });
105093 }
105094 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
105095 };
105096 }
105097 if (originalGetDirectories) {
105098 // Call getDirectories only if directory actually present on the host
105099 // This is needed to ensure that we arent getting directories that we fake about presence for
105100 host.compilerHost.getDirectories = function (path) {
105101 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
105102 originalGetDirectories.call(host.compilerHost, path) :
105103 [];
105104 };
105105 }
105106 // This is something we keep for life time of the host
105107 if (originalRealpath) {
105108 host.compilerHost.realpath = function (s) {
105109 var _a;
105110 return ((_a = host.getSymlinkCache().getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.get(host.toPath(s))) ||
105111 originalRealpath.call(host.compilerHost, s);
105112 };
105113 }
105114 return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists };
105115 function onProgramCreateComplete() {
105116 host.compilerHost.fileExists = originalFileExists;
105117 host.compilerHost.directoryExists = originalDirectoryExists;
105118 host.compilerHost.getDirectories = originalGetDirectories;
105119 // DO not revert realpath as it could be used later
105120 }
105121 // This implementation of fileExists checks if the file being requested is
105122 // .d.ts file for the referenced Project.
105123 // If it is it returns true irrespective of whether that file exists on host
105124 function fileExists(file) {
105125 if (originalFileExists.call(host.compilerHost, file))
105126 return true;
105127 if (!host.getResolvedProjectReferences())
105128 return false;
105129 if (!ts.isDeclarationFileName(file))
105130 return false;
105131 // Project references go to source file instead of .d.ts file
105132 return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
105133 }
105134 function fileExistsIfProjectReferenceDts(file) {
105135 var source = host.getSourceOfProjectReferenceRedirect(file);
105136 return source !== undefined ?
105137 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
105138 undefined;
105139 }
105140 function directoryExistsIfProjectReferenceDeclDir(dir) {
105141 var dirPath = host.toPath(dir);
105142 var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
105143 return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
105144 // Any parent directory of declaration dir
105145 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
105146 // Any directory inside declaration dir
105147 ts.startsWith(dirPath, declDirPath + "/"); });
105148 }
105149 function handleDirectoryCouldBeSymlink(directory) {
105150 var _a;
105151 if (!host.getResolvedProjectReferences())
105152 return;
105153 // Because we already watch node_modules, handle symlinks in there
105154 if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
105155 return;
105156 var symlinkCache = host.getSymlinkCache();
105157 var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
105158 if ((_a = symlinkCache.getSymlinkedDirectories()) === null || _a === void 0 ? void 0 : _a.has(directoryPath))
105159 return;
105160 var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
105161 var realPath;
105162 if (real === directory ||
105163 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
105164 // not symlinked
105165 symlinkCache.setSymlinkedDirectory(directoryPath, false);
105166 return;
105167 }
105168 symlinkCache.setSymlinkedDirectory(directoryPath, {
105169 real: ts.ensureTrailingDirectorySeparator(real),
105170 realPath: realPath
105171 });
105172 }
105173 function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
105174 var _a;
105175 var fileOrDirectoryExistsUsingSource = isFile ?
105176 function (file) { return fileExistsIfProjectReferenceDts(file); } :
105177 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
105178 // Check current directory or file
105179 var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
105180 if (result !== undefined)
105181 return result;
105182 var symlinkCache = host.getSymlinkCache();
105183 var symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
105184 if (!symlinkedDirectories)
105185 return false;
105186 var fileOrDirectoryPath = host.toPath(fileOrDirectory);
105187 if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
105188 return false;
105189 if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.has(fileOrDirectoryPath)))
105190 return true;
105191 // If it contains node_modules check if its one of the symlinked path we know of
105192 return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
105193 var directoryPath = _a[0], symlinkedDirectory = _a[1];
105194 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
105195 return undefined;
105196 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
105197 if (isFile && result) {
105198 // Store the real path for the file'
105199 var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
105200 symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
105201 }
105202 return result;
105203 }) || false;
105204 }
105205 }
105206 /*@internal*/
105207 ts.emitSkippedWithNoDiagnostics = { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
105208 /*@internal*/
105209 function handleNoEmitOptions(program, sourceFile, writeFile, cancellationToken) {
105210 var options = program.getCompilerOptions();
105211 if (options.noEmit) {
105212 // Cache the semantic diagnostics
105213 program.getSemanticDiagnostics(sourceFile, cancellationToken);
105214 return sourceFile || ts.outFile(options) ?
105215 ts.emitSkippedWithNoDiagnostics :
105216 program.emitBuildInfo(writeFile, cancellationToken);
105217 }
105218 // If the noEmitOnError flag is set, then check if we have any errors so far. If so,
105219 // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
105220 // get any preEmit diagnostics, not just the ones
105221 if (!options.noEmitOnError)
105222 return undefined;
105223 var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
105224 if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
105225 diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
105226 }
105227 if (!diagnostics.length)
105228 return undefined;
105229 var emittedFiles;
105230 if (!sourceFile && !ts.outFile(options)) {
105231 var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
105232 if (emitResult.diagnostics)
105233 diagnostics = __spreadArrays(diagnostics, emitResult.diagnostics);
105234 emittedFiles = emitResult.emittedFiles;
105235 }
105236 return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
105237 }
105238 ts.handleNoEmitOptions = handleNoEmitOptions;
105239 /*@internal*/
105240 function filterSemanticDiagnotics(diagnostic, option) {
105241 return ts.filter(diagnostic, function (d) { return !d.skippedOn || !option[d.skippedOn]; });
105242 }
105243 ts.filterSemanticDiagnotics = filterSemanticDiagnotics;
105244 /* @internal */
105245 function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
105246 if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105247 return {
105248 fileExists: function (f) { return directoryStructureHost.fileExists(f); },
105249 readDirectory: function (root, extensions, excludes, includes, depth) {
105250 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
105251 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
105252 },
105253 readFile: function (f) { return directoryStructureHost.readFile(f); },
105254 useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
105255 getCurrentDirectory: function () { return host.getCurrentDirectory(); },
105256 onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
105257 trace: host.trace ? function (s) { return host.trace(s); } : undefined
105258 };
105259 }
105260 ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
105261 /* @internal */
105262 function createPrependNodes(projectReferences, getCommandLine, readFile) {
105263 if (!projectReferences)
105264 return ts.emptyArray;
105265 var nodes;
105266 for (var i = 0; i < projectReferences.length; i++) {
105267 var ref = projectReferences[i];
105268 var resolvedRefOpts = getCommandLine(ref, i);
105269 if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
105270 var out = ts.outFile(resolvedRefOpts.options);
105271 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
105272 if (!out)
105273 continue;
105274 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
105275 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
105276 (nodes || (nodes = [])).push(node);
105277 }
105278 }
105279 return nodes || ts.emptyArray;
105280 }
105281 ts.createPrependNodes = createPrependNodes;
105282 function resolveProjectReferencePath(hostOrRef, ref) {
105283 var passedInRef = ref ? ref : hostOrRef;
105284 return ts.resolveConfigFileProjectName(passedInRef.path);
105285 }
105286 ts.resolveProjectReferencePath = resolveProjectReferencePath;
105287 /* @internal */
105288 /**
105289 * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
105290 * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
105291 * This returns a diagnostic even if the module will be an untyped module.
105292 */
105293 function getResolutionDiagnostic(options, _a) {
105294 var extension = _a.extension;
105295 switch (extension) {
105296 case ".ts" /* Ts */:
105297 case ".d.ts" /* Dts */:
105298 // These are always allowed.
105299 return undefined;
105300 case ".tsx" /* Tsx */:
105301 return needJsx();
105302 case ".jsx" /* Jsx */:
105303 return needJsx() || needAllowJs();
105304 case ".js" /* Js */:
105305 return needAllowJs();
105306 case ".json" /* Json */:
105307 return needResolveJsonModule();
105308 }
105309 function needJsx() {
105310 return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
105311 }
105312 function needAllowJs() {
105313 return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
105314 }
105315 function needResolveJsonModule() {
105316 return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
105317 }
105318 }
105319 ts.getResolutionDiagnostic = getResolutionDiagnostic;
105320 function getModuleNames(_a) {
105321 var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
105322 var res = imports.map(function (i) { return i.text; });
105323 for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
105324 var aug = moduleAugmentations_1[_i];
105325 if (aug.kind === 10 /* StringLiteral */) {
105326 res.push(aug.text);
105327 }
105328 // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
105329 }
105330 return res;
105331 }
105332})(ts || (ts = {}));
105333/*@internal*/
105334var ts;
105335(function (ts) {
105336 function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
105337 var outputFiles = [];
105338 var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
105339 return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
105340 function writeFile(fileName, text, writeByteOrderMark) {
105341 outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
105342 }
105343 }
105344 ts.getFileEmitOutput = getFileEmitOutput;
105345 var BuilderState;
105346 (function (BuilderState) {
105347 /**
105348 * Get the referencedFile from the imported module symbol
105349 */
105350 function getReferencedFileFromImportedModuleSymbol(symbol) {
105351 if (symbol.declarations && symbol.declarations[0]) {
105352 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
105353 return declarationSourceFile && declarationSourceFile.resolvedPath;
105354 }
105355 }
105356 /**
105357 * Get the referencedFile from the import name node from file
105358 */
105359 function getReferencedFileFromImportLiteral(checker, importName) {
105360 var symbol = checker.getSymbolAtLocation(importName);
105361 return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
105362 }
105363 /**
105364 * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
105365 */
105366 function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
105367 return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
105368 }
105369 /**
105370 * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
105371 */
105372 function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
105373 var referencedFiles;
105374 // We need to use a set here since the code can contain the same import twice,
105375 // but that will only be one dependency.
105376 // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
105377 if (sourceFile.imports && sourceFile.imports.length > 0) {
105378 var checker = program.getTypeChecker();
105379 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
105380 var importName = _a[_i];
105381 var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
105382 if (declarationSourceFilePath) {
105383 addReferencedFile(declarationSourceFilePath);
105384 }
105385 }
105386 }
105387 var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
105388 // Handle triple slash references
105389 if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
105390 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
105391 var referencedFile = _c[_b];
105392 var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
105393 addReferencedFile(referencedPath);
105394 }
105395 }
105396 // Handle type reference directives
105397 if (sourceFile.resolvedTypeReferenceDirectiveNames) {
105398 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
105399 if (!resolvedTypeReferenceDirective) {
105400 return;
105401 }
105402 var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
105403 var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
105404 addReferencedFile(typeFilePath);
105405 });
105406 }
105407 // Add module augmentation as references
105408 if (sourceFile.moduleAugmentations.length) {
105409 var checker = program.getTypeChecker();
105410 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
105411 var moduleName = _e[_d];
105412 if (!ts.isStringLiteral(moduleName)) {
105413 continue;
105414 }
105415 var symbol = checker.getSymbolAtLocation(moduleName);
105416 if (!symbol) {
105417 continue;
105418 }
105419 // Add any file other than our own as reference
105420 addReferenceFromAmbientModule(symbol);
105421 }
105422 }
105423 // From ambient modules
105424 for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
105425 var ambientModule = _g[_f];
105426 if (ambientModule.declarations.length > 1) {
105427 addReferenceFromAmbientModule(ambientModule);
105428 }
105429 }
105430 return referencedFiles;
105431 function addReferenceFromAmbientModule(symbol) {
105432 // Add any file other than our own as reference
105433 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
105434 var declaration = _a[_i];
105435 var declarationSourceFile = ts.getSourceFileOfNode(declaration);
105436 if (declarationSourceFile &&
105437 declarationSourceFile !== sourceFile) {
105438 addReferencedFile(declarationSourceFile.resolvedPath);
105439 }
105440 }
105441 }
105442 function addReferencedFile(referencedPath) {
105443 (referencedFiles || (referencedFiles = new ts.Set())).add(referencedPath);
105444 }
105445 }
105446 /**
105447 * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
105448 */
105449 function canReuseOldState(newReferencedMap, oldState) {
105450 return oldState && !oldState.referencedMap === !newReferencedMap;
105451 }
105452 BuilderState.canReuseOldState = canReuseOldState;
105453 /**
105454 * Creates the state of file references and signature for the new program from oldState if it is safe
105455 */
105456 function create(newProgram, getCanonicalFileName, oldState) {
105457 var fileInfos = new ts.Map();
105458 var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined;
105459 var exportedModulesMap = referencedMap ? new ts.Map() : undefined;
105460 var hasCalledUpdateShapeSignature = new ts.Set();
105461 var useOldState = canReuseOldState(referencedMap, oldState);
105462 // Ensure source files have parent pointers set
105463 newProgram.getTypeChecker();
105464 // Create the reference map, and set the file infos
105465 for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
105466 var sourceFile = _a[_i];
105467 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
105468 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
105469 if (referencedMap) {
105470 var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
105471 if (newReferences) {
105472 referencedMap.set(sourceFile.resolvedPath, newReferences);
105473 }
105474 // Copy old visible to outside files map
105475 if (useOldState) {
105476 var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
105477 if (exportedModules) {
105478 exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
105479 }
105480 }
105481 }
105482 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
105483 }
105484 return {
105485 fileInfos: fileInfos,
105486 referencedMap: referencedMap,
105487 exportedModulesMap: exportedModulesMap,
105488 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
105489 };
105490 }
105491 BuilderState.create = create;
105492 /**
105493 * Releases needed properties
105494 */
105495 function releaseCache(state) {
105496 state.allFilesExcludingDefaultLibraryFile = undefined;
105497 state.allFileNames = undefined;
105498 }
105499 BuilderState.releaseCache = releaseCache;
105500 /**
105501 * Creates a clone of the state
105502 */
105503 function clone(state) {
105504 // Dont need to backup allFiles info since its cache anyway
105505 return {
105506 fileInfos: new ts.Map(state.fileInfos),
105507 referencedMap: state.referencedMap && new ts.Map(state.referencedMap),
105508 exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap),
105509 hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature),
105510 };
105511 }
105512 BuilderState.clone = clone;
105513 /**
105514 * Gets the files affected by the path from the program
105515 */
105516 function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
105517 // Since the operation could be cancelled, the signatures are always stored in the cache
105518 // They will be committed once it is safe to use them
105519 // eg when calling this api from tsserver, if there is no cancellation of the operation
105520 // In the other cases the affected files signatures are committed only after the iteration through the result is complete
105521 var signatureCache = cacheToUpdateSignature || new ts.Map();
105522 var sourceFile = programOfThisState.getSourceFileByPath(path);
105523 if (!sourceFile) {
105524 return ts.emptyArray;
105525 }
105526 if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
105527 return [sourceFile];
105528 }
105529 var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
105530 if (!cacheToUpdateSignature) {
105531 // Commit all the signatures in the signature cache
105532 updateSignaturesFromCache(state, signatureCache);
105533 }
105534 return result;
105535 }
105536 BuilderState.getFilesAffectedBy = getFilesAffectedBy;
105537 /**
105538 * Updates the signatures from the cache into state's fileinfo signatures
105539 * This should be called whenever it is safe to commit the state of the builder
105540 */
105541 function updateSignaturesFromCache(state, signatureCache) {
105542 signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
105543 }
105544 BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
105545 function updateSignatureOfFile(state, signature, path) {
105546 state.fileInfos.get(path).signature = signature;
105547 state.hasCalledUpdateShapeSignature.add(path);
105548 }
105549 BuilderState.updateSignatureOfFile = updateSignatureOfFile;
105550 /**
105551 * Returns if the shape of the signature has changed since last emit
105552 */
105553 function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
105554 ts.Debug.assert(!!sourceFile);
105555 ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
105556 // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
105557 if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
105558 return false;
105559 }
105560 var info = state.fileInfos.get(sourceFile.resolvedPath);
105561 if (!info)
105562 return ts.Debug.fail();
105563 var prevSignature = info.signature;
105564 var latestSignature;
105565 if (sourceFile.isDeclarationFile) {
105566 latestSignature = sourceFile.version;
105567 if (exportedModulesMapCache && latestSignature !== prevSignature) {
105568 // All the references in this file are exported
105569 var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
105570 exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
105571 }
105572 }
105573 else {
105574 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile,
105575 /*emitOnlyDtsFiles*/ true, cancellationToken,
105576 /*customTransformers*/ undefined,
105577 /*forceDtsEmit*/ true);
105578 var firstDts_1 = emitOutput_1.outputFiles &&
105579 programOfThisState.getCompilerOptions().declarationMap ?
105580 emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
105581 emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
105582 if (firstDts_1) {
105583 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; })); });
105584 latestSignature = computeHash(firstDts_1.text);
105585 if (exportedModulesMapCache && latestSignature !== prevSignature) {
105586 updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
105587 }
105588 }
105589 else {
105590 latestSignature = prevSignature; // TODO: GH#18217
105591 }
105592 }
105593 cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
105594 return !prevSignature || latestSignature !== prevSignature;
105595 }
105596 BuilderState.updateShapeSignature = updateShapeSignature;
105597 /**
105598 * Coverts the declaration emit result into exported modules map
105599 */
105600 function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
105601 if (!exportedModulesFromDeclarationEmit) {
105602 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
105603 return;
105604 }
105605 var exportedModules;
105606 exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
105607 exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
105608 function addExportedModule(exportedModulePath) {
105609 if (exportedModulePath) {
105610 if (!exportedModules) {
105611 exportedModules = new ts.Set();
105612 }
105613 exportedModules.add(exportedModulePath);
105614 }
105615 }
105616 }
105617 /**
105618 * Updates the exported modules from cache into state's exported modules map
105619 * This should be called whenever it is safe to commit the state of the builder
105620 */
105621 function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
105622 if (exportedModulesMapCache) {
105623 ts.Debug.assert(!!state.exportedModulesMap);
105624 exportedModulesMapCache.forEach(function (exportedModules, path) {
105625 if (exportedModules) {
105626 state.exportedModulesMap.set(path, exportedModules);
105627 }
105628 else {
105629 state.exportedModulesMap.delete(path);
105630 }
105631 });
105632 }
105633 }
105634 BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
105635 /**
105636 * Get all the dependencies of the sourceFile
105637 */
105638 function getAllDependencies(state, programOfThisState, sourceFile) {
105639 var compilerOptions = programOfThisState.getCompilerOptions();
105640 // With --out or --outFile all outputs go into single file, all files depend on each other
105641 if (ts.outFile(compilerOptions)) {
105642 return getAllFileNames(state, programOfThisState);
105643 }
105644 // If this is non module emit, or its a global file, it depends on all the source files
105645 if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
105646 return getAllFileNames(state, programOfThisState);
105647 }
105648 // Get the references, traversing deep from the referenceMap
105649 var seenMap = new ts.Set();
105650 var queue = [sourceFile.resolvedPath];
105651 while (queue.length) {
105652 var path = queue.pop();
105653 if (!seenMap.has(path)) {
105654 seenMap.add(path);
105655 var references = state.referencedMap.get(path);
105656 if (references) {
105657 var iterator = references.keys();
105658 for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
105659 queue.push(iterResult.value);
105660 }
105661 }
105662 }
105663 }
105664 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; }));
105665 }
105666 BuilderState.getAllDependencies = getAllDependencies;
105667 /**
105668 * Gets the names of all files from the program
105669 */
105670 function getAllFileNames(state, programOfThisState) {
105671 if (!state.allFileNames) {
105672 var sourceFiles = programOfThisState.getSourceFiles();
105673 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
105674 }
105675 return state.allFileNames;
105676 }
105677 /**
105678 * Gets the files referenced by the the file path
105679 */
105680 function getReferencedByPaths(state, referencedFilePath) {
105681 return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
105682 var filePath = _a[0], referencesInFile = _a[1];
105683 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
105684 }));
105685 }
105686 BuilderState.getReferencedByPaths = getReferencedByPaths;
105687 /**
105688 * For script files that contains only ambient external modules, although they are not actually external module files,
105689 * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
105690 * there are no point to rebuild all script files if these special files have changed. However, if any statement
105691 * in the file is not ambient external module, we treat it as a regular script file.
105692 */
105693 function containsOnlyAmbientModules(sourceFile) {
105694 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
105695 var statement = _a[_i];
105696 if (!ts.isModuleWithStringLiteralName(statement)) {
105697 return false;
105698 }
105699 }
105700 return true;
105701 }
105702 /**
105703 * Return true if file contains anything that augments to global scope we need to build them as if
105704 * they are global files as well as module
105705 */
105706 function containsGlobalScopeAugmentation(sourceFile) {
105707 return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
105708 }
105709 /**
105710 * Return true if the file will invalidate all files because it affectes global scope
105711 */
105712 function isFileAffectingGlobalScope(sourceFile) {
105713 return containsGlobalScopeAugmentation(sourceFile) ||
105714 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
105715 }
105716 /**
105717 * Gets all files of the program excluding the default library file
105718 */
105719 function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
105720 // Use cached result
105721 if (state.allFilesExcludingDefaultLibraryFile) {
105722 return state.allFilesExcludingDefaultLibraryFile;
105723 }
105724 var result;
105725 if (firstSourceFile)
105726 addSourceFile(firstSourceFile);
105727 for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
105728 var sourceFile = _a[_i];
105729 if (sourceFile !== firstSourceFile) {
105730 addSourceFile(sourceFile);
105731 }
105732 }
105733 state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
105734 return state.allFilesExcludingDefaultLibraryFile;
105735 function addSourceFile(sourceFile) {
105736 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
105737 (result || (result = [])).push(sourceFile);
105738 }
105739 }
105740 }
105741 BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
105742 /**
105743 * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
105744 */
105745 function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
105746 var compilerOptions = programOfThisState.getCompilerOptions();
105747 // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
105748 // so returning the file itself is good enough.
105749 if (compilerOptions && ts.outFile(compilerOptions)) {
105750 return [sourceFileWithUpdatedShape];
105751 }
105752 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
105753 }
105754 /**
105755 * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
105756 */
105757 function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
105758 if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
105759 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
105760 }
105761 var compilerOptions = programOfThisState.getCompilerOptions();
105762 if (compilerOptions && (compilerOptions.isolatedModules || ts.outFile(compilerOptions))) {
105763 return [sourceFileWithUpdatedShape];
105764 }
105765 // Now we need to if each file in the referencedBy list has a shape change as well.
105766 // Because if so, its own referencedBy files need to be saved as well to make the
105767 // emitting result consistent with files on disk.
105768 var seenFileNamesMap = new ts.Map();
105769 // Start with the paths this file was referenced by
105770 seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
105771 var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
105772 while (queue.length > 0) {
105773 var currentPath = queue.pop();
105774 if (!seenFileNamesMap.has(currentPath)) {
105775 var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
105776 seenFileNamesMap.set(currentPath, currentSourceFile);
105777 if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
105778 queue.push.apply(// TODO: GH#18217
105779 queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
105780 }
105781 }
105782 }
105783 // Return array of values that needs emit
105784 // Return array of values that needs emit
105785 return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
105786 }
105787 })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
105788})(ts || (ts = {}));
105789/*@internal*/
105790var ts;
105791(function (ts) {
105792 var BuilderFileEmit;
105793 (function (BuilderFileEmit) {
105794 BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
105795 BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
105796 })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
105797 function hasSameKeys(map1, map2) {
105798 // Has same size and every key is present in both maps
105799 return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
105800 }
105801 /**
105802 * Create the state so that we can iterate on changedFiles/affected files
105803 */
105804 function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
105805 var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
105806 state.program = newProgram;
105807 var compilerOptions = newProgram.getCompilerOptions();
105808 state.compilerOptions = compilerOptions;
105809 // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
105810 if (!ts.outFile(compilerOptions)) {
105811 state.semanticDiagnosticsPerFile = new ts.Map();
105812 }
105813 state.changedFilesSet = new ts.Set();
105814 var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
105815 var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
105816 var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
105817 !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
105818 if (useOldState) {
105819 // Verify the sanity of old state
105820 if (!oldState.currentChangedFilePath) {
105821 var affectedSignatures = oldState.currentAffectedFilesSignatures;
105822 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
105823 }
105824 var changedFilesSet = oldState.changedFilesSet;
105825 if (canCopySemanticDiagnostics) {
105826 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
105827 }
105828 // Copy old state's changed files set
105829 changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); });
105830 if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) {
105831 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
105832 state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind);
105833 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
105834 state.seenAffectedFiles = new ts.Set();
105835 }
105836 }
105837 // Update changed files and copy semantic diagnostics if we can
105838 var referencedMap = state.referencedMap;
105839 var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
105840 var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
105841 var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
105842 state.fileInfos.forEach(function (info, sourceFilePath) {
105843 var oldInfo;
105844 var newReferences;
105845 // if not using old state, every file is changed
105846 if (!useOldState ||
105847 // File wasnt present in old state
105848 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
105849 // versions dont match
105850 oldInfo.version !== info.version ||
105851 // Referenced files changed
105852 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
105853 // Referenced file was deleted in the new program
105854 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
105855 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
105856 state.changedFilesSet.add(sourceFilePath);
105857 }
105858 else if (canCopySemanticDiagnostics) {
105859 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
105860 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
105861 return;
105862 }
105863 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
105864 return;
105865 }
105866 // Unchanged file copy diagnostics
105867 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
105868 if (diagnostics) {
105869 state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
105870 if (!state.semanticDiagnosticsFromOldState) {
105871 state.semanticDiagnosticsFromOldState = new ts.Set();
105872 }
105873 state.semanticDiagnosticsFromOldState.add(sourceFilePath);
105874 }
105875 }
105876 });
105877 // If the global file is removed, add all files as changed
105878 if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
105879 ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
105880 .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); });
105881 }
105882 else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
105883 // Add all files to affectedFilesPendingEmit since emit changed
105884 newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
105885 ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
105886 state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set();
105887 }
105888 state.buildInfoEmitPending = !!state.changedFilesSet.size;
105889 return state;
105890 }
105891 function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
105892 if (!diagnostics.length)
105893 return ts.emptyArray;
105894 var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
105895 return diagnostics.map(function (diagnostic) {
105896 var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
105897 result.reportsUnnecessary = diagnostic.reportsUnnecessary;
105898 result.reportsDeprecated = diagnostic.reportDeprecated;
105899 result.source = diagnostic.source;
105900 result.skippedOn = diagnostic.skippedOn;
105901 var relatedInformation = diagnostic.relatedInformation;
105902 result.relatedInformation = relatedInformation ?
105903 relatedInformation.length ?
105904 relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
105905 ts.emptyArray :
105906 undefined;
105907 return result;
105908 });
105909 function toPath(path) {
105910 return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
105911 }
105912 }
105913 function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
105914 var file = diagnostic.file;
105915 return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
105916 }
105917 /**
105918 * Releases program and other related not needed properties
105919 */
105920 function releaseCache(state) {
105921 ts.BuilderState.releaseCache(state);
105922 state.program = undefined;
105923 }
105924 /**
105925 * Creates a clone of the state
105926 */
105927 function cloneBuilderProgramState(state) {
105928 var newState = ts.BuilderState.clone(state);
105929 newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile);
105930 newState.changedFilesSet = new ts.Set(state.changedFilesSet);
105931 newState.affectedFiles = state.affectedFiles;
105932 newState.affectedFilesIndex = state.affectedFilesIndex;
105933 newState.currentChangedFilePath = state.currentChangedFilePath;
105934 newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures);
105935 newState.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap && new ts.Map(state.currentAffectedFilesExportedModulesMap);
105936 newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles);
105937 newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
105938 newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState);
105939 newState.program = state.program;
105940 newState.compilerOptions = state.compilerOptions;
105941 newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
105942 newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
105943 newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
105944 newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles);
105945 newState.programEmitComplete = state.programEmitComplete;
105946 return newState;
105947 }
105948 /**
105949 * Verifies that source file is ok to be used in calls that arent handled by next
105950 */
105951 function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
105952 ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
105953 }
105954 /**
105955 * This function returns the next affected file to be processed.
105956 * Note that until doneAffected is called it would keep reporting same result
105957 * This is to allow the callers to be able to actually remove affected file only when the operation is complete
105958 * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
105959 */
105960 function getNextAffectedFile(state, cancellationToken, computeHash) {
105961 while (true) {
105962 var affectedFiles = state.affectedFiles;
105963 if (affectedFiles) {
105964 var seenAffectedFiles = state.seenAffectedFiles;
105965 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
105966 while (affectedFilesIndex < affectedFiles.length) {
105967 var affectedFile = affectedFiles[affectedFilesIndex];
105968 if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
105969 // Set the next affected file as seen and remove the cached semantic diagnostics
105970 state.affectedFilesIndex = affectedFilesIndex;
105971 handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
105972 return affectedFile;
105973 }
105974 affectedFilesIndex++;
105975 }
105976 // Remove the changed file from the change set
105977 state.changedFilesSet.delete(state.currentChangedFilePath);
105978 state.currentChangedFilePath = undefined;
105979 // Commit the changes in file signature
105980 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
105981 state.currentAffectedFilesSignatures.clear();
105982 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
105983 state.affectedFiles = undefined;
105984 }
105985 // Get next changed file
105986 var nextKey = state.changedFilesSet.keys().next();
105987 if (nextKey.done) {
105988 // Done
105989 return undefined;
105990 }
105991 // With --out or --outFile all outputs go into single file
105992 // so operations are performed directly on program, return program
105993 var program = ts.Debug.checkDefined(state.program);
105994 var compilerOptions = program.getCompilerOptions();
105995 if (ts.outFile(compilerOptions)) {
105996 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
105997 return program;
105998 }
105999 // Get next batch of affected files
106000 if (!state.currentAffectedFilesSignatures)
106001 state.currentAffectedFilesSignatures = new ts.Map();
106002 if (state.exportedModulesMap) {
106003 if (!state.currentAffectedFilesExportedModulesMap)
106004 state.currentAffectedFilesExportedModulesMap = new ts.Map();
106005 }
106006 state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
106007 state.currentChangedFilePath = nextKey.value;
106008 state.affectedFilesIndex = 0;
106009 if (!state.seenAffectedFiles)
106010 state.seenAffectedFiles = new ts.Set();
106011 }
106012 }
106013 /**
106014 * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
106015 */
106016 function getNextAffectedFilePendingEmit(state) {
106017 var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
106018 if (affectedFilesPendingEmit) {
106019 var seenEmittedFiles = (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map()));
106020 for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
106021 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
106022 if (affectedFile) {
106023 var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
106024 var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
106025 if (seenKind === undefined || seenKind < emitKind) {
106026 // emit this file
106027 state.affectedFilesPendingEmitIndex = i;
106028 return { affectedFile: affectedFile, emitKind: emitKind };
106029 }
106030 }
106031 }
106032 state.affectedFilesPendingEmit = undefined;
106033 state.affectedFilesPendingEmitKind = undefined;
106034 state.affectedFilesPendingEmitIndex = undefined;
106035 }
106036 return undefined;
106037 }
106038 /**
106039 * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
106040 * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
106041 */
106042 function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
106043 removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
106044 // If affected files is everything except default library, then nothing more to do
106045 if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
106046 if (!state.cleanedDiagnosticsOfLibFiles) {
106047 state.cleanedDiagnosticsOfLibFiles = true;
106048 var program_1 = ts.Debug.checkDefined(state.program);
106049 var options_2 = program_1.getCompilerOptions();
106050 ts.forEach(program_1.getSourceFiles(), function (f) {
106051 return program_1.isSourceFileDefaultLibrary(f) &&
106052 !ts.skipTypeChecking(f, options_2, program_1) &&
106053 removeSemanticDiagnosticsOf(state, f.resolvedPath);
106054 });
106055 }
106056 return;
106057 }
106058 if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
106059 forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
106060 }
106061 }
106062 /**
106063 * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
106064 * Also we need to make sure signature is updated for these files
106065 */
106066 function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
106067 removeSemanticDiagnosticsOf(state, path);
106068 if (!state.changedFilesSet.has(path)) {
106069 var program = ts.Debug.checkDefined(state.program);
106070 var sourceFile = program.getSourceFileByPath(path);
106071 if (sourceFile) {
106072 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
106073 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
106074 // This ensures that we dont later during incremental builds considering wrong signature.
106075 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
106076 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
106077 // If not dts emit, nothing more to do
106078 if (ts.getEmitDeclarations(state.compilerOptions)) {
106079 addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
106080 }
106081 }
106082 }
106083 return false;
106084 }
106085 /**
106086 * Removes semantic diagnostics for path and
106087 * returns true if there are no more semantic diagnostics from the old state
106088 */
106089 function removeSemanticDiagnosticsOf(state, path) {
106090 if (!state.semanticDiagnosticsFromOldState) {
106091 return true;
106092 }
106093 state.semanticDiagnosticsFromOldState.delete(path);
106094 state.semanticDiagnosticsPerFile.delete(path);
106095 return !state.semanticDiagnosticsFromOldState.size;
106096 }
106097 function isChangedSignagure(state, path) {
106098 var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
106099 var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
106100 return newSignature !== oldSignagure;
106101 }
106102 /**
106103 * Iterate on referencing modules that export entities from affected file
106104 */
106105 function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
106106 // If there was change in signature (dts output) for the changed file,
106107 // then only we need to handle pending file emit
106108 if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
106109 return;
106110 }
106111 if (!isChangedSignagure(state, affectedFile.resolvedPath))
106112 return;
106113 // Since isolated modules dont change js files, files affected by change in signature is itself
106114 // But we need to cleanup semantic diagnostics and queue dts emit for affected files
106115 if (state.compilerOptions.isolatedModules) {
106116 var seenFileNamesMap = new ts.Map();
106117 seenFileNamesMap.set(affectedFile.resolvedPath, true);
106118 var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
106119 while (queue.length > 0) {
106120 var currentPath = queue.pop();
106121 if (!seenFileNamesMap.has(currentPath)) {
106122 seenFileNamesMap.set(currentPath, true);
106123 var result = fn(state, currentPath);
106124 if (result && isChangedSignagure(state, currentPath)) {
106125 var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
106126 queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
106127 }
106128 }
106129 }
106130 }
106131 ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
106132 var seenFileAndExportsOfFile = new ts.Set();
106133 // Go through exported modules from cache first
106134 // If exported modules has path, all files referencing file exported from are affected
106135 if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
106136 return exportedModules &&
106137 exportedModules.has(affectedFile.resolvedPath) &&
106138 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
106139 })) {
106140 return;
106141 }
106142 // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
106143 ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
106144 return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
106145 exportedModules.has(affectedFile.resolvedPath) &&
106146 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
106147 });
106148 }
106149 /**
106150 * Iterate on files referencing referencedPath
106151 */
106152 function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
106153 return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
106154 return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
106155 });
106156 }
106157 /**
106158 * fn on file and iterate on anything that exports this file
106159 */
106160 function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
106161 if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
106162 return false;
106163 }
106164 if (fn(state, filePath)) {
106165 // If there are no more diagnostics from old cache, done
106166 return true;
106167 }
106168 ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
106169 // Go through exported modules from cache first
106170 // If exported modules has path, all files referencing file exported from are affected
106171 if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
106172 return exportedModules &&
106173 exportedModules.has(filePath) &&
106174 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
106175 })) {
106176 return true;
106177 }
106178 // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
106179 if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
106180 return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
106181 exportedModules.has(filePath) &&
106182 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
106183 })) {
106184 return true;
106185 }
106186 // Remove diagnostics of files that import this file (without going to exports of referencing files)
106187 return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
106188 return referencesInFile.has(filePath) &&
106189 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
106190 fn(state, referencingFilePath);
106191 } // Dont add to seen since this is not yet done with the export removal
106192 );
106193 }
106194 /**
106195 * This is called after completing operation on the next affected file.
106196 * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
106197 */
106198 function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
106199 if (isBuildInfoEmit) {
106200 state.buildInfoEmitPending = false;
106201 }
106202 else if (affected === state.program) {
106203 state.changedFilesSet.clear();
106204 state.programEmitComplete = true;
106205 }
106206 else {
106207 state.seenAffectedFiles.add(affected.resolvedPath);
106208 if (emitKind !== undefined) {
106209 (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind);
106210 }
106211 if (isPendingEmit) {
106212 state.affectedFilesPendingEmitIndex++;
106213 state.buildInfoEmitPending = true;
106214 }
106215 else {
106216 state.affectedFilesIndex++;
106217 }
106218 }
106219 }
106220 /**
106221 * Returns the result with affected file
106222 */
106223 function toAffectedFileResult(state, result, affected) {
106224 doneWithAffectedFile(state, affected);
106225 return { result: result, affected: affected };
106226 }
106227 /**
106228 * Returns the result with affected file
106229 */
106230 function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
106231 doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
106232 return { result: result, affected: affected };
106233 }
106234 /**
106235 * Gets semantic diagnostics for the file which are
106236 * bindAndCheckDiagnostics (from cache) and program diagnostics
106237 */
106238 function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
106239 return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
106240 }
106241 /**
106242 * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
106243 * 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
106244 */
106245 function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
106246 var path = sourceFile.resolvedPath;
106247 if (state.semanticDiagnosticsPerFile) {
106248 var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
106249 // Report the bind and check diagnostics from the cache if we already have those diagnostics present
106250 if (cachedDiagnostics) {
106251 return ts.filterSemanticDiagnotics(cachedDiagnostics, state.compilerOptions);
106252 }
106253 }
106254 // Diagnostics werent cached, get them from program, and cache the result
106255 var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
106256 if (state.semanticDiagnosticsPerFile) {
106257 state.semanticDiagnosticsPerFile.set(path, diagnostics);
106258 }
106259 return ts.filterSemanticDiagnotics(diagnostics, state.compilerOptions);
106260 }
106261 /**
106262 * Gets the program information to be emitted in buildInfo so that we can use it to create new program
106263 */
106264 function getProgramBuildInfo(state, getCanonicalFileName) {
106265 if (ts.outFile(state.compilerOptions))
106266 return undefined;
106267 var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
106268 var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
106269 var fileInfos = {};
106270 state.fileInfos.forEach(function (value, key) {
106271 var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
106272 fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
106273 });
106274 var result = {
106275 fileInfos: fileInfos,
106276 options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
106277 };
106278 if (state.referencedMap) {
106279 var referencedMap = {};
106280 for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
106281 var key = _a[_i];
106282 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
106283 }
106284 result.referencedMap = referencedMap;
106285 }
106286 if (state.exportedModulesMap) {
106287 var exportedModulesMap = {};
106288 for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
106289 var key = _c[_b];
106290 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
106291 // Not in temporary cache, use existing value
106292 if (newValue === undefined)
106293 exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
106294 // Value in cache and has updated value map, use that
106295 else if (newValue)
106296 exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
106297 }
106298 result.exportedModulesMap = exportedModulesMap;
106299 }
106300 if (state.semanticDiagnosticsPerFile) {
106301 var semanticDiagnosticsPerFile = [];
106302 for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
106303 var key = _e[_d];
106304 var value = state.semanticDiagnosticsPerFile.get(key);
106305 semanticDiagnosticsPerFile.push(value.length ?
106306 [
106307 relativeToBuildInfo(key),
106308 state.hasReusableDiagnostic ?
106309 value :
106310 convertToReusableDiagnostics(value, relativeToBuildInfo)
106311 ] :
106312 relativeToBuildInfo(key));
106313 }
106314 result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
106315 }
106316 if (state.affectedFilesPendingEmit) {
106317 var affectedFilesPendingEmit = [];
106318 var seenFiles = new ts.Set();
106319 for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) {
106320 var path = _g[_f];
106321 if (ts.tryAddToSet(seenFiles, path)) {
106322 affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]);
106323 }
106324 }
106325 result.affectedFilesPendingEmit = affectedFilesPendingEmit;
106326 }
106327 return result;
106328 function relativeToBuildInfoEnsuringAbsolutePath(path) {
106329 return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
106330 }
106331 function relativeToBuildInfo(path) {
106332 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
106333 }
106334 }
106335 function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
106336 var result = {};
106337 var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
106338 for (var name in options) {
106339 if (ts.hasProperty(options, name)) {
106340 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
106341 }
106342 }
106343 if (result.configFilePath) {
106344 result.configFilePath = relativeToBuildInfo(result.configFilePath);
106345 }
106346 return result;
106347 }
106348 function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
106349 if (option) {
106350 if (option.type === "list") {
106351 var values = value;
106352 if (option.element.isFilePath && values.length) {
106353 return values.map(relativeToBuildInfo);
106354 }
106355 }
106356 else if (option.isFilePath) {
106357 return relativeToBuildInfo(value);
106358 }
106359 }
106360 return value;
106361 }
106362 function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
106363 ts.Debug.assert(!!diagnostics.length);
106364 return diagnostics.map(function (diagnostic) {
106365 var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
106366 result.reportsUnnecessary = diagnostic.reportsUnnecessary;
106367 result.reportDeprecated = diagnostic.reportsDeprecated;
106368 result.source = diagnostic.source;
106369 result.skippedOn = diagnostic.skippedOn;
106370 var relatedInformation = diagnostic.relatedInformation;
106371 result.relatedInformation = relatedInformation ?
106372 relatedInformation.length ?
106373 relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
106374 ts.emptyArray :
106375 undefined;
106376 return result;
106377 });
106378 }
106379 function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
106380 var file = diagnostic.file;
106381 return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
106382 }
106383 var BuilderProgramKind;
106384 (function (BuilderProgramKind) {
106385 BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
106386 BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
106387 })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
106388 function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
106389 var host;
106390 var newProgram;
106391 var oldProgram;
106392 if (newProgramOrRootNames === undefined) {
106393 ts.Debug.assert(hostOrOptions === undefined);
106394 host = oldProgramOrHost;
106395 oldProgram = configFileParsingDiagnosticsOrOldProgram;
106396 ts.Debug.assert(!!oldProgram);
106397 newProgram = oldProgram.getProgram();
106398 }
106399 else if (ts.isArray(newProgramOrRootNames)) {
106400 oldProgram = configFileParsingDiagnosticsOrOldProgram;
106401 newProgram = ts.createProgram({
106402 rootNames: newProgramOrRootNames,
106403 options: hostOrOptions,
106404 host: oldProgramOrHost,
106405 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
106406 configFileParsingDiagnostics: configFileParsingDiagnostics,
106407 projectReferences: projectReferences
106408 });
106409 host = oldProgramOrHost;
106410 }
106411 else {
106412 newProgram = newProgramOrRootNames;
106413 host = hostOrOptions;
106414 oldProgram = oldProgramOrHost;
106415 configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
106416 }
106417 return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
106418 }
106419 ts.getBuilderCreationParameters = getBuilderCreationParameters;
106420 function createBuilderProgram(kind, _a) {
106421 var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
106422 // Return same program if underlying program doesnt change
106423 var oldState = oldProgram && oldProgram.getState();
106424 if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
106425 newProgram = undefined; // TODO: GH#18217
106426 oldState = undefined;
106427 return oldProgram;
106428 }
106429 /**
106430 * Create the canonical file name for identity
106431 */
106432 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106433 /**
106434 * Computing hash to for signature verification
106435 */
106436 var computeHash = host.createHash || ts.generateDjb2Hash;
106437 var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
106438 var backupState;
106439 newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
106440 // To ensure that we arent storing any references to old program or new program without state
106441 newProgram = undefined; // TODO: GH#18217
106442 oldProgram = undefined;
106443 oldState = undefined;
106444 var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
106445 builderProgram.getState = function () { return state; };
106446 builderProgram.backupState = function () {
106447 ts.Debug.assert(backupState === undefined);
106448 backupState = cloneBuilderProgramState(state);
106449 };
106450 builderProgram.restoreState = function () {
106451 state = ts.Debug.checkDefined(backupState);
106452 backupState = undefined;
106453 };
106454 builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
106455 builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
106456 builderProgram.emit = emit;
106457 builderProgram.releaseProgram = function () {
106458 releaseCache(state);
106459 backupState = undefined;
106460 };
106461 if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
106462 builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
106463 }
106464 else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
106465 builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
106466 builderProgram.emitNextAffectedFile = emitNextAffectedFile;
106467 builderProgram.emitBuildInfo = emitBuildInfo;
106468 }
106469 else {
106470 ts.notImplemented();
106471 }
106472 return builderProgram;
106473 function emitBuildInfo(writeFile, cancellationToken) {
106474 if (state.buildInfoEmitPending) {
106475 var result = ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken);
106476 state.buildInfoEmitPending = false;
106477 return result;
106478 }
106479 return ts.emitSkippedWithNoDiagnostics;
106480 }
106481 /**
106482 * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
106483 * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
106484 * in that order would be used to write the files
106485 */
106486 function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106487 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
106488 var emitKind = 1 /* Full */;
106489 var isPendingEmitFile = false;
106490 if (!affected) {
106491 if (!ts.outFile(state.compilerOptions)) {
106492 var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
106493 if (!pendingAffectedFile) {
106494 if (!state.buildInfoEmitPending) {
106495 return undefined;
106496 }
106497 var affected_1 = ts.Debug.checkDefined(state.program);
106498 return toAffectedFileEmitResult(state,
106499 // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
106500 // Otherwise just affected file
106501 affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */,
106502 /*isPendingEmitFile*/ false,
106503 /*isBuildInfoEmit*/ true);
106504 }
106505 (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
106506 isPendingEmitFile = true;
106507 }
106508 else {
106509 var program = ts.Debug.checkDefined(state.program);
106510 if (state.programEmitComplete)
106511 return undefined;
106512 affected = program;
106513 }
106514 }
106515 return toAffectedFileEmitResult(state,
106516 // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
106517 // Otherwise just affected file
106518 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);
106519 }
106520 /**
106521 * Emits the JavaScript and declaration files.
106522 * When targetSource file is specified, emits the files corresponding to that source file,
106523 * otherwise for the whole program.
106524 * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
106525 * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
106526 * it will only emit all the affected files instead of whole program
106527 *
106528 * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
106529 * in that order would be used to write the files
106530 */
106531 function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106532 var restorePendingEmitOnHandlingNoEmitSuccess = false;
106533 var savedAffectedFilesPendingEmit;
106534 var savedAffectedFilesPendingEmitKind;
106535 var savedAffectedFilesPendingEmitIndex;
106536 // 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
106537 // This ensures pending files to emit is updated in tsbuildinfo
106538 // 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)
106539 if (kind !== BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
106540 !targetSourceFile &&
106541 !ts.outFile(state.compilerOptions) &&
106542 !state.compilerOptions.noEmit &&
106543 state.compilerOptions.noEmitOnError) {
106544 restorePendingEmitOnHandlingNoEmitSuccess = true;
106545 savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
106546 savedAffectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
106547 savedAffectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
106548 }
106549 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
106550 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
106551 }
106552 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, writeFile, cancellationToken);
106553 if (result)
106554 return result;
106555 if (restorePendingEmitOnHandlingNoEmitSuccess) {
106556 state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
106557 state.affectedFilesPendingEmitKind = savedAffectedFilesPendingEmitKind;
106558 state.affectedFilesPendingEmitIndex = savedAffectedFilesPendingEmitIndex;
106559 }
106560 // Emit only affected files if using builder for emit
106561 if (!targetSourceFile && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
106562 // Emit and report any errors we ran into.
106563 var sourceMaps = [];
106564 var emitSkipped = false;
106565 var diagnostics = void 0;
106566 var emittedFiles = [];
106567 var affectedEmitResult = void 0;
106568 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
106569 emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
106570 diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
106571 emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
106572 sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
106573 }
106574 return {
106575 emitSkipped: emitSkipped,
106576 diagnostics: diagnostics || ts.emptyArray,
106577 emittedFiles: emittedFiles,
106578 sourceMaps: sourceMaps
106579 };
106580 }
106581 return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
106582 }
106583 /**
106584 * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
106585 * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
106586 */
106587 function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
106588 while (true) {
106589 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
106590 if (!affected) {
106591 // Done
106592 return undefined;
106593 }
106594 else if (affected === state.program) {
106595 // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
106596 return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
106597 }
106598 // Add file to affected file pending emit to handle for later emit time
106599 // 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
106600 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram || state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
106601 addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
106602 }
106603 // Get diagnostics for the affected file if its not ignored
106604 if (ignoreSourceFile && ignoreSourceFile(affected)) {
106605 // Get next affected file
106606 doneWithAffectedFile(state, affected);
106607 continue;
106608 }
106609 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
106610 }
106611 }
106612 /**
106613 * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
106614 * The semantic diagnostics are cached and managed here
106615 * Note that it is assumed that when asked about semantic diagnostics through this API,
106616 * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
106617 * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
106618 * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
106619 */
106620 function getSemanticDiagnostics(sourceFile, cancellationToken) {
106621 assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
106622 var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
106623 if (ts.outFile(compilerOptions)) {
106624 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
106625 // We dont need to cache the diagnostics just return them from program
106626 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
106627 }
106628 if (sourceFile) {
106629 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
106630 }
106631 // When semantic builder asks for diagnostics of the whole program,
106632 // ensure that all the affected files are handled
106633 // eslint-disable-next-line no-empty
106634 while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
106635 }
106636 var diagnostics;
106637 for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
106638 var sourceFile_1 = _a[_i];
106639 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
106640 }
106641 return diagnostics || ts.emptyArray;
106642 }
106643 }
106644 ts.createBuilderProgram = createBuilderProgram;
106645 function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
106646 if (!state.affectedFilesPendingEmit)
106647 state.affectedFilesPendingEmit = [];
106648 if (!state.affectedFilesPendingEmitKind)
106649 state.affectedFilesPendingEmitKind = new ts.Map();
106650 var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
106651 state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
106652 state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
106653 // affectedFilesPendingEmitIndex === undefined
106654 // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
106655 // so start from 0 as array would be affectedFilesPendingEmit
106656 // else, continue to iterate from existing index, the current set is appended to existing files
106657 if (state.affectedFilesPendingEmitIndex === undefined) {
106658 state.affectedFilesPendingEmitIndex = 0;
106659 }
106660 }
106661 function getMapOfReferencedSet(mapLike, toPath) {
106662 if (!mapLike)
106663 return undefined;
106664 var map = new ts.Map();
106665 // Copies keys/values from template. Note that for..in will not throw if
106666 // template is undefined, and instead will just exit the loop.
106667 for (var key in mapLike) {
106668 if (ts.hasProperty(mapLike, key)) {
106669 map.set(toPath(key), new ts.Set(mapLike[key].map(toPath)));
106670 }
106671 }
106672 return map;
106673 }
106674 function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
106675 var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
106676 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106677 var fileInfos = new ts.Map();
106678 for (var key in program.fileInfos) {
106679 if (ts.hasProperty(program.fileInfos, key)) {
106680 fileInfos.set(toPath(key), program.fileInfos[key]);
106681 }
106682 }
106683 var state = {
106684 fileInfos: fileInfos,
106685 compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
106686 referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
106687 exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
106688 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]; }),
106689 hasReusableDiagnostic: true,
106690 affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }),
106691 affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }),
106692 affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
106693 };
106694 return {
106695 getState: function () { return state; },
106696 backupState: ts.noop,
106697 restoreState: ts.noop,
106698 getProgram: ts.notImplemented,
106699 getProgramOrUndefined: ts.returnUndefined,
106700 releaseProgram: ts.noop,
106701 getCompilerOptions: function () { return state.compilerOptions; },
106702 getSourceFile: ts.notImplemented,
106703 getSourceFiles: ts.notImplemented,
106704 getOptionsDiagnostics: ts.notImplemented,
106705 getGlobalDiagnostics: ts.notImplemented,
106706 getConfigFileParsingDiagnostics: ts.notImplemented,
106707 getSyntacticDiagnostics: ts.notImplemented,
106708 getDeclarationDiagnostics: ts.notImplemented,
106709 getSemanticDiagnostics: ts.notImplemented,
106710 emit: ts.notImplemented,
106711 getAllDependencies: ts.notImplemented,
106712 getCurrentDirectory: ts.notImplemented,
106713 emitNextAffectedFile: ts.notImplemented,
106714 getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
106715 emitBuildInfo: ts.notImplemented,
106716 close: ts.noop,
106717 };
106718 function toPath(path) {
106719 return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
106720 }
106721 function toAbsolutePath(path) {
106722 return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
106723 }
106724 }
106725 ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
106726 function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
106727 return {
106728 getState: ts.notImplemented,
106729 backupState: ts.noop,
106730 restoreState: ts.noop,
106731 getProgram: getProgram,
106732 getProgramOrUndefined: function () { return state.program; },
106733 releaseProgram: function () { return state.program = undefined; },
106734 getCompilerOptions: function () { return state.compilerOptions; },
106735 getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
106736 getSourceFiles: function () { return getProgram().getSourceFiles(); },
106737 getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
106738 getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
106739 getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
106740 getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
106741 getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
106742 getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
106743 emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
106744 emitBuildInfo: function (writeFile, cancellationToken) { return getProgram().emitBuildInfo(writeFile, cancellationToken); },
106745 getAllDependencies: ts.notImplemented,
106746 getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
106747 close: ts.noop,
106748 };
106749 function getProgram() {
106750 return ts.Debug.checkDefined(state.program);
106751 }
106752 }
106753 ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
106754})(ts || (ts = {}));
106755var ts;
106756(function (ts) {
106757 function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
106758 return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
106759 }
106760 ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
106761 function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
106762 return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
106763 }
106764 ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
106765 function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
106766 var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
106767 return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
106768 }
106769 ts.createAbstractBuilder = createAbstractBuilder;
106770})(ts || (ts = {}));
106771/*@internal*/
106772var ts;
106773(function (ts) {
106774 function removeIgnoredPath(path) {
106775 // Consider whole staging folder as if node_modules changed.
106776 if (ts.endsWith(path, "/node_modules/.staging")) {
106777 return ts.removeSuffix(path, "/.staging");
106778 }
106779 return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
106780 undefined :
106781 path;
106782 }
106783 ts.removeIgnoredPath = removeIgnoredPath;
106784 /**
106785 * Filter out paths like
106786 * "/", "/user", "/user/username", "/user/username/folderAtRoot",
106787 * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
106788 * @param dirPath
106789 */
106790 function canWatchDirectory(dirPath) {
106791 var rootLength = ts.getRootLength(dirPath);
106792 if (dirPath.length === rootLength) {
106793 // Ignore "/", "c:/"
106794 return false;
106795 }
106796 var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
106797 if (nextDirectorySeparator === -1) {
106798 // ignore "/user", "c:/users" or "c:/folderAtRoot"
106799 return false;
106800 }
106801 var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
106802 var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
106803 if (isNonDirectorySeparatorRoot &&
106804 dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
106805 pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
106806 nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
106807 if (nextDirectorySeparator === -1) {
106808 // ignore "//vda1cs4850/c$/folderAtRoot"
106809 return false;
106810 }
106811 pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
106812 }
106813 if (isNonDirectorySeparatorRoot &&
106814 pathPartForUserCheck.search(/users\//i) !== 0) {
106815 // Paths like c:/folderAtRoot/subFolder are allowed
106816 return true;
106817 }
106818 for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
106819 searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
106820 if (searchIndex === 0) {
106821 // Folder isnt at expected minimum levels
106822 return false;
106823 }
106824 }
106825 return true;
106826 }
106827 ts.canWatchDirectory = canWatchDirectory;
106828 function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
106829 var filesWithChangedSetOfUnresolvedImports;
106830 var filesWithInvalidatedResolutions;
106831 var filesWithInvalidatedNonRelativeUnresolvedImports;
106832 var nonRelativeExternalModuleResolutions = ts.createMultiMap();
106833 var resolutionsWithFailedLookups = [];
106834 var resolvedFileToResolution = ts.createMultiMap();
106835 var hasChangedAutomaticTypeDirectiveNames = false;
106836 var failedLookupChecks = [];
106837 var startsWithPathChecks = [];
106838 var isInDirectoryChecks = [];
106839 var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
106840 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
106841 // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
106842 // The key in the map is source file's path.
106843 // The values are Map of resolutions with key being name lookedup.
106844 var resolvedModuleNames = new ts.Map();
106845 var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
106846 var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
106847 var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
106848 var resolvedTypeReferenceDirectives = new ts.Map();
106849 var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
106850 /**
106851 * These are the extensions that failed lookup files will have by default,
106852 * any other extension of failed lookup will be store that path in custom failed lookup path
106853 * This helps in not having to comb through all resolutions when files are added/removed
106854 * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
106855 */
106856 var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
106857 var customFailedLookupPaths = new ts.Map();
106858 var directoryWatchesOfFailedLookups = new ts.Map();
106859 var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
106860 var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
106861 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
106862 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
106863 var typeRootsWatches = new ts.Map();
106864 return {
106865 startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
106866 finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
106867 // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
106868 // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
106869 startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
106870 finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
106871 resolveModuleNames: resolveModuleNames,
106872 getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
106873 resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
106874 removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
106875 removeResolutionsOfFile: removeResolutionsOfFile,
106876 hasChangedAutomaticTypeDirectiveNames: function () { return hasChangedAutomaticTypeDirectiveNames; },
106877 invalidateResolutionOfFile: invalidateResolutionOfFile,
106878 invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
106879 setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
106880 createHasInvalidatedResolution: createHasInvalidatedResolution,
106881 updateTypeRootsWatch: updateTypeRootsWatch,
106882 closeTypeRootsWatch: closeTypeRootsWatch,
106883 clear: clear
106884 };
106885 function getResolvedModule(resolution) {
106886 return resolution.resolvedModule;
106887 }
106888 function getResolvedTypeReferenceDirective(resolution) {
106889 return resolution.resolvedTypeReferenceDirective;
106890 }
106891 function isInDirectoryPath(dir, file) {
106892 if (dir === undefined || file.length <= dir.length) {
106893 return false;
106894 }
106895 return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
106896 }
106897 function clear() {
106898 ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
106899 customFailedLookupPaths.clear();
106900 nonRelativeExternalModuleResolutions.clear();
106901 closeTypeRootsWatch();
106902 resolvedModuleNames.clear();
106903 resolvedTypeReferenceDirectives.clear();
106904 resolvedFileToResolution.clear();
106905 resolutionsWithFailedLookups.length = 0;
106906 failedLookupChecks.length = 0;
106907 startsWithPathChecks.length = 0;
106908 isInDirectoryChecks.length = 0;
106909 // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
106910 // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
106911 clearPerDirectoryResolutions();
106912 hasChangedAutomaticTypeDirectiveNames = false;
106913 }
106914 function startRecordingFilesWithChangedResolutions() {
106915 filesWithChangedSetOfUnresolvedImports = [];
106916 }
106917 function finishRecordingFilesWithChangedResolutions() {
106918 var collected = filesWithChangedSetOfUnresolvedImports;
106919 filesWithChangedSetOfUnresolvedImports = undefined;
106920 return collected;
106921 }
106922 function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
106923 if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
106924 return false;
106925 }
106926 // Invalidated if file has unresolved imports
106927 var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
106928 return !!value && !!value.length;
106929 }
106930 function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
106931 // Ensure pending resolutions are applied
106932 invalidateResolutionsOfFailedLookupLocations();
106933 if (forceAllFilesAsInvalidated) {
106934 // Any file asked would have invalidated resolution
106935 filesWithInvalidatedResolutions = undefined;
106936 return ts.returnTrue;
106937 }
106938 var collected = filesWithInvalidatedResolutions;
106939 filesWithInvalidatedResolutions = undefined;
106940 return function (path) { return (!!collected && collected.has(path)) ||
106941 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
106942 }
106943 function clearPerDirectoryResolutions() {
106944 perDirectoryResolvedModuleNames.clear();
106945 nonRelativeModuleNameCache.clear();
106946 perDirectoryResolvedTypeReferenceDirectives.clear();
106947 nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
106948 nonRelativeExternalModuleResolutions.clear();
106949 }
106950 function finishCachingPerDirectoryResolution() {
106951 filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
106952 clearPerDirectoryResolutions();
106953 directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
106954 if (watcher.refCount === 0) {
106955 directoryWatchesOfFailedLookups.delete(path);
106956 watcher.watcher.close();
106957 }
106958 });
106959 hasChangedAutomaticTypeDirectiveNames = false;
106960 }
106961 function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
106962 var _a;
106963 var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
106964 // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
106965 if (!resolutionHost.getGlobalCache) {
106966 return primaryResult;
106967 }
106968 // otherwise try to load typings from @types
106969 var globalCache = resolutionHost.getGlobalCache();
106970 if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
106971 // create different collection of failed lookup locations for second pass
106972 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
106973 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
106974 if (resolvedModule) {
106975 // Modify existing resolution so its saved in the directory cache as well
106976 primaryResult.resolvedModule = resolvedModule;
106977 (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
106978 return primaryResult;
106979 }
106980 }
106981 // Default return the result from the first pass
106982 return primaryResult;
106983 }
106984 function resolveNamesWithLocalCache(_a) {
106985 var _b;
106986 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;
106987 var path = resolutionHost.toPath(containingFile);
106988 var resolutionsInFile = cache.get(path) || cache.set(path, new ts.Map()).get(path);
106989 var dirPath = ts.getDirectoryPath(path);
106990 var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
106991 var perDirectoryResolution = perDirectoryCache.get(dirPath);
106992 if (!perDirectoryResolution) {
106993 perDirectoryResolution = new ts.Map();
106994 perDirectoryCache.set(dirPath, perDirectoryResolution);
106995 }
106996 var resolvedModules = [];
106997 var compilerOptions = resolutionHost.getCompilationSettings();
106998 var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
106999 // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
107000 var program = resolutionHost.getCurrentProgram();
107001 var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
107002 var unmatchedRedirects = oldRedirect ?
107003 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
107004 !!redirectedReference;
107005 var seenNamesInFile = new ts.Map();
107006 for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
107007 var name = names_3[_i];
107008 var resolution = resolutionsInFile.get(name);
107009 // Resolution is valid if it is present and not invalidated
107010 if (!seenNamesInFile.has(name) &&
107011 unmatchedRedirects || !resolution || resolution.isInvalidated ||
107012 // If the name is unresolved import that was invalidated, recalculate
107013 (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
107014 var existingResolution = resolution;
107015 var resolutionInDirectory = perDirectoryResolution.get(name);
107016 if (resolutionInDirectory) {
107017 resolution = resolutionInDirectory;
107018 }
107019 else {
107020 resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
107021 perDirectoryResolution.set(name, resolution);
107022 }
107023 resolutionsInFile.set(name, resolution);
107024 watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
107025 if (existingResolution) {
107026 stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
107027 }
107028 if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
107029 filesWithChangedSetOfUnresolvedImports.push(path);
107030 // reset log changes to avoid recording the same file multiple times
107031 logChanges = false;
107032 }
107033 }
107034 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
107035 seenNamesInFile.set(name, true);
107036 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
107037 }
107038 // Stop watching and remove the unused name
107039 resolutionsInFile.forEach(function (resolution, name) {
107040 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
107041 stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
107042 resolutionsInFile.delete(name);
107043 }
107044 });
107045 return resolvedModules;
107046 function resolutionIsEqualTo(oldResolution, newResolution) {
107047 if (oldResolution === newResolution) {
107048 return true;
107049 }
107050 if (!oldResolution || !newResolution) {
107051 return false;
107052 }
107053 var oldResult = getResolutionWithResolvedFileName(oldResolution);
107054 var newResult = getResolutionWithResolvedFileName(newResolution);
107055 if (oldResult === newResult) {
107056 return true;
107057 }
107058 if (!oldResult || !newResult) {
107059 return false;
107060 }
107061 return oldResult.resolvedFileName === newResult.resolvedFileName;
107062 }
107063 }
107064 function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
107065 return resolveNamesWithLocalCache({
107066 names: typeDirectiveNames,
107067 containingFile: containingFile,
107068 redirectedReference: redirectedReference,
107069 cache: resolvedTypeReferenceDirectives,
107070 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
107071 loader: ts.resolveTypeReferenceDirective,
107072 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
107073 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
107074 });
107075 }
107076 function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
107077 return resolveNamesWithLocalCache({
107078 names: moduleNames,
107079 containingFile: containingFile,
107080 redirectedReference: redirectedReference,
107081 cache: resolvedModuleNames,
107082 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
107083 loader: resolveModuleName,
107084 getResolutionWithResolvedFileName: getResolvedModule,
107085 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
107086 reusedNames: reusedNames,
107087 logChanges: logChangesWhenResolvingModule,
107088 });
107089 }
107090 function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
107091 var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
107092 return cache && cache.get(moduleName);
107093 }
107094 function isNodeModulesAtTypesDirectory(dirPath) {
107095 return ts.endsWith(dirPath, "/node_modules/@types");
107096 }
107097 function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
107098 if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
107099 // Ensure failed look up is normalized path
107100 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
107101 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
107102 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
107103 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
107104 if (failedLookupPathSplit.length > rootSplitLength + 1) {
107105 // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
107106 return {
107107 dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
107108 dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
107109 };
107110 }
107111 else {
107112 // Always watch root directory non recursively
107113 return {
107114 dir: rootDir,
107115 dirPath: rootPath,
107116 nonRecursive: false
107117 };
107118 }
107119 }
107120 return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
107121 }
107122 function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
107123 // If directory path contains node module, get the most parent node_modules directory for watching
107124 while (ts.pathContainsNodeModules(dirPath)) {
107125 dir = ts.getDirectoryPath(dir);
107126 dirPath = ts.getDirectoryPath(dirPath);
107127 }
107128 // If the directory is node_modules use it to watch, always watch it recursively
107129 if (ts.isNodeModulesDirectory(dirPath)) {
107130 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
107131 }
107132 var nonRecursive = true;
107133 // Use some ancestor of the root directory
107134 var subDirectoryPath, subDirectory;
107135 if (rootPath !== undefined) {
107136 while (!isInDirectoryPath(dirPath, rootPath)) {
107137 var parentPath = ts.getDirectoryPath(dirPath);
107138 if (parentPath === dirPath) {
107139 break;
107140 }
107141 nonRecursive = false;
107142 subDirectoryPath = dirPath;
107143 subDirectory = dir;
107144 dirPath = parentPath;
107145 dir = ts.getDirectoryPath(dir);
107146 }
107147 }
107148 return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
107149 }
107150 function isPathWithDefaultFailedLookupExtension(path) {
107151 return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
107152 }
107153 function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
107154 if (resolution.refCount) {
107155 resolution.refCount++;
107156 ts.Debug.assertDefined(resolution.files);
107157 }
107158 else {
107159 resolution.refCount = 1;
107160 ts.Debug.assert(ts.length(resolution.files) === 0); // This resolution shouldnt be referenced by any file yet
107161 if (ts.isExternalModuleNameRelative(name)) {
107162 watchFailedLookupLocationOfResolution(resolution);
107163 }
107164 else {
107165 nonRelativeExternalModuleResolutions.add(name, resolution);
107166 }
107167 var resolved = getResolutionWithResolvedFileName(resolution);
107168 if (resolved && resolved.resolvedFileName) {
107169 resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
107170 }
107171 }
107172 (resolution.files || (resolution.files = [])).push(filePath);
107173 }
107174 function watchFailedLookupLocationOfResolution(resolution) {
107175 ts.Debug.assert(!!resolution.refCount);
107176 var failedLookupLocations = resolution.failedLookupLocations;
107177 if (!failedLookupLocations.length)
107178 return;
107179 resolutionsWithFailedLookups.push(resolution);
107180 var setAtRoot = false;
107181 for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
107182 var failedLookupLocation = failedLookupLocations_1[_i];
107183 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
107184 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
107185 if (toWatch) {
107186 var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
107187 // If the failed lookup location path is not one of the supported extensions,
107188 // store it in the custom path
107189 if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
107190 var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
107191 customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
107192 }
107193 if (dirPath === rootPath) {
107194 ts.Debug.assert(!nonRecursive);
107195 setAtRoot = true;
107196 }
107197 else {
107198 setDirectoryWatcher(dir, dirPath, nonRecursive);
107199 }
107200 }
107201 }
107202 if (setAtRoot) {
107203 // This is always non recursive
107204 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
107205 }
107206 }
107207 function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
107208 var program = resolutionHost.getCurrentProgram();
107209 if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
107210 resolutions.forEach(watchFailedLookupLocationOfResolution);
107211 }
107212 }
107213 function setDirectoryWatcher(dir, dirPath, nonRecursive) {
107214 var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
107215 if (dirWatcher) {
107216 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
107217 dirWatcher.refCount++;
107218 }
107219 else {
107220 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
107221 }
107222 }
107223 function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
107224 ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
107225 resolution.refCount--;
107226 if (resolution.refCount) {
107227 return;
107228 }
107229 var resolved = getResolutionWithResolvedFileName(resolution);
107230 if (resolved && resolved.resolvedFileName) {
107231 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
107232 }
107233 if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
107234 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
107235 return;
107236 }
107237 var failedLookupLocations = resolution.failedLookupLocations;
107238 var removeAtRoot = false;
107239 for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
107240 var failedLookupLocation = failedLookupLocations_2[_i];
107241 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
107242 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
107243 if (toWatch) {
107244 var dirPath = toWatch.dirPath;
107245 var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
107246 if (refCount) {
107247 if (refCount === 1) {
107248 customFailedLookupPaths.delete(failedLookupLocationPath);
107249 }
107250 else {
107251 ts.Debug.assert(refCount > 1);
107252 customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
107253 }
107254 }
107255 if (dirPath === rootPath) {
107256 removeAtRoot = true;
107257 }
107258 else {
107259 removeDirectoryWatcher(dirPath);
107260 }
107261 }
107262 }
107263 if (removeAtRoot) {
107264 removeDirectoryWatcher(rootPath);
107265 }
107266 }
107267 function removeDirectoryWatcher(dirPath) {
107268 var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
107269 // Do not close the watcher yet since it might be needed by other failed lookup locations.
107270 dirWatcher.refCount--;
107271 }
107272 function createDirectoryWatcher(directory, dirPath, nonRecursive) {
107273 return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
107274 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
107275 if (cachedDirectoryStructureHost) {
107276 // Since the file existence changed, update the sourceFiles cache
107277 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
107278 }
107279 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
107280 }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
107281 }
107282 function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
107283 // Deleted file, stop watching failed lookups for all the resolutions in the file
107284 var resolutions = cache.get(filePath);
107285 if (resolutions) {
107286 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
107287 cache.delete(filePath);
107288 }
107289 }
107290 function removeResolutionsFromProjectReferenceRedirects(filePath) {
107291 if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
107292 return;
107293 }
107294 var program = resolutionHost.getCurrentProgram();
107295 if (!program) {
107296 return;
107297 }
107298 // If this file is input file for the referenced project, get it
107299 var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
107300 if (!resolvedProjectReference) {
107301 return;
107302 }
107303 // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
107304 resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
107305 }
107306 function removeResolutionsOfFile(filePath) {
107307 removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
107308 removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
107309 }
107310 function invalidateResolutions(resolutions, canInvalidate) {
107311 if (!resolutions)
107312 return false;
107313 var invalidated = false;
107314 for (var _i = 0, resolutions_2 = resolutions; _i < resolutions_2.length; _i++) {
107315 var resolution = resolutions_2[_i];
107316 if (resolution.isInvalidated || !canInvalidate(resolution))
107317 continue;
107318 resolution.isInvalidated = invalidated = true;
107319 for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) {
107320 var containingFilePath = _b[_a];
107321 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath);
107322 // When its a file with inferred types resolution, invalidate type reference directive resolution
107323 hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile);
107324 }
107325 }
107326 return invalidated;
107327 }
107328 function invalidateResolutionOfFile(filePath) {
107329 removeResolutionsOfFile(filePath);
107330 // Resolution is invalidated if the resulting file name is same as the deleted file path
107331 var prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
107332 if (invalidateResolutions(resolvedFileToResolution.get(filePath), ts.returnTrue) &&
107333 hasChangedAutomaticTypeDirectiveNames &&
107334 !prevHasChangedAutomaticTypeDirectiveNames) {
107335 resolutionHost.onChangedAutomaticTypeDirectiveNames();
107336 }
107337 }
107338 function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
107339 ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
107340 filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
107341 }
107342 function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
107343 if (isCreatingWatchedDirectory) {
107344 // Watching directory is created
107345 // Invalidate any resolution has failed lookup in this directory
107346 isInDirectoryChecks.push(fileOrDirectoryPath);
107347 }
107348 else {
107349 // If something to do with folder/file starting with "." in node_modules folder, skip it
107350 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
107351 if (!updatedPath)
107352 return false;
107353 fileOrDirectoryPath = updatedPath;
107354 // prevent saving an open file from over-eagerly triggering invalidation
107355 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
107356 return false;
107357 }
107358 // Some file or directory in the watching directory is created
107359 // Return early if it does not have any of the watching extension or not the custom failed lookup path
107360 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
107361 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
107362 isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
107363 // Invalidate any resolution from this directory
107364 failedLookupChecks.push(fileOrDirectoryPath);
107365 startsWithPathChecks.push(fileOrDirectoryPath);
107366 }
107367 else {
107368 if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
107369 return false;
107370 }
107371 // Ignore emits from the program
107372 if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
107373 return false;
107374 }
107375 // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
107376 failedLookupChecks.push(fileOrDirectoryPath);
107377 }
107378 }
107379 resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
107380 }
107381 function invalidateResolutionsOfFailedLookupLocations() {
107382 if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) {
107383 return false;
107384 }
107385 var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution);
107386 failedLookupChecks.length = 0;
107387 startsWithPathChecks.length = 0;
107388 isInDirectoryChecks.length = 0;
107389 return invalidated;
107390 }
107391 function canInvalidateFailedLookupResolution(resolution) {
107392 return resolution.failedLookupLocations.some(function (location) {
107393 var locationPath = resolutionHost.toPath(location);
107394 return ts.contains(failedLookupChecks, locationPath) ||
107395 startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) ||
107396 isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); });
107397 });
107398 }
107399 function closeTypeRootsWatch() {
107400 ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
107401 }
107402 function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
107403 if (isInDirectoryPath(rootPath, typeRootPath)) {
107404 return rootPath;
107405 }
107406 var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
107407 return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
107408 }
107409 function createTypeRootsWatch(typeRootPath, typeRoot) {
107410 // Create new watch and recursive info
107411 return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
107412 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
107413 if (cachedDirectoryStructureHost) {
107414 // Since the file existence changed, update the sourceFiles cache
107415 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
107416 }
107417 // For now just recompile
107418 // We could potentially store more data here about whether it was/would be really be used or not
107419 // and with that determine to trigger compilation but for now this is enough
107420 hasChangedAutomaticTypeDirectiveNames = true;
107421 resolutionHost.onChangedAutomaticTypeDirectiveNames();
107422 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
107423 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
107424 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
107425 if (dirPath) {
107426 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
107427 }
107428 }, 1 /* Recursive */);
107429 }
107430 /**
107431 * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
107432 * To be called when compiler options change
107433 */
107434 function updateTypeRootsWatch() {
107435 var options = resolutionHost.getCompilationSettings();
107436 if (options.types) {
107437 // No need to do any watch since resolution cache is going to handle the failed lookups
107438 // for the types added by this
107439 closeTypeRootsWatch();
107440 return;
107441 }
107442 // we need to assume the directories exist to ensure that we can get all the type root directories that get included
107443 // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
107444 var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
107445 if (typeRoots) {
107446 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
107447 createNewValue: createTypeRootsWatch,
107448 onDeleteValue: ts.closeFileWatcher
107449 });
107450 }
107451 else {
107452 closeTypeRootsWatch();
107453 }
107454 }
107455 /**
107456 * Use this function to return if directory exists to get type roots to watch
107457 * If we return directory exists then only the paths will be added to type roots
107458 * Hence return true for all directories except root directories which are filtered from watching
107459 */
107460 function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
107461 var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
107462 var dirPath = resolutionHost.toPath(dir);
107463 return dirPath === rootPath || canWatchDirectory(dirPath);
107464 }
107465 }
107466 ts.createResolutionCache = createResolutionCache;
107467})(ts || (ts = {}));
107468// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
107469/* @internal */
107470var ts;
107471(function (ts) {
107472 var moduleSpecifiers;
107473 (function (moduleSpecifiers) {
107474 var RelativePreference;
107475 (function (RelativePreference) {
107476 RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
107477 RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
107478 RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
107479 })(RelativePreference || (RelativePreference = {}));
107480 // See UserPreferences#importPathEnding
107481 var Ending;
107482 (function (Ending) {
107483 Ending[Ending["Minimal"] = 0] = "Minimal";
107484 Ending[Ending["Index"] = 1] = "Index";
107485 Ending[Ending["JsExtension"] = 2] = "JsExtension";
107486 })(Ending || (Ending = {}));
107487 function getPreferences(_a, compilerOptions, importingSourceFile) {
107488 var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
107489 return {
107490 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
107491 ending: getEnding(),
107492 };
107493 function getEnding() {
107494 switch (importModuleSpecifierEnding) {
107495 case "minimal": return 0 /* Minimal */;
107496 case "index": return 1 /* Index */;
107497 case "js": return 2 /* JsExtension */;
107498 default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
107499 : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
107500 }
107501 }
107502 }
107503 function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
107504 return {
107505 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
107506 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
107507 2 /* JsExtension */ :
107508 ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
107509 };
107510 }
107511 function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
107512 var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
107513 if (res === oldImportSpecifier)
107514 return undefined;
107515 return res;
107516 }
107517 moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
107518 // Note: importingSourceFile is just for usesJsExtensionOnImports
107519 function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
107520 if (preferences === void 0) { preferences = {}; }
107521 return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
107522 }
107523 moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
107524 function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
107525 var info = getInfo(importingSourceFileName, host);
107526 var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
107527 return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
107528 }
107529 moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
107530 function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
107531 var info = getInfo(importingSourceFileName, host);
107532 var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
107533 return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
107534 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
107535 }
107536 /** Returns an import for each symlink and for the realpath. */
107537 function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
107538 var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
107539 if (ambient)
107540 return [ambient];
107541 var info = getInfo(importingSourceFile.path, host);
107542 var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
107543 var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
107544 var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
107545 var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
107546 return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
107547 }
107548 moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
107549 // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
107550 function getInfo(importingSourceFileName, host) {
107551 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
107552 var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
107553 return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
107554 }
107555 function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
107556 var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
107557 var ending = _b.ending, relativePreference = _b.relativePreference;
107558 var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
107559 var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
107560 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
107561 if (!baseUrl || relativePreference === 0 /* Relative */) {
107562 return relativePath;
107563 }
107564 var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
107565 if (!relativeToBaseUrl) {
107566 return relativePath;
107567 }
107568 var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
107569 var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
107570 var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
107571 if (relativePreference === 1 /* NonRelative */) {
107572 return nonRelative;
107573 }
107574 if (relativePreference !== 2 /* Auto */)
107575 ts.Debug.assertNever(relativePreference);
107576 // Prefer a relative import over a baseUrl import if it has fewer components.
107577 return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
107578 }
107579 function countPathComponents(path) {
107580 var count = 0;
107581 for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
107582 if (path.charCodeAt(i) === 47 /* slash */)
107583 count++;
107584 }
107585 return count;
107586 }
107587 moduleSpecifiers.countPathComponents = countPathComponents;
107588 function usesJsExtensionOnImports(_a) {
107589 var imports = _a.imports;
107590 return ts.firstDefined(imports, function (_a) {
107591 var text = _a.text;
107592 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
107593 }) || false;
107594 }
107595 function numberOfDirectorySeparators(str) {
107596 var match = str.match(/\//g);
107597 return match ? match.length : 0;
107598 }
107599 function comparePathsByNumberOfDirectorySeparators(a, b) {
107600 return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
107601 }
107602 function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
107603 var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
107604 var cwd = host.getCurrentDirectory();
107605 var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
107606 var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
107607 var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
107608 var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
107609 if (!preferSymlinks) {
107610 var result_13 = ts.forEach(targets, cb);
107611 if (result_13)
107612 return result_13;
107613 }
107614 var links = host.getSymlinkCache
107615 ? host.getSymlinkCache()
107616 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
107617 var symlinkedDirectories = links.getSymlinkedDirectories();
107618 var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
107619 var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) {
107620 if (resolved === false)
107621 return undefined;
107622 if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) {
107623 return undefined; // Don't want to a package to globally import from itself
107624 }
107625 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.real.length), resolved.real) === 0 /* EqualTo */; });
107626 if (target === undefined)
107627 return undefined;
107628 var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName);
107629 var option = ts.resolvePath(path, relative);
107630 if (!host.fileExists || host.fileExists(option)) {
107631 var result_14 = cb(option);
107632 if (result_14)
107633 return result_14;
107634 }
107635 });
107636 return result ||
107637 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
107638 }
107639 moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
107640 /**
107641 * Looks for existing imports that use symlinks to this module.
107642 * Symlinks will be returned first so they are preferred over the real path.
107643 */
107644 function getAllModulePaths(importingFileName, importedFileName, host) {
107645 var cwd = host.getCurrentDirectory();
107646 var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
107647 var allFileNames = new ts.Map();
107648 var importedFileFromNodeModules = false;
107649 forEachFileNameOfModule(importingFileName, importedFileName, host,
107650 /*preferSymlinks*/ true, function (path) {
107651 // dont return value, so we collect everything
107652 allFileNames.set(path, getCanonicalFileName(path));
107653 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
107654 });
107655 // Sort by paths closest to importing file Name directory
107656 var sortedPaths = [];
107657 var _loop_23 = function (directory) {
107658 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
107659 var pathsInDirectory;
107660 allFileNames.forEach(function (canonicalFileName, fileName) {
107661 if (ts.startsWith(canonicalFileName, directoryStart)) {
107662 // If the importedFile is from node modules, use only paths in node_modules folder as option
107663 if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
107664 (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
107665 }
107666 allFileNames.delete(fileName);
107667 }
107668 });
107669 if (pathsInDirectory) {
107670 if (pathsInDirectory.length > 1) {
107671 pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
107672 }
107673 sortedPaths.push.apply(sortedPaths, pathsInDirectory);
107674 }
107675 var newDirectory = ts.getDirectoryPath(directory);
107676 if (newDirectory === directory)
107677 return out_directory_1 = directory, "break";
107678 directory = newDirectory;
107679 out_directory_1 = directory;
107680 };
107681 var out_directory_1;
107682 for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
107683 var state_8 = _loop_23(directory);
107684 directory = out_directory_1;
107685 if (state_8 === "break")
107686 break;
107687 }
107688 if (allFileNames.size) {
107689 var remainingPaths = ts.arrayFrom(allFileNames.values());
107690 if (remainingPaths.length > 1)
107691 remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
107692 sortedPaths.push.apply(sortedPaths, remainingPaths);
107693 }
107694 return sortedPaths;
107695 }
107696 function tryGetModuleNameFromAmbientModule(moduleSymbol) {
107697 var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
107698 if (decl) {
107699 return decl.name.text;
107700 }
107701 }
107702 function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
107703 for (var key in paths) {
107704 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
107705 var patternText_1 = _a[_i];
107706 var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
107707 var indexOfStar = pattern.indexOf("*");
107708 if (indexOfStar !== -1) {
107709 var prefix = pattern.substr(0, indexOfStar);
107710 var suffix = pattern.substr(indexOfStar + 1);
107711 if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
107712 ts.startsWith(relativeToBaseUrl, prefix) &&
107713 ts.endsWith(relativeToBaseUrl, suffix) ||
107714 !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
107715 var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
107716 return key.replace("*", matchedStar);
107717 }
107718 }
107719 else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
107720 return key;
107721 }
107722 }
107723 }
107724 }
107725 function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
107726 var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
107727 if (normalizedTargetPath === undefined) {
107728 return undefined;
107729 }
107730 var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
107731 var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
107732 return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
107733 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
107734 : ts.removeFileExtension(relativePath);
107735 }
107736 function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
107737 var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
107738 if (!host.fileExists || !host.readFile) {
107739 return undefined;
107740 }
107741 var parts = getNodeModulePathParts(moduleFileName);
107742 if (!parts) {
107743 return undefined;
107744 }
107745 // Simplify the full file path to something that can be resolved by Node.
107746 var moduleSpecifier = moduleFileName;
107747 if (!packageNameOnly) {
107748 var packageRootIndex = parts.packageRootIndex;
107749 var moduleFileNameForExtensionless = void 0;
107750 while (true) {
107751 // If the module could be imported by a directory name, use that directory's name
107752 var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
107753 if (packageRootPath) {
107754 moduleSpecifier = packageRootPath;
107755 break;
107756 }
107757 if (!moduleFileNameForExtensionless)
107758 moduleFileNameForExtensionless = moduleFileToTry;
107759 // try with next level of directory
107760 packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
107761 if (packageRootIndex === -1) {
107762 moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
107763 break;
107764 }
107765 }
107766 }
107767 var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
107768 // Get a path that's relative to node_modules or the importing file's path
107769 // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
107770 var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
107771 if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
107772 return undefined;
107773 }
107774 // If the module was found in @types, get the actual Node package name
107775 var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
107776 var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
107777 // For classic resolution, only allow importing from node_modules/@types, not other node_modules
107778 return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
107779 function tryDirectoryWithPackageJson(packageRootIndex) {
107780 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
107781 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
107782 var moduleFileToTry = moduleFileName;
107783 if (host.fileExists(packageJsonPath)) {
107784 var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
107785 var versionPaths = packageJsonContent.typesVersions
107786 ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
107787 : undefined;
107788 if (versionPaths) {
107789 var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
107790 var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
107791 if (fromPaths !== undefined) {
107792 moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
107793 }
107794 }
107795 // If the file is the main module, it can be imported by the package name
107796 var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
107797 if (ts.isString(mainFileRelative)) {
107798 var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
107799 if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
107800 return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
107801 }
107802 }
107803 }
107804 return { moduleFileToTry: moduleFileToTry };
107805 }
107806 function getExtensionlessFileName(path) {
107807 // We still have a file name - remove the extension
107808 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
107809 // If the file is /index, it can be imported by its directory name
107810 // IFF there is not _also_ a file by the same name
107811 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
107812 return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
107813 }
107814 return fullModulePathWithoutExtension;
107815 }
107816 }
107817 function tryGetAnyFileFromPath(host, path) {
107818 if (!host.fileExists)
107819 return;
107820 // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
107821 var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
107822 for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
107823 var e = extensions_3[_i];
107824 var fullPath = path + e;
107825 if (host.fileExists(fullPath)) {
107826 return fullPath;
107827 }
107828 }
107829 }
107830 function getNodeModulePathParts(fullPath) {
107831 // If fullPath can't be valid module file within node_modules, returns undefined.
107832 // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
107833 // Returns indices: ^ ^ ^ ^
107834 var topLevelNodeModulesIndex = 0;
107835 var topLevelPackageNameIndex = 0;
107836 var packageRootIndex = 0;
107837 var fileNameIndex = 0;
107838 var States;
107839 (function (States) {
107840 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
107841 States[States["NodeModules"] = 1] = "NodeModules";
107842 States[States["Scope"] = 2] = "Scope";
107843 States[States["PackageContent"] = 3] = "PackageContent";
107844 })(States || (States = {}));
107845 var partStart = 0;
107846 var partEnd = 0;
107847 var state = 0 /* BeforeNodeModules */;
107848 while (partEnd >= 0) {
107849 partStart = partEnd;
107850 partEnd = fullPath.indexOf("/", partStart + 1);
107851 switch (state) {
107852 case 0 /* BeforeNodeModules */:
107853 if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
107854 topLevelNodeModulesIndex = partStart;
107855 topLevelPackageNameIndex = partEnd;
107856 state = 1 /* NodeModules */;
107857 }
107858 break;
107859 case 1 /* NodeModules */:
107860 case 2 /* Scope */:
107861 if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
107862 state = 2 /* Scope */;
107863 }
107864 else {
107865 packageRootIndex = partEnd;
107866 state = 3 /* PackageContent */;
107867 }
107868 break;
107869 case 3 /* PackageContent */:
107870 if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
107871 state = 1 /* NodeModules */;
107872 }
107873 else {
107874 state = 3 /* PackageContent */;
107875 }
107876 break;
107877 }
107878 }
107879 fileNameIndex = partStart;
107880 return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
107881 }
107882 function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
107883 return ts.firstDefined(rootDirs, function (rootDir) {
107884 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
107885 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
107886 });
107887 }
107888 function removeExtensionAndIndexPostFix(fileName, ending, options) {
107889 if (ts.fileExtensionIs(fileName, ".json" /* Json */))
107890 return fileName;
107891 var noExtension = ts.removeFileExtension(fileName);
107892 switch (ending) {
107893 case 0 /* Minimal */:
107894 return ts.removeSuffix(noExtension, "/index");
107895 case 1 /* Index */:
107896 return noExtension;
107897 case 2 /* JsExtension */:
107898 return noExtension + getJSExtensionForFile(fileName, options);
107899 default:
107900 return ts.Debug.assertNever(ending);
107901 }
107902 }
107903 function getJSExtensionForFile(fileName, options) {
107904 var ext = ts.extensionFromPath(fileName);
107905 switch (ext) {
107906 case ".ts" /* Ts */:
107907 case ".d.ts" /* Dts */:
107908 return ".js" /* Js */;
107909 case ".tsx" /* Tsx */:
107910 return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
107911 case ".js" /* Js */:
107912 case ".jsx" /* Jsx */:
107913 case ".json" /* Json */:
107914 return ext;
107915 case ".tsbuildinfo" /* TsBuildInfo */:
107916 return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
107917 default:
107918 return ts.Debug.assertNever(ext);
107919 }
107920 }
107921 function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
107922 var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
107923 return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
107924 }
107925 function isPathRelativeToParent(path) {
107926 return ts.startsWith(path, "..");
107927 }
107928 })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
107929})(ts || (ts = {}));
107930/*@internal*/
107931var ts;
107932(function (ts) {
107933 var sysFormatDiagnosticsHost = ts.sys ? {
107934 getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
107935 getNewLine: function () { return ts.sys.newLine; },
107936 getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
107937 } : undefined; // TODO: GH#18217
107938 /**
107939 * Create a function that reports error by writing to the system and handles the formating of the diagnostic
107940 */
107941 function createDiagnosticReporter(system, pretty) {
107942 var host = system === ts.sys ? sysFormatDiagnosticsHost : {
107943 getCurrentDirectory: function () { return system.getCurrentDirectory(); },
107944 getNewLine: function () { return system.newLine; },
107945 getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
107946 };
107947 if (!pretty) {
107948 return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
107949 }
107950 var diagnostics = new Array(1);
107951 return function (diagnostic) {
107952 diagnostics[0] = diagnostic;
107953 system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
107954 diagnostics[0] = undefined; // TODO: GH#18217
107955 };
107956 }
107957 ts.createDiagnosticReporter = createDiagnosticReporter;
107958 /**
107959 * @returns Whether the screen was cleared.
107960 */
107961 function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
107962 if (system.clearScreen &&
107963 !options.preserveWatchOutput &&
107964 !options.extendedDiagnostics &&
107965 !options.diagnostics &&
107966 ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
107967 system.clearScreen();
107968 return true;
107969 }
107970 return false;
107971 }
107972 ts.screenStartingMessageCodes = [
107973 ts.Diagnostics.Starting_compilation_in_watch_mode.code,
107974 ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
107975 ];
107976 function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
107977 return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
107978 ? newLine + newLine
107979 : newLine;
107980 }
107981 /**
107982 * Get locale specific time based on whether we are in test mode
107983 */
107984 function getLocaleTimeString(system) {
107985 return !system.now ?
107986 new Date().toLocaleTimeString() :
107987 system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
107988 }
107989 ts.getLocaleTimeString = getLocaleTimeString;
107990 /**
107991 * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
107992 */
107993 function createWatchStatusReporter(system, pretty) {
107994 return pretty ?
107995 function (diagnostic, newLine, options) {
107996 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
107997 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
107998 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
107999 system.write(output);
108000 } :
108001 function (diagnostic, newLine, options) {
108002 var output = "";
108003 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
108004 output += newLine;
108005 }
108006 output += getLocaleTimeString(system) + " - ";
108007 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
108008 system.write(output);
108009 };
108010 }
108011 ts.createWatchStatusReporter = createWatchStatusReporter;
108012 /** Parses config file using System interface */
108013 function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
108014 var host = system;
108015 host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
108016 var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
108017 host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
108018 return result;
108019 }
108020 ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
108021 function getErrorCountForSummary(diagnostics) {
108022 return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
108023 }
108024 ts.getErrorCountForSummary = getErrorCountForSummary;
108025 function getWatchErrorSummaryDiagnosticMessage(errorCount) {
108026 return errorCount === 1 ?
108027 ts.Diagnostics.Found_1_error_Watching_for_file_changes :
108028 ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
108029 }
108030 ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
108031 function getErrorSummaryText(errorCount, newLine) {
108032 if (errorCount === 0)
108033 return "";
108034 var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
108035 return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
108036 }
108037 ts.getErrorSummaryText = getErrorSummaryText;
108038 function listFiles(program, writeFileName) {
108039 if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
108040 ts.forEach(program.getSourceFiles(), function (file) {
108041 writeFileName(file.fileName);
108042 });
108043 }
108044 }
108045 ts.listFiles = listFiles;
108046 /**
108047 * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
108048 */
108049 function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108050 var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
108051 // First get and report any syntactic errors.
108052 var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
108053 var configFileParsingDiagnosticsLength = allDiagnostics.length;
108054 ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
108055 // If we didn't have any syntactic errors, then also try getting the global and
108056 // semantic errors.
108057 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
108058 ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
108059 if (!isListFilesOnly) {
108060 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
108061 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
108062 ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
108063 }
108064 }
108065 }
108066 // Emit and report any errors we ran into.
108067 var emitResult = isListFilesOnly
108068 ? { emitSkipped: true, diagnostics: ts.emptyArray }
108069 : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
108070 var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
108071 ts.addRange(allDiagnostics, emitDiagnostics);
108072 var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
108073 diagnostics.forEach(reportDiagnostic);
108074 if (writeFileName) {
108075 var currentDir_1 = program.getCurrentDirectory();
108076 ts.forEach(emittedFiles, function (file) {
108077 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
108078 writeFileName("TSFILE: " + filepath);
108079 });
108080 listFiles(program, writeFileName);
108081 }
108082 if (reportSummary) {
108083 reportSummary(getErrorCountForSummary(diagnostics));
108084 }
108085 return {
108086 emitResult: emitResult,
108087 diagnostics: diagnostics,
108088 };
108089 }
108090 ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
108091 function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108092 var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
108093 if (emitResult.emitSkipped && diagnostics.length > 0) {
108094 // If the emitter didn't emit anything, then pass that value along.
108095 return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
108096 }
108097 else if (diagnostics.length > 0) {
108098 // The emitter emitted something, inform the caller if that happened in the presence
108099 // of diagnostics or not.
108100 return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
108101 }
108102 return ts.ExitStatus.Success;
108103 }
108104 ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
108105 ts.noopFileWatcher = { close: ts.noop };
108106 ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
108107 function createWatchHost(system, reportWatchStatus) {
108108 if (system === void 0) { system = ts.sys; }
108109 var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
108110 return {
108111 onWatchStatusChange: onWatchStatusChange,
108112 watchFile: ts.maybeBind(system, system.watchFile) || ts.returnNoopFileWatcher,
108113 watchDirectory: ts.maybeBind(system, system.watchDirectory) || ts.returnNoopFileWatcher,
108114 setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
108115 clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
108116 };
108117 }
108118 ts.createWatchHost = createWatchHost;
108119 ts.WatchType = {
108120 ConfigFile: "Config file",
108121 SourceFile: "Source file",
108122 MissingFile: "Missing file",
108123 WildcardDirectory: "Wild card directory",
108124 FailedLookupLocations: "Failed Lookup Locations",
108125 TypeRoots: "Type roots"
108126 };
108127 function createWatchFactory(host, options) {
108128 var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
108129 var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
108130 var result = ts.getWatchFactory(watchLogLevel, writeLog);
108131 result.writeLog = writeLog;
108132 return result;
108133 }
108134 ts.createWatchFactory = createWatchFactory;
108135 function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
108136 if (directoryStructureHost === void 0) { directoryStructureHost = host; }
108137 var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
108138 var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
108139 return {
108140 getSourceFile: function (fileName, languageVersion, onError) {
108141 var text;
108142 try {
108143 ts.performance.mark("beforeIORead");
108144 text = host.readFile(fileName, getCompilerOptions().charset);
108145 ts.performance.mark("afterIORead");
108146 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
108147 }
108148 catch (e) {
108149 if (onError) {
108150 onError(e.message);
108151 }
108152 text = "";
108153 }
108154 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
108155 },
108156 getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
108157 getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
108158 writeFile: writeFile,
108159 getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
108160 useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
108161 getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
108162 getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
108163 fileExists: function (f) { return host.fileExists(f); },
108164 readFile: function (f) { return host.readFile(f); },
108165 trace: ts.maybeBind(host, host.trace),
108166 directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
108167 getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
108168 realpath: ts.maybeBind(host, host.realpath),
108169 getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
108170 createHash: ts.maybeBind(host, host.createHash),
108171 readDirectory: ts.maybeBind(host, host.readDirectory),
108172 };
108173 function writeFile(fileName, text, writeByteOrderMark, onError) {
108174 try {
108175 ts.performance.mark("beforeIOWrite");
108176 // NOTE: If patchWriteFileEnsuringDirectory has been called,
108177 // the host.writeFile will do its own directory creation and
108178 // the ensureDirectoriesExist call will always be redundant.
108179 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); });
108180 ts.performance.mark("afterIOWrite");
108181 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
108182 }
108183 catch (e) {
108184 if (onError) {
108185 onError(e.message);
108186 }
108187 }
108188 }
108189 }
108190 ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
108191 function setGetSourceFileAsHashVersioned(compilerHost, host) {
108192 var originalGetSourceFile = compilerHost.getSourceFile;
108193 var computeHash = host.createHash || ts.generateDjb2Hash;
108194 compilerHost.getSourceFile = function () {
108195 var args = [];
108196 for (var _i = 0; _i < arguments.length; _i++) {
108197 args[_i] = arguments[_i];
108198 }
108199 var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
108200 if (result) {
108201 result.version = computeHash.call(host, result.text);
108202 }
108203 return result;
108204 };
108205 }
108206 ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
108207 /**
108208 * Creates the watch compiler host that can be extended with config file or root file names and options host
108209 */
108210 function createProgramHost(system, createProgram) {
108211 var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
108212 return {
108213 useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
108214 getNewLine: function () { return system.newLine; },
108215 getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
108216 getDefaultLibLocation: getDefaultLibLocation,
108217 getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
108218 fileExists: function (path) { return system.fileExists(path); },
108219 readFile: function (path, encoding) { return system.readFile(path, encoding); },
108220 directoryExists: function (path) { return system.directoryExists(path); },
108221 getDirectories: function (path) { return system.getDirectories(path); },
108222 readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
108223 realpath: ts.maybeBind(system, system.realpath),
108224 getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
108225 trace: function (s) { return system.write(s + system.newLine); },
108226 createDirectory: function (path) { return system.createDirectory(path); },
108227 writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
108228 createHash: ts.maybeBind(system, system.createHash),
108229 createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
108230 };
108231 }
108232 ts.createProgramHost = createProgramHost;
108233 /**
108234 * Creates the watch compiler host that can be extended with config file or root file names and options host
108235 */
108236 function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
108237 if (system === void 0) { system = ts.sys; }
108238 var writeFileName = function (s) { return system.write(s + system.newLine); };
108239 var result = createProgramHost(system, createProgram);
108240 ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
108241 result.afterProgramCreate = function (builderProgram) {
108242 var compilerOptions = builderProgram.getCompilerOptions();
108243 var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
108244 emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
108245 };
108246 return result;
108247 }
108248 /**
108249 * Report error and exit
108250 */
108251 function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
108252 reportDiagnostic(diagnostic);
108253 system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
108254 }
108255 /**
108256 * Creates the watch compiler host from system for config file in watch mode
108257 */
108258 function createWatchCompilerHostOfConfigFile(_a) {
108259 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;
108260 var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
108261 var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
108262 host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
108263 host.configFileName = configFileName;
108264 host.optionsToExtend = optionsToExtend;
108265 host.watchOptionsToExtend = watchOptionsToExtend;
108266 host.extraFileExtensions = extraFileExtensions;
108267 return host;
108268 }
108269 ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
108270 /**
108271 * Creates the watch compiler host from system for compiling root files and options in watch mode
108272 */
108273 function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
108274 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;
108275 var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
108276 host.rootFiles = rootFiles;
108277 host.options = options;
108278 host.watchOptions = watchOptions;
108279 host.projectReferences = projectReferences;
108280 return host;
108281 }
108282 ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
108283 function performIncrementalCompilation(input) {
108284 var system = input.system || ts.sys;
108285 var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
108286 var builderProgram = ts.createIncrementalProgram(input);
108287 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);
108288 if (input.afterProgramEmitAndDiagnostics)
108289 input.afterProgramEmitAndDiagnostics(builderProgram);
108290 return exitStatus;
108291 }
108292 ts.performIncrementalCompilation = performIncrementalCompilation;
108293})(ts || (ts = {}));
108294var ts;
108295(function (ts) {
108296 function readBuilderProgram(compilerOptions, host) {
108297 if (ts.outFile(compilerOptions))
108298 return undefined;
108299 var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
108300 if (!buildInfoPath)
108301 return undefined;
108302 var content = host.readFile(buildInfoPath);
108303 if (!content)
108304 return undefined;
108305 var buildInfo = ts.getBuildInfo(content);
108306 if (buildInfo.version !== ts.version)
108307 return undefined;
108308 if (!buildInfo.program)
108309 return undefined;
108310 return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
108311 }
108312 ts.readBuilderProgram = readBuilderProgram;
108313 function createIncrementalCompilerHost(options, system) {
108314 if (system === void 0) { system = ts.sys; }
108315 var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
108316 host.createHash = ts.maybeBind(system, system.createHash);
108317 ts.setGetSourceFileAsHashVersioned(host, system);
108318 ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
108319 return host;
108320 }
108321 ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
108322 function createIncrementalProgram(_a) {
108323 var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
108324 host = host || createIncrementalCompilerHost(options);
108325 createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
108326 var oldProgram = readBuilderProgram(options, host);
108327 return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
108328 }
108329 ts.createIncrementalProgram = createIncrementalProgram;
108330 function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
108331 if (ts.isArray(rootFilesOrConfigFileName)) {
108332 return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
108333 rootFiles: rootFilesOrConfigFileName,
108334 options: options,
108335 watchOptions: watchOptionsOrExtraFileExtensions,
108336 projectReferences: projectReferencesOrWatchOptionsToExtend,
108337 system: system,
108338 createProgram: createProgram,
108339 reportDiagnostic: reportDiagnostic,
108340 reportWatchStatus: reportWatchStatus,
108341 });
108342 }
108343 else {
108344 return ts.createWatchCompilerHostOfConfigFile({
108345 configFileName: rootFilesOrConfigFileName,
108346 optionsToExtend: options,
108347 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
108348 extraFileExtensions: watchOptionsOrExtraFileExtensions,
108349 system: system,
108350 createProgram: createProgram,
108351 reportDiagnostic: reportDiagnostic,
108352 reportWatchStatus: reportWatchStatus,
108353 });
108354 }
108355 }
108356 ts.createWatchCompilerHost = createWatchCompilerHost;
108357 function createWatchProgram(host) {
108358 var builderProgram;
108359 var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
108360 var missingFilesMap; // Map of file watchers for the missing files
108361 var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
108362 var timerToUpdateProgram; // timer callback to recompile the program
108363 var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
108364 var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
108365 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
108366 var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
108367 var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
108368 var currentDirectory = host.getCurrentDirectory();
108369 var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
108370 var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
108371 var configFileSpecs;
108372 var configFileParsingDiagnostics;
108373 var canConfigFileJsonReportNoInputFiles = false;
108374 var hasChangedConfigFileParsingErrors = false;
108375 var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
108376 var directoryStructureHost = cachedDirectoryStructureHost || host;
108377 var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
108378 // From tsc we want to get already parsed result and hence check for rootFileNames
108379 var newLine = updateNewLine();
108380 if (configFileName && host.configFileParsingResult) {
108381 setConfigFileParsingResult(host.configFileParsingResult);
108382 newLine = updateNewLine();
108383 }
108384 reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
108385 if (configFileName && !host.configFileParsingResult) {
108386 newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
108387 ts.Debug.assert(!rootFileNames);
108388 parseConfigFile();
108389 newLine = updateNewLine();
108390 }
108391 var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
108392 var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
108393 writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
108394 var configFileWatcher;
108395 if (configFileName) {
108396 configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
108397 }
108398 var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
108399 ts.setGetSourceFileAsHashVersioned(compilerHost, host);
108400 // Members for CompilerHost
108401 var getNewSourceFile = compilerHost.getSourceFile;
108402 compilerHost.getSourceFile = function (fileName) {
108403 var args = [];
108404 for (var _i = 1; _i < arguments.length; _i++) {
108405 args[_i - 1] = arguments[_i];
108406 }
108407 return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
108408 };
108409 compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
108410 compilerHost.getNewLine = function () { return newLine; };
108411 compilerHost.fileExists = fileExists;
108412 compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
108413 // Members for ResolutionCacheHost
108414 compilerHost.toPath = toPath;
108415 compilerHost.getCompilationSettings = function () { return compilerOptions; };
108416 compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
108417 compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
108418 compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
108419 compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
108420 compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
108421 compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
108422 compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
108423 compilerHost.fileIsOpen = ts.returnFalse;
108424 compilerHost.getCurrentProgram = getCurrentProgram;
108425 compilerHost.writeLog = writeLog;
108426 // Cache for the module resolution
108427 var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
108428 ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
108429 currentDirectory,
108430 /*logChangesWhenResolvingModule*/ false);
108431 // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
108432 compilerHost.resolveModuleNames = host.resolveModuleNames ?
108433 (function () {
108434 var args = [];
108435 for (var _i = 0; _i < arguments.length; _i++) {
108436 args[_i] = arguments[_i];
108437 }
108438 return host.resolveModuleNames.apply(host, args);
108439 }) :
108440 (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
108441 compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
108442 (function () {
108443 var args = [];
108444 for (var _i = 0; _i < arguments.length; _i++) {
108445 args[_i] = arguments[_i];
108446 }
108447 return host.resolveTypeReferenceDirectives.apply(host, args);
108448 }) :
108449 (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
108450 var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
108451 builderProgram = readBuilderProgram(compilerOptions, compilerHost);
108452 synchronizeProgram();
108453 // Update the wild card directory watch
108454 watchConfigFileWildCardDirectories();
108455 return configFileName ?
108456 { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
108457 { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
108458 function close() {
108459 clearInvalidateResolutionsOfFailedLookupLocations();
108460 resolutionCache.clear();
108461 ts.clearMap(sourceFilesCache, function (value) {
108462 if (value && value.fileWatcher) {
108463 value.fileWatcher.close();
108464 value.fileWatcher = undefined;
108465 }
108466 });
108467 if (configFileWatcher) {
108468 configFileWatcher.close();
108469 configFileWatcher = undefined;
108470 }
108471 if (watchedWildcardDirectories) {
108472 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
108473 watchedWildcardDirectories = undefined;
108474 }
108475 if (missingFilesMap) {
108476 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
108477 missingFilesMap = undefined;
108478 }
108479 }
108480 function getCurrentBuilderProgram() {
108481 return builderProgram;
108482 }
108483 function getCurrentProgram() {
108484 return builderProgram && builderProgram.getProgramOrUndefined();
108485 }
108486 function synchronizeProgram() {
108487 writeLog("Synchronizing program");
108488 clearInvalidateResolutionsOfFailedLookupLocations();
108489 var program = getCurrentBuilderProgram();
108490 if (hasChangedCompilerOptions) {
108491 newLine = updateNewLine();
108492 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
108493 resolutionCache.clear();
108494 }
108495 }
108496 // All resolutions are invalid if user provided resolutions
108497 var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
108498 if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
108499 if (hasChangedConfigFileParsingErrors) {
108500 builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
108501 hasChangedConfigFileParsingErrors = false;
108502 }
108503 }
108504 else {
108505 createNewProgram(hasInvalidatedResolution);
108506 }
108507 if (host.afterProgramCreate && program !== builderProgram) {
108508 host.afterProgramCreate(builderProgram);
108509 }
108510 return builderProgram;
108511 }
108512 function createNewProgram(hasInvalidatedResolution) {
108513 // Compile the program
108514 writeLog("CreatingProgramWith::");
108515 writeLog(" roots: " + JSON.stringify(rootFileNames));
108516 writeLog(" options: " + JSON.stringify(compilerOptions));
108517 var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
108518 hasChangedCompilerOptions = false;
108519 hasChangedConfigFileParsingErrors = false;
108520 resolutionCache.startCachingPerDirectoryResolution();
108521 compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
108522 compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
108523 builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
108524 resolutionCache.finishCachingPerDirectoryResolution();
108525 // Update watches
108526 ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
108527 if (needsUpdateInTypeRootWatch) {
108528 resolutionCache.updateTypeRootsWatch();
108529 }
108530 if (missingFilePathsRequestedForRelease) {
108531 // These are the paths that program creater told us as not in use any more but were missing on the disk.
108532 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
108533 // if there is already watcher for it (for missing files)
108534 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
108535 // so that at later time we have correct result of their presence
108536 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
108537 var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
108538 if (!missingFilesMap.has(missingFilePath)) {
108539 sourceFilesCache.delete(missingFilePath);
108540 }
108541 }
108542 missingFilePathsRequestedForRelease = undefined;
108543 }
108544 }
108545 function updateRootFileNames(files) {
108546 ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
108547 rootFileNames = files;
108548 scheduleProgramUpdate();
108549 }
108550 function updateNewLine() {
108551 return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
108552 }
108553 function toPath(fileName) {
108554 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
108555 }
108556 function isFileMissingOnHost(hostSourceFile) {
108557 return typeof hostSourceFile === "boolean";
108558 }
108559 function isFilePresenceUnknownOnHost(hostSourceFile) {
108560 return typeof hostSourceFile.version === "boolean";
108561 }
108562 function fileExists(fileName) {
108563 var path = toPath(fileName);
108564 // If file is missing on host from cache, we can definitely say file doesnt exist
108565 // otherwise we need to ensure from the disk
108566 if (isFileMissingOnHost(sourceFilesCache.get(path))) {
108567 return false;
108568 }
108569 return directoryStructureHost.fileExists(fileName);
108570 }
108571 function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
108572 var hostSourceFile = sourceFilesCache.get(path);
108573 // No source file on the host
108574 if (isFileMissingOnHost(hostSourceFile)) {
108575 return undefined;
108576 }
108577 // Create new source file if requested or the versions dont match
108578 if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
108579 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
108580 if (hostSourceFile) {
108581 if (sourceFile) {
108582 // Set the source file and create file watcher now that file was present on the disk
108583 hostSourceFile.sourceFile = sourceFile;
108584 hostSourceFile.version = sourceFile.version;
108585 if (!hostSourceFile.fileWatcher) {
108586 hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
108587 }
108588 }
108589 else {
108590 // There is no source file on host any more, close the watch, missing file paths will track it
108591 if (hostSourceFile.fileWatcher) {
108592 hostSourceFile.fileWatcher.close();
108593 }
108594 sourceFilesCache.set(path, false);
108595 }
108596 }
108597 else {
108598 if (sourceFile) {
108599 var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
108600 sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
108601 }
108602 else {
108603 sourceFilesCache.set(path, false);
108604 }
108605 }
108606 return sourceFile;
108607 }
108608 return hostSourceFile.sourceFile;
108609 }
108610 function nextSourceFileVersion(path) {
108611 var hostSourceFile = sourceFilesCache.get(path);
108612 if (hostSourceFile !== undefined) {
108613 if (isFileMissingOnHost(hostSourceFile)) {
108614 // The next version, lets set it as presence unknown file
108615 sourceFilesCache.set(path, { version: false });
108616 }
108617 else {
108618 hostSourceFile.version = false;
108619 }
108620 }
108621 }
108622 function getSourceVersion(path) {
108623 var hostSourceFile = sourceFilesCache.get(path);
108624 return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
108625 }
108626 function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
108627 var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
108628 // If this is the source file thats in the cache and new program doesnt need it,
108629 // remove the cached entry.
108630 // Note we arent deleting entry if file became missing in new program or
108631 // there was version update and new source file was created.
108632 if (hostSourceFileInfo !== undefined) {
108633 // record the missing file paths so they can be removed later if watchers arent tracking them
108634 if (isFileMissingOnHost(hostSourceFileInfo)) {
108635 (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
108636 }
108637 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
108638 if (hostSourceFileInfo.fileWatcher) {
108639 hostSourceFileInfo.fileWatcher.close();
108640 }
108641 sourceFilesCache.delete(oldSourceFile.resolvedPath);
108642 if (!hasSourceFileByPath) {
108643 resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
108644 }
108645 }
108646 }
108647 }
108648 function reportWatchDiagnostic(message) {
108649 if (host.onWatchStatusChange) {
108650 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
108651 }
108652 }
108653 function hasChangedAutomaticTypeDirectiveNames() {
108654 return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
108655 }
108656 function clearInvalidateResolutionsOfFailedLookupLocations() {
108657 if (!timerToInvalidateFailedLookupResolutions)
108658 return false;
108659 host.clearTimeout(timerToInvalidateFailedLookupResolutions);
108660 timerToInvalidateFailedLookupResolutions = undefined;
108661 return true;
108662 }
108663 function scheduleInvalidateResolutionsOfFailedLookupLocations() {
108664 if (!host.setTimeout || !host.clearTimeout) {
108665 return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
108666 }
108667 var pending = clearInvalidateResolutionsOfFailedLookupLocations();
108668 writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled earlier one" : ""));
108669 timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
108670 }
108671 function invalidateResolutionsOfFailedLookup() {
108672 timerToInvalidateFailedLookupResolutions = undefined;
108673 if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
108674 scheduleProgramUpdate();
108675 }
108676 }
108677 // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
108678 // operations (such as saving all modified files in an editor) a chance to complete before we kick
108679 // off a new compilation.
108680 function scheduleProgramUpdate() {
108681 if (!host.setTimeout || !host.clearTimeout) {
108682 return;
108683 }
108684 if (timerToUpdateProgram) {
108685 host.clearTimeout(timerToUpdateProgram);
108686 }
108687 writeLog("Scheduling update");
108688 timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
108689 }
108690 function scheduleProgramReload() {
108691 ts.Debug.assert(!!configFileName);
108692 reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
108693 scheduleProgramUpdate();
108694 }
108695 function updateProgramWithWatchStatus() {
108696 timerToUpdateProgram = undefined;
108697 reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
108698 updateProgram();
108699 }
108700 function updateProgram() {
108701 switch (reloadLevel) {
108702 case ts.ConfigFileProgramReloadLevel.Partial:
108703 ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
108704 reloadFileNamesFromConfigFile();
108705 break;
108706 case ts.ConfigFileProgramReloadLevel.Full:
108707 ts.perfLogger.logStartUpdateProgram("FullConfigReload");
108708 reloadConfigFile();
108709 break;
108710 default:
108711 ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
108712 synchronizeProgram();
108713 break;
108714 }
108715 ts.perfLogger.logStopUpdateProgram("Done");
108716 return getCurrentBuilderProgram();
108717 }
108718 function reloadFileNamesFromConfigFile() {
108719 writeLog("Reloading new file names and options");
108720 var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
108721 if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
108722 hasChangedConfigFileParsingErrors = true;
108723 }
108724 rootFileNames = result.fileNames;
108725 // Update the program
108726 synchronizeProgram();
108727 }
108728 function reloadConfigFile() {
108729 writeLog("Reloading config file: " + configFileName);
108730 reloadLevel = ts.ConfigFileProgramReloadLevel.None;
108731 if (cachedDirectoryStructureHost) {
108732 cachedDirectoryStructureHost.clearCache();
108733 }
108734 parseConfigFile();
108735 hasChangedCompilerOptions = true;
108736 synchronizeProgram();
108737 // Update the wild card directory watch
108738 watchConfigFileWildCardDirectories();
108739 }
108740 function parseConfigFile() {
108741 setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
108742 }
108743 function setConfigFileParsingResult(configFileParseResult) {
108744 rootFileNames = configFileParseResult.fileNames;
108745 compilerOptions = configFileParseResult.options;
108746 watchOptions = configFileParseResult.watchOptions;
108747 configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
108748 projectReferences = configFileParseResult.projectReferences;
108749 configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
108750 canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
108751 hasChangedConfigFileParsingErrors = true;
108752 }
108753 function onSourceFileChange(fileName, eventKind, path) {
108754 updateCachedSystemWithFile(fileName, path, eventKind);
108755 // Update the source file cache
108756 if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
108757 resolutionCache.invalidateResolutionOfFile(path);
108758 }
108759 resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
108760 nextSourceFileVersion(path);
108761 // Update the program
108762 scheduleProgramUpdate();
108763 }
108764 function updateCachedSystemWithFile(fileName, path, eventKind) {
108765 if (cachedDirectoryStructureHost) {
108766 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
108767 }
108768 }
108769 function watchMissingFilePath(missingFilePath) {
108770 return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
108771 }
108772 function onMissingFileChange(fileName, eventKind, missingFilePath) {
108773 updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
108774 if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
108775 missingFilesMap.get(missingFilePath).close();
108776 missingFilesMap.delete(missingFilePath);
108777 // Delete the entry in the source files cache so that new source file is created
108778 nextSourceFileVersion(missingFilePath);
108779 // When a missing file is created, we should update the graph.
108780 scheduleProgramUpdate();
108781 }
108782 }
108783 function watchConfigFileWildCardDirectories() {
108784 if (configFileSpecs) {
108785 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(configFileSpecs.wildcardDirectories)), watchWildcardDirectory);
108786 }
108787 else if (watchedWildcardDirectories) {
108788 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
108789 }
108790 }
108791 function watchWildcardDirectory(directory, flags) {
108792 return watchDirectory(host, directory, function (fileOrDirectory) {
108793 ts.Debug.assert(!!configFileName);
108794 var fileOrDirectoryPath = toPath(fileOrDirectory);
108795 // Since the file existence changed, update the sourceFiles cache
108796 if (cachedDirectoryStructureHost) {
108797 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
108798 }
108799 nextSourceFileVersion(fileOrDirectoryPath);
108800 if (ts.isIgnoredFileFromWildCardWatching({
108801 watchedDirPath: toPath(directory),
108802 fileOrDirectory: fileOrDirectory,
108803 fileOrDirectoryPath: fileOrDirectoryPath,
108804 configFileName: configFileName,
108805 configFileSpecs: configFileSpecs,
108806 options: compilerOptions,
108807 program: getCurrentBuilderProgram(),
108808 currentDirectory: currentDirectory,
108809 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
108810 writeLog: writeLog
108811 }))
108812 return;
108813 // Reload is pending, do the reload
108814 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
108815 reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
108816 // Schedule Update the program
108817 scheduleProgramUpdate();
108818 }
108819 }, flags, watchOptions, ts.WatchType.WildcardDirectory);
108820 }
108821 }
108822 ts.createWatchProgram = createWatchProgram;
108823})(ts || (ts = {}));
108824/*@internal*/
108825var ts;
108826(function (ts) {
108827 var UpToDateStatusType;
108828 (function (UpToDateStatusType) {
108829 UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
108830 UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
108831 /**
108832 * The project appears out of date because its upstream inputs are newer than its outputs,
108833 * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
108834 * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
108835 */
108836 UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
108837 /**
108838 * The project appears out of date because its upstream inputs are newer than its outputs,
108839 * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
108840 * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
108841 */
108842 UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
108843 UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
108844 UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
108845 UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
108846 UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
108847 UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
108848 UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
108849 UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
108850 /**
108851 * Projects with no outputs (i.e. "solution" files)
108852 */
108853 UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
108854 })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
108855 function resolveConfigFileProjectName(project) {
108856 if (ts.fileExtensionIs(project, ".json" /* Json */)) {
108857 return project;
108858 }
108859 return ts.combinePaths(project, "tsconfig.json");
108860 }
108861 ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
108862})(ts || (ts = {}));
108863var ts;
108864(function (ts) {
108865 var minimumDate = new Date(-8640000000000000);
108866 var maximumDate = new Date(8640000000000000);
108867 var BuildResultFlags;
108868 (function (BuildResultFlags) {
108869 BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
108870 /**
108871 * No errors of any kind occurred during build
108872 */
108873 BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
108874 /**
108875 * None of the .d.ts files emitted by this build were
108876 * different from the existing files on disk
108877 */
108878 BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
108879 BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
108880 BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
108881 BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
108882 BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
108883 BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
108884 BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
108885 })(BuildResultFlags || (BuildResultFlags = {}));
108886 function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
108887 var existingValue = configFileMap.get(resolved);
108888 var newValue;
108889 if (!existingValue) {
108890 newValue = createT();
108891 configFileMap.set(resolved, newValue);
108892 }
108893 return existingValue || newValue;
108894 }
108895 function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
108896 return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); });
108897 }
108898 function newer(date1, date2) {
108899 return date2 > date1 ? date2 : date1;
108900 }
108901 function isDeclarationFile(fileName) {
108902 return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
108903 }
108904 /*@internal*/
108905 function isCircularBuildOrder(buildOrder) {
108906 return !!buildOrder && !!buildOrder.buildOrder;
108907 }
108908 ts.isCircularBuildOrder = isCircularBuildOrder;
108909 /*@internal*/
108910 function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
108911 return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
108912 }
108913 ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
108914 /**
108915 * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
108916 */
108917 function createBuilderStatusReporter(system, pretty) {
108918 return function (diagnostic) {
108919 var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
108920 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
108921 system.write(output);
108922 };
108923 }
108924 ts.createBuilderStatusReporter = createBuilderStatusReporter;
108925 function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
108926 var host = ts.createProgramHost(system, createProgram);
108927 host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
108928 host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
108929 host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
108930 host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
108931 host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
108932 host.now = ts.maybeBind(system, system.now); // For testing
108933 return host;
108934 }
108935 function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
108936 if (system === void 0) { system = ts.sys; }
108937 var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
108938 host.reportErrorSummary = reportErrorSummary;
108939 return host;
108940 }
108941 ts.createSolutionBuilderHost = createSolutionBuilderHost;
108942 function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
108943 if (system === void 0) { system = ts.sys; }
108944 var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
108945 var watchHost = ts.createWatchHost(system, reportWatchStatus);
108946 ts.copyProperties(host, watchHost);
108947 return host;
108948 }
108949 ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
108950 function getCompilerOptionsOfBuildOptions(buildOptions) {
108951 var result = {};
108952 ts.commonOptionsWithBuild.forEach(function (option) {
108953 if (ts.hasProperty(buildOptions, option.name))
108954 result[option.name] = buildOptions[option.name];
108955 });
108956 return result;
108957 }
108958 function createSolutionBuilder(host, rootNames, defaultOptions) {
108959 return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
108960 }
108961 ts.createSolutionBuilder = createSolutionBuilder;
108962 function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
108963 return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
108964 }
108965 ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
108966 function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
108967 var host = hostOrHostWithWatch;
108968 var hostWithWatch = hostOrHostWithWatch;
108969 var currentDirectory = host.getCurrentDirectory();
108970 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
108971 // State of the solution
108972 var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
108973 var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
108974 ts.setGetSourceFileAsHashVersioned(compilerHost, host);
108975 compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
108976 compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
108977 compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
108978 var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
108979 if (!compilerHost.resolveModuleNames) {
108980 var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
108981 compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
108982 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
108983 };
108984 }
108985 var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
108986 var state = {
108987 host: host,
108988 hostWithWatch: hostWithWatch,
108989 currentDirectory: currentDirectory,
108990 getCanonicalFileName: getCanonicalFileName,
108991 parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
108992 writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
108993 // State of solution
108994 options: options,
108995 baseCompilerOptions: baseCompilerOptions,
108996 rootNames: rootNames,
108997 baseWatchOptions: baseWatchOptions,
108998 resolvedConfigFilePaths: new ts.Map(),
108999 configFileCache: new ts.Map(),
109000 projectStatus: new ts.Map(),
109001 buildInfoChecked: new ts.Map(),
109002 extendedConfigCache: new ts.Map(),
109003 builderPrograms: new ts.Map(),
109004 diagnostics: new ts.Map(),
109005 projectPendingBuild: new ts.Map(),
109006 projectErrorsReported: new ts.Map(),
109007 compilerHost: compilerHost,
109008 moduleResolutionCache: moduleResolutionCache,
109009 // Mutable state
109010 buildOrder: undefined,
109011 readFileWithCache: function (f) { return host.readFile(f); },
109012 projectCompilerOptions: baseCompilerOptions,
109013 cache: undefined,
109014 allProjectBuildPending: true,
109015 needsSummary: true,
109016 watchAllProjectsPending: watch,
109017 currentInvalidatedProject: undefined,
109018 // Watch state
109019 watch: watch,
109020 allWatchedWildcardDirectories: new ts.Map(),
109021 allWatchedInputFiles: new ts.Map(),
109022 allWatchedConfigFiles: new ts.Map(),
109023 timerToBuildInvalidatedProject: undefined,
109024 reportFileChangeDetected: false,
109025 watchFile: watchFile,
109026 watchFilePath: watchFilePath,
109027 watchDirectory: watchDirectory,
109028 writeLog: writeLog,
109029 };
109030 return state;
109031 }
109032 function toPath(state, fileName) {
109033 return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
109034 }
109035 function toResolvedConfigFilePath(state, fileName) {
109036 var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
109037 var path = resolvedConfigFilePaths.get(fileName);
109038 if (path !== undefined)
109039 return path;
109040 var resolvedPath = toPath(state, fileName);
109041 resolvedConfigFilePaths.set(fileName, resolvedPath);
109042 return resolvedPath;
109043 }
109044 function isParsedCommandLine(entry) {
109045 return !!entry.options;
109046 }
109047 function parseConfigFile(state, configFileName, configFilePath) {
109048 var configFileCache = state.configFileCache;
109049 var value = configFileCache.get(configFilePath);
109050 if (value) {
109051 return isParsedCommandLine(value) ? value : undefined;
109052 }
109053 var diagnostic;
109054 var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
109055 var parsed;
109056 if (host.getParsedCommandLine) {
109057 parsed = host.getParsedCommandLine(configFileName);
109058 if (!parsed)
109059 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
109060 }
109061 else {
109062 parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
109063 parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
109064 parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
109065 }
109066 configFileCache.set(configFilePath, parsed || diagnostic);
109067 return parsed;
109068 }
109069 function resolveProjectName(state, name) {
109070 return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
109071 }
109072 function createBuildOrder(state, roots) {
109073 var temporaryMarks = new ts.Map();
109074 var permanentMarks = new ts.Map();
109075 var circularityReportStack = [];
109076 var buildOrder;
109077 var circularDiagnostics;
109078 for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
109079 var root = roots_1[_i];
109080 visit(root);
109081 }
109082 return circularDiagnostics ?
109083 { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
109084 buildOrder || ts.emptyArray;
109085 function visit(configFileName, inCircularContext) {
109086 var projPath = toResolvedConfigFilePath(state, configFileName);
109087 // Already visited
109088 if (permanentMarks.has(projPath))
109089 return;
109090 // Circular
109091 if (temporaryMarks.has(projPath)) {
109092 if (!inCircularContext) {
109093 (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
109094 }
109095 return;
109096 }
109097 temporaryMarks.set(projPath, true);
109098 circularityReportStack.push(configFileName);
109099 var parsed = parseConfigFile(state, configFileName, projPath);
109100 if (parsed && parsed.projectReferences) {
109101 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
109102 var ref = _a[_i];
109103 var resolvedRefPath = resolveProjectName(state, ref.path);
109104 visit(resolvedRefPath, inCircularContext || ref.circular);
109105 }
109106 }
109107 circularityReportStack.pop();
109108 permanentMarks.set(projPath, true);
109109 (buildOrder || (buildOrder = [])).push(configFileName);
109110 }
109111 }
109112 function getBuildOrder(state) {
109113 return state.buildOrder || createStateBuildOrder(state);
109114 }
109115 function createStateBuildOrder(state) {
109116 var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
109117 // Clear all to ResolvedConfigFilePaths cache to start fresh
109118 state.resolvedConfigFilePaths.clear();
109119 // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues`
109120 var currentProjects = new ts.Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(function (resolved) { return [toResolvedConfigFilePath(state, resolved), true]; }));
109121 var noopOnDelete = { onDeleteValue: ts.noop };
109122 // Config file cache
109123 ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
109124 ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
109125 ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
109126 ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
109127 ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
109128 ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
109129 ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
109130 // Remove watches for the program no longer in the solution
109131 if (state.watch) {
109132 ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
109133 ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
109134 ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
109135 }
109136 return state.buildOrder = buildOrder;
109137 }
109138 function getBuildOrderFor(state, project, onlyReferences) {
109139 var resolvedProject = project && resolveProjectName(state, project);
109140 var buildOrderFromState = getBuildOrder(state);
109141 if (isCircularBuildOrder(buildOrderFromState))
109142 return buildOrderFromState;
109143 if (resolvedProject) {
109144 var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
109145 var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
109146 if (projectIndex === -1)
109147 return undefined;
109148 }
109149 var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
109150 ts.Debug.assert(!isCircularBuildOrder(buildOrder));
109151 ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
109152 ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
109153 return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
109154 }
109155 function enableCache(state) {
109156 if (state.cache) {
109157 disableCache(state);
109158 }
109159 var compilerHost = state.compilerHost, host = state.host;
109160 var originalReadFileWithCache = state.readFileWithCache;
109161 var originalGetSourceFile = compilerHost.getSourceFile;
109162 var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
109163 var args = [];
109164 for (var _i = 0; _i < arguments.length; _i++) {
109165 args[_i] = arguments[_i];
109166 }
109167 return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
109168 }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
109169 state.readFileWithCache = readFileWithCache;
109170 compilerHost.getSourceFile = getSourceFileWithCache;
109171 state.cache = {
109172 originalReadFile: originalReadFile,
109173 originalFileExists: originalFileExists,
109174 originalDirectoryExists: originalDirectoryExists,
109175 originalCreateDirectory: originalCreateDirectory,
109176 originalWriteFile: originalWriteFile,
109177 originalReadFileWithCache: originalReadFileWithCache,
109178 originalGetSourceFile: originalGetSourceFile,
109179 };
109180 }
109181 function disableCache(state) {
109182 if (!state.cache)
109183 return;
109184 var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
109185 host.readFile = cache.originalReadFile;
109186 host.fileExists = cache.originalFileExists;
109187 host.directoryExists = cache.originalDirectoryExists;
109188 host.createDirectory = cache.originalCreateDirectory;
109189 host.writeFile = cache.originalWriteFile;
109190 compilerHost.getSourceFile = cache.originalGetSourceFile;
109191 state.readFileWithCache = cache.originalReadFileWithCache;
109192 extendedConfigCache.clear();
109193 if (moduleResolutionCache) {
109194 moduleResolutionCache.directoryToModuleNameMap.clear();
109195 moduleResolutionCache.moduleNameToDirectoryMap.clear();
109196 }
109197 state.cache = undefined;
109198 }
109199 function clearProjectStatus(state, resolved) {
109200 state.projectStatus.delete(resolved);
109201 state.diagnostics.delete(resolved);
109202 }
109203 function addProjToQueue(_a, proj, reloadLevel) {
109204 var projectPendingBuild = _a.projectPendingBuild;
109205 var value = projectPendingBuild.get(proj);
109206 if (value === undefined) {
109207 projectPendingBuild.set(proj, reloadLevel);
109208 }
109209 else if (value < reloadLevel) {
109210 projectPendingBuild.set(proj, reloadLevel);
109211 }
109212 }
109213 function setupInitialBuild(state, cancellationToken) {
109214 // Set initial build if not already built
109215 if (!state.allProjectBuildPending)
109216 return;
109217 state.allProjectBuildPending = false;
109218 if (state.options.watch) {
109219 reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
109220 }
109221 enableCache(state);
109222 var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
109223 buildOrder.forEach(function (configFileName) {
109224 return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
109225 });
109226 if (cancellationToken) {
109227 cancellationToken.throwIfCancellationRequested();
109228 }
109229 }
109230 var InvalidatedProjectKind;
109231 (function (InvalidatedProjectKind) {
109232 InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
109233 InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
109234 InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
109235 })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
109236 function doneInvalidatedProject(state, projectPath) {
109237 state.projectPendingBuild.delete(projectPath);
109238 state.currentInvalidatedProject = undefined;
109239 return state.diagnostics.has(projectPath) ?
109240 ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
109241 ts.ExitStatus.Success;
109242 }
109243 function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
109244 var updateOutputFileStampsPending = true;
109245 return {
109246 kind: InvalidatedProjectKind.UpdateOutputFileStamps,
109247 project: project,
109248 projectPath: projectPath,
109249 buildOrder: buildOrder,
109250 getCompilerOptions: function () { return config.options; },
109251 getCurrentDirectory: function () { return state.currentDirectory; },
109252 updateOutputFileStatmps: function () {
109253 updateOutputTimestamps(state, config, projectPath);
109254 updateOutputFileStampsPending = false;
109255 },
109256 done: function () {
109257 if (updateOutputFileStampsPending) {
109258 updateOutputTimestamps(state, config, projectPath);
109259 }
109260 return doneInvalidatedProject(state, projectPath);
109261 }
109262 };
109263 }
109264 var BuildStep;
109265 (function (BuildStep) {
109266 BuildStep[BuildStep["CreateProgram"] = 0] = "CreateProgram";
109267 BuildStep[BuildStep["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
109268 BuildStep[BuildStep["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
109269 BuildStep[BuildStep["Emit"] = 3] = "Emit";
109270 BuildStep[BuildStep["EmitBundle"] = 4] = "EmitBundle";
109271 BuildStep[BuildStep["EmitBuildInfo"] = 5] = "EmitBuildInfo";
109272 BuildStep[BuildStep["BuildInvalidatedProjectOfBundle"] = 6] = "BuildInvalidatedProjectOfBundle";
109273 BuildStep[BuildStep["QueueReferencingProjects"] = 7] = "QueueReferencingProjects";
109274 BuildStep[BuildStep["Done"] = 8] = "Done";
109275 })(BuildStep || (BuildStep = {}));
109276 function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
109277 var step = kind === InvalidatedProjectKind.Build ? BuildStep.CreateProgram : BuildStep.EmitBundle;
109278 var program;
109279 var buildResult;
109280 var invalidatedProjectOfBundle;
109281 return kind === InvalidatedProjectKind.Build ?
109282 {
109283 kind: kind,
109284 project: project,
109285 projectPath: projectPath,
109286 buildOrder: buildOrder,
109287 getCompilerOptions: function () { return config.options; },
109288 getCurrentDirectory: function () { return state.currentDirectory; },
109289 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
109290 getProgram: function () {
109291 return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
109292 },
109293 getSourceFile: function (fileName) {
109294 return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
109295 },
109296 getSourceFiles: function () {
109297 return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
109298 },
109299 getOptionsDiagnostics: function (cancellationToken) {
109300 return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
109301 },
109302 getGlobalDiagnostics: function (cancellationToken) {
109303 return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
109304 },
109305 getConfigFileParsingDiagnostics: function () {
109306 return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
109307 },
109308 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
109309 return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
109310 },
109311 getAllDependencies: function (sourceFile) {
109312 return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
109313 },
109314 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
109315 return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
109316 },
109317 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
109318 return withProgramOrUndefined(function (program) {
109319 return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
109320 program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
109321 });
109322 },
109323 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
109324 if (targetSourceFile || emitOnlyDtsFiles) {
109325 return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
109326 }
109327 executeSteps(BuildStep.SemanticDiagnostics, cancellationToken);
109328 if (step === BuildStep.EmitBuildInfo) {
109329 return emitBuildInfo(writeFile, cancellationToken);
109330 }
109331 if (step !== BuildStep.Emit)
109332 return undefined;
109333 return emit(writeFile, cancellationToken, customTransformers);
109334 },
109335 done: done
109336 } :
109337 {
109338 kind: kind,
109339 project: project,
109340 projectPath: projectPath,
109341 buildOrder: buildOrder,
109342 getCompilerOptions: function () { return config.options; },
109343 getCurrentDirectory: function () { return state.currentDirectory; },
109344 emit: function (writeFile, customTransformers) {
109345 if (step !== BuildStep.EmitBundle)
109346 return invalidatedProjectOfBundle;
109347 return emitBundle(writeFile, customTransformers);
109348 },
109349 done: done,
109350 };
109351 function done(cancellationToken, writeFile, customTransformers) {
109352 executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers);
109353 return doneInvalidatedProject(state, projectPath);
109354 }
109355 function withProgramOrUndefined(action) {
109356 executeSteps(BuildStep.CreateProgram);
109357 return program && action(program);
109358 }
109359 function withProgramOrEmptyArray(action) {
109360 return withProgramOrUndefined(action) || ts.emptyArray;
109361 }
109362 function createProgram() {
109363 ts.Debug.assert(program === undefined);
109364 if (state.options.dry) {
109365 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
109366 buildResult = BuildResultFlags.Success;
109367 step = BuildStep.QueueReferencingProjects;
109368 return;
109369 }
109370 if (state.options.verbose)
109371 reportStatus(state, ts.Diagnostics.Building_project_0, project);
109372 if (config.fileNames.length === 0) {
109373 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
109374 // Nothing to build - must be a solution file, basically
109375 buildResult = BuildResultFlags.None;
109376 step = BuildStep.QueueReferencingProjects;
109377 return;
109378 }
109379 var host = state.host, compilerHost = state.compilerHost;
109380 state.projectCompilerOptions = config.options;
109381 // Update module resolution cache if needed
109382 updateModuleResolutionCache(state, project, config);
109383 // Create program
109384 program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
109385 if (state.watch) {
109386 state.builderPrograms.set(projectPath, program);
109387 }
109388 step++;
109389 }
109390 function handleDiagnostics(diagnostics, errorFlags, errorType) {
109391 var _a;
109392 if (diagnostics.length) {
109393 (_a = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType), buildResult = _a.buildResult, step = _a.step);
109394 }
109395 else {
109396 step++;
109397 }
109398 }
109399 function getSyntaxDiagnostics(cancellationToken) {
109400 ts.Debug.assertIsDefined(program);
109401 handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
109402 }
109403 function getSemanticDiagnostics(cancellationToken) {
109404 handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
109405 }
109406 function emit(writeFileCallback, cancellationToken, customTransformers) {
109407 var _a;
109408 ts.Debug.assertIsDefined(program);
109409 ts.Debug.assert(step === BuildStep.Emit);
109410 // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
109411 program.backupState();
109412 var declDiagnostics;
109413 var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
109414 var outputFiles = [];
109415 var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics,
109416 /*writeFileName*/ undefined,
109417 /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken,
109418 /*emitOnlyDts*/ false, customTransformers).emitResult;
109419 // Don't emit .d.ts if there are decl file errors
109420 if (declDiagnostics) {
109421 program.restoreState();
109422 (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step);
109423 return {
109424 emitSkipped: true,
109425 diagnostics: emitResult.diagnostics
109426 };
109427 }
109428 // Actual Emit
109429 var host = state.host, compilerHost = state.compilerHost;
109430 var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
109431 var newestDeclarationFileContentChangedTime = minimumDate;
109432 var anyDtsChanged = false;
109433 var emitterDiagnostics = ts.createDiagnosticCollection();
109434 var emittedOutputs = new ts.Map();
109435 outputFiles.forEach(function (_a) {
109436 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
109437 var priorChangeTime;
109438 if (!anyDtsChanged && isDeclarationFile(name)) {
109439 // Check for unchanged .d.ts files
109440 if (host.fileExists(name) && state.readFileWithCache(name) === text) {
109441 priorChangeTime = host.getModifiedTime(name);
109442 }
109443 else {
109444 resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
109445 anyDtsChanged = true;
109446 }
109447 }
109448 emittedOutputs.set(toPath(state, name), name);
109449 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
109450 if (priorChangeTime !== undefined) {
109451 newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
109452 }
109453 });
109454 finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime,
109455 /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
109456 return emitResult;
109457 }
109458 function emitBuildInfo(writeFileCallback, cancellationToken) {
109459 ts.Debug.assertIsDefined(program);
109460 ts.Debug.assert(step === BuildStep.EmitBuildInfo);
109461 var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
109462 if (emitResult.diagnostics.length) {
109463 reportErrors(state, emitResult.diagnostics);
109464 state.diagnostics.set(projectPath, __spreadArrays(state.diagnostics.get(projectPath), emitResult.diagnostics));
109465 buildResult = BuildResultFlags.EmitErrors & buildResult;
109466 }
109467 if (emitResult.emittedFiles && state.writeFileName) {
109468 emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
109469 }
109470 afterProgramDone(state, program, config);
109471 step = BuildStep.QueueReferencingProjects;
109472 return emitResult;
109473 }
109474 function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
109475 var _a;
109476 var emitDiagnostics = emitterDiagnostics.getDiagnostics();
109477 if (emitDiagnostics.length) {
109478 (_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
109479 return emitDiagnostics;
109480 }
109481 if (state.writeFileName) {
109482 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
109483 }
109484 // Update time stamps for rest of the outputs
109485 var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
109486 state.diagnostics.delete(projectPath);
109487 state.projectStatus.set(projectPath, {
109488 type: ts.UpToDateStatusType.UpToDate,
109489 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
109490 maximumDate :
109491 newestDeclarationFileContentChangedTime,
109492 oldestOutputFileName: oldestOutputFileName
109493 });
109494 afterProgramDone(state, program, config);
109495 step = BuildStep.QueueReferencingProjects;
109496 buildResult = resultFlags;
109497 return emitDiagnostics;
109498 }
109499 function emitBundle(writeFileCallback, customTransformers) {
109500 ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
109501 if (state.options.dry) {
109502 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
109503 buildResult = BuildResultFlags.Success;
109504 step = BuildStep.QueueReferencingProjects;
109505 return undefined;
109506 }
109507 if (state.options.verbose)
109508 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
109509 // Update js, and source map
109510 var compilerHost = state.compilerHost;
109511 state.projectCompilerOptions = config.options;
109512 var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
109513 var refName = resolveProjectName(state, ref.path);
109514 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
109515 }, customTransformers);
109516 if (ts.isString(outputFiles)) {
109517 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
109518 step = BuildStep.BuildInvalidatedProjectOfBundle;
109519 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
109520 }
109521 // Actual Emit
109522 ts.Debug.assert(!!outputFiles.length);
109523 var emitterDiagnostics = ts.createDiagnosticCollection();
109524 var emittedOutputs = new ts.Map();
109525 outputFiles.forEach(function (_a) {
109526 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
109527 emittedOutputs.set(toPath(state, name), name);
109528 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
109529 });
109530 var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate,
109531 /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
109532 return { emitSkipped: false, diagnostics: emitDiagnostics };
109533 }
109534 function executeSteps(till, cancellationToken, writeFile, customTransformers) {
109535 while (step <= till && step < BuildStep.Done) {
109536 var currentStep = step;
109537 switch (step) {
109538 case BuildStep.CreateProgram:
109539 createProgram();
109540 break;
109541 case BuildStep.SyntaxDiagnostics:
109542 getSyntaxDiagnostics(cancellationToken);
109543 break;
109544 case BuildStep.SemanticDiagnostics:
109545 getSemanticDiagnostics(cancellationToken);
109546 break;
109547 case BuildStep.Emit:
109548 emit(writeFile, cancellationToken, customTransformers);
109549 break;
109550 case BuildStep.EmitBuildInfo:
109551 emitBuildInfo(writeFile, cancellationToken);
109552 break;
109553 case BuildStep.EmitBundle:
109554 emitBundle(writeFile, customTransformers);
109555 break;
109556 case BuildStep.BuildInvalidatedProjectOfBundle:
109557 ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
109558 step = BuildStep.Done;
109559 break;
109560 case BuildStep.QueueReferencingProjects:
109561 queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
109562 step++;
109563 break;
109564 // Should never be done
109565 case BuildStep.Done:
109566 default:
109567 ts.assertType(step);
109568 }
109569 ts.Debug.assert(step > currentStep);
109570 }
109571 }
109572 }
109573 function needsBuild(_a, status, config) {
109574 var options = _a.options;
109575 if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
109576 return true;
109577 return config.fileNames.length === 0 ||
109578 !!ts.getConfigFileParsingDiagnostics(config).length ||
109579 !ts.isIncrementalCompilation(config.options);
109580 }
109581 function getNextInvalidatedProject(state, buildOrder, reportQueue) {
109582 if (!state.projectPendingBuild.size)
109583 return undefined;
109584 if (isCircularBuildOrder(buildOrder))
109585 return undefined;
109586 if (state.currentInvalidatedProject) {
109587 // Only if same buildOrder the currentInvalidated project can be sent again
109588 return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
109589 state.currentInvalidatedProject :
109590 undefined;
109591 }
109592 var options = state.options, projectPendingBuild = state.projectPendingBuild;
109593 for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
109594 var project = buildOrder[projectIndex];
109595 var projectPath = toResolvedConfigFilePath(state, project);
109596 var reloadLevel = state.projectPendingBuild.get(projectPath);
109597 if (reloadLevel === undefined)
109598 continue;
109599 if (reportQueue) {
109600 reportQueue = false;
109601 reportBuildQueue(state, buildOrder);
109602 }
109603 var config = parseConfigFile(state, project, projectPath);
109604 if (!config) {
109605 reportParseConfigFileDiagnostic(state, projectPath);
109606 projectPendingBuild.delete(projectPath);
109607 continue;
109608 }
109609 if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
109610 watchConfigFile(state, project, projectPath, config);
109611 watchWildCardDirectories(state, project, projectPath, config);
109612 watchInputFiles(state, project, projectPath, config);
109613 }
109614 else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
109615 // Update file names
109616 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
109617 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
109618 config.fileNames = result.fileNames;
109619 watchInputFiles(state, project, projectPath, config);
109620 }
109621 var status = getUpToDateStatus(state, config, projectPath);
109622 verboseReportProjectStatus(state, project, status);
109623 if (!options.force) {
109624 if (status.type === ts.UpToDateStatusType.UpToDate) {
109625 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
109626 projectPendingBuild.delete(projectPath);
109627 // Up to date, skip
109628 if (options.dry) {
109629 // In a dry build, inform the user of this fact
109630 reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
109631 }
109632 continue;
109633 }
109634 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
109635 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
109636 return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
109637 }
109638 }
109639 if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
109640 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
109641 projectPendingBuild.delete(projectPath);
109642 if (options.verbose) {
109643 reportStatus(state, status.upstreamProjectBlocked ?
109644 ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
109645 ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
109646 }
109647 continue;
109648 }
109649 if (status.type === ts.UpToDateStatusType.ContainerOnly) {
109650 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
109651 projectPendingBuild.delete(projectPath);
109652 // Do nothing
109653 continue;
109654 }
109655 return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
109656 InvalidatedProjectKind.Build :
109657 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
109658 }
109659 return undefined;
109660 }
109661 function listEmittedFile(_a, proj, file) {
109662 var writeFileName = _a.writeFileName;
109663 if (writeFileName && proj.options.listEmittedFiles) {
109664 writeFileName("TSFILE: " + file);
109665 }
109666 }
109667 function getOldProgram(_a, proj, parsed) {
109668 var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
109669 if (options.force)
109670 return undefined;
109671 var value = builderPrograms.get(proj);
109672 if (value)
109673 return value;
109674 return ts.readBuilderProgram(parsed.options, compilerHost);
109675 }
109676 function afterProgramDone(state, program, config) {
109677 if (program) {
109678 if (program && state.writeFileName)
109679 ts.listFiles(program, state.writeFileName);
109680 if (state.host.afterProgramEmitAndDiagnostics) {
109681 state.host.afterProgramEmitAndDiagnostics(program);
109682 }
109683 program.releaseProgram();
109684 }
109685 else if (state.host.afterEmitBundle) {
109686 state.host.afterEmitBundle(config);
109687 }
109688 state.projectCompilerOptions = state.baseCompilerOptions;
109689 }
109690 function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
109691 var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
109692 reportAndStoreErrors(state, resolvedPath, diagnostics);
109693 // List files if any other build error using program (emit errors already report files)
109694 state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
109695 if (canEmitBuildInfo)
109696 return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
109697 afterProgramDone(state, program, config);
109698 return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects };
109699 }
109700 function updateModuleResolutionCache(state, proj, config) {
109701 if (!state.moduleResolutionCache)
109702 return;
109703 // Update module resolution cache if needed
109704 var moduleResolutionCache = state.moduleResolutionCache;
109705 var projPath = toPath(state, proj);
109706 if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
109707 // The own map will be for projectCompilerOptions
109708 ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
109709 moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
109710 moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
109711 }
109712 else {
109713 // Set correct own map
109714 ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
109715 var ref = {
109716 sourceFile: config.options.configFile,
109717 commandLine: config
109718 };
109719 moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
109720 moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
109721 }
109722 moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
109723 moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
109724 }
109725 function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
109726 // Check tsconfig time
109727 var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
109728 if (oldestOutputFileTime < tsconfigTime) {
109729 return {
109730 type: ts.UpToDateStatusType.OutOfDateWithSelf,
109731 outOfDateOutputFileName: oldestOutputFileName,
109732 newerInputFileName: configFile
109733 };
109734 }
109735 }
109736 function getUpToDateStatusWorker(state, project, resolvedPath) {
109737 var newestInputFileName = undefined;
109738 var newestInputFileTime = minimumDate;
109739 var host = state.host;
109740 // Get timestamps of input files
109741 for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
109742 var inputFile = _a[_i];
109743 if (!host.fileExists(inputFile)) {
109744 return {
109745 type: ts.UpToDateStatusType.Unbuildable,
109746 reason: inputFile + " does not exist"
109747 };
109748 }
109749 var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
109750 if (inputTime > newestInputFileTime) {
109751 newestInputFileName = inputFile;
109752 newestInputFileTime = inputTime;
109753 }
109754 }
109755 // Container if no files are specified in the project
109756 if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) {
109757 return {
109758 type: ts.UpToDateStatusType.ContainerOnly
109759 };
109760 }
109761 // Collect the expected outputs of this project
109762 var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
109763 // Now see if all outputs are newer than the newest input
109764 var oldestOutputFileName = "(none)";
109765 var oldestOutputFileTime = maximumDate;
109766 var newestOutputFileName = "(none)";
109767 var newestOutputFileTime = minimumDate;
109768 var missingOutputFileName;
109769 var newestDeclarationFileContentChangedTime = minimumDate;
109770 var isOutOfDateWithInputs = false;
109771 for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
109772 var output = outputs_1[_b];
109773 // Output is missing; can stop checking
109774 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
109775 if (!host.fileExists(output)) {
109776 missingOutputFileName = output;
109777 break;
109778 }
109779 var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
109780 if (outputTime < oldestOutputFileTime) {
109781 oldestOutputFileTime = outputTime;
109782 oldestOutputFileName = output;
109783 }
109784 // If an output is older than the newest input, we can stop checking
109785 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
109786 if (outputTime < newestInputFileTime) {
109787 isOutOfDateWithInputs = true;
109788 break;
109789 }
109790 if (outputTime > newestOutputFileTime) {
109791 newestOutputFileTime = outputTime;
109792 newestOutputFileName = output;
109793 }
109794 // Keep track of when the most recent time a .d.ts file was changed.
109795 // In addition to file timestamps, we also keep track of when a .d.ts file
109796 // had its file touched but not had its contents changed - this allows us
109797 // to skip a downstream typecheck
109798 if (isDeclarationFile(output)) {
109799 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
109800 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
109801 }
109802 }
109803 var pseudoUpToDate = false;
109804 var usesPrepend = false;
109805 var upstreamChangedProject;
109806 if (project.projectReferences) {
109807 state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
109808 for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
109809 var ref = _d[_c];
109810 usesPrepend = usesPrepend || !!(ref.prepend);
109811 var resolvedRef = ts.resolveProjectReferencePath(ref);
109812 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
109813 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
109814 // Its a circular reference ignore the status of this project
109815 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
109816 refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
109817 continue;
109818 }
109819 // An upstream project is blocked
109820 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
109821 refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
109822 return {
109823 type: ts.UpToDateStatusType.UpstreamBlocked,
109824 upstreamProjectName: ref.path,
109825 upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
109826 };
109827 }
109828 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
109829 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
109830 return {
109831 type: ts.UpToDateStatusType.UpstreamOutOfDate,
109832 upstreamProjectName: ref.path
109833 };
109834 }
109835 // Check oldest output file name only if there is no missing output file name
109836 if (!missingOutputFileName) {
109837 // If the upstream project's newest file is older than our oldest output, we
109838 // can't be out of date because of it
109839 if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
109840 continue;
109841 }
109842 // If the upstream project has only change .d.ts files, and we've built
109843 // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
109844 if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
109845 pseudoUpToDate = true;
109846 upstreamChangedProject = ref.path;
109847 continue;
109848 }
109849 // We have an output older than an upstream output - we are out of date
109850 ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
109851 return {
109852 type: ts.UpToDateStatusType.OutOfDateWithUpstream,
109853 outOfDateOutputFileName: oldestOutputFileName,
109854 newerProjectName: ref.path
109855 };
109856 }
109857 }
109858 }
109859 if (missingOutputFileName !== undefined) {
109860 return {
109861 type: ts.UpToDateStatusType.OutputMissing,
109862 missingOutputFileName: missingOutputFileName
109863 };
109864 }
109865 if (isOutOfDateWithInputs) {
109866 return {
109867 type: ts.UpToDateStatusType.OutOfDateWithSelf,
109868 outOfDateOutputFileName: oldestOutputFileName,
109869 newerInputFileName: newestInputFileName
109870 };
109871 }
109872 else {
109873 // Check tsconfig time
109874 var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
109875 if (configStatus)
109876 return configStatus;
109877 // Check extended config time
109878 var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
109879 if (extendedConfigStatus)
109880 return extendedConfigStatus;
109881 }
109882 if (!state.buildInfoChecked.has(resolvedPath)) {
109883 state.buildInfoChecked.set(resolvedPath, true);
109884 var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
109885 if (buildInfoPath) {
109886 var value = state.readFileWithCache(buildInfoPath);
109887 var buildInfo = value && ts.getBuildInfo(value);
109888 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
109889 return {
109890 type: ts.UpToDateStatusType.TsVersionOutputOfDate,
109891 version: buildInfo.version
109892 };
109893 }
109894 }
109895 }
109896 if (usesPrepend && pseudoUpToDate) {
109897 return {
109898 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
109899 outOfDateOutputFileName: oldestOutputFileName,
109900 newerProjectName: upstreamChangedProject
109901 };
109902 }
109903 // Up to date
109904 return {
109905 type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
109906 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
109907 newestInputFileTime: newestInputFileTime,
109908 newestOutputFileTime: newestOutputFileTime,
109909 newestInputFileName: newestInputFileName,
109910 newestOutputFileName: newestOutputFileName,
109911 oldestOutputFileName: oldestOutputFileName
109912 };
109913 }
109914 function getUpToDateStatus(state, project, resolvedPath) {
109915 if (project === undefined) {
109916 return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
109917 }
109918 var prior = state.projectStatus.get(resolvedPath);
109919 if (prior !== undefined) {
109920 return prior;
109921 }
109922 var actual = getUpToDateStatusWorker(state, project, resolvedPath);
109923 state.projectStatus.set(resolvedPath, actual);
109924 return actual;
109925 }
109926 function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
109927 var host = state.host;
109928 var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
109929 if (!skipOutputs || outputs.length !== skipOutputs.size) {
109930 var reportVerbose = !!state.options.verbose;
109931 var now = host.now ? host.now() : new Date();
109932 for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
109933 var file = outputs_2[_i];
109934 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
109935 continue;
109936 }
109937 if (reportVerbose) {
109938 reportVerbose = false;
109939 reportStatus(state, verboseMessage, proj.options.configFilePath);
109940 }
109941 if (isDeclarationFile(file)) {
109942 priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
109943 }
109944 host.setModifiedTime(file, now);
109945 }
109946 }
109947 return priorNewestUpdateTime;
109948 }
109949 function updateOutputTimestamps(state, proj, resolvedPath) {
109950 if (state.options.dry) {
109951 return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
109952 }
109953 var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
109954 state.projectStatus.set(resolvedPath, {
109955 type: ts.UpToDateStatusType.UpToDate,
109956 newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
109957 oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
109958 });
109959 }
109960 function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
109961 // Queue only if there are no errors
109962 if (buildResult & BuildResultFlags.AnyErrors)
109963 return;
109964 // Only composite projects can be referenced by other projects
109965 if (!config.options.composite)
109966 return;
109967 // Always use build order to queue projects
109968 for (var index = projectIndex + 1; index < buildOrder.length; index++) {
109969 var nextProject = buildOrder[index];
109970 var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
109971 if (state.projectPendingBuild.has(nextProjectPath))
109972 continue;
109973 var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
109974 if (!nextProjectConfig || !nextProjectConfig.projectReferences)
109975 continue;
109976 for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
109977 var ref = _a[_i];
109978 var resolvedRefPath = resolveProjectName(state, ref.path);
109979 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
109980 continue;
109981 // If the project is referenced with prepend, always build downstream projects,
109982 // If declaration output is changed, build the project
109983 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
109984 var status = state.projectStatus.get(nextProjectPath);
109985 if (status) {
109986 switch (status.type) {
109987 case ts.UpToDateStatusType.UpToDate:
109988 if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
109989 if (ref.prepend) {
109990 state.projectStatus.set(nextProjectPath, {
109991 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
109992 outOfDateOutputFileName: status.oldestOutputFileName,
109993 newerProjectName: project
109994 });
109995 }
109996 else {
109997 status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
109998 }
109999 break;
110000 }
110001 // falls through
110002 case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
110003 case ts.UpToDateStatusType.OutOfDateWithPrepend:
110004 if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
110005 state.projectStatus.set(nextProjectPath, {
110006 type: ts.UpToDateStatusType.OutOfDateWithUpstream,
110007 outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
110008 newerProjectName: project
110009 });
110010 }
110011 break;
110012 case ts.UpToDateStatusType.UpstreamBlocked:
110013 if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
110014 clearProjectStatus(state, nextProjectPath);
110015 }
110016 break;
110017 }
110018 }
110019 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
110020 break;
110021 }
110022 }
110023 }
110024 function build(state, project, cancellationToken, onlyReferences) {
110025 var buildOrder = getBuildOrderFor(state, project, onlyReferences);
110026 if (!buildOrder)
110027 return ts.ExitStatus.InvalidProject_OutputsSkipped;
110028 setupInitialBuild(state, cancellationToken);
110029 var reportQueue = true;
110030 var successfulProjects = 0;
110031 while (true) {
110032 var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
110033 if (!invalidatedProject)
110034 break;
110035 reportQueue = false;
110036 invalidatedProject.done(cancellationToken);
110037 if (!state.diagnostics.has(invalidatedProject.projectPath))
110038 successfulProjects++;
110039 }
110040 disableCache(state);
110041 reportErrorSummary(state, buildOrder);
110042 startWatching(state, buildOrder);
110043 return isCircularBuildOrder(buildOrder)
110044 ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
110045 : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
110046 ? ts.ExitStatus.Success
110047 : successfulProjects
110048 ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
110049 : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
110050 }
110051 function clean(state, project, onlyReferences) {
110052 var buildOrder = getBuildOrderFor(state, project, onlyReferences);
110053 if (!buildOrder)
110054 return ts.ExitStatus.InvalidProject_OutputsSkipped;
110055 if (isCircularBuildOrder(buildOrder)) {
110056 reportErrors(state, buildOrder.circularDiagnostics);
110057 return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
110058 }
110059 var options = state.options, host = state.host;
110060 var filesToDelete = options.dry ? [] : undefined;
110061 for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
110062 var proj = buildOrder_1[_i];
110063 var resolvedPath = toResolvedConfigFilePath(state, proj);
110064 var parsed = parseConfigFile(state, proj, resolvedPath);
110065 if (parsed === undefined) {
110066 // File has gone missing; fine to ignore here
110067 reportParseConfigFileDiagnostic(state, resolvedPath);
110068 continue;
110069 }
110070 var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
110071 for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
110072 var output = outputs_3[_a];
110073 if (host.fileExists(output)) {
110074 if (filesToDelete) {
110075 filesToDelete.push(output);
110076 }
110077 else {
110078 host.deleteFile(output);
110079 invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
110080 }
110081 }
110082 }
110083 }
110084 if (filesToDelete) {
110085 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
110086 }
110087 return ts.ExitStatus.Success;
110088 }
110089 function invalidateProject(state, resolved, reloadLevel) {
110090 // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
110091 if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
110092 reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
110093 }
110094 if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
110095 state.configFileCache.delete(resolved);
110096 state.buildOrder = undefined;
110097 }
110098 state.needsSummary = true;
110099 clearProjectStatus(state, resolved);
110100 addProjToQueue(state, resolved, reloadLevel);
110101 enableCache(state);
110102 }
110103 function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
110104 state.reportFileChangeDetected = true;
110105 invalidateProject(state, resolvedPath, reloadLevel);
110106 scheduleBuildInvalidatedProject(state);
110107 }
110108 function scheduleBuildInvalidatedProject(state) {
110109 var hostWithWatch = state.hostWithWatch;
110110 if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
110111 return;
110112 }
110113 if (state.timerToBuildInvalidatedProject) {
110114 hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
110115 }
110116 state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
110117 }
110118 function buildNextInvalidatedProject(state) {
110119 state.timerToBuildInvalidatedProject = undefined;
110120 if (state.reportFileChangeDetected) {
110121 state.reportFileChangeDetected = false;
110122 state.projectErrorsReported.clear();
110123 reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
110124 }
110125 var buildOrder = getBuildOrder(state);
110126 var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
110127 if (invalidatedProject) {
110128 invalidatedProject.done();
110129 if (state.projectPendingBuild.size) {
110130 // Schedule next project for build
110131 if (state.watch && !state.timerToBuildInvalidatedProject) {
110132 scheduleBuildInvalidatedProject(state);
110133 }
110134 return;
110135 }
110136 }
110137 disableCache(state);
110138 reportErrorSummary(state, buildOrder);
110139 }
110140 function watchConfigFile(state, resolved, resolvedPath, parsed) {
110141 if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
110142 return;
110143 state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
110144 invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
110145 }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
110146 }
110147 function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
110148 if (!state.watch)
110149 return;
110150 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) {
110151 if (ts.isIgnoredFileFromWildCardWatching({
110152 watchedDirPath: toPath(state, dir),
110153 fileOrDirectory: fileOrDirectory,
110154 fileOrDirectoryPath: toPath(state, fileOrDirectory),
110155 configFileName: resolved,
110156 configFileSpecs: parsed.configFileSpecs,
110157 currentDirectory: state.currentDirectory,
110158 options: parsed.options,
110159 program: state.builderPrograms.get(resolvedPath),
110160 useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
110161 writeLog: function (s) { return state.writeLog(s); }
110162 }))
110163 return;
110164 invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
110165 }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
110166 }
110167 function watchInputFiles(state, resolved, resolvedPath, parsed) {
110168 if (!state.watch)
110169 return;
110170 ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
110171 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); },
110172 onDeleteValue: ts.closeFileWatcher,
110173 });
110174 }
110175 function startWatching(state, buildOrder) {
110176 if (!state.watchAllProjectsPending)
110177 return;
110178 state.watchAllProjectsPending = false;
110179 for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
110180 var resolved = _a[_i];
110181 var resolvedPath = toResolvedConfigFilePath(state, resolved);
110182 var cfg = parseConfigFile(state, resolved, resolvedPath);
110183 // Watch this file
110184 watchConfigFile(state, resolved, resolvedPath, cfg);
110185 if (cfg) {
110186 // Update watchers for wildcard directories
110187 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
110188 // Watch input files
110189 watchInputFiles(state, resolved, resolvedPath, cfg);
110190 }
110191 }
110192 }
110193 function stopWatching(state) {
110194 ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
110195 ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
110196 ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
110197 }
110198 function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
110199 var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
110200 return {
110201 build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
110202 clean: function (project) { return clean(state, project); },
110203 buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
110204 cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
110205 getNextInvalidatedProject: function (cancellationToken) {
110206 setupInitialBuild(state, cancellationToken);
110207 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
110208 },
110209 getBuildOrder: function () { return getBuildOrder(state); },
110210 getUpToDateStatusOfProject: function (project) {
110211 var configFileName = resolveProjectName(state, project);
110212 var configFilePath = toResolvedConfigFilePath(state, configFileName);
110213 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
110214 },
110215 invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
110216 buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
110217 getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
110218 close: function () { return stopWatching(state); },
110219 };
110220 }
110221 function relName(state, path) {
110222 return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
110223 }
110224 function reportStatus(state, message) {
110225 var args = [];
110226 for (var _i = 2; _i < arguments.length; _i++) {
110227 args[_i - 2] = arguments[_i];
110228 }
110229 state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
110230 }
110231 function reportWatchStatus(state, message) {
110232 var args = [];
110233 for (var _i = 2; _i < arguments.length; _i++) {
110234 args[_i - 2] = arguments[_i];
110235 }
110236 if (state.hostWithWatch.onWatchStatusChange) {
110237 state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
110238 }
110239 }
110240 function reportErrors(_a, errors) {
110241 var host = _a.host;
110242 errors.forEach(function (err) { return host.reportDiagnostic(err); });
110243 }
110244 function reportAndStoreErrors(state, proj, errors) {
110245 reportErrors(state, errors);
110246 state.projectErrorsReported.set(proj, true);
110247 if (errors.length) {
110248 state.diagnostics.set(proj, errors);
110249 }
110250 }
110251 function reportParseConfigFileDiagnostic(state, proj) {
110252 reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
110253 }
110254 function reportErrorSummary(state, buildOrder) {
110255 if (!state.needsSummary)
110256 return;
110257 state.needsSummary = false;
110258 var canReportSummary = state.watch || !!state.host.reportErrorSummary;
110259 var diagnostics = state.diagnostics;
110260 var totalErrors = 0;
110261 if (isCircularBuildOrder(buildOrder)) {
110262 reportBuildQueue(state, buildOrder.buildOrder);
110263 reportErrors(state, buildOrder.circularDiagnostics);
110264 if (canReportSummary)
110265 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
110266 }
110267 else {
110268 // Report errors from the other projects
110269 buildOrder.forEach(function (project) {
110270 var projectPath = toResolvedConfigFilePath(state, project);
110271 if (!state.projectErrorsReported.has(projectPath)) {
110272 reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
110273 }
110274 });
110275 if (canReportSummary)
110276 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
110277 }
110278 if (state.watch) {
110279 reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
110280 }
110281 else if (state.host.reportErrorSummary) {
110282 state.host.reportErrorSummary(totalErrors);
110283 }
110284 }
110285 /**
110286 * Report the build ordering inferred from the current project graph if we're in verbose mode
110287 */
110288 function reportBuildQueue(state, buildQueue) {
110289 if (state.options.verbose) {
110290 reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n * " + relName(state, s); }).join(""));
110291 }
110292 }
110293 function reportUpToDateStatus(state, configFileName, status) {
110294 switch (status.type) {
110295 case ts.UpToDateStatusType.OutOfDateWithSelf:
110296 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));
110297 case ts.UpToDateStatusType.OutOfDateWithUpstream:
110298 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));
110299 case ts.UpToDateStatusType.OutputMissing:
110300 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));
110301 case ts.UpToDateStatusType.UpToDate:
110302 if (status.newestInputFileTime !== undefined) {
110303 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 || ""));
110304 }
110305 // Don't report anything for "up to date because it was already built" -- too verbose
110306 break;
110307 case ts.UpToDateStatusType.OutOfDateWithPrepend:
110308 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));
110309 case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
110310 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
110311 case ts.UpToDateStatusType.UpstreamOutOfDate:
110312 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));
110313 case ts.UpToDateStatusType.UpstreamBlocked:
110314 return reportStatus(state, status.upstreamProjectBlocked ?
110315 ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
110316 ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
110317 case ts.UpToDateStatusType.Unbuildable:
110318 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
110319 case ts.UpToDateStatusType.TsVersionOutputOfDate:
110320 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);
110321 case ts.UpToDateStatusType.ContainerOnly:
110322 // Don't report status on "solution" projects
110323 // falls through
110324 case ts.UpToDateStatusType.ComputingUpstream:
110325 // Should never leak from getUptoDateStatusWorker
110326 break;
110327 default:
110328 ts.assertType(status);
110329 }
110330 }
110331 /**
110332 * Report the up-to-date status of a project if we're in verbose mode
110333 */
110334 function verboseReportProjectStatus(state, configFileName, status) {
110335 if (state.options.verbose) {
110336 reportUpToDateStatus(state, configFileName, status);
110337 }
110338 }
110339})(ts || (ts = {}));
110340var ts;
110341(function (ts) {
110342 var server;
110343 (function (server) {
110344 /* @internal */
110345 server.ActionSet = "action::set";
110346 /* @internal */
110347 server.ActionInvalidate = "action::invalidate";
110348 /* @internal */
110349 server.ActionPackageInstalled = "action::packageInstalled";
110350 /* @internal */
110351 server.EventTypesRegistry = "event::typesRegistry";
110352 /* @internal */
110353 server.EventBeginInstallTypes = "event::beginInstallTypes";
110354 /* @internal */
110355 server.EventEndInstallTypes = "event::endInstallTypes";
110356 /* @internal */
110357 server.EventInitializationFailed = "event::initializationFailed";
110358 /* @internal */
110359 var Arguments;
110360 (function (Arguments) {
110361 Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
110362 Arguments.LogFile = "--logFile";
110363 Arguments.EnableTelemetry = "--enableTelemetry";
110364 Arguments.TypingSafeListLocation = "--typingSafeListLocation";
110365 Arguments.TypesMapLocation = "--typesMapLocation";
110366 /**
110367 * This argument specifies the location of the NPM executable.
110368 * typingsInstaller will run the command with `${npmLocation} install ...`.
110369 */
110370 Arguments.NpmLocation = "--npmLocation";
110371 /**
110372 * Flag indicating that the typings installer should try to validate the default npm location.
110373 * If the default npm is not found when this flag is enabled, fallback to `npm install`
110374 */
110375 Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
110376 })(Arguments = server.Arguments || (server.Arguments = {}));
110377 /* @internal */
110378 function hasArgument(argumentName) {
110379 return ts.sys.args.indexOf(argumentName) >= 0;
110380 }
110381 server.hasArgument = hasArgument;
110382 /* @internal */
110383 function findArgument(argumentName) {
110384 var index = ts.sys.args.indexOf(argumentName);
110385 return index >= 0 && index < ts.sys.args.length - 1
110386 ? ts.sys.args[index + 1]
110387 : undefined;
110388 }
110389 server.findArgument = findArgument;
110390 /* @internal */
110391 function nowString() {
110392 // E.g. "12:34:56.789"
110393 var d = new Date();
110394 return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
110395 }
110396 server.nowString = nowString;
110397 })(server = ts.server || (ts.server = {}));
110398})(ts || (ts = {}));
110399/* @internal */
110400var ts;
110401(function (ts) {
110402 var JsTyping;
110403 (function (JsTyping) {
110404 function isTypingUpToDate(cachedTyping, availableTypingVersions) {
110405 var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
110406 return availableVersion.compareTo(cachedTyping.version) <= 0;
110407 }
110408 JsTyping.isTypingUpToDate = isTypingUpToDate;
110409 JsTyping.nodeCoreModuleList = [
110410 "assert",
110411 "async_hooks",
110412 "buffer",
110413 "child_process",
110414 "cluster",
110415 "console",
110416 "constants",
110417 "crypto",
110418 "dgram",
110419 "dns",
110420 "domain",
110421 "events",
110422 "fs",
110423 "http",
110424 "https",
110425 "http2",
110426 "inspector",
110427 "net",
110428 "os",
110429 "path",
110430 "perf_hooks",
110431 "process",
110432 "punycode",
110433 "querystring",
110434 "readline",
110435 "repl",
110436 "stream",
110437 "string_decoder",
110438 "timers",
110439 "tls",
110440 "tty",
110441 "url",
110442 "util",
110443 "v8",
110444 "vm",
110445 "zlib"
110446 ];
110447 JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList);
110448 function nonRelativeModuleNameForTypingCache(moduleName) {
110449 return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
110450 }
110451 JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
110452 function loadSafeList(host, safeListPath) {
110453 var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
110454 return new ts.Map(ts.getEntries(result.config));
110455 }
110456 JsTyping.loadSafeList = loadSafeList;
110457 function loadTypesMap(host, typesMapPath) {
110458 var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
110459 if (result.config) {
110460 return new ts.Map(ts.getEntries(result.config.simpleMap));
110461 }
110462 return undefined;
110463 }
110464 JsTyping.loadTypesMap = loadTypesMap;
110465 /**
110466 * @param host is the object providing I/O related operations.
110467 * @param fileNames are the file names that belong to the same project
110468 * @param projectRootPath is the path to the project root directory
110469 * @param safeListPath is the path used to retrieve the safe list
110470 * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
110471 * @param typeAcquisition is used to customize the typing acquisition process
110472 * @param compilerOptions are used as a source for typing inference
110473 */
110474 function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
110475 if (!typeAcquisition || !typeAcquisition.enable) {
110476 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
110477 }
110478 // A typing name to typing file path mapping
110479 var inferredTypings = new ts.Map();
110480 // Only infer typings for .js and .jsx files
110481 fileNames = ts.mapDefined(fileNames, function (fileName) {
110482 var path = ts.normalizePath(fileName);
110483 if (ts.hasJSFileExtension(path)) {
110484 return path;
110485 }
110486 });
110487 var filesToWatch = [];
110488 if (typeAcquisition.include)
110489 addInferredTypings(typeAcquisition.include, "Explicitly included types");
110490 var exclude = typeAcquisition.exclude || [];
110491 // Directories to search for package.json, bower.json and other typing information
110492 var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath));
110493 possibleSearchDirs.add(projectRootPath);
110494 possibleSearchDirs.forEach(function (searchDir) {
110495 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
110496 getTypingNamesFromJson(packageJsonPath, filesToWatch);
110497 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
110498 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
110499 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
110500 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
110501 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
110502 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
110503 });
110504 getTypingNamesFromSourceFileNames(fileNames);
110505 // add typings for unresolved imports
110506 if (unresolvedImports) {
110507 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
110508 addInferredTypings(module_1, "Inferred typings from unresolved imports");
110509 }
110510 // Add the cached typing locations for inferred typings that are already installed
110511 packageNameToTypingLocation.forEach(function (typing, name) {
110512 var registryEntry = typesRegistry.get(name);
110513 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
110514 inferredTypings.set(name, typing.typingLocation);
110515 }
110516 });
110517 // Remove typings that the user has added to the exclude list
110518 for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
110519 var excludeTypingName = exclude_1[_i];
110520 var didDelete = inferredTypings.delete(excludeTypingName);
110521 if (didDelete && log)
110522 log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
110523 }
110524 var newTypingNames = [];
110525 var cachedTypingPaths = [];
110526 inferredTypings.forEach(function (inferred, typing) {
110527 if (inferred !== undefined) {
110528 cachedTypingPaths.push(inferred);
110529 }
110530 else {
110531 newTypingNames.push(typing);
110532 }
110533 });
110534 var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
110535 if (log)
110536 log("Result: " + JSON.stringify(result));
110537 return result;
110538 function addInferredTyping(typingName) {
110539 if (!inferredTypings.has(typingName)) {
110540 inferredTypings.set(typingName, undefined); // TODO: GH#18217
110541 }
110542 }
110543 function addInferredTypings(typingNames, message) {
110544 if (log)
110545 log(message + ": " + JSON.stringify(typingNames));
110546 ts.forEach(typingNames, addInferredTyping);
110547 }
110548 /**
110549 * Get the typing info from common package manager json files like package.json or bower.json
110550 */
110551 function getTypingNamesFromJson(jsonPath, filesToWatch) {
110552 if (!host.fileExists(jsonPath)) {
110553 return;
110554 }
110555 filesToWatch.push(jsonPath);
110556 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
110557 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
110558 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
110559 }
110560 /**
110561 * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
110562 * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
110563 * to the 'angular-route' typing name.
110564 * @param fileNames are the names for source files in the project
110565 */
110566 function getTypingNamesFromSourceFileNames(fileNames) {
110567 var fromFileNames = ts.mapDefined(fileNames, function (j) {
110568 if (!ts.hasJSFileExtension(j))
110569 return undefined;
110570 var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
110571 var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
110572 return safeList.get(cleanedTypingName);
110573 });
110574 if (fromFileNames.length) {
110575 addInferredTypings(fromFileNames, "Inferred typings from file names");
110576 }
110577 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
110578 if (hasJsxFile) {
110579 if (log)
110580 log("Inferred 'react' typings due to presence of '.jsx' extension");
110581 addInferredTyping("react");
110582 }
110583 }
110584 /**
110585 * Infer typing names from packages folder (ex: node_module, bower_components)
110586 * @param packagesFolderPath is the path to the packages folder
110587 */
110588 function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
110589 filesToWatch.push(packagesFolderPath);
110590 // Todo: add support for ModuleResolutionHost too
110591 if (!host.directoryExists(packagesFolderPath)) {
110592 return;
110593 }
110594 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
110595 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
110596 if (log)
110597 log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
110598 var packageNames = [];
110599 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
110600 var fileName = fileNames_1[_i];
110601 var normalizedFileName = ts.normalizePath(fileName);
110602 var baseFileName = ts.getBaseFileName(normalizedFileName);
110603 if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
110604 continue;
110605 }
110606 var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
110607 var packageJson = result_1.config;
110608 // npm 3's package.json contains a "_requiredBy" field
110609 // we should include all the top level module names for npm 2, and only module names whose
110610 // "_requiredBy" field starts with "#" or equals "/" for npm 3.
110611 if (baseFileName === "package.json" && packageJson._requiredBy &&
110612 ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
110613 continue;
110614 }
110615 // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
110616 // to download d.ts files from DefinitelyTyped
110617 if (!packageJson.name) {
110618 continue;
110619 }
110620 var ownTypes = packageJson.types || packageJson.typings;
110621 if (ownTypes) {
110622 var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
110623 if (log)
110624 log(" Package '" + packageJson.name + "' provides its own types.");
110625 inferredTypings.set(packageJson.name, absolutePath);
110626 }
110627 else {
110628 packageNames.push(packageJson.name);
110629 }
110630 }
110631 addInferredTypings(packageNames, " Found package names");
110632 }
110633 }
110634 JsTyping.discoverTypings = discoverTypings;
110635 var NameValidationResult;
110636 (function (NameValidationResult) {
110637 NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
110638 NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
110639 NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
110640 NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
110641 NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
110642 NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
110643 })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
110644 var maxPackageNameLength = 214;
110645 /**
110646 * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
110647 */
110648 function validatePackageName(packageName) {
110649 return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
110650 }
110651 JsTyping.validatePackageName = validatePackageName;
110652 function validatePackageNameWorker(packageName, supportScopedPackage) {
110653 if (!packageName) {
110654 return 1 /* EmptyName */;
110655 }
110656 if (packageName.length > maxPackageNameLength) {
110657 return 2 /* NameTooLong */;
110658 }
110659 if (packageName.charCodeAt(0) === 46 /* dot */) {
110660 return 3 /* NameStartsWithDot */;
110661 }
110662 if (packageName.charCodeAt(0) === 95 /* _ */) {
110663 return 4 /* NameStartsWithUnderscore */;
110664 }
110665 // check if name is scope package like: starts with @ and has one '/' in the middle
110666 // scoped packages are not currently supported
110667 if (supportScopedPackage) {
110668 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
110669 if (matches) {
110670 var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
110671 if (scopeResult !== 0 /* Ok */) {
110672 return { name: matches[1], isScopeName: true, result: scopeResult };
110673 }
110674 var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
110675 if (packageResult !== 0 /* Ok */) {
110676 return { name: matches[2], isScopeName: false, result: packageResult };
110677 }
110678 return 0 /* Ok */;
110679 }
110680 }
110681 if (encodeURIComponent(packageName) !== packageName) {
110682 return 5 /* NameContainsNonURISafeCharacters */;
110683 }
110684 return 0 /* Ok */;
110685 }
110686 function renderPackageNameValidationFailure(result, typing) {
110687 return typeof result === "object" ?
110688 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
110689 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
110690 }
110691 JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
110692 function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
110693 var kind = isScopeName ? "Scope" : "Package";
110694 switch (result) {
110695 case 1 /* EmptyName */:
110696 return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
110697 case 2 /* NameTooLong */:
110698 return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
110699 case 3 /* NameStartsWithDot */:
110700 return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
110701 case 4 /* NameStartsWithUnderscore */:
110702 return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
110703 case 5 /* NameContainsNonURISafeCharacters */:
110704 return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
110705 case 0 /* Ok */:
110706 return ts.Debug.fail(); // Shouldn't have called this.
110707 default:
110708 throw ts.Debug.assertNever(result);
110709 }
110710 }
110711 })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
110712})(ts || (ts = {}));
110713var ts;
110714(function (ts) {
110715 var server;
110716 (function (server) {
110717 var typingsInstaller;
110718 (function (typingsInstaller) {
110719 var nullLog = {
110720 isEnabled: function () { return false; },
110721 writeLine: ts.noop
110722 };
110723 function typingToFileName(cachePath, packageName, installTypingHost, log) {
110724 try {
110725 var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
110726 return result.resolvedModule && result.resolvedModule.resolvedFileName;
110727 }
110728 catch (e) {
110729 if (log.isEnabled()) {
110730 log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
110731 }
110732 return undefined;
110733 }
110734 }
110735 /*@internal*/
110736 function installNpmPackages(npmPath, tsVersion, packageNames, install) {
110737 var hasError = false;
110738 for (var remaining = packageNames.length; remaining > 0;) {
110739 var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
110740 remaining = result.remaining;
110741 hasError = install(result.command) || hasError;
110742 }
110743 return hasError;
110744 }
110745 typingsInstaller.installNpmPackages = installNpmPackages;
110746 /*@internal*/
110747 function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
110748 var sliceStart = packageNames.length - remaining;
110749 var command, toSlice = remaining;
110750 while (true) {
110751 command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
110752 if (command.length < 8000) {
110753 break;
110754 }
110755 toSlice = toSlice - Math.floor(toSlice / 2);
110756 }
110757 return { command: command, remaining: remaining - toSlice };
110758 }
110759 typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
110760 function endsWith(str, suffix, caseSensitive) {
110761 var expectedPos = str.length - suffix.length;
110762 return expectedPos >= 0 &&
110763 (str.indexOf(suffix, expectedPos) === expectedPos ||
110764 (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
110765 }
110766 function isPackageOrBowerJson(fileName, caseSensitive) {
110767 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
110768 }
110769 function sameFiles(a, b, caseSensitive) {
110770 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
110771 }
110772 var ProjectWatcherType;
110773 (function (ProjectWatcherType) {
110774 ProjectWatcherType["FileWatcher"] = "FileWatcher";
110775 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
110776 })(ProjectWatcherType || (ProjectWatcherType = {}));
110777 var TypingsInstaller = /** @class */ (function () {
110778 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
110779 if (log === void 0) { log = nullLog; }
110780 this.installTypingHost = installTypingHost;
110781 this.globalCachePath = globalCachePath;
110782 this.safeListPath = safeListPath;
110783 this.typesMapLocation = typesMapLocation;
110784 this.throttleLimit = throttleLimit;
110785 this.log = log;
110786 this.packageNameToTypingLocation = new ts.Map();
110787 this.missingTypingsSet = new ts.Set();
110788 this.knownCachesSet = new ts.Set();
110789 this.projectWatchers = new ts.Map();
110790 this.pendingRunRequests = [];
110791 this.installRunCount = 1;
110792 this.inFlightRequestCount = 0;
110793 this.latestDistTag = "latest";
110794 this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
110795 this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
110796 if (this.log.isEnabled()) {
110797 this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
110798 }
110799 this.processCacheLocation(this.globalCachePath);
110800 }
110801 TypingsInstaller.prototype.closeProject = function (req) {
110802 this.closeWatchers(req.projectName);
110803 };
110804 TypingsInstaller.prototype.closeWatchers = function (projectName) {
110805 if (this.log.isEnabled()) {
110806 this.log.writeLine("Closing file watchers for project '" + projectName + "'");
110807 }
110808 var watchers = this.projectWatchers.get(projectName);
110809 if (!watchers) {
110810 if (this.log.isEnabled()) {
110811 this.log.writeLine("No watchers are registered for project '" + projectName + "'");
110812 }
110813 return;
110814 }
110815 ts.clearMap(watchers, ts.closeFileWatcher);
110816 this.projectWatchers.delete(projectName);
110817 if (this.log.isEnabled()) {
110818 this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
110819 }
110820 };
110821 TypingsInstaller.prototype.install = function (req) {
110822 var _this = this;
110823 if (this.log.isEnabled()) {
110824 this.log.writeLine("Got install request " + JSON.stringify(req));
110825 }
110826 // load existing typing information from the cache
110827 if (req.cachePath) {
110828 if (this.log.isEnabled()) {
110829 this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
110830 }
110831 this.processCacheLocation(req.cachePath);
110832 }
110833 if (this.safeList === undefined) {
110834 this.initializeSafeList();
110835 }
110836 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);
110837 if (this.log.isEnabled()) {
110838 this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
110839 }
110840 // start watching files
110841 this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
110842 // install typings
110843 if (discoverTypingsResult.newTypingNames.length) {
110844 this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
110845 }
110846 else {
110847 this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
110848 if (this.log.isEnabled()) {
110849 this.log.writeLine("No new typings were requested as a result of typings discovery");
110850 }
110851 }
110852 };
110853 TypingsInstaller.prototype.initializeSafeList = function () {
110854 // Prefer the safe list from the types map if it exists
110855 if (this.typesMapLocation) {
110856 var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
110857 if (safeListFromMap) {
110858 this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
110859 this.safeList = safeListFromMap;
110860 return;
110861 }
110862 this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
110863 }
110864 this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
110865 };
110866 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
110867 if (this.log.isEnabled()) {
110868 this.log.writeLine("Processing cache location '" + cacheLocation + "'");
110869 }
110870 if (this.knownCachesSet.has(cacheLocation)) {
110871 if (this.log.isEnabled()) {
110872 this.log.writeLine("Cache location was already processed...");
110873 }
110874 return;
110875 }
110876 var packageJson = ts.combinePaths(cacheLocation, "package.json");
110877 var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
110878 if (this.log.isEnabled()) {
110879 this.log.writeLine("Trying to find '" + packageJson + "'...");
110880 }
110881 if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
110882 var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
110883 var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
110884 if (this.log.isEnabled()) {
110885 this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
110886 this.log.writeLine("Loaded content of '" + packageLockJson + "'");
110887 }
110888 if (npmConfig.devDependencies && npmLock.dependencies) {
110889 for (var key in npmConfig.devDependencies) {
110890 if (!ts.hasProperty(npmLock.dependencies, key)) {
110891 // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
110892 continue;
110893 }
110894 // key is @types/<package name>
110895 var packageName = ts.getBaseFileName(key);
110896 if (!packageName) {
110897 continue;
110898 }
110899 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
110900 if (!typingFile) {
110901 this.missingTypingsSet.add(packageName);
110902 continue;
110903 }
110904 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
110905 if (existingTypingFile) {
110906 if (existingTypingFile.typingLocation === typingFile) {
110907 continue;
110908 }
110909 if (this.log.isEnabled()) {
110910 this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
110911 }
110912 }
110913 if (this.log.isEnabled()) {
110914 this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
110915 }
110916 var info = ts.getProperty(npmLock.dependencies, key);
110917 var version_1 = info && info.version;
110918 if (!version_1) {
110919 continue;
110920 }
110921 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
110922 this.packageNameToTypingLocation.set(packageName, newTyping);
110923 }
110924 }
110925 }
110926 if (this.log.isEnabled()) {
110927 this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
110928 }
110929 this.knownCachesSet.add(cacheLocation);
110930 };
110931 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
110932 var _this = this;
110933 return ts.mapDefined(typingsToInstall, function (typing) {
110934 var typingKey = ts.mangleScopedPackageName(typing);
110935 if (_this.missingTypingsSet.has(typingKey)) {
110936 if (_this.log.isEnabled())
110937 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
110938 return undefined;
110939 }
110940 var validationResult = ts.JsTyping.validatePackageName(typing);
110941 if (validationResult !== 0 /* Ok */) {
110942 // add typing name to missing set so we won't process it again
110943 _this.missingTypingsSet.add(typingKey);
110944 if (_this.log.isEnabled())
110945 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
110946 return undefined;
110947 }
110948 if (!_this.typesRegistry.has(typingKey)) {
110949 if (_this.log.isEnabled())
110950 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
110951 return undefined;
110952 }
110953 if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
110954 if (_this.log.isEnabled())
110955 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
110956 return undefined;
110957 }
110958 return typingKey;
110959 });
110960 };
110961 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
110962 var npmConfigPath = ts.combinePaths(directory, "package.json");
110963 if (this.log.isEnabled()) {
110964 this.log.writeLine("Npm config file: " + npmConfigPath);
110965 }
110966 if (!this.installTypingHost.fileExists(npmConfigPath)) {
110967 if (this.log.isEnabled()) {
110968 this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
110969 }
110970 this.ensureDirectoryExists(directory, this.installTypingHost);
110971 this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
110972 }
110973 };
110974 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
110975 var _this = this;
110976 if (this.log.isEnabled()) {
110977 this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
110978 }
110979 var filteredTypings = this.filterTypings(typingsToInstall);
110980 if (filteredTypings.length === 0) {
110981 if (this.log.isEnabled()) {
110982 this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
110983 }
110984 this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
110985 return;
110986 }
110987 this.ensurePackageDirectoryExists(cachePath);
110988 var requestId = this.installRunCount;
110989 this.installRunCount++;
110990 // send progress event
110991 this.sendResponse({
110992 kind: server.EventBeginInstallTypes,
110993 eventId: requestId,
110994 // qualified explicitly to prevent occasional shadowing
110995 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
110996 typingsInstallerVersion: ts.version,
110997 projectName: req.projectName
110998 });
110999 var scopedTypings = filteredTypings.map(typingsName);
111000 this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
111001 try {
111002 if (!ok) {
111003 if (_this.log.isEnabled()) {
111004 _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
111005 }
111006 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
111007 var typing = filteredTypings_1[_i];
111008 _this.missingTypingsSet.add(typing);
111009 }
111010 return;
111011 }
111012 // TODO: watch project directory
111013 if (_this.log.isEnabled()) {
111014 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
111015 }
111016 var installedTypingFiles = [];
111017 for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
111018 var packageName = filteredTypings_2[_a];
111019 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
111020 if (!typingFile) {
111021 _this.missingTypingsSet.add(packageName);
111022 continue;
111023 }
111024 // packageName is guaranteed to exist in typesRegistry by filterTypings
111025 var distTags = _this.typesRegistry.get(packageName);
111026 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
111027 var newTyping = { typingLocation: typingFile, version: newVersion };
111028 _this.packageNameToTypingLocation.set(packageName, newTyping);
111029 installedTypingFiles.push(typingFile);
111030 }
111031 if (_this.log.isEnabled()) {
111032 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
111033 }
111034 _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
111035 }
111036 finally {
111037 var response = {
111038 kind: server.EventEndInstallTypes,
111039 eventId: requestId,
111040 projectName: req.projectName,
111041 packagesToInstall: scopedTypings,
111042 installSuccess: ok,
111043 // qualified explicitly to prevent occasional shadowing
111044 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
111045 typingsInstallerVersion: ts.version
111046 };
111047 _this.sendResponse(response);
111048 }
111049 });
111050 };
111051 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
111052 var directoryName = ts.getDirectoryPath(directory);
111053 if (!host.directoryExists(directoryName)) {
111054 this.ensureDirectoryExists(directoryName, host);
111055 }
111056 if (!host.directoryExists(directory)) {
111057 host.createDirectory(directory);
111058 }
111059 };
111060 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
111061 var _this = this;
111062 if (!files.length) {
111063 // shut down existing watchers
111064 this.closeWatchers(projectName);
111065 return;
111066 }
111067 var watchers = this.projectWatchers.get(projectName);
111068 var toRemove = new ts.Map();
111069 if (!watchers) {
111070 watchers = new ts.Map();
111071 this.projectWatchers.set(projectName, watchers);
111072 }
111073 else {
111074 ts.copyEntries(watchers, toRemove);
111075 }
111076 // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
111077 watchers.isInvoked = false;
111078 var isLoggingEnabled = this.log.isEnabled();
111079 var createProjectWatcher = function (path, projectWatcherType) {
111080 var canonicalPath = _this.toCanonicalFileName(path);
111081 toRemove.delete(canonicalPath);
111082 if (watchers.has(canonicalPath)) {
111083 return;
111084 }
111085 if (isLoggingEnabled) {
111086 _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
111087 }
111088 var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
111089 _this.installTypingHost.watchFile(path, function (f, eventKind) {
111090 if (isLoggingEnabled) {
111091 _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
111092 }
111093 if (!watchers.isInvoked) {
111094 watchers.isInvoked = true;
111095 _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
111096 }
111097 }, /*pollingInterval*/ 2000, options) :
111098 _this.installTypingHost.watchDirectory(path, function (f) {
111099 if (isLoggingEnabled) {
111100 _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
111101 }
111102 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
111103 return;
111104 }
111105 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
111106 !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
111107 watchers.isInvoked = true;
111108 _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
111109 }
111110 }, /*recursive*/ true, options);
111111 watchers.set(canonicalPath, isLoggingEnabled ? {
111112 close: function () {
111113 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
111114 watcher.close();
111115 }
111116 } : watcher);
111117 };
111118 // Create watches from list of files
111119 for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
111120 var file = files_1[_i];
111121 if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
111122 // package.json or bower.json exists, watch the file to detect changes and update typings
111123 createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
111124 continue;
111125 }
111126 // path in projectRoot, watch project root
111127 if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
111128 var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
111129 if (subDirectory !== -1) {
111130 // Watch subDirectory
111131 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
111132 }
111133 else {
111134 // Watch the directory itself
111135 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
111136 }
111137 continue;
111138 }
111139 // path in global cache, watch global cache
111140 if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
111141 createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
111142 continue;
111143 }
111144 // watch node_modules or bower_components
111145 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
111146 }
111147 // Remove unused watches
111148 toRemove.forEach(function (watch, path) {
111149 watch.close();
111150 watchers.delete(path);
111151 });
111152 };
111153 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
111154 return {
111155 projectName: request.projectName,
111156 typeAcquisition: request.typeAcquisition,
111157 compilerOptions: request.compilerOptions,
111158 typings: typings,
111159 unresolvedImports: request.unresolvedImports,
111160 kind: server.ActionSet
111161 };
111162 };
111163 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
111164 this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
111165 this.executeWithThrottling();
111166 };
111167 TypingsInstaller.prototype.executeWithThrottling = function () {
111168 var _this = this;
111169 var _loop_1 = function () {
111170 this_1.inFlightRequestCount++;
111171 var request = this_1.pendingRunRequests.pop();
111172 this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
111173 _this.inFlightRequestCount--;
111174 request.onRequestCompleted(ok);
111175 _this.executeWithThrottling();
111176 });
111177 };
111178 var this_1 = this;
111179 while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
111180 _loop_1();
111181 }
111182 };
111183 return TypingsInstaller;
111184 }());
111185 typingsInstaller.TypingsInstaller = TypingsInstaller;
111186 /* @internal */
111187 function typingsName(packageName) {
111188 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
111189 }
111190 typingsInstaller.typingsName = typingsName;
111191 })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
111192 })(server = ts.server || (ts.server = {}));
111193})(ts || (ts = {}));
111194var ts;
111195(function (ts) {
111196 var server;
111197 (function (server) {
111198 var typingsInstaller;
111199 (function (typingsInstaller) {
111200 var fs = require("fs");
111201 var path = require("path");
111202 var FileLog = (function () {
111203 function FileLog(logFile) {
111204 var _this = this;
111205 this.logFile = logFile;
111206 this.isEnabled = function () {
111207 return typeof _this.logFile === "string";
111208 };
111209 this.writeLine = function (text) {
111210 if (typeof _this.logFile !== "string")
111211 return;
111212 try {
111213 fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
111214 }
111215 catch (e) {
111216 _this.logFile = undefined;
111217 }
111218 };
111219 }
111220 return FileLog;
111221 }());
111222 function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
111223 if (path.basename(processName).indexOf("node") === 0) {
111224 var npmPath = path.join(path.dirname(process.argv[0]), "npm");
111225 if (!validateDefaultNpmLocation) {
111226 return npmPath;
111227 }
111228 if (host.fileExists(npmPath)) {
111229 return "\"" + npmPath + "\"";
111230 }
111231 }
111232 return "npm";
111233 }
111234 function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
111235 if (!host.fileExists(typesRegistryFilePath)) {
111236 if (log.isEnabled()) {
111237 log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
111238 }
111239 return new ts.Map();
111240 }
111241 try {
111242 var content = JSON.parse(host.readFile(typesRegistryFilePath));
111243 return new ts.Map(ts.getEntries(content.entries));
111244 }
111245 catch (e) {
111246 if (log.isEnabled()) {
111247 log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
111248 }
111249 return new ts.Map();
111250 }
111251 }
111252 var typesRegistryPackageName = "types-registry";
111253 function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
111254 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
111255 }
111256 var NodeTypingsInstaller = (function (_super) {
111257 __extends(NodeTypingsInstaller, _super);
111258 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
111259 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;
111260 _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
111261 if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
111262 _this.npmPath = "\"" + _this.npmPath + "\"";
111263 }
111264 if (_this.log.isEnabled()) {
111265 _this.log.writeLine("Process id: " + process.pid);
111266 _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
111267 _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
111268 }
111269 (_this.nodeExecSync = require("child_process").execSync);
111270 _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
111271 try {
111272 if (_this.log.isEnabled()) {
111273 _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
111274 }
111275 _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
111276 if (_this.log.isEnabled()) {
111277 _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
111278 }
111279 }
111280 catch (e) {
111281 if (_this.log.isEnabled()) {
111282 _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
111283 }
111284 _this.delayedInitializationError = {
111285 kind: "event::initializationFailed",
111286 message: e.message,
111287 stack: e.stack,
111288 };
111289 }
111290 _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
111291 return _this;
111292 }
111293 NodeTypingsInstaller.prototype.listen = function () {
111294 var _this = this;
111295 process.on("message", function (req) {
111296 if (_this.delayedInitializationError) {
111297 _this.sendResponse(_this.delayedInitializationError);
111298 _this.delayedInitializationError = undefined;
111299 }
111300 switch (req.kind) {
111301 case "discover":
111302 _this.install(req);
111303 break;
111304 case "closeProject":
111305 _this.closeProject(req);
111306 break;
111307 case "typesRegistry": {
111308 var typesRegistry_1 = {};
111309 _this.typesRegistry.forEach(function (value, key) {
111310 typesRegistry_1[key] = value;
111311 });
111312 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
111313 _this.sendResponse(response);
111314 break;
111315 }
111316 case "installPackage": {
111317 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
111318 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
111319 if (cwd) {
111320 _this.installWorker(-1, [packageName_1], cwd, function (success) {
111321 var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
111322 var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
111323 _this.sendResponse(response);
111324 });
111325 }
111326 else {
111327 var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
111328 _this.sendResponse(response);
111329 }
111330 break;
111331 }
111332 default:
111333 ts.Debug.assertNever(req);
111334 }
111335 });
111336 };
111337 NodeTypingsInstaller.prototype.sendResponse = function (response) {
111338 if (this.log.isEnabled()) {
111339 this.log.writeLine("Sending response:\n " + JSON.stringify(response));
111340 }
111341 process.send(response);
111342 if (this.log.isEnabled()) {
111343 this.log.writeLine("Response has been sent.");
111344 }
111345 };
111346 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
111347 var _this = this;
111348 if (this.log.isEnabled()) {
111349 this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
111350 }
111351 var start = Date.now();
111352 var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
111353 if (this.log.isEnabled()) {
111354 this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
111355 }
111356 onRequestCompleted(!hasError);
111357 };
111358 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
111359 if (this.log.isEnabled()) {
111360 this.log.writeLine("Exec: " + command);
111361 }
111362 try {
111363 var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
111364 if (this.log.isEnabled()) {
111365 this.log.writeLine(" Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
111366 }
111367 return false;
111368 }
111369 catch (error) {
111370 var stdout = error.stdout, stderr = error.stderr;
111371 this.log.writeLine(" Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + " stderr:" + indent(ts.sys.newLine, stderr));
111372 return true;
111373 }
111374 };
111375 return NodeTypingsInstaller;
111376 }(typingsInstaller.TypingsInstaller));
111377 typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
111378 function getDirectoryOfPackageJson(fileName, host) {
111379 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
111380 if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
111381 return directory;
111382 }
111383 });
111384 }
111385 var logFilePath = server.findArgument(server.Arguments.LogFile);
111386 var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
111387 var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
111388 var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
111389 var npmLocation = server.findArgument(server.Arguments.NpmLocation);
111390 var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
111391 var log = new FileLog(logFilePath);
111392 if (log.isEnabled()) {
111393 process.on("uncaughtException", function (e) {
111394 log.writeLine("Unhandled exception: " + e + " at " + e.stack);
111395 });
111396 }
111397 process.on("disconnect", function () {
111398 if (log.isEnabled()) {
111399 log.writeLine("Parent process has exited, shutting down...");
111400 }
111401 process.exit(0);
111402 });
111403 var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
111404 installer.listen();
111405 function indent(newline, str) {
111406 return str && str.length
111407 ? newline + " " + str.replace(/\r?\n/, newline + " ")
111408 : "";
111409 }
111410 })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
111411 })(server = ts.server || (ts.server = {}));
111412})(ts || (ts = {}));
111413//# sourceMappingURL=typingsInstaller.js.map
\No newline at end of file