-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathexportInfoMap.ts
669 lines (622 loc) · 31 KB
/
exportInfoMap.ts
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
import {
__String,
addToSeen,
append,
arrayIsEqualTo,
CancellationToken,
consumesNodeCoreModules,
createMultiMap,
Debug,
emptyArray,
ensureTrailingDirectorySeparator,
findIndex,
forEachAncestorDirectoryStoppingAtGlobalCache,
forEachEntry,
FutureSourceFile,
getBaseFileName,
GetCanonicalFileName,
getDefaultLikeExportNameFromDeclaration,
getDirectoryPath,
getLocalSymbolForExportDefault,
getNodeModulePathParts,
getPackageNameFromTypesPackageName,
getRegexFromPattern,
getSubPatternFromSpec,
getSymbolId,
hostGetCanonicalFileName,
hostUsesCaseSensitiveFileNames,
InternalSymbolName,
isExternalModuleNameRelative,
isExternalModuleSymbol,
isExternalOrCommonJsModule,
isKnownSymbol,
isNonGlobalAmbientModule,
isPrivateIdentifierSymbol,
LanguageServiceHost,
mapDefined,
ModuleSpecifierCache,
ModuleSpecifierResolutionHost,
moduleSpecifiers,
moduleSymbolToValidIdentifier,
nodeCoreModules,
nodeModulesPathPart,
PackageJsonImportFilter,
Path,
pathContainsNodeModules,
Program,
ScriptTarget,
shouldUseUriStyleNodeCoreModules,
skipAlias,
SourceFile,
startsWith,
Statement,
stripQuotes,
Symbol,
SymbolFlags,
timestamp,
TypeChecker,
unescapeLeadingUnderscores,
unmangleScopedPackageName,
UserPreferences,
} from "./_namespaces/ts.js";
/** @internal */
export const enum ImportKind {
Named,
Default,
Namespace,
CommonJS,
}
/** @internal */
export const enum ExportKind {
Named,
Default,
ExportEquals,
UMD,
Module,
}
/** @internal */
export interface SymbolExportInfo {
readonly symbol: Symbol;
readonly moduleSymbol: Symbol;
/** Set if `moduleSymbol` is an external module, not an ambient module */
moduleFileName: string | undefined;
exportKind: ExportKind;
targetFlags: SymbolFlags;
/** True if export was only found via the package.json AutoImportProvider (for telemetry). */
isFromPackageJson: boolean;
}
/**
* @internal
* ExportInfo for an export that does not exist yet, so does not have a symbol.
*/
export type FutureSymbolExportInfo = Omit<SymbolExportInfo, "symbol"> & { readonly symbol?: undefined; };
interface CachedSymbolExportInfo {
// Used to rehydrate `symbol` and `moduleSymbol` when transient
id: number;
symbolName: string;
capitalizedSymbolName: string | undefined;
symbolTableKey: __String;
moduleName: string;
moduleFile: SourceFile | undefined;
packageName: string | undefined;
// SymbolExportInfo, but optional symbols
readonly symbol: Symbol | undefined;
readonly moduleSymbol: Symbol | undefined;
moduleFileName: string | undefined;
exportKind: ExportKind;
targetFlags: SymbolFlags;
isFromPackageJson: boolean;
}
/** @internal */
export interface ExportInfoMap {
isUsableByFile(importingFile: Path): boolean;
clear(): void;
add(importingFile: Path, symbol: Symbol, key: __String, moduleSymbol: Symbol, moduleFile: SourceFile | undefined, exportKind: ExportKind, isFromPackageJson: boolean, checker: TypeChecker): void;
get(importingFile: Path, key: ExportMapInfoKey): readonly SymbolExportInfo[] | undefined;
search<T>(importingFile: Path, preferCapitalized: boolean, matches: (name: string, targetFlags: SymbolFlags) => boolean, action: (info: readonly SymbolExportInfo[], symbolName: string, isFromAmbientModule: boolean, key: ExportMapInfoKey) => T | undefined): T | undefined;
releaseSymbols(): void;
isEmpty(): boolean;
/** @returns Whether the change resulted in the cache being cleared */
onFileChanged(oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean): boolean;
}
/** @internal */
export interface CacheableExportInfoMapHost {
getCurrentProgram(): Program | undefined;
getPackageJsonAutoImportProvider(): Program | undefined;
getGlobalTypingsCacheLocation(): string | undefined;
}
export type ExportMapInfoKey = string & { __exportInfoKey: void; };
/** @internal */
export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): ExportInfoMap {
let exportInfoId = 1;
const exportInfo = createMultiMap<ExportMapInfoKey, CachedSymbolExportInfo>();
const symbols = new Map<number, [symbol: Symbol, moduleSymbol: Symbol]>();
/**
* Key: node_modules package name (no @types).
* Value: path to deepest node_modules folder seen that is
* both visible to `usableByFileName` and contains the package.
*
* Later, we can see if a given SymbolExportInfo is shadowed by
* a another installation of the same package in a deeper
* node_modules folder by seeing if its path starts with the
* value stored here.
*/
const packages = new Map<string, string>();
let usableByFileName: Path | undefined;
const cache: ExportInfoMap = {
isUsableByFile: importingFile => importingFile === usableByFileName,
isEmpty: () => !exportInfo.size,
clear: () => {
exportInfo.clear();
symbols.clear();
usableByFileName = undefined;
},
add: (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, checker) => {
if (importingFile !== usableByFileName) {
cache.clear();
usableByFileName = importingFile;
}
let packageName;
if (moduleFile) {
const nodeModulesPathParts = getNodeModulePathParts(moduleFile.fileName);
if (nodeModulesPathParts) {
const { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex } = nodeModulesPathParts;
packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex)));
if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) {
const prevDeepestNodeModulesPath = packages.get(packageName);
const nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex + 1);
if (prevDeepestNodeModulesPath) {
const prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(nodeModulesPathPart);
if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) {
packages.set(packageName, nodeModulesPath);
}
}
else {
packages.set(packageName, nodeModulesPath);
}
}
}
}
const isDefault = exportKind === ExportKind.Default;
const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol;
// 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`.
// 2. A re-export merged with an export from a module augmentation can result in `symbol`
// being an external module symbol; the name it is re-exported by will be `symbolTableKey`
// (which comes from the keys of `moduleSymbol.exports`.)
// 3. Otherwise, we have a default/namespace import that can be imported by any name, and
// `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to
// get a better name.
const names = exportKind === ExportKind.Named || isExternalModuleSymbol(namedSymbol)
? unescapeLeadingUnderscores(symbolTableKey)
: getNamesForExportedSymbol(namedSymbol, checker, /*scriptTarget*/ undefined);
const symbolName = typeof names === "string" ? names : names[0];
const capitalizedSymbolName = typeof names === "string" ? undefined : names[1];
const moduleName = stripQuotes(moduleSymbol.name);
const id = exportInfoId++;
const target = skipAlias(symbol, checker);
const storedSymbol = symbol.flags & SymbolFlags.Transient ? undefined : symbol;
const storedModuleSymbol = moduleSymbol.flags & SymbolFlags.Transient ? undefined : moduleSymbol;
if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]);
exportInfo.add(key(symbolName, symbol, isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), {
id,
symbolTableKey,
symbolName,
capitalizedSymbolName,
moduleName,
moduleFile,
moduleFileName: moduleFile?.fileName,
packageName,
exportKind,
targetFlags: target.flags,
isFromPackageJson,
symbol: storedSymbol,
moduleSymbol: storedModuleSymbol,
});
},
get: (importingFile, key) => {
if (importingFile !== usableByFileName) return;
const result = exportInfo.get(key);
return result?.map(rehydrateCachedInfo);
},
search: (importingFile, preferCapitalized, matches, action) => {
if (importingFile !== usableByFileName) return;
return forEachEntry(exportInfo, (info, key) => {
const { symbolName, ambientModuleName } = parseKey(key);
const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName;
if (matches(name, info[0].targetFlags)) {
const rehydrated = info.map(rehydrateCachedInfo);
const filtered = rehydrated.filter((r, i) => isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName));
if (filtered.length) {
const res = action(filtered, name, !!ambientModuleName, key);
if (res !== undefined) return res;
}
}
});
},
releaseSymbols: () => {
symbols.clear();
},
onFileChanged: (oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean) => {
if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) {
// File is purely global; doesn't affect export map
return false;
}
if (
usableByFileName && usableByFileName !== newSourceFile.path ||
// If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node.
// Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list.
typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) ||
// Module agumentation and ambient module changes can add or remove exports available to be auto-imported.
// Changes elsewhere in the file can change the *type* of an export in a module augmentation,
// but type info is gathered in getCompletionEntryDetails, which doesn't use the cache.
!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) ||
!ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)
) {
cache.clear();
return true;
}
usableByFileName = newSourceFile.path;
return false;
},
};
if (Debug.isDebugging) {
Object.defineProperty(cache, "__cache", { value: exportInfo });
}
return cache;
function rehydrateCachedInfo(info: CachedSymbolExportInfo): SymbolExportInfo {
if (info.symbol && info.moduleSymbol) return info as SymbolExportInfo;
const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info;
const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray;
if (cachedSymbol && cachedModuleSymbol) {
return {
symbol: cachedSymbol,
moduleSymbol: cachedModuleSymbol,
moduleFileName,
exportKind,
targetFlags,
isFromPackageJson,
};
}
const checker = (isFromPackageJson
? host.getPackageJsonAutoImportProvider()!
: host.getCurrentProgram()!).getTypeChecker();
const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(
info.moduleFile
? checker.getMergedSymbol(info.moduleFile.symbol)
: checker.tryFindAmbientModule(info.moduleName),
);
const symbol = info.symbol || cachedSymbol || Debug.checkDefined(
exportKind === ExportKind.ExportEquals
? checker.resolveExternalModuleSymbol(moduleSymbol)
: checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol),
`Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`,
);
symbols.set(id, [symbol, moduleSymbol]);
return {
symbol,
moduleSymbol,
moduleFileName,
exportKind,
targetFlags,
isFromPackageJson,
};
}
function key(importedName: string, symbol: Symbol, ambientModuleName: string | undefined, checker: TypeChecker) {
const moduleKey = ambientModuleName || "";
return `${importedName.length} ${getSymbolId(skipAlias(symbol, checker))} ${importedName} ${moduleKey}` as ExportMapInfoKey;
}
function parseKey(key: ExportMapInfoKey) {
const firstSpace = key.indexOf(" ");
const secondSpace = key.indexOf(" ", firstSpace + 1);
const symbolNameLength = parseInt(key.substring(0, firstSpace), 10);
const data = key.substring(secondSpace + 1);
const symbolName = data.substring(0, symbolNameLength);
const moduleKey = data.substring(symbolNameLength + 1);
const ambientModuleName = moduleKey === "" ? undefined : moduleKey;
return { symbolName, ambientModuleName };
}
function fileIsGlobalOnly(file: SourceFile) {
return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames;
}
function ambientModuleDeclarationsAreEqual(oldSourceFile: SourceFile, newSourceFile: SourceFile) {
if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) {
return false;
}
let oldFileStatementIndex = -1;
let newFileStatementIndex = -1;
for (const ambientModuleName of newSourceFile.ambientModuleNames) {
const isMatchingModuleDeclaration = (node: Statement) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName;
oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1);
newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1);
if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) {
return false;
}
}
return true;
}
function isNotShadowedByDeeperNodeModulesPackage(info: SymbolExportInfo, packageName: string | undefined) {
if (!packageName || !info.moduleFileName) return true;
const typingsCacheLocation = host.getGlobalTypingsCacheLocation();
if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) return true;
const packageDeepestNodeModulesPath = packages.get(packageName);
return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath);
}
}
/** @internal */
export function isImportable(
program: Program,
fromFile: SourceFile,
toFile: SourceFile | undefined,
toModule: Symbol,
preferences: UserPreferences,
packageJsonFilter: PackageJsonImportFilter | undefined,
moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost,
moduleSpecifierCache: ModuleSpecifierCache | undefined,
): boolean {
if (!toFile) {
// Ambient module
let useNodePrefix;
const moduleName = stripQuotes(toModule.name);
if (nodeCoreModules.has(moduleName) && (useNodePrefix = shouldUseUriStyleNodeCoreModules(fromFile, program)) !== undefined) {
return useNodePrefix === startsWith(moduleName, "node:");
}
return !packageJsonFilter
|| packageJsonFilter.allowsImportingAmbientModule(toModule, moduleSpecifierResolutionHost)
|| fileContainsPackageImport(fromFile, moduleName);
}
Debug.assertIsDefined(toFile);
if (fromFile === toFile) return false;
const cachedResult = moduleSpecifierCache?.get(fromFile.path, toFile.path, preferences, {});
if (cachedResult?.isBlockedByPackageJsonDependencies !== undefined) {
return !cachedResult.isBlockedByPackageJsonDependencies || !!cachedResult.packageName && fileContainsPackageImport(fromFile, cachedResult.packageName);
}
const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost);
const globalTypingsCache = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation?.();
const hasImportablePath = !!moduleSpecifiers.forEachFileNameOfModule(
fromFile.fileName,
toFile.fileName,
moduleSpecifierResolutionHost,
/*preferSymlinks*/ false,
toPath => {
const file = program.getSourceFile(toPath);
// Determine to import using toPath only if toPath is what we were looking at
// or there doesnt exist the file in the program by the symlink
return (file === toFile || !file) &&
isImportablePath(
fromFile.fileName,
toPath,
getCanonicalFileName,
globalTypingsCache,
moduleSpecifierResolutionHost,
);
},
);
if (packageJsonFilter) {
const importInfo = hasImportablePath ? packageJsonFilter.getSourceFileInfo(toFile, moduleSpecifierResolutionHost) : undefined;
moduleSpecifierCache?.setBlockedByPackageJsonDependencies(fromFile.path, toFile.path, preferences, {}, importInfo?.packageName, !importInfo?.importable);
return !!importInfo?.importable || hasImportablePath && !!importInfo?.packageName && fileContainsPackageImport(fromFile, importInfo.packageName);
}
return hasImportablePath;
}
function fileContainsPackageImport(sourceFile: SourceFile, packageName: string) {
return sourceFile.imports && sourceFile.imports.some(i => i.text === packageName || i.text.startsWith(packageName + "/"));
}
/**
* Don't include something from a `node_modules` that isn't actually reachable by a global import.
* A relative import to node_modules is usually a bad idea.
*/
function isImportablePath(
fromPath: string,
toPath: string,
getCanonicalFileName: GetCanonicalFileName,
globalCachePath: string | undefined,
host: ModuleSpecifierResolutionHost,
): boolean {
// If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
const toNodeModules = forEachAncestorDirectoryStoppingAtGlobalCache(
host,
toPath,
ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined,
);
const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules));
return toNodeModulesParent === undefined
|| startsWith(getCanonicalFileName(fromPath), toNodeModulesParent)
|| (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
}
/** @internal */
export function forEachExternalModuleToImportFrom(
program: Program,
host: LanguageServiceHost,
preferences: UserPreferences,
useAutoImportProvider: boolean,
cb: (module: Symbol, moduleFile: SourceFile | undefined, program: Program, isFromPackageJson: boolean) => void,
): void {
const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host);
const excludePatterns = preferences.autoImportFileExcludePatterns && getIsExcludedPatterns(preferences, useCaseSensitiveFileNames);
forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, host, (module, file) => cb(module, file, program, /*isFromPackageJson*/ false));
const autoImportProvider = useAutoImportProvider && host.getPackageJsonAutoImportProvider?.();
if (autoImportProvider) {
const start = timestamp();
const checker = program.getTypeChecker();
forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, host, (module, file) => {
if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(module.name, /*location*/ undefined, SymbolFlags.Module, /*excludeGlobals*/ false)) {
// The AutoImportProvider filters files already in the main program out of its *root* files,
// but non-root files can still be present in both programs, and already in the export info map
// at this point. This doesn't create any incorrect behavior, but is a waste of time and memory,
// so we filter them out here.
cb(module, file, autoImportProvider, /*isFromPackageJson*/ true);
}
});
host.log?.(`forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`);
}
}
function getIsExcludedPatterns(preferences: UserPreferences, useCaseSensitiveFileNames: boolean) {
return mapDefined(preferences.autoImportFileExcludePatterns, spec => {
// The client is expected to send rooted path specs since we don't know
// what directory a relative path is relative to.
const pattern = getSubPatternFromSpec(spec, "", "exclude");
return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined;
});
}
function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], excludePatterns: readonly RegExp[] | undefined, host: LanguageServiceHost, cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) {
const isExcluded = excludePatterns && getIsExcluded(excludePatterns, host);
for (const ambient of checker.getAmbientModules()) {
if (!ambient.name.includes("*") && !(excludePatterns && ambient.declarations?.every(d => isExcluded!(d.getSourceFile())))) {
cb(ambient, /*sourceFile*/ undefined);
}
}
for (const sourceFile of allSourceFiles) {
if (isExternalOrCommonJsModule(sourceFile) && !isExcluded?.(sourceFile)) {
cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
}
}
}
function getIsExcluded(excludePatterns: readonly RegExp[], host: LanguageServiceHost) {
const realpathsWithSymlinks = host.getSymlinkCache?.().getSymlinkedDirectoriesByRealpath();
return (({ fileName, path }: SourceFile) => {
if (excludePatterns.some(p => p.test(fileName))) return true;
if (realpathsWithSymlinks?.size && pathContainsNodeModules(fileName)) {
let dir = getDirectoryPath(fileName);
return forEachAncestorDirectoryStoppingAtGlobalCache(
host,
getDirectoryPath(path),
dirPath => {
const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath));
if (symlinks) {
return symlinks.some(s => excludePatterns.some(p => p.test(fileName.replace(dir, s))));
}
dir = getDirectoryPath(dir);
},
) ?? false;
}
return false;
});
}
/** @internal */
export function getIsFileExcluded(host: LanguageServiceHost, preferences: UserPreferences): (sourceFile: SourceFile) => boolean {
if (!preferences.autoImportFileExcludePatterns) return () => false;
return getIsExcluded(getIsExcludedPatterns(preferences, hostUsesCaseSensitiveFileNames(host)), host);
}
/** @internal */
export function getExportInfoMap(importingFile: SourceFile | FutureSourceFile, host: LanguageServiceHost, program: Program, preferences: UserPreferences, cancellationToken: CancellationToken | undefined): ExportInfoMap {
const start = timestamp();
// Pulling the AutoImportProvider project will trigger its updateGraph if pending,
// which will invalidate the export map cache if things change, so pull it before
// checking the cache.
host.getPackageJsonAutoImportProvider?.();
const cache = host.getCachedExportInfoMap?.() || createCacheableExportInfoMap({
getCurrentProgram: () => program,
getPackageJsonAutoImportProvider: () => host.getPackageJsonAutoImportProvider?.(),
getGlobalTypingsCacheLocation: () => host.getGlobalTypingsCacheLocation?.(),
});
if (cache.isUsableByFile(importingFile.path)) {
host.log?.("getExportInfoMap: cache hit");
return cache;
}
host.log?.("getExportInfoMap: cache miss or empty; calculating new results");
let moduleCount = 0;
try {
forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, (moduleSymbol, moduleFile, program, isFromPackageJson) => {
if (++moduleCount % 100 === 0) cancellationToken?.throwIfCancellationRequested();
const seenExports = new Set<__String>();
const checker = program.getTypeChecker();
const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker);
// Note: I think we shouldn't actually see resolved module symbols here, but weird merges
// can cause it to happen: see 'completionsImport_mergedReExport.ts'
if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) {
cache.add(
importingFile.path,
defaultInfo.symbol,
defaultInfo.exportKind === ExportKind.Default ? InternalSymbolName.Default : InternalSymbolName.ExportEquals,
moduleSymbol,
moduleFile,
defaultInfo.exportKind,
isFromPackageJson,
checker,
);
}
checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => {
if (exported !== defaultInfo?.symbol && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) {
cache.add(
importingFile.path,
exported,
key,
moduleSymbol,
moduleFile,
ExportKind.Named,
isFromPackageJson,
checker,
);
}
});
});
}
catch (err) {
// Ensure cache is reset if operation is cancelled
cache.clear();
throw err;
}
host.log?.(`getExportInfoMap: done in ${timestamp() - start} ms`);
return cache;
}
/** @internal */
export function getDefaultLikeExportInfo(moduleSymbol: Symbol, checker: TypeChecker): {
symbol: Symbol;
exportKind: ExportKind;
} | undefined {
const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
if (exportEquals !== moduleSymbol) {
const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, exportEquals);
if (defaultExport) return { symbol: defaultExport, exportKind: ExportKind.Default };
return { symbol: exportEquals, exportKind: ExportKind.ExportEquals };
}
const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol);
if (defaultExport) return { symbol: defaultExport, exportKind: ExportKind.Default };
}
function isImportableSymbol(symbol: Symbol, checker: TypeChecker) {
return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol);
}
function getNamesForExportedSymbol(defaultExport: Symbol, checker: TypeChecker, scriptTarget: ScriptTarget | undefined) {
let names: string | string[] | undefined;
forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, (name, capitalizedName) => {
names = capitalizedName ? [name, capitalizedName] : name;
return true;
});
return Debug.checkDefined(names);
}
/**
* @internal
* May call `cb` multiple times with the same name.
* Terminates when `cb` returns a truthy value.
*/
export function forEachNameOfDefaultExport<T>(defaultExport: Symbol, checker: TypeChecker, scriptTarget: ScriptTarget | undefined, cb: (name: string, capitalizedName?: string) => T | undefined): T | undefined {
let chain: Symbol[] | undefined;
let current: Symbol | undefined = defaultExport;
const seen = new Set<Symbol>();
while (current) {
// The predecessor to this function also looked for a name on the `localSymbol`
// of default exports, but I think `getDefaultLikeExportNameFromDeclaration`
// accomplishes the same thing via syntax - no tests failed when I removed it.
const fromDeclaration = getDefaultLikeExportNameFromDeclaration(current);
if (fromDeclaration) {
const final = cb(fromDeclaration);
if (final) return final;
}
if (current.escapedName !== InternalSymbolName.Default && current.escapedName !== InternalSymbolName.ExportEquals) {
const final = cb(current.name);
if (final) return final;
}
chain = append(chain, current);
if (!addToSeen(seen, current)) break;
current = current.flags & SymbolFlags.Alias ? checker.getImmediateAliasedSymbol(current) : undefined;
}
for (const symbol of chain ?? emptyArray) {
if (symbol.parent && isExternalModuleSymbol(symbol.parent)) {
const final = cb(
moduleSymbolToValidIdentifier(symbol.parent, scriptTarget, /*forceCapitalize*/ false),
moduleSymbolToValidIdentifier(symbol.parent, scriptTarget, /*forceCapitalize*/ true),
);
if (final) return final;
}
}
}