forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.js
More file actions
4290 lines (4290 loc) · 264 KB
/
program.js
File metadata and controls
4290 lines (4290 loc) · 264 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getModuleNameStringLiteralAt = exports.getResolutionDiagnostic = exports.resolveProjectReferencePath = exports.createPrependNodes = exports.parseConfigHostFromCompilerHostLike = exports.filterSemanticDiagnostics = exports.handleNoEmitOptions = exports.emitSkippedWithNoDiagnostics = exports.createProgram = exports.plainJSErrors = exports.getImpliedNodeFormatForFileWorker = exports.getImpliedNodeFormatForFile = exports.getConfigFileParsingDiagnostics = exports.isProgramUptoDate = exports.getReferencedFileLocation = exports.isReferenceFileLocation = exports.isReferencedFile = exports.getInferredLibraryNameResolveFrom = exports.inferredTypesContainingFile = exports.forEachResolvedProjectReference = exports.loadWithModeAwareCache = exports.createTypeReferenceResolutionLoader = exports.typeReferenceResolutionNameAndModeGetter = exports.createModuleResolutionLoader = exports.moduleResolutionNameAndModeGetter = exports.getResolutionModeOverrideForClause = exports.getModeForUsageLocation = exports.isExclusivelyTypeOnlyImportOrExport = exports.getModeForResolutionAtIndex = exports.getModeForFileReference = exports.flattenDiagnosticMessageText = exports.formatDiagnosticsWithColorAndContext = exports.formatLocation = exports.formatColorAndReset = exports.ForegroundColorEscapeSequences = exports.formatDiagnostic = exports.formatDiagnostics = exports.getPreEmitDiagnostics = exports.changeCompilerHostLikeToUseCache = exports.createCompilerHostWorker = exports.createWriteFileMeasuringIO = exports.createGetSourceFile = exports.createCompilerHost = exports.computeCommonSourceDirectoryOfFilenames = exports.resolveTripleslashReference = exports.findConfigFile = void 0;
var ts_1 = require("./_namespaces/ts");
var performance = require("./_namespaces/ts.performance");
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
return (0, ts_1.forEachAncestorDirectory)(searchPath, function (ancestor) {
var fileName = (0, ts_1.combinePaths)(ancestor, configName);
return fileExists(fileName) ? fileName : undefined;
});
}
exports.findConfigFile = findConfigFile;
function resolveTripleslashReference(moduleName, containingFile) {
var basePath = (0, ts_1.getDirectoryPath)(containingFile);
var referencedFileName = (0, ts_1.isRootedDiskPath)(moduleName) ? moduleName : (0, ts_1.combinePaths)(basePath, moduleName);
return (0, ts_1.normalizePath)(referencedFileName);
}
exports.resolveTripleslashReference = resolveTripleslashReference;
/** @internal */
function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
var commonPathComponents;
var failed = (0, ts_1.forEach)(fileNames, function (sourceFile) {
// Each file contributes into common source file path
var sourcePathComponents = (0, ts_1.getNormalizedPathComponents)(sourceFile, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
for (var i = 0; i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
return true;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
// A common path can not be found when paths span multiple drives on windows, for example
if (failed) {
return "";
}
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return (0, ts_1.getPathFromPathComponents)(commonPathComponents);
}
exports.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
return createCompilerHostWorker(options, setParentNodes);
}
exports.createCompilerHost = createCompilerHost;
/** @internal */
function createGetSourceFile(readFile, getCompilerOptions, setParentNodes) {
return function (fileName, languageVersionOrOptions, onError) {
var text;
try {
performance.mark("beforeIORead");
text = readFile(fileName, getCompilerOptions().charset);
performance.mark("afterIORead");
performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
catch (e) {
if (onError) {
onError(e.message);
}
text = "";
}
return text !== undefined ? (0, ts_1.createSourceFile)(fileName, text, languageVersionOrOptions, setParentNodes) : undefined;
};
}
exports.createGetSourceFile = createGetSourceFile;
/** @internal */
function createWriteFileMeasuringIO(actualWriteFile, createDirectory, directoryExists) {
return function (fileName, data, writeByteOrderMark, onError) {
try {
performance.mark("beforeIOWrite");
// NOTE: If patchWriteFileEnsuringDirectory has been called,
// the system.writeFile will do its own directory creation and
// the ensureDirectoriesExist call will always be redundant.
(0, ts_1.writeFileEnsuringDirectories)(fileName, data, writeByteOrderMark, actualWriteFile, createDirectory, directoryExists);
performance.mark("afterIOWrite");
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
}
catch (e) {
if (onError) {
onError(e.message);
}
}
};
}
exports.createWriteFileMeasuringIO = createWriteFileMeasuringIO;
/** @internal */
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts_1.sys; }
var existingDirectories = new Map();
var getCanonicalFileName = (0, ts_1.createGetCanonicalFileName)(system.useCaseSensitiveFileNames);
function directoryExists(directoryPath) {
if (existingDirectories.has(directoryPath)) {
return true;
}
if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
existingDirectories.set(directoryPath, true);
return true;
}
return false;
}
function getDefaultLibLocation() {
return (0, ts_1.getDirectoryPath)((0, ts_1.normalizePath)(system.getExecutingFilePath()));
}
var newLine = (0, ts_1.getNewLineCharacter)(options);
var realpath = system.realpath && (function (path) { return system.realpath(path); });
var compilerHost = {
getSourceFile: createGetSourceFile(function (fileName) { return compilerHost.readFile(fileName); }, function () { return options; }, setParentNodes),
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return (0, ts_1.combinePaths)(getDefaultLibLocation(), (0, ts_1.getDefaultLibFileName)(options)); },
writeFile: createWriteFileMeasuringIO(function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }),
getCurrentDirectory: (0, ts_1.memoize)(function () { return system.getCurrentDirectory(); }),
useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
getCanonicalFileName: getCanonicalFileName,
getNewLine: function () { return newLine; },
fileExists: function (fileName) { return system.fileExists(fileName); },
readFile: function (fileName) { return system.readFile(fileName); },
trace: function (s) { return system.write(s + newLine); },
directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
createDirectory: function (d) { return system.createDirectory(d); },
createHash: (0, ts_1.maybeBind)(system, system.createHash)
};
return compilerHost;
}
exports.createCompilerHostWorker = createCompilerHostWorker;
/** @internal */
function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
var originalReadFile = host.readFile;
var originalFileExists = host.fileExists;
var originalDirectoryExists = host.directoryExists;
var originalCreateDirectory = host.createDirectory;
var originalWriteFile = host.writeFile;
var readFileCache = new Map();
var fileExistsCache = new Map();
var directoryExistsCache = new Map();
var sourceFileCache = new Map();
var readFileWithCache = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
// Cache json or buildInfo
if (!(0, ts_1.fileExtensionIs)(fileName, ".json" /* Extension.Json */) && !(0, ts_1.isBuildInfoFile)(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
};
var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
var key = toPath(fileName);
var impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : undefined;
var forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat);
var value = forImpliedNodeFormat === null || forImpliedNodeFormat === void 0 ? void 0 : forImpliedNodeFormat.get(key);
if (value)
return value;
var sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
if (sourceFile && ((0, ts_1.isDeclarationFileName)(fileName) || (0, ts_1.fileExtensionIs)(fileName, ".json" /* Extension.Json */))) {
sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || new Map()).set(key, sourceFile));
}
return sourceFile;
} : undefined;
// fileExists for any kind of extension
host.fileExists = function (fileName) {
var key = toPath(fileName);
var value = fileExistsCache.get(key);
if (value !== undefined)
return value;
var newValue = originalFileExists.call(host, fileName);
fileExistsCache.set(key, !!newValue);
return newValue;
};
if (originalWriteFile) {
host.writeFile = function (fileName, data) {
var rest = [];
for (var _i = 2; _i < arguments.length; _i++) {
rest[_i - 2] = arguments[_i];
}
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.forEach(function (map) { return map.delete(key); });
}
else if (getSourceFileWithCache) {
sourceFileCache.forEach(function (map) {
var sourceFile = map.get(key);
if (sourceFile && sourceFile.text !== data) {
map.delete(key);
}
});
}
originalWriteFile.call.apply(originalWriteFile, __spreadArray([host, fileName, data], rest, false));
};
}
// directoryExists
if (originalDirectoryExists) {
host.directoryExists = function (directory) {
var key = toPath(directory);
var value = directoryExistsCache.get(key);
if (value !== undefined)
return value;
var newValue = originalDirectoryExists.call(host, directory);
directoryExistsCache.set(key, !!newValue);
return newValue;
};
if (originalCreateDirectory) {
host.createDirectory = function (directory) {
var key = toPath(directory);
directoryExistsCache.delete(key);
originalCreateDirectory.call(host, directory);
};
}
}
return {
originalReadFile: originalReadFile,
originalFileExists: originalFileExists,
originalDirectoryExists: originalDirectoryExists,
originalCreateDirectory: originalCreateDirectory,
originalWriteFile: originalWriteFile,
getSourceFileWithCache: getSourceFileWithCache,
readFileWithCache: readFileWithCache
};
}
exports.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics;
diagnostics = (0, ts_1.addRange)(diagnostics, program.getConfigFileParsingDiagnostics());
diagnostics = (0, ts_1.addRange)(diagnostics, program.getOptionsDiagnostics(cancellationToken));
diagnostics = (0, ts_1.addRange)(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
diagnostics = (0, ts_1.addRange)(diagnostics, program.getGlobalDiagnostics(cancellationToken));
diagnostics = (0, ts_1.addRange)(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
if ((0, ts_1.getEmitDeclarations)(program.getCompilerOptions())) {
diagnostics = (0, ts_1.addRange)(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return (0, ts_1.sortAndDeduplicateDiagnostics)(diagnostics || ts_1.emptyArray);
}
exports.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
output += formatDiagnostic(diagnostic, host);
}
return output;
}
exports.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
var errorMessage = "".concat((0, ts_1.diagnosticCategoryName)(diagnostic), " TS").concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())).concat(host.getNewLine());
if (diagnostic.file) {
var _a = (0, ts_1.getLineAndCharacterOfPosition)(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
var fileName = diagnostic.file.fileName;
var relativeFileName = (0, ts_1.convertToRelativePath)(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
return "".concat(relativeFileName, "(").concat(line + 1, ",").concat(character + 1, "): ") + errorMessage;
}
return errorMessage;
}
exports.formatDiagnostic = formatDiagnostic;
/** @internal */
var ForegroundColorEscapeSequences;
(function (ForegroundColorEscapeSequences) {
ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
})(ForegroundColorEscapeSequences || (exports.ForegroundColorEscapeSequences = ForegroundColorEscapeSequences = {}));
var gutterStyleSequence = "\u001b[7m";
var gutterSeparator = " ";
var resetEscapeSequence = "\u001b[0m";
var ellipsis = "...";
var halfIndent = " ";
var indent = " ";
function getCategoryFormat(category) {
switch (category) {
case ts_1.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
case ts_1.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts_1.DiagnosticCategory.Suggestion: return ts_1.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts_1.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
/** @internal */
function formatColorAndReset(text, formatStyle) {
return formatStyle + text + resetEscapeSequence;
}
exports.formatColorAndReset = formatColorAndReset;
function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
var _a = (0, ts_1.getLineAndCharacterOfPosition)(file, start), firstLine = _a.line, firstLineChar = _a.character;
var _b = (0, ts_1.getLineAndCharacterOfPosition)(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
var lastLineInFile = (0, ts_1.getLineAndCharacterOfPosition)(file, file.text.length).line;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
var context = "";
for (var i = firstLine; i <= lastLine; i++) {
context += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
context += indent + formatColorAndReset((0, ts_1.padLeft)(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
var lineStart = (0, ts_1.getPositionOfLineAndCharacter)(file, i, 0);
var lineEnd = i < lastLineInFile ? (0, ts_1.getPositionOfLineAndCharacter)(file, i + 1, 0) : file.text.length;
var lineContent = file.text.slice(lineStart, lineEnd);
lineContent = (0, ts_1.trimStringEnd)(lineContent); // trim from end
lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
context += indent + formatColorAndReset((0, ts_1.padLeft)(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
context += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
context += indent + formatColorAndReset((0, ts_1.padLeft)("", gutterWidth), gutterStyleSequence) + gutterSeparator;
context += squiggleColor;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
var lastCharForLine = i === lastLine ? lastLineChar : undefined;
context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
context += lineContent.replace(/./g, "~");
}
context += resetEscapeSequence;
}
return context;
}
/** @internal */
function formatLocation(file, start, host, color) {
if (color === void 0) { color = formatColorAndReset; }
var _a = (0, ts_1.getLineAndCharacterOfPosition)(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
var relativeFileName = host ? (0, ts_1.convertToRelativePath)(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
var output = "";
output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
output += color("".concat(firstLine + 1), ForegroundColorEscapeSequences.Yellow);
output += ":";
output += color("".concat(firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
return output;
}
exports.formatLocation = formatLocation;
function formatDiagnosticsWithColorAndContext(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
if (diagnostic.file) {
var file = diagnostic.file, start = diagnostic.start;
output += formatLocation(file, start, host); // TODO: GH#18217
output += " - ";
}
output += formatColorAndReset((0, ts_1.diagnosticCategoryName)(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS".concat(diagnostic.code, ": "), ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file && diagnostic.code !== ts_1.Diagnostics.File_appears_to_be_binary.code) {
output += host.getNewLine();
output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
}
if (diagnostic.relatedInformation) {
output += host.getNewLine();
for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
var _c = _b[_a], file = _c.file, start = _c.start, length_1 = _c.length, messageText = _c.messageText;
if (file) {
output += host.getNewLine();
output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
output += formatCodeSpan(file, start, length_1, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
}
output += host.getNewLine();
output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
}
}
output += host.getNewLine();
}
return output;
}
exports.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
function flattenDiagnosticMessageText(diag, newLine, indent) {
if (indent === void 0) { indent = 0; }
if ((0, ts_1.isString)(diag)) {
return diag;
}
else if (diag === undefined) {
return "";
}
var result = "";
if (indent) {
result += newLine;
for (var i = 0; i < indent; i++) {
result += " ";
}
}
result += diag.messageText;
indent++;
if (diag.next) {
for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
var kid = _a[_i];
result += flattenDiagnosticMessageText(kid, newLine, indent);
}
}
return result;
}
exports.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
/**
* Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly
* provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file.
*/
function getModeForFileReference(ref, containingFileMode) {
return ((0, ts_1.isString)(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode;
}
exports.getModeForFileReference = getModeForFileReference;
function getModeForResolutionAtIndex(file, index) {
if (file.impliedNodeFormat === undefined)
return undefined;
// we ensure all elements of file.imports and file.moduleAugmentations have the relevant parent pointers set during program setup,
// so it's safe to use them even pre-bind
return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index));
}
exports.getModeForResolutionAtIndex = getModeForResolutionAtIndex;
/** @internal */
function isExclusivelyTypeOnlyImportOrExport(decl) {
var _a;
if ((0, ts_1.isExportDeclaration)(decl)) {
return decl.isTypeOnly;
}
if ((_a = decl.importClause) === null || _a === void 0 ? void 0 : _a.isTypeOnly) {
return true;
}
return false;
}
exports.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport;
/**
* Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if
* one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm).
* Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when
* `moduleResolution` is `node16`+.
* @param file The file the import or import-like reference is contained within
* @param usage The module reference string
* @returns The final resolution mode of the import
*/
function getModeForUsageLocation(file, usage) {
var _a, _b;
if (file.impliedNodeFormat === undefined)
return undefined;
if (((0, ts_1.isImportDeclaration)(usage.parent) || (0, ts_1.isExportDeclaration)(usage.parent))) {
var isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent);
if (isTypeOnly) {
var override = getResolutionModeOverrideForClause(usage.parent.assertClause);
if (override) {
return override;
}
}
}
if (usage.parent.parent && (0, ts_1.isImportTypeNode)(usage.parent.parent)) {
var override = getResolutionModeOverrideForClause((_a = usage.parent.parent.assertions) === null || _a === void 0 ? void 0 : _a.assertClause);
if (override) {
return override;
}
}
if (file.impliedNodeFormat !== ts_1.ModuleKind.ESNext) {
// in cjs files, import call expressions are esm format, otherwise everything is cjs
return (0, ts_1.isImportCall)((0, ts_1.walkUpParenthesizedExpressions)(usage.parent)) ? ts_1.ModuleKind.ESNext : ts_1.ModuleKind.CommonJS;
}
// in esm files, import=require statements are cjs format, otherwise everything is esm
// imports are only parent'd up to their containing declaration/expression, so access farther parents with care
var exprParentParent = (_b = (0, ts_1.walkUpParenthesizedExpressions)(usage.parent)) === null || _b === void 0 ? void 0 : _b.parent;
return exprParentParent && (0, ts_1.isImportEqualsDeclaration)(exprParentParent) ? ts_1.ModuleKind.CommonJS : ts_1.ModuleKind.ESNext;
}
exports.getModeForUsageLocation = getModeForUsageLocation;
/** @internal */
function getResolutionModeOverrideForClause(clause, grammarErrorOnNode) {
if (!clause)
return undefined;
if ((0, ts_1.length)(clause.elements) !== 1) {
grammarErrorOnNode === null || grammarErrorOnNode === void 0 ? void 0 : grammarErrorOnNode(clause, ts_1.Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require);
return undefined;
}
var elem = clause.elements[0];
if (!(0, ts_1.isStringLiteralLike)(elem.name))
return undefined;
if (elem.name.text !== "resolution-mode") {
grammarErrorOnNode === null || grammarErrorOnNode === void 0 ? void 0 : grammarErrorOnNode(elem.name, ts_1.Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions);
return undefined;
}
if (!(0, ts_1.isStringLiteralLike)(elem.value))
return undefined;
if (elem.value.text !== "import" && elem.value.text !== "require") {
grammarErrorOnNode === null || grammarErrorOnNode === void 0 ? void 0 : grammarErrorOnNode(elem.value, ts_1.Diagnostics.resolution_mode_should_be_either_require_or_import);
return undefined;
}
return elem.value.text === "import" ? ts_1.ModuleKind.ESNext : ts_1.ModuleKind.CommonJS;
}
exports.getResolutionModeOverrideForClause = getResolutionModeOverrideForClause;
var emptyResolution = {
resolvedModule: undefined,
resolvedTypeReferenceDirective: undefined,
};
function getModuleResolutionName(literal) {
return literal.text;
}
/** @internal */
exports.moduleResolutionNameAndModeGetter = {
getName: getModuleResolutionName,
getMode: function (entry, file) { return getModeForUsageLocation(file, entry); },
};
/** @internal */
function createModuleResolutionLoader(containingFile, redirectedReference, options, host, cache) {
return {
nameAndMode: exports.moduleResolutionNameAndModeGetter,
resolve: function (moduleName, resolutionMode) { return (0, ts_1.resolveModuleName)(moduleName, containingFile, options, host, cache, redirectedReference, resolutionMode); },
};
}
exports.createModuleResolutionLoader = createModuleResolutionLoader;
function getTypeReferenceResolutionName(entry) {
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
return !(0, ts_1.isString)(entry) ? (0, ts_1.toFileNameLowerCase)(entry.fileName) : entry;
}
/** @internal */
exports.typeReferenceResolutionNameAndModeGetter = {
getName: getTypeReferenceResolutionName,
getMode: function (entry, file) { return getModeForFileReference(entry, file === null || file === void 0 ? void 0 : file.impliedNodeFormat); },
};
/** @internal */
function createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, host, cache) {
return {
nameAndMode: exports.typeReferenceResolutionNameAndModeGetter,
resolve: function (typeRef, resoluionMode) { return (0, ts_1.resolveTypeReferenceDirective)(typeRef, containingFile, options, host, redirectedReference, cache, resoluionMode); },
};
}
exports.createTypeReferenceResolutionLoader = createTypeReferenceResolutionLoader;
/** @internal */
function loadWithModeAwareCache(entries, containingFile, redirectedReference, options, containingSourceFile, host, resolutionCache, createLoader) {
if (entries.length === 0)
return ts_1.emptyArray;
var resolutions = [];
var cache = new Map();
var loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache);
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
var name_1 = loader.nameAndMode.getName(entry);
var mode = loader.nameAndMode.getMode(entry, containingSourceFile);
var key = (0, ts_1.createModeAwareCacheKey)(name_1, mode);
var result = cache.get(key);
if (!result) {
cache.set(key, result = loader.resolve(name_1, mode));
}
resolutions.push(result);
}
return resolutions;
}
exports.loadWithModeAwareCache = loadWithModeAwareCache;
/** @internal */
function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, function (resolvedRef, parent) { return resolvedRef && cb(resolvedRef, parent); });
}
exports.forEachResolvedProjectReference = forEachResolvedProjectReference;
function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
var seenResolvedRefs;
return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined);
function worker(projectReferences, resolvedProjectReferences, parent) {
// Visit project references first
if (cbRef) {
var result = cbRef(projectReferences, parent);
if (result)
return result;
}
return (0, ts_1.forEach)(resolvedProjectReferences, function (resolvedRef, index) {
if (resolvedRef && (seenResolvedRefs === null || seenResolvedRefs === void 0 ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
// ignore recursives
return undefined;
}
var result = cbResolvedRef(resolvedRef, parent, index);
if (result || !resolvedRef)
return result;
(seenResolvedRefs || (seenResolvedRefs = new Set())).add(resolvedRef.sourceFile.path);
return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
});
}
}
/** @internal */
exports.inferredTypesContainingFile = "__inferred type names__.ts";
/** @internal */
function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) {
var containingDirectory = options.configFilePath ? (0, ts_1.getDirectoryPath)(options.configFilePath) : currentDirectory;
return (0, ts_1.combinePaths)(containingDirectory, "__lib_node_modules_lookup_".concat(libFileName, "__.ts"));
}
exports.getInferredLibraryNameResolveFrom = getInferredLibraryNameResolveFrom;
function getLibraryNameFromLibFileName(libFileName) {
// Support resolving to lib.dom.d.ts -> @typescript/lib-dom, and
// lib.dom.iterable.d.ts -> @typescript/lib-dom/iterable
// lib.es2015.symbol.wellknown.d.ts -> @typescript/lib-es2015/symbol-wellknown
var components = libFileName.split(".");
var path = components[1];
var i = 2;
while (components[i] && components[i] !== "d") {
path += (i === 2 ? "/" : "-") + components[i];
i++;
}
return "@typescript/lib-" + path;
}
function getLibFileNameFromLibReference(libReference) {
var libName = (0, ts_1.toFileNameLowerCase)(libReference.fileName);
var libFileName = ts_1.libMap.get(libName);
return { libName: libName, libFileName: libFileName };
}
/** @internal */
function isReferencedFile(reason) {
switch (reason === null || reason === void 0 ? void 0 : reason.kind) {
case ts_1.FileIncludeKind.Import:
case ts_1.FileIncludeKind.ReferenceFile:
case ts_1.FileIncludeKind.TypeReferenceDirective:
case ts_1.FileIncludeKind.LibReferenceDirective:
return true;
default:
return false;
}
}
exports.isReferencedFile = isReferencedFile;
/** @internal */
function isReferenceFileLocation(location) {
return location.pos !== undefined;
}
exports.isReferenceFileLocation = isReferenceFileLocation;
/** @internal */
function getReferencedFileLocation(getSourceFileByPath, ref) {
var _a, _b, _c;
var _d, _e, _f, _g, _h, _j;
var file = ts_1.Debug.checkDefined(getSourceFileByPath(ref.file));
var kind = ref.kind, index = ref.index;
var pos, end, packageId, resolutionMode;
switch (kind) {
case ts_1.FileIncludeKind.Import:
var importLiteral = getModuleNameStringLiteralAt(file, index);
packageId = (_f = (_e = (_d = file.resolvedModules) === null || _d === void 0 ? void 0 : _d.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) === null || _e === void 0 ? void 0 : _e.resolvedModule) === null || _f === void 0 ? void 0 : _f.packageId;
if (importLiteral.pos === -1)
return { file: file, packageId: packageId, text: importLiteral.text };
pos = (0, ts_1.skipTrivia)(file.text, importLiteral.pos);
end = importLiteral.end;
break;
case ts_1.FileIncludeKind.ReferenceFile:
(_a = file.referencedFiles[index], pos = _a.pos, end = _a.end);
break;
case ts_1.FileIncludeKind.TypeReferenceDirective:
(_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end, resolutionMode = _b.resolutionMode);
packageId = (_j = (_h = (_g = file.resolvedTypeReferenceDirectiveNames) === null || _g === void 0 ? void 0 : _g.get((0, ts_1.toFileNameLowerCase)(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) === null || _h === void 0 ? void 0 : _h.resolvedTypeReferenceDirective) === null || _j === void 0 ? void 0 : _j.packageId;
break;
case ts_1.FileIncludeKind.LibReferenceDirective:
(_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end);
break;
default:
return ts_1.Debug.assertNever(kind);
}
return { file: file, pos: pos, end: end, packageId: packageId };
}
exports.getReferencedFileLocation = getReferencedFileLocation;
/**
* Determines if program structure is upto date or needs to be recreated
*
* @internal
*/
function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) {
// If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames()))
return false;
// If root file names don't match
if (!(0, ts_1.arrayIsEqualTo)(program.getRootFileNames(), rootFileNames))
return false;
var seenResolvedRefs;
// If project references don't match
if (!(0, ts_1.arrayIsEqualTo)(program.getProjectReferences(), projectReferences, projectReferenceUptoDate))
return false;
// If any file is not up-to-date, then the whole program is not up-to-date
if (program.getSourceFiles().some(sourceFileNotUptoDate))
return false;
// If any of the missing file paths are now created
if (program.getMissingFilePaths().some(fileExists))
return false;
var currentOptions = program.getCompilerOptions();
// If the compilation settings do no match, then the program is not up-to-date
if (!(0, ts_1.compareDataObjects)(currentOptions, newOptions))
return false;
// If library resolution is invalidated, then the program is not up-to-date
if (program.resolvedLibReferences && (0, ts_1.forEachEntry)(program.resolvedLibReferences, function (_value, libFileName) { return hasInvalidatedLibResolutions(libFileName); }))
return false;
// If everything matches but the text of config file is changed,
// error locations can change for program options, so update the program
if (currentOptions.configFile && newOptions.configFile)
return currentOptions.configFile.text === newOptions.configFile.text;
return true;
function sourceFileNotUptoDate(sourceFile) {
return !sourceFileVersionUptoDate(sourceFile) ||
hasInvalidatedResolutions(sourceFile.path);
}
function sourceFileVersionUptoDate(sourceFile) {
return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
}
function projectReferenceUptoDate(oldRef, newRef, index) {
return (0, ts_1.projectReferenceIsEqualTo)(oldRef, newRef) &&
resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
}
function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
if (oldResolvedRef) {
// Assume true
if ((0, ts_1.contains)(seenResolvedRefs, oldResolvedRef))
return true;
var refPath_1 = resolveProjectReferencePath(oldRef);
var newParsedCommandLine = getParsedCommandLine(refPath_1);
// Check if config file exists
if (!newParsedCommandLine)
return false;
// If change in source file
if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile)
return false;
// check file names
if (!(0, ts_1.arrayIsEqualTo)(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames))
return false;
// Add to seen before checking the referenced paths of this config file
(seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
// If child project references are upto date, this project reference is uptodate
return !(0, ts_1.forEach)(oldResolvedRef.references, function (childResolvedRef, index) {
return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
});
}
// In old program, not able to resolve project reference path,
// so if config file doesnt exist, it is uptodate.
var refPath = resolveProjectReferencePath(oldRef);
return !getParsedCommandLine(refPath);
}
}
exports.isProgramUptoDate = isProgramUptoDate;
function getConfigFileParsingDiagnostics(configFileParseResult) {
return configFileParseResult.options.configFile ? __spreadArray(__spreadArray([], configFileParseResult.options.configFile.parseDiagnostics, true), configFileParseResult.errors, true) :
configFileParseResult.errors;
}
exports.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
/**
* A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the
* `options` parameter.
*
* @param fileName The normalized absolute path to check the format of (it need not exist on disk)
* @param [packageJsonInfoCache] A cache for package file lookups - it's best to have a cache when this function is called often
* @param host The ModuleResolutionHost which can perform the filesystem lookups for package json data
* @param options The compiler options to perform the analysis under - relevant options are `moduleResolution` and `traceResolution`
* @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format
*/
function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) {
var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options);
return typeof result === "object" ? result.impliedNodeFormat : result;
}
exports.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile;
/** @internal */
function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) {
switch ((0, ts_1.getEmitModuleResolutionKind)(options)) {
case ts_1.ModuleResolutionKind.Node16:
case ts_1.ModuleResolutionKind.NodeNext:
return (0, ts_1.fileExtensionIsOneOf)(fileName, [".d.mts" /* Extension.Dmts */, ".mts" /* Extension.Mts */, ".mjs" /* Extension.Mjs */]) ? ts_1.ModuleKind.ESNext :
(0, ts_1.fileExtensionIsOneOf)(fileName, [".d.cts" /* Extension.Dcts */, ".cts" /* Extension.Cts */, ".cjs" /* Extension.Cjs */]) ? ts_1.ModuleKind.CommonJS :
(0, ts_1.fileExtensionIsOneOf)(fileName, [".d.ts" /* Extension.Dts */, ".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */]) ? lookupFromPackageJson() :
undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline
default:
return undefined;
}
function lookupFromPackageJson() {
var state = (0, ts_1.getTemporaryModuleResolutionState)(packageJsonInfoCache, host, options);
var packageJsonLocations = [];
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = (0, ts_1.getPackageScopeForPath)(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts_1.ModuleKind.ESNext : ts_1.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
exports.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker;
/** @internal */
exports.plainJSErrors = new Set([
// binder errors
ts_1.Diagnostics.Cannot_redeclare_block_scoped_variable_0.code,
ts_1.Diagnostics.A_module_cannot_have_multiple_default_exports.code,
ts_1.Diagnostics.Another_export_default_is_here.code,
ts_1.Diagnostics.The_first_export_default_is_here.code,
ts_1.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code,
ts_1.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code,
ts_1.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code,
ts_1.Diagnostics.constructor_is_a_reserved_word.code,
ts_1.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code,
ts_1.Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code,
ts_1.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code,
ts_1.Diagnostics.Invalid_use_of_0_in_strict_mode.code,
ts_1.Diagnostics.A_label_is_not_allowed_here.code,
ts_1.Diagnostics.with_statements_are_not_allowed_in_strict_mode.code,
// grammar errors
ts_1.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code,
ts_1.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code,
ts_1.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code,
ts_1.Diagnostics.A_class_member_cannot_have_the_0_keyword.code,
ts_1.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code,
ts_1.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code,
ts_1.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
ts_1.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
ts_1.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code,
ts_1.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code,
ts_1.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code,
ts_1.Diagnostics.A_destructuring_declaration_must_have_an_initializer.code,
ts_1.Diagnostics.A_get_accessor_cannot_have_parameters.code,
ts_1.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code,
ts_1.Diagnostics.A_rest_element_cannot_have_a_property_name.code,
ts_1.Diagnostics.A_rest_element_cannot_have_an_initializer.code,
ts_1.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code,
ts_1.Diagnostics.A_rest_parameter_cannot_have_an_initializer.code,
ts_1.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code,
ts_1.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code,
ts_1.Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code,
ts_1.Diagnostics.A_set_accessor_cannot_have_rest_parameter.code,
ts_1.Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code,
ts_1.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
ts_1.Diagnostics.An_export_declaration_cannot_have_modifiers.code,
ts_1.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
ts_1.Diagnostics.An_import_declaration_cannot_have_modifiers.code,
ts_1.Diagnostics.An_object_member_cannot_be_declared_optional.code,
ts_1.Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code,
ts_1.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code,
ts_1.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code,
ts_1.Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code,
ts_1.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code,
ts_1.Diagnostics.Classes_can_only_extend_a_single_class.code,
ts_1.Diagnostics.Classes_may_not_have_a_field_named_constructor.code,
ts_1.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.code,
ts_1.Diagnostics.Duplicate_label_0.code,
ts_1.Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code,
ts_1.Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code,
ts_1.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code,
ts_1.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code,
ts_1.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code,
ts_1.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code,
ts_1.Diagnostics.Jump_target_cannot_cross_function_boundary.code,
ts_1.Diagnostics.Line_terminator_not_permitted_before_arrow.code,
ts_1.Diagnostics.Modifiers_cannot_appear_here.code,
ts_1.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code,
ts_1.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code,
ts_1.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
ts_1.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code,
ts_1.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code,
ts_1.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code,
ts_1.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code,
ts_1.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code,
ts_1.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code,
ts_1.Diagnostics.Trailing_comma_not_allowed.code,
ts_1.Diagnostics.Variable_declaration_list_cannot_be_empty.code,
ts_1.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code,
ts_1.Diagnostics._0_expected.code,
ts_1.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code,
ts_1.Diagnostics._0_list_cannot_be_empty.code,
ts_1.Diagnostics._0_modifier_already_seen.code,
ts_1.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code,
ts_1.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code,
ts_1.Diagnostics._0_modifier_cannot_appear_on_a_parameter.code,
ts_1.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code,
ts_1.Diagnostics._0_modifier_cannot_be_used_here.code,
ts_1.Diagnostics._0_modifier_must_precede_1_modifier.code,
ts_1.Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code,
ts_1.Diagnostics.const_declarations_must_be_initialized.code,
ts_1.Diagnostics.extends_clause_already_seen.code,
ts_1.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code,
ts_1.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code,
ts_1.Diagnostics.Class_constructor_may_not_be_a_generator.code,
ts_1.Diagnostics.Class_constructor_may_not_be_an_accessor.code,
ts_1.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
// Type errors
ts_1.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code,
]);
/**
* Determine if source file needs to be re-created even if its text hasn't changed
*/
function shouldProgramCreateNewSourceFiles(program, newOptions) {
if (!program)
return false;
// If any compiler options change, we can't reuse old source file even if version match
// The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
return (0, ts_1.optionsHaveChanges)(program.getCompilerOptions(), newOptions, ts_1.sourceFileAffectingCompilerOptions);
}
function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion) {
return {
rootNames: rootNames,
options: options,
host: host,
oldProgram: oldProgram,
configFileParsingDiagnostics: configFileParsingDiagnostics,
typeScriptVersion: typeScriptVersion,
};
}
function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
var _a, _b, _c, _d, _e, _f;
var createProgramOptions = (0, ts_1.isArray)(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences, typeScriptVersion = createProgramOptions.typeScriptVersion;
var oldProgram = createProgramOptions.oldProgram;
var reportInvalidIgnoreDeprecations = (0, ts_1.memoize)(function () { return createOptionValueDiagnostic("ignoreDeprecations", ts_1.Diagnostics.Invalid_value_for_ignoreDeprecations); });
var processingDefaultLibFiles;
var processingOtherFiles;
var files;
var symlinks;
var commonSourceDirectory;
var typeChecker;
var classifiableNames;
var ambientModuleNameToUnmodifiedFileName = new Map();
var fileReasons = (0, ts_1.createMultiMap)();
var cachedBindAndCheckDiagnosticsForFile = {};
var cachedDeclarationDiagnosticsForFile = {};
var resolvedTypeReferenceDirectives = (0, ts_1.createModeAwareCache)();
var fileProcessingDiagnostics;
var automaticTypeDirectiveNames;
var automaticTypeDirectiveResolutions;
var resolvedLibReferences;
var resolvedLibProcessing;
var packageMap;
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
// This works as imported modules are discovered recursively in a depth first manner, specifically:
// - For each root file, findSourceFile is called.
// - This calls processImportedModules for each module imported in the source file.
// - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
var currentNodeModulesDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = new Map();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = new Map();
ts_1.tracing === null || ts_1.tracing === void 0 ? void 0 : ts_1.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true);
performance.mark("beforeProgram");
var host = createProgramOptions.host || createCompilerHost(options);
var configParsingHost = parseConfigHostFromCompilerHostLike(host);
var skipDefaultLib = options.noLib;
var getDefaultLibraryFileName = (0, ts_1.memoize)(function () { return host.getDefaultLibFileName(options); });
var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : (0, ts_1.getDirectoryPath)(getDefaultLibraryFileName());
/**
* Diagnostics for the program
* Only add diagnostics directly if it always would be done irrespective of program structure reuse.
* Otherwise fileProcessingDiagnostics is correct locations so that the diagnostics can be reported in all structure use scenarios
*/
var programDiagnostics = (0, ts_1.createDiagnosticCollection)();
var currentDirectory = host.getCurrentDirectory();
var supportedExtensions = (0, ts_1.getSupportedExtensions)(options);
var supportedExtensionsWithJsonIfResolveJsonModule = (0, ts_1.getSupportedExtensionsWithJsonIfResolveJsonModule)(options, supportedExtensions);
// Map storing if there is emit blocking diagnostics for given input