Laravel Sampe Tulang
Laravel Sampe Tulang
set(currentPath, true);
var result = fn(state, currentPath);
if (result && isChangedSignature(state, currentPath)) {
var currentSourceFile =
ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
queue.push.apply(queue,
ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
}
}
}
}
ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
var seenFileAndExportsOfFile = new ts.Set();
// Go through exported modules from cache first
// If exported modules has path, all files referencing file exported from
are affected
if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function
(exportedModules, exportedFromPath) {
return exportedModules &&
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath,
seenFileAndExportsOfFile, fn);
})) {
return;
}
// If exported from path is not from cache and exported modules has path,
all files referencing file exported from are affected
ts.forEachEntry(state.exportedModulesMap, function (exportedModules,
exportedFromPath) {
return !
state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we
already iterated this through cache, ignore it
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath,
seenFileAndExportsOfFile, fn);
});
}
/**
* Iterate on files referencing referencedPath
*/
function forEachFilesReferencingPath(state, referencedPath,
seenFileAndExportsOfFile, fn) {
return ts.forEachEntry(state.referencedMap, function (referencesInFile,
filePath) {
return referencesInFile.has(referencedPath) &&
forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
});
}
/**
* fn on file and iterate on anything that exports this file
*/
function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile,
fn) {
if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
return false;
}
if (fn(state, filePath)) {
// If there are no more diagnostics from old cache, done
return true;
}
ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
// Go through exported modules from cache first
// If exported modules has path, all files referencing file exported from
are affected
if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function
(exportedModules, exportedFromPath) {
return exportedModules &&
exportedModules.has(filePath) &&
forEachFileAndExportsOfFile(state, exportedFromPath,
seenFileAndExportsOfFile, fn);
})) {
return true;
}
// If exported from path is not from cache and exported modules has path,
all files referencing file exported from are affected
if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules,
exportedFromPath) {
return !
state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we
already iterated this through cache, ignore it
exportedModules.has(filePath) &&
forEachFileAndExportsOfFile(state, exportedFromPath,
seenFileAndExportsOfFile, fn);
})) {
return true;
}
// Remove diagnostics of files that import this file (without going to
exports of referencing files)
return !!ts.forEachEntry(state.referencedMap, function (referencesInFile,
referencingFilePath) {
return referencesInFile.has(filePath) &&
!seenFileAndExportsOfFile.has(referencingFilePath) && // Not
already removed diagnostic file
fn(state, referencingFilePath);
} // Dont add to seen since this is not yet done with the export removal
);
}
/**
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the
iteration is handled correctly
*/
function doneWithAffectedFile(state, affected, emitKind, isPendingEmit,
isBuildInfoEmit) {
if (isBuildInfoEmit) {
state.buildInfoEmitPending = false;
}
else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
else {
state.seenAffectedFiles.add(affected.resolvedPath);
if (emitKind !== undefined) {
(state.seenEmittedFiles || (state.seenEmittedFiles = new
ts.Map())).set(affected.resolvedPath, emitKind);
}
if (isPendingEmit) {
state.affectedFilesPendingEmitIndex++;
state.buildInfoEmitPending = true;
}
else {
state.affectedFilesIndex++;
}
}
}
/**
* Returns the result with affected file
*/
function toAffectedFileResult(state, result, affected) {
doneWithAffectedFile(state, affected);
return { result: result, affected: affected };
}
/**
* Returns the result with affected file
*/
function toAffectedFileEmitResult(state, result, affected, emitKind,
isPendingEmit, isBuildInfoEmit) {
doneWithAffectedFile(state, affected, emitKind, isPendingEmit,
isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
* Gets semantic diagnostics for the file which are
* bindAndCheckDiagnostics (from cache) and program diagnostics
*/
function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state,
sourceFile, cancellationToken),
ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
}
/**
* Gets the binder and checker diagnostics either from cache if present, or
otherwise from program and caches it
* 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
*/
function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile,
cancellationToken) {
var path = sourceFile.resolvedPath;
if (state.semanticDiagnosticsPerFile) {
var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
// Report the bind and check diagnostics from the cache if we already
have those diagnostics present
if (cachedDiagnostics) {
return ts.filterSemanticDiagnotics(cachedDiagnostics,
state.compilerOptions);
}
}
// Diagnostics werent cached, get them from program, and cache the result
var diagnostics =
ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile,
cancellationToken);
if (state.semanticDiagnosticsPerFile) {
state.semanticDiagnosticsPerFile.set(path, diagnostics);
}
return ts.filterSemanticDiagnotics(diagnostics, state.compilerOptions);
}
/**
* Gets the program information to be emitted in buildInfo so that we can use
it to create new program
*/
function getProgramBuildInfo(state, getCanonicalFileName) {
if (ts.outFile(state.compilerOptions))
return undefined;
var currentDirectory =
ts.Debug.checkDefined(state.program).getCurrentDirectory();
var buildInfoDirectory =
ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePat
h(state.compilerOptions), currentDirectory));
var fileInfos = {};
state.fileInfos.forEach(function (value, key) {
var signature = state.currentAffectedFilesSignatures &&
state.currentAffectedFilesSignatures.get(key);
fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value :
{ version: value.version, signature: signature, affectsGlobalScope:
value.affectsGlobalScope };
});
var result = {
fileInfos: fileInfos,
options: convertToReusableCompilerOptions(state.compilerOptions,
relativeToBuildInfoEnsuringAbsolutePath)
};
if (state.referencedMap) {
var referencedMap = {};
for (var _i = 0, _a =
ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i <
_a.length; _i++) {
var key = _a[_i];
referencedMap[relativeToBuildInfo(key)] =
ts.arrayFrom(state.referencedMap.get(key).keys(),
relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
}
result.referencedMap = referencedMap;
}
if (state.exportedModulesMap) {
var exportedModulesMap = {};
for (var _b = 0, _c =
ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive);
_b < _c.length; _b++) {
var key = _c[_b];
var newValue = state.currentAffectedFilesExportedModulesMap &&
state.currentAffectedFilesExportedModulesMap.get(key);
// Not in temporary cache, use existing value
if (newValue === undefined)
exportedModulesMap[relativeToBuildInfo(key)] =
ts.arrayFrom(state.exportedModulesMap.get(key).keys(),
relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
// Value in cache and has updated value map, use that
else if (newValue)
exportedModulesMap[relativeToBuildInfo(key)] =
ts.arrayFrom(newValue.keys(),
relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
}
result.exportedModulesMap = exportedModulesMap;
}
if (state.semanticDiagnosticsPerFile) {
var semanticDiagnosticsPerFile = [];
for (var _d = 0, _e =
ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSen
sitive); _d < _e.length; _d++) {
var key = _e[_d];
var value = state.semanticDiagnosticsPerFile.get(key);
semanticDiagnosticsPerFile.push(value.length ?
[
relativeToBuildInfo(key),
state.hasReusableDiagnostic ?
value :
convertToReusableDiagnostics(value,
relativeToBuildInfo)
] :
relativeToBuildInfo(key));
}
result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
}
if (state.affectedFilesPendingEmit) {
var affectedFilesPendingEmit = [];
var seenFiles = new ts.Set();
for (var _f = 0, _g =
state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.c
ompareStringsCaseSensitive); _f < _g.length; _f++) {
var path = _g[_f];
if (ts.tryAddToSet(seenFiles, path)) {
affectedFilesPendingEmit.push([relativeToBuildInfo(path),
state.affectedFilesPendingEmitKind.get(path)]);
}
}
result.affectedFilesPendingEmit = affectedFilesPendingEmit;
}
return result;
function relativeToBuildInfoEnsuringAbsolutePath(path) {
return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path,
currentDirectory));
}
function relativeToBuildInfo(path) {
return
ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory,
path, getCanonicalFileName));
}
}
function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
var result = {};
var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
for (var name in options) {
if (ts.hasProperty(options, name)) {
result[name] =
convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()),
options[name], relativeToBuildInfo);
}
}
if (result.configFilePath) {
result.configFilePath = relativeToBuildInfo(result.configFilePath);
}
return result;
}
function convertToReusableCompilerOptionValue(option, value,
relativeToBuildInfo) {
if (option) {
if (option.type === "list") {
var values = value;
if (option.element.isFilePath && values.length) {
return values.map(relativeToBuildInfo);
}
}
else if (option.isFilePath) {
return relativeToBuildInfo(value);
}
}
return value;
}
function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
ts.Debug.assert(!!diagnostics.length);
return diagnostics.map(function (diagnostic) {
var result = convertToReusableDiagnosticRelatedInformation(diagnostic,
relativeToBuildInfo);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
result.reportDeprecated = diagnostic.reportsDeprecated;
result.source = diagnostic.source;
result.skippedOn = diagnostic.skippedOn;
var relatedInformation = diagnostic.relatedInformation;
result.relatedInformation = relatedInformation ?
relatedInformation.length ?
relatedInformation.map(function (r) { return
convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
[] :
undefined;
return result;
});
}
function convertToReusableDiagnosticRelatedInformation(diagnostic,
relativeToBuildInfo) {
var file = diagnostic.file;
return __assign(__assign({}, diagnostic), { file: file ?
relativeToBuildInfo(file.resolvedPath) : undefined });
}
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"]
= 0] = "SemanticDiagnosticsBuilderProgram";
BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] =
1] = "EmitAndSemanticDiagnosticsBuilderProgram";
})(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions,
oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences) {
var host;
var newProgram;
var oldProgram;
if (newProgramOrRootNames === undefined) {
ts.Debug.assert(hostOrOptions === undefined);
host = oldProgramOrHost;
oldProgram = configFileParsingDiagnosticsOrOldProgram;
ts.Debug.assert(!!oldProgram);
newProgram = oldProgram.getProgram();
}
else if (ts.isArray(newProgramOrRootNames)) {
oldProgram = configFileParsingDiagnosticsOrOldProgram;
newProgram = ts.createProgram({
rootNames: newProgramOrRootNames,
options: hostOrOptions,
host: oldProgramOrHost,
oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
configFileParsingDiagnostics: configFileParsingDiagnostics,
projectReferences: projectReferences
});
host = oldProgramOrHost;
}
else {
newProgram = newProgramOrRootNames;
host = hostOrOptions;
oldProgram = oldProgramOrHost;
configFileParsingDiagnostics =
configFileParsingDiagnosticsOrOldProgram;
}
return { host: host, newProgram: newProgram, oldProgram: oldProgram,
configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
}
ts.getBuilderCreationParameters = getBuilderCreationParameters;
function createBuilderProgram(kind, _a) {
var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram,
configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
// Return same program if underlying program doesnt change
var oldState = oldProgram && oldProgram.getState();
if (oldState && newProgram === oldState.program &&
configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
newProgram = undefined; // TODO: GH#18217
oldState = undefined;
return oldProgram;
}
/**
* Create the canonical file name for identity
*/
var getCanonicalFileName =
ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
/**
* Computing hash to for signature verification
*/
var computeHash = ts.maybeBind(host, host.createHash);
var state = createBuilderProgramState(newProgram, getCanonicalFileName,
oldState);
var backupState;
newProgram.getProgramBuildInfo = function () { return
getProgramBuildInfo(state, getCanonicalFileName); };
// To ensure that we arent storing any references to old program or new
program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
oldState = undefined;
var builderProgram = createRedirectedBuilderProgram(state,
configFileParsingDiagnostics);
builderProgram.getState = function () { return state; };
builderProgram.backupState = function () {
ts.Debug.assert(backupState === undefined);
backupState = cloneBuilderProgramState(state);
};
builderProgram.restoreState = function () {
state = ts.Debug.checkDefined(backupState);
backupState = undefined;
};
builderProgram.getAllDependencies = function (sourceFile) { return
ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program),
sourceFile); };
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
builderProgram.emit = emit;
builderProgram.releaseProgram = function () {
releaseCache(state);
backupState = undefined;
};
if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
builderProgram.getSemanticDiagnosticsOfNextAffectedFile =
getSemanticDiagnosticsOfNextAffectedFile;
}
else if (kind ===
BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
builderProgram.getSemanticDiagnosticsOfNextAffectedFile =
getSemanticDiagnosticsOfNextAffectedFile;
builderProgram.emitNextAffectedFile = emitNextAffectedFile;
builderProgram.emitBuildInfo = emitBuildInfo;
}
else {
ts.notImplemented();
}
return builderProgram;
function emitBuildInfo(writeFile, cancellationToken) {
if (state.buildInfoEmitPending) {
var result =
ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host,
host.writeFile), cancellationToken);
state.buildInfoEmitPending = false;
return result;
}
return ts.emitSkippedWithNoDiagnostics;
}
/**
* Emits the next affected file's emit result (EmitResult and sourceFiles
emitted) or returns undefined if iteration is complete
* The first of writeFile if provided, writeFile of BuilderProgramHost if
provided, writeFile of compiler host
* in that order would be used to write the files
*/
function emitNextAffectedFile(writeFile, cancellationToken,
emitOnlyDtsFiles, customTransformers) {
var affected = getNextAffectedFile(state, cancellationToken,
computeHash);
var emitKind = 1 /* Full */;
var isPendingEmitFile = false;
if (!affected) {
if (!ts.outFile(state.compilerOptions)) {
var pendingAffectedFile =
getNextAffectedFilePendingEmit(state);
if (!pendingAffectedFile) {
if (!state.buildInfoEmitPending) {
return undefined;
}
var affected_1 = ts.Debug.checkDefined(state.program);
return toAffectedFileEmitResult(state,
// When whole program is affected, do emit only once (eg
when --out or --outFile is specified)
// Otherwise just affected file
affected_1.emitBuildInfo(writeFile || ts.maybeBind(host,
host.writeFile), cancellationToken), affected_1, 1 /* Full */,
/*isPendingEmitFile*/ false,
/*isBuildInfoEmit*/ true);
}
(affected = pendingAffectedFile.affectedFile, emitKind =
pendingAffectedFile.emitKind);
isPendingEmitFile = true;
}
else {
var program = ts.Debug.checkDefined(state.program);
if (state.programEmitComplete)
return undefined;
affected = program;
}
}
return toAffectedFileEmitResult(state,
// When whole program is affected, do emit only once (eg when --out or
--outFile is specified)
// Otherwise just affected file
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);
}
/**
* Emits the JavaScript and declaration files.
* When targetSource file is specified, emits the files corresponding to
that source file,
* otherwise for the whole program.
* In case of EmitAndSemanticDiagnosticsBuilderProgram, when
targetSourceFile is specified,
* it is assumed that that file is handled from affected file list. If
targetSourceFile is not specified,
* it will only emit all the affected files instead of whole program
*
* The first of writeFile if provided, writeFile of BuilderProgramHost if
provided, writeFile of compiler host
* in that order would be used to write the files
*/
function emit(targetSourceFile, writeFile, cancellationToken,
emitOnlyDtsFiles, customTransformers) {
var restorePendingEmitOnHandlingNoEmitSuccess = false;
var savedAffectedFilesPendingEmit;
var savedAffectedFilesPendingEmitKind;
var savedAffectedFilesPendingEmitIndex;
// 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
// This ensures pending files to emit is updated in tsbuildinfo
// 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)
if (kind !==
BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
!targetSourceFile &&
!ts.outFile(state.compilerOptions) &&
!state.compilerOptions.noEmit &&
state.compilerOptions.noEmitOnError) {
restorePendingEmitOnHandlingNoEmitSuccess = true;
savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit &&
state.affectedFilesPendingEmit.slice();
savedAffectedFilesPendingEmitKind =
state.affectedFilesPendingEmitKind && new
ts.Map(state.affectedFilesPendingEmitKind);
savedAffectedFilesPendingEmitIndex =
state.affectedFilesPendingEmitIndex;
}
if (kind ===
BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
}
var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile,
writeFile, cancellationToken);
if (result)
return result;
if (restorePendingEmitOnHandlingNoEmitSuccess) {
state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
state.affectedFilesPendingEmitKind =
savedAffectedFilesPendingEmitKind;
state.affectedFilesPendingEmitIndex =
savedAffectedFilesPendingEmitIndex;
}
// Emit only affected files if using builder for emit
if (!targetSourceFile && kind ===
BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
// Emit and report any errors we ran into.
var sourceMaps = [];
var emitSkipped = false;
var diagnostics = void 0;
var emittedFiles = [];
var affectedEmitResult = void 0;
while (affectedEmitResult = emitNextAffectedFile(writeFile,
cancellationToken, emitOnlyDtsFiles, customTransformers)) {
emitSkipped = emitSkipped ||
affectedEmitResult.result.emitSkipped;
diagnostics = ts.addRange(diagnostics,
affectedEmitResult.result.diagnostics);
emittedFiles = ts.addRange(emittedFiles,
affectedEmitResult.result.emittedFiles);
sourceMaps = ts.addRange(sourceMaps,
affectedEmitResult.result.sourceMaps);
}
return {
emitSkipped: emitSkipped,
diagnostics: diagnostics || ts.emptyArray,
emittedFiles: emittedFiles,
sourceMaps: sourceMaps
};
}
return ts.Debug.checkDefined(state.program).emit(targetSourceFile,
writeFile || ts.maybeBind(host, host.writeFile), cancellationToken,
emitOnlyDtsFiles, customTransformers);
}
/**
* Return the semantic diagnostics for the next affected file or undefined
if iteration is complete
* If provided ignoreSourceFile would be called before getting the
diagnostics and would ignore the sourceFile if the returned value was true
*/
function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken,
ignoreSourceFile) {
while (true) {
var affected = getNextAffectedFile(state, cancellationToken,
computeHash);
if (!affected) {
// Done
return undefined;
}
else if (affected === state.program) {
// When whole program is affected, get all semantic diagnostics
(eg when --out or --outFile is specified)
return toAffectedFileResult(state,
state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined,
cancellationToken), affected);
}
// Add file to affected file pending emit to handle for later emit
time
// 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
if (kind ===
BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram ||
state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
addToAffectedFilesPendingEmit(state, affected.resolvedPath,
1 /* Full */);
}
// Get diagnostics for the affected file if its not ignored
if (ignoreSourceFile && ignoreSourceFile(affected)) {
// Get next affected file
doneWithAffectedFile(state, affected);
continue;
}
return toAffectedFileResult(state,
getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
}
}
/**
* Gets the semantic diagnostics from the program corresponding to this
state of file (if provided) or whole program
* The semantic diagnostics are cached and managed here
* Note that it is assumed that when asked about semantic diagnostics
through this API,
* the file has been taken out of affected files so it is safe to use cache
or get from program and cache the diagnostics
* In case of SemanticDiagnosticsBuilderProgram if the source file is not
provided,
* it will iterate through all the affected files, to ensure that cache
stays valid and yet provide a way to get all semantic diagnostics
*/
function getSemanticDiagnostics(sourceFile, cancellationToken) {
assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
var compilerOptions =
ts.Debug.checkDefined(state.program).getCompilerOptions();
if (ts.outFile(compilerOptions)) {
ts.Debug.assert(!state.semanticDiagnosticsPerFile);
// We dont need to cache the diagnostics just return them from
program
return
ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile,
cancellationToken);
}
if (sourceFile) {
return getSemanticDiagnosticsOfFile(state, sourceFile,
cancellationToken);
}
// When semantic builder asks for diagnostics of the whole program,
// ensure that all the affected files are handled
// eslint-disable-next-line no-empty
while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
}
var diagnostics;
for (var _i = 0, _a =
ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
var sourceFile_1 = _a[_i];
diagnostics = ts.addRange(diagnostics,
getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
if (!state.affectedFilesPendingEmit)
state.affectedFilesPendingEmit = [];
if (!state.affectedFilesPendingEmitKind)
state.affectedFilesPendingEmitKind = new ts.Map();
var existingKind =
state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit,
existingKind || kind);
// affectedFilesPendingEmitIndex === undefined
// - means the emit state.affectedFilesPendingEmit was undefined before
adding current affected files
// so start from 0 as array would be affectedFilesPendingEmit
// else, continue to iterate from existing index, the current set is
appended to existing files
if (state.affectedFilesPendingEmitIndex === undefined) {
state.affectedFilesPendingEmitIndex = 0;
}
}
function getMapOfReferencedSet(mapLike, toPath) {
if (!mapLike)
return undefined;
var map = new ts.Map();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (var key in mapLike) {
if (ts.hasProperty(mapLike, key)) {
map.set(toPath(key), new ts.Set(mapLike[key].map(toPath)));
}
}
return map;
}
function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host)
{
var buildInfoDirectory =
ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath,
host.getCurrentDirectory()));
var getCanonicalFileName =
ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
var fileInfos = new ts.Map();
for (var key in program.fileInfos) {
if (ts.hasProperty(program.fileInfos, key)) {
fileInfos.set(toPath(key), program.fileInfos[key]);
}
}
var state = {
fileInfos: fileInfos,
compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options,
toAbsolutePath),
referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap,
toPath),
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]; }),
hasReusableDiagnostic: true,
affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit,
function (value) { return toPath(value[0]); }),
affectedFilesPendingEmitKind: program.affectedFilesPendingEmit &&
ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return
toPath(value[0]); }, function (value) { return value[1]; }),
affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
};
return {
getState: function () { return state; },
backupState: ts.noop,
restoreState: ts.noop,
getProgram: ts.notImplemented,
getProgramOrUndefined: ts.returnUndefined,
releaseProgram: ts.noop,
getCompilerOptions: function () { return state.compilerOptions; },
getSourceFile: ts.notImplemented,
getSourceFiles: ts.notImplemented,
getOptionsDiagnostics: ts.notImplemented,
getGlobalDiagnostics: ts.notImplemented,
getConfigFileParsingDiagnostics: ts.notImplemented,
getSyntacticDiagnostics: ts.notImplemented,
getDeclarationDiagnostics: ts.notImplemented,
getSemanticDiagnostics: ts.notImplemented,
emit: ts.notImplemented,
getAllDependencies: ts.notImplemented,
getCurrentDirectory: ts.notImplemented,
emitNextAffectedFile: ts.notImplemented,
getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
emitBuildInfo: ts.notImplemented,
close: ts.noop,
};
function toPath(path) {
return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
}
function toAbsolutePath(path) {
return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
}
}
ts.createBuildProgramUsingProgramBuildInfo =
createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
backupState: ts.noop,
restoreState: ts.noop,
getProgram: getProgram,
getProgramOrUndefined: function () { return state.program; },
releaseProgram: function () { return state.program = undefined; },
getCompilerOptions: function () { return state.compilerOptions; },
getSourceFile: function (fileName) { return
getProgram().getSourceFile(fileName); },
getSourceFiles: function () { return getProgram().getSourceFiles(); },
getOptionsDiagnostics: function (cancellationToken) { return
getProgram().getOptionsDiagnostics(cancellationToken); },
getGlobalDiagnostics: function (cancellationToken) { return
getProgram().getGlobalDiagnostics(cancellationToken); },
getConfigFileParsingDiagnostics: function () { return
configFileParsingDiagnostics; },
getSyntacticDiagnostics: function (sourceFile, cancellationToken)
{ return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
getDeclarationDiagnostics: function (sourceFile, cancellationToken)
{ return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
getSemanticDiagnostics: function (sourceFile, cancellationToken)
{ return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts,
customTransformers) { return getProgram().emit(sourceFile, writeFile,
cancellationToken, emitOnlyDts, customTransformers); },
emitBuildInfo: function (writeFile, cancellationToken) { return
getProgram().emitBuildInfo(writeFile, cancellationToken); },
getAllDependencies: ts.notImplemented,
getCurrentDirectory: function () { return
getProgram().getCurrentDirectory(); },
close: ts.noop,
};
function getProgram() {
return ts.Debug.checkDefined(state.program);
}
}
ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames,
hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences) {
return
ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram,
ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions,
oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences));
}
ts.createSemanticDiagnosticsBuilderProgram =
createSemanticDiagnosticsBuilderProgram;
function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames,
hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences) {
return
ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProg
ram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions,
oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences));
}
ts.createEmitAndSemanticDiagnosticsBuilderProgram =
createEmitAndSemanticDiagnosticsBuilderProgram;
function createAbstractBuilder(newProgramOrRootNames, hostOrOptions,
oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences) {
var _a = ts.getBuilderCreationParameters(newProgramOrRootNames,
hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram,
configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram,
newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
return ts.createRedirectedBuilderProgram({ program: newProgram,
compilerOptions: newProgram.getCompilerOptions() },
newConfigFileParsingDiagnostics);
}
ts.createAbstractBuilder = createAbstractBuilder;
})(ts || (ts = {}));
/*@internal*/
var ts;
(function (ts) {
function removeIgnoredPath(path) {
// Consider whole staging folder as if node_modules changed.
if (ts.endsWith(path, "/node_modules/.staging")) {
return ts.removeSuffix(path, "/.staging");
}
return ts.some(ts.ignoredPaths, function (searchPath) { return
ts.stringContains(path, searchPath); }) ?
undefined :
path;
}
ts.removeIgnoredPath = removeIgnoredPath;
/**
* Filter out paths like
* "/", "/user", "/user/username", "/user/username/folderAtRoot",
* "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot",
"c:/folderAtRoot"
* @param dirPath
*/
function canWatchDirectory(dirPath) {
var rootLength = ts.getRootLength(dirPath);
if (dirPath.length === rootLength) {
// Ignore "/", "c:/"
return false;
}
var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator,
rootLength);
if (nextDirectorySeparator === -1) {
// ignore "/user", "c:/users" or "c:/folderAtRoot"
return false;
}
var pathPartForUserCheck = dirPath.substring(rootLength,
nextDirectorySeparator + 1);
var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !
== 47 /* slash */;
if (isNonDirectorySeparatorRoot &&
dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style
nextPart
nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator,
nextDirectorySeparator + 1);
if (nextDirectorySeparator === -1) {
// ignore "//vda1cs4850/c$/folderAtRoot"
return false;
}
pathPartForUserCheck = dirPath.substring(rootLength +
pathPartForUserCheck.length, nextDirectorySeparator + 1);
}
if (isNonDirectorySeparatorRoot &&
pathPartForUserCheck.search(/users\//i) !== 0) {
// Paths like c:/folderAtRoot/subFolder are allowed
return true;
}
for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2;
searchLevels > 0; searchLevels--) {
searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
if (searchIndex === 0) {
// Folder isnt at expected minimum levels
return false;
}
}
return true;
}
ts.canWatchDirectory = canWatchDirectory;
function createResolutionCache(resolutionHost, rootDirForResolution,
logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var filesWithInvalidatedNonRelativeUnresolvedImports;
var nonRelativeExternalModuleResolutions = ts.createMultiMap();
var resolutionsWithFailedLookups = [];
var resolvedFileToResolution = ts.createMultiMap();
var hasChangedAutomaticTypeDirectiveNames = false;
var failedLookupChecks = [];
var startsWithPathChecks = [];
var isInDirectoryChecks = [];
var getCurrentDirectory = ts.memoize(function () { return
resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
var cachedDirectoryStructureHost =
resolutionHost.getCachedDirectoryStructureHost();
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the
cache of resolutions per file.
// The key in the map is source file's path.
// The values are Map of resolutions with key being name lookedup.
var resolvedModuleNames = new ts.Map();
var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
var moduleResolutionCache =
ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames,
nonRelativeModuleNameCache, getCurrentDirectory(),
resolutionHost.getCanonicalFileName);
var resolvedTypeReferenceDirectives = new ts.Map();
var perDirectoryResolvedTypeReferenceDirectives =
ts.createCacheWithRedirects();
/**
* These are the extensions that failed lookup files will have by default,
* any other extension of failed lookup will be store that path in custom
failed lookup path
* This helps in not having to comb through all resolutions when files are
added/removed
* Note that .d.ts file also has .d.ts extension hence will be part of
default extensions
*/
var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */,
".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
var customFailedLookupPaths = new ts.Map();
var directoryWatchesOfFailedLookups = new ts.Map();
var rootDir = rootDirForResolution &&
ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResoluti
on, getCurrentDirectory()));
var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO:
GH#18217
var rootSplitLength = rootPath !== undefined ?
rootPath.split(ts.directorySeparator).length : 0;
// TypeRoot watches for the types that get added as part of
getAutomaticTypeDirectiveNames
var typeRootsWatches = new ts.Map();
return {
startRecordingFilesWithChangedResolutions:
startRecordingFilesWithChangedResolutions,
finishRecordingFilesWithChangedResolutions:
finishRecordingFilesWithChangedResolutions,
// perDirectoryResolvedModuleNames and
perDirectoryResolvedTypeReferenceDirectives could be non empty if there was
exception during program update
// (between startCachingPerDirectoryResolution and
finishCachingPerDirectoryResolution)
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution:
finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache:
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsFromProjectReferenceRedirects:
removeResolutionsFromProjectReferenceRedirects,
removeResolutionsOfFile: removeResolutionsOfFile,
hasChangedAutomaticTypeDirectiveNames: function () { return
hasChangedAutomaticTypeDirectiveNames; },
invalidateResolutionOfFile: invalidateResolutionOfFile,
invalidateResolutionsOfFailedLookupLocations:
invalidateResolutionsOfFailedLookupLocations,
setFilesWithInvalidatedNonRelativeUnresolvedImports:
setFilesWithInvalidatedNonRelativeUnresolvedImports,
createHasInvalidatedResolution: createHasInvalidatedResolution,
updateTypeRootsWatch: updateTypeRootsWatch,
closeTypeRootsWatch: closeTypeRootsWatch,
clear: clear
};
function getResolvedModule(resolution) {
return resolution.resolvedModule;
}
function getResolvedTypeReferenceDirective(resolution) {
return resolution.resolvedTypeReferenceDirective;
}
function isInDirectoryPath(dir, file) {
if (dir === undefined || file.length <= dir.length) {
return false;
}
return ts.startsWith(file, dir) && file[dir.length] ===
ts.directorySeparator;
}
function clear() {
ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
customFailedLookupPaths.clear();
nonRelativeExternalModuleResolutions.clear();
closeTypeRootsWatch();
resolvedModuleNames.clear();
resolvedTypeReferenceDirectives.clear();
resolvedFileToResolution.clear();
resolutionsWithFailedLookups.length = 0;
failedLookupChecks.length = 0;
startsWithPathChecks.length = 0;
isInDirectoryChecks.length = 0;
// perDirectoryResolvedModuleNames and
perDirectoryResolvedTypeReferenceDirectives could be non empty if there was
exception during program update
// (between startCachingPerDirectoryResolution and
finishCachingPerDirectoryResolution)
clearPerDirectoryResolutions();
hasChangedAutomaticTypeDirectiveNames = false;
}
function startRecordingFilesWithChangedResolutions() {
filesWithChangedSetOfUnresolvedImports = [];
}
function finishRecordingFilesWithChangedResolutions() {
var collected = filesWithChangedSetOfUnresolvedImports;
filesWithChangedSetOfUnresolvedImports = undefined;
return collected;
}
function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
return false;
}
// Invalidated if file has unresolved imports
var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
return !!value && !!value.length;
}
function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
// Ensure pending resolutions are applied
invalidateResolutionsOfFailedLookupLocations();
if (forceAllFilesAsInvalidated) {
// Any file asked would have invalidated resolution
filesWithInvalidatedResolutions = undefined;
return ts.returnTrue;
}
var collected = filesWithInvalidatedResolutions;
filesWithInvalidatedResolutions = undefined;
return function (path) { return (!!collected && collected.has(path)) ||
isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
nonRelativeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelative
ModuleResolutions);
nonRelativeExternalModuleResolutions.clear();
}
function finishCachingPerDirectoryResolution() {
filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
clearPerDirectoryResolutions();
directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
if (watcher.refCount === 0) {
directoryWatchesOfFailedLookups.delete(path);
watcher.watcher.close();
}
});
hasChangedAutomaticTypeDirectiveNames = false;
}
function resolveModuleName(moduleName, containingFile, compilerOptions,
host, redirectedReference) {
var _a;
var primaryResult = ts.resolveModuleName(moduleName, containingFile,
compilerOptions, host, moduleResolutionCache, redirectedReference);
// return result immediately only if global cache support is not
enabled or if it is .ts, .tsx or .d.ts
if (!resolutionHost.getGlobalCache) {
return primaryResult;
}
// otherwise try to load typings from @types
var globalCache = resolutionHost.getGlobalCache();
if (globalCache !== undefined && !
ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule &&
ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
// create different collection of failed lookup locations for
second pass
// if it will fail and we've already found something during the
first pass - we don't want to pollute its results
var _b =
ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolu
tionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host,
globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations =
_b.failedLookupLocations;
if (resolvedModule) {
// Modify existing resolution so its saved in the directory
cache as well
primaryResult.resolvedModule = resolvedModule;
(_a = primaryResult.failedLookupLocations).push.apply(_a,
failedLookupLocations);
return primaryResult;
}
}
// Default return the result from the first pass
return primaryResult;
}
function resolveNamesWithLocalCache(_a) {
var _b;
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;
var path = resolutionHost.toPath(containingFile);
var resolutionsInFile = cache.get(path) || cache.set(path, new
ts.Map()).get(path);
var dirPath = ts.getDirectoryPath(path);
var perDirectoryCache =
perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
var perDirectoryResolution = perDirectoryCache.get(dirPath);
if (!perDirectoryResolution) {
perDirectoryResolution = new ts.Map();
perDirectoryCache.set(dirPath, perDirectoryResolution);
}
var resolvedModules = [];
var compilerOptions = resolutionHost.getCompilationSettings();
var hasInvalidatedNonRelativeUnresolvedImport = logChanges &&
isFileWithInvalidatedNonRelativeUnresolvedImports(path);
// All the resolutions in this file are invalidated if this file wasnt
resolved using same redirect
var program = resolutionHost.getCurrentProgram();
var oldRedirect = program &&
program.getResolvedProjectReferenceToRedirect(containingFile);
var unmatchedRedirects = oldRedirect ?
!redirectedReference || redirectedReference.sourceFile.path !==
oldRedirect.sourceFile.path :
!!redirectedReference;
var seenNamesInFile = new ts.Map();
for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
var name = names_3[_i];
var resolution = resolutionsInFile.get(name);
// Resolution is valid if it is present and not invalidated
if (!seenNamesInFile.has(name) &&
unmatchedRedirects || !resolution || resolution.isInvalidated
||
// If the name is unresolved import that was invalidated,
recalculate
(hasInvalidatedNonRelativeUnresolvedImport && !
ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
var existingResolution = resolution;
var resolutionInDirectory = perDirectoryResolution.get(name);
if (resolutionInDirectory) {
resolution = resolutionInDirectory;
}
else {
resolution = loader(name, containingFile, compilerOptions,
((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 :
_b.call(resolutionHost)) || resolutionHost, redirectedReference);
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
watchFailedLookupLocationsOfExternalModuleResolutions(name,
resolution, path, getResolutionWithResolvedFileName);
if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution, path,
getResolutionWithResolvedFileName);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !
resolutionIsEqualTo(existingResolution, resolution)) {
filesWithChangedSetOfUnresolvedImports.push(path);
// reset log changes to avoid recording the same file
multiple times
logChanges = false;
}
}
ts.Debug.assert(resolution !== undefined && !
resolution.isInvalidated);
seenNamesInFile.set(name, true);
resolvedModules.push(getResolutionWithResolvedFileName(resolution));
}
// Stop watching and remove the unused name
resolutionsInFile.forEach(function (resolution, name) {
if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name))
{
stopWatchFailedLookupLocationOfResolution(resolution, path,
getResolutionWithResolvedFileName);
resolutionsInFile.delete(name);
}
});
return resolvedModules;
function resolutionIsEqualTo(oldResolution, newResolution) {
if (oldResolution === newResolution) {
return true;
}
if (!oldResolution || !newResolution) {
return false;
}
var oldResult = getResolutionWithResolvedFileName(oldResolution);
var newResult = getResolutionWithResolvedFileName(newResolution);
if (oldResult === newResult) {
return true;
}
if (!oldResult || !newResult) {
return false;
}
return oldResult.resolvedFileName === newResult.resolvedFileName;
}
}
function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile,
redirectedReference) {
return resolveNamesWithLocalCache({
names: typeDirectiveNames,
containingFile: containingFile,
redirectedReference: redirectedReference,
cache: resolvedTypeReferenceDirectives,
perDirectoryCacheWithRedirects:
perDirectoryResolvedTypeReferenceDirectives,
loader: ts.resolveTypeReferenceDirective,
getResolutionWithResolvedFileName:
getResolvedTypeReferenceDirective,
shouldRetryResolution: function (resolution) { return
resolution.resolvedTypeReferenceDirective === undefined; },
});
}
function resolveModuleNames(moduleNames, containingFile, reusedNames,
redirectedReference) {
return resolveNamesWithLocalCache({
names: moduleNames,
containingFile: containingFile,
redirectedReference: redirectedReference,
cache: resolvedModuleNames,
perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
loader: resolveModuleName,
getResolutionWithResolvedFileName: getResolvedModule,
shouldRetryResolution: function (resolution) { return !
resolution.resolvedModule || !
ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
reusedNames: reusedNames,
logChanges: logChangesWhenResolvingModule,
});
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName,
containingFile) {
var cache =
resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesAtTypesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules/@types");
}
function getDirectoryToWatchFailedLookupLocation(failedLookupLocation,
failedLookupLocationPath) {
if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
// Ensure failed look up is normalized path
failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ?
ts.normalizePath(failedLookupLocation) :
ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
var failedLookupPathSplit =
failedLookupLocationPath.split(ts.directorySeparator);
var failedLookupSplit =
failedLookupLocation.split(ts.directorySeparator);
ts.Debug.assert(failedLookupSplit.length ===
failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + "
failedLookupLocationPath: " + failedLookupLocationPath);
if (failedLookupPathSplit.length > rootSplitLength + 1) {
// Instead of watching root, watch directory in root to avoid
watching excluded directories not needed for module resolution
return {
dir: failedLookupSplit.slice(0, rootSplitLength +
1).join(ts.directorySeparator),
dirPath: failedLookupPathSplit.slice(0, rootSplitLength +
1).join(ts.directorySeparator)
};
}
else {
// Always watch root directory non recursively
return {
dir: rootDir,
dirPath: rootPath,
nonRecursive: false
};
}
}
return
getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNorm
alizedAbsolutePath(failedLookupLocation, getCurrentDirectory())),
ts.getDirectoryPath(failedLookupLocationPath));
}
function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath)
{
// If directory path contains node module, get the most parent
node_modules directory for watching
while (ts.pathContainsNodeModules(dirPath)) {
dir = ts.getDirectoryPath(dir);
dirPath = ts.getDirectoryPath(dirPath);
}
// If the directory is node_modules use it to watch, always watch it
recursively
if (ts.isNodeModulesDirectory(dirPath)) {
return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir:
dir, dirPath: dirPath } : undefined;
}
var nonRecursive = true;
// Use some ancestor of the root directory
var subDirectoryPath, subDirectory;
if (rootPath !== undefined) {
while (!isInDirectoryPath(dirPath, rootPath)) {
var parentPath = ts.getDirectoryPath(dirPath);
if (parentPath === dirPath) {
break;
}
nonRecursive = false;
subDirectoryPath = dirPath;
subDirectory = dir;
dirPath = parentPath;
dir = ts.getDirectoryPath(dir);
}
}
return canWatchDirectory(dirPath) ? { dir: subDirectory || dir,
dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
}
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
function watchFailedLookupLocationsOfExternalModuleResolutions(name,
resolution, filePath, getResolutionWithResolvedFileName) {
if (resolution.refCount) {
resolution.refCount++;
ts.Debug.assertDefined(resolution.files);
}
else {
resolution.refCount = 1;
ts.Debug.assert(ts.length(resolution.files) === 0); // This
resolution shouldnt be referenced by any file yet
if (ts.isExternalModuleNameRelative(name)) {
watchFailedLookupLocationOfResolution(resolution);
}
else {
nonRelativeExternalModuleResolutions.add(name, resolution);
}
var resolved = getResolutionWithResolvedFileName(resolution);
if (resolved && resolved.resolvedFileName) {
resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName),
resolution);
}
}
(resolution.files || (resolution.files = [])).push(filePath);
}
function watchFailedLookupLocationOfResolution(resolution) {
ts.Debug.assert(!!resolution.refCount);
var failedLookupLocations = resolution.failedLookupLocations;
if (!failedLookupLocations.length)
return;
resolutionsWithFailedLookups.push(resolution);
var setAtRoot = false;
for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i <
failedLookupLocations_1.length; _i++) {
var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath =
resolutionHost.toPath(failedLookupLocation);
var toWatch =
getDirectoryToWatchFailedLookupLocation(failedLookupLocation,
failedLookupLocationPath);
if (toWatch) {
var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive
= toWatch.nonRecursive;
// If the failed lookup location path is not one of the
supported extensions,
// store it in the custom path
if (!
isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
var refCount =
customFailedLookupPaths.get(failedLookupLocationPath) || 0;
customFailedLookupPaths.set(failedLookupLocationPath,
refCount + 1);
}
if (dirPath === rootPath) {
ts.Debug.assert(!nonRecursive);
setAtRoot = true;
}
else {
setDirectoryWatcher(dir, dirPath, nonRecursive);
}
}
}
if (setAtRoot) {
// This is always non recursive
setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); //
TODO: GH#18217
}
}
function
watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
var program = resolutionHost.getCurrentProgram();
if (!program || !
program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
resolutions.forEach(watchFailedLookupLocationOfResolution);
}
}
function setDirectoryWatcher(dir, dirPath, nonRecursive) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
if (dirWatcher) {
ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
dirWatcher.refCount++;
}
else {
directoryWatchesOfFailedLookups.set(dirPath, { watcher:
createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive:
nonRecursive });
}
}
function stopWatchFailedLookupLocationOfResolution(resolution, filePath,
getResolutionWithResolvedFileName) {
ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files),
filePath);
resolution.refCount--;
if (resolution.refCount) {
return;
}
var resolved = getResolutionWithResolvedFileName(resolution);
if (resolved && resolved.resolvedFileName) {
resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName),
resolution);
}
if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution))
{
// If not watching failed lookups, it wont be there in
resolutionsWithFailedLookups
return;
}
var failedLookupLocations = resolution.failedLookupLocations;
var removeAtRoot = false;
for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i <
failedLookupLocations_2.length; _i++) {
var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath =
resolutionHost.toPath(failedLookupLocation);
var toWatch =
getDirectoryToWatchFailedLookupLocation(failedLookupLocation,
failedLookupLocationPath);
if (toWatch) {
var dirPath = toWatch.dirPath;
var refCount =
customFailedLookupPaths.get(failedLookupLocationPath);
if (refCount) {
if (refCount === 1) {
customFailedLookupPaths.delete(failedLookupLocationPath);
}
else {
ts.Debug.assert(refCount > 1);
customFailedLookupPaths.set(failedLookupLocationPath,
refCount - 1);
}
}
if (dirPath === rootPath) {
removeAtRoot = true;
}
else {
removeDirectoryWatcher(dirPath);
}
}
}
if (removeAtRoot) {
removeDirectoryWatcher(rootPath);
}
}
function removeDirectoryWatcher(dirPath) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
// Do not close the watcher yet since it might be needed by other
failed lookup locations.
dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath, nonRecursive) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory,
function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
// Since the file existence changed, update the sourceFiles
cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory,
fileOrDirectoryPath);
}
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory,
fileOrDirectoryPath);
}
// For now just recompile
// We could potentially store more data here about whether it
was/would be really be used or not
// and with that determine to trigger compilation but for now this
is enough
hasChangedAutomaticTypeDirectiveNames = true;
resolutionHost.onChangedAutomaticTypeDirectiveNames();
// Since directory watchers invoked are flaky, the failed lookup
location events might not be triggered
// So handle to failed lookup locations here as well to ensure we
are invalidating resolutions
var dirPath =
getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
if (dirPath) {
removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromD
irectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending,
compilerOptions);
if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
return relativePath;
}
var baseDirectory = ts.getPathsBasePath(compilerOptions, host) ||
baseUrl;
var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName,
baseDirectory, getCanonicalFileName);
if (!relativeToBaseUrl) {
return relativePath;
}
var importRelativeToBaseUrl =
removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
var fromPaths = paths &&
tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl),
importRelativeToBaseUrl, paths);
var nonRelative = fromPaths === undefined && baseUrl !== undefined ?
importRelativeToBaseUrl : fromPaths;
if (!nonRelative) {
return relativePath;
}
if (relativePreference === 1 /* NonRelative */) {
return nonRelative;
}
if (relativePreference !== 2 /* Auto */)
ts.Debug.assertNever(relativePreference);
// Prefer a relative import over a baseUrl import if it has fewer
components.
return isPathRelativeToParent(nonRelative) ||
countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath
: nonRelative;
}
function countPathComponents(path) {
var count = 0;
for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
if (path.charCodeAt(i) === 47 /* slash */)
count++;
}
return count;
}
moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
var text = _a.text;
return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) :
undefined;
}) || false;
}
function numberOfDirectorySeparators(str) {
var match = str.match(/\//g);
return match ? match.length : 0;
}
function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
return ts.compareBooleans(b.isRedirect, a.isRedirect) ||
ts.compareValues(numberOfDirectorySeparators(a.path),
numberOfDirectorySeparators(b.path));
}
function forEachFileNameOfModule(importingFileName, importedFileName, host,
preferSymlinks, cb) {
var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
var cwd = host.getCurrentDirectory();
var referenceRedirect =
host.isSourceOfProjectReferenceRedirect(importedFileName) ?
host.getProjectReferenceRedirect(importedFileName) : undefined;
var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName,
cwd, getCanonicalFileName)) || ts.emptyArray;
var importedFileNames = __spreadArrays((referenceRedirect ?
[referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
var targets = importedFileNames.map(function (f) { return
ts.getNormalizedAbsolutePath(f, cwd); });
if (!preferSymlinks) {
var result_15 = ts.forEach(targets, function (p) { return cb(p,
referenceRedirect === p); });
if (result_15)
return result_15;
}
var links = host.getSymlinkCache
? host.getSymlinkCache()
: ts.discoverProbableSymlinks(host.getSourceFiles(),
getCanonicalFileName, cwd);
var symlinkedDirectories = links.getSymlinkedDirectories();
var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames ||
host.useCaseSensitiveFileNames();
var result = symlinkedDirectories &&
ts.forEachEntry(symlinkedDirectories, function (resolved, path) {
if (resolved === false)
return undefined;
if (ts.startsWithDirectory(importingFileName, resolved.realPath,
getCanonicalFileName)) {
return undefined; // Don't want to a package to globally import
from itself
}
return ts.forEach(targets, function (target) {
if (!ts.containsPath(resolved.real, target, !
useCaseSensitiveFileNames)) {
return;
}
var relative = ts.getRelativePathFromDirectory(resolved.real,
target, getCanonicalFileName);
var option = ts.resolvePath(path, relative);
if (!host.fileExists || host.fileExists(option)) {
var result_16 = cb(option, target === referenceRedirect);
if (result_16)
return result_16;
}
});
});
return result ||
(preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p
=== referenceRedirect); }) : undefined);
}
moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
/**
* Looks for existing imports that use symlinks to this module.
* Symlinks will be returned first so they are preferred over the real
path.
*/
function getAllModulePaths(importingFileName, importedFileName, host) {
var cwd = host.getCurrentDirectory();
var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
var allFileNames = new ts.Map();
var importedFileFromNodeModules = false;
forEachFileNameOfModule(importingFileName, importedFileName, host,
/*preferSymlinks*/ true, function (path, isRedirect) {
var isInNodeModules = ts.pathContainsNodeModules(path);
allFileNames.set(path, { path: getCanonicalFileName(path),
isRedirect: isRedirect, isInNodeModules: isInNodeModules });
importedFileFromNodeModules = importedFileFromNodeModules ||
isInNodeModules;
// don't return value, so we collect everything
});
// Sort by paths closest to importing file Name directory
var sortedPaths = [];
var _loop_24 = function (directory) {
var directoryStart =
ts.ensureTrailingDirectorySeparator(directory);
var pathsInDirectory;
allFileNames.forEach(function (_a, fileName) {
var path = _a.path, isRedirect = _a.isRedirect, isInNodeModules
= _a.isInNodeModules;
if (ts.startsWith(path, directoryStart)) {
(pathsInDirectory || (pathsInDirectory = [])).push({ path:
fileName, isRedirect: isRedirect, isInNodeModules: isInNodeModules });
allFileNames.delete(fileName);
}
});
if (pathsInDirectory) {
if (pathsInDirectory.length > 1) {
pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
}
sortedPaths.push.apply(sortedPaths, pathsInDirectory);
}
var newDirectory = ts.getDirectoryPath(directory);
if (newDirectory === directory)
return out_directory_1 = directory, "break";
directory = newDirectory;
out_directory_1 = directory;
};
var out_directory_1;
for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName,
cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
var state_8 = _loop_24(directory);
directory = out_directory_1;
if (state_8 === "break")
break;
}
if (allFileNames.size) {
var remainingPaths = ts.arrayFrom(allFileNames.values());
if (remainingPaths.length > 1)
remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
sortedPaths.push.apply(sortedPaths, remainingPaths);
}
return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol) {
var decl = ts.find(moduleSymbol.declarations, function (d) { return
ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !
ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
if (decl) {
return decl.name.text;
}
}
function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex,
relativeToBaseUrl, paths) {
for (var key in paths) {
for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
var patternText_1 = _a[_i];
var pattern =
ts.removeFileExtension(ts.normalizePath(patternText_1));
var indexOfStar = pattern.indexOf("*");
if (indexOfStar !== -1) {
var prefix = pattern.substr(0, indexOfStar);
var suffix = pattern.substr(indexOfStar + 1);
if (relativeToBaseUrl.length >= prefix.length +
suffix.length &&
ts.startsWith(relativeToBaseUrl, prefix) &&
ts.endsWith(relativeToBaseUrl, suffix) ||
!suffix && relativeToBaseUrl ===
ts.removeTrailingDirectorySeparator(prefix)) {
var matchedStar =
relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
return key.replace("*", matchedStar);
}
}
else if (pattern === relativeToBaseUrl || pattern ===
relativeToBaseUrlWithIndex) {
return key;
}
}
}
}
function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName,
sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName,
rootDirs, getCanonicalFileName);
if (normalizedTargetPath === undefined) {
return undefined;
}
var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory,
rootDirs, getCanonicalFileName);
var relativePath = normalizedSourcePath !== undefined ?
ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath,
normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
return ts.getEmitModuleResolutionKind(compilerOptions) ===
ts.ModuleResolutionKind.NodeJs
? removeExtensionAndIndexPostFix(relativePath, ending,
compilerOptions)
: ts.removeFileExtension(relativePath);
}
function tryGetModuleNameAsNodeModule(_a, _b, host, options,
packageNameOnly) {
var path = _a.path, isRedirect = _a.isRedirect;
var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory =
_b.sourceDirectory;
if (!host.fileExists || !host.readFile) {
return undefined;
}
var parts = getNodeModulePathParts(path);
if (!parts) {
return undefined;
}
// Simplify the full file path to something that can be resolved by
Node.
var moduleSpecifier = path;
var isPackageRootPath = false;
if (!packageNameOnly) {
var packageRootIndex = parts.packageRootIndex;
var moduleFileNameForExtensionless = void 0;
while (true) {
// If the module could be imported by a directory name, use
that directory's name
var _c = tryDirectoryWithPackageJson(packageRootIndex),
moduleFileToTry = _c.moduleFileToTry, packageRootPath = _c.packageRootPath;
if (packageRootPath) {
moduleSpecifier = packageRootPath;
isPackageRootPath = true;
break;
}
if (!moduleFileNameForExtensionless)
moduleFileNameForExtensionless = moduleFileToTry;
// try with next level of directory
packageRootIndex = path.indexOf(ts.directorySeparator,
packageRootIndex + 1);
if (packageRootIndex === -1) {
moduleSpecifier =
getExtensionlessFileName(moduleFileNameForExtensionless);
break;
}
}
}
if (isRedirect && !isPackageRootPath) {
return undefined;
}
var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation &&
host.getGlobalTypingsCacheLocation();
// Get a path that's relative to node_modules or the importing file's
path
// if node_modules folder is in this folder or any of its parent
folders, no need to keep it.
var pathToTopLevelNodeModules =
getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) ||
globalTypingsCacheLocation &&
ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation),
pathToTopLevelNodeModules))) {
return undefined;
}
// If the module was found in @types, get the actual Node package name
var nodeModulesDirectoryName =
moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
var packageName =
ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
// For classic resolution, only allow importing from
node_modules/@types, not other node_modules
return ts.getEmitModuleResolutionKind(options) !==
ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ?
undefined : packageName;
function tryDirectoryWithPackageJson(packageRootIndex) {
var packageRootPath = path.substring(0, packageRootIndex);
var packageJsonPath = ts.combinePaths(packageRootPath,
"package.json");
var moduleFileToTry = path;
if (host.fileExists(packageJsonPath)) {
var packageJsonContent =
JSON.parse(host.readFile(packageJsonPath));
var versionPaths = packageJsonContent.typesVersions
?
ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
: undefined;
if (versionPaths) {
var subModuleName = path.slice(packageRootPath.length + 1);
var fromPaths =
tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName),
removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options),
versionPaths.paths);
if (fromPaths !== undefined) {
moduleFileToTry = ts.combinePaths(packageRootPath,
fromPaths);
}
}
// If the file is the main module, it can be imported by the
package name
var mainFileRelative = packageJsonContent.typings ||
packageJsonContent.types || packageJsonContent.main;
if (ts.isString(mainFileRelative)) {
var mainExportFile = ts.toPath(mainFileRelative,
packageRootPath, getCanonicalFileName);
if (ts.removeFileExtension(mainExportFile) ===
ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
return { packageRootPath: packageRootPath,
moduleFileToTry: moduleFileToTry };
}
}
}
return { moduleFileToTry: moduleFileToTry };
}
function getExtensionlessFileName(path) {
// We still have a file name - remove the extension
var fullModulePathWithoutExtension = ts.removeFileExtension(path);
// If the file is /index, it can be imported by its directory name
// IFF there is not _also_ a file by the same name
if
(getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)
) === "/index" && !tryGetAnyFileFromPath(host,
fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
return fullModulePathWithoutExtension.substring(0,
parts.fileNameIndex);
}
return fullModulePathWithoutExtension;
}
}
function tryGetAnyFileFromPath(host, path) {
if (!host.fileExists)
return;
// We check all js, `node` and `json` extensions in addition to TS,
since node module resolution would also choose those over the directory
var extensions = ts.getSupportedExtensions({ allowJs: true },
[{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent:
false, scriptKind: 6 /* JSON */ }]);
for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length;
_i++) {
var e = extensions_3[_i];
var fullPath = path + e;
if (host.fileExists(fullPath)) {
return fullPath;
}
}
}
function getNodeModulePathParts(fullPath) {
// If fullPath can't be valid module file within node_modules, returns
undefined.
// Example of expected pattern:
/base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/
[subdirectory/]file.js
// Returns indices: ^ ^
^ ^
var topLevelNodeModulesIndex = 0;
var topLevelPackageNameIndex = 0;
var packageRootIndex = 0;
var fileNameIndex = 0;
var States;
(function (States) {
States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
States[States["NodeModules"] = 1] = "NodeModules";
States[States["Scope"] = 2] = "Scope";
States[States["PackageContent"] = 3] = "PackageContent";
})(States || (States = {}));
var partStart = 0;
var partEnd = 0;
var state = 0 /* BeforeNodeModules */;
while (partEnd >= 0) {
partStart = partEnd;
partEnd = fullPath.indexOf("/", partStart + 1);
switch (state) {
case 0 /* BeforeNodeModules */:
if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) ===
partStart) {
topLevelNodeModulesIndex = partStart;
topLevelPackageNameIndex = partEnd;
state = 1 /* NodeModules */;
}
break;
case 1 /* NodeModules */:
case 2 /* Scope */:
if (state === 1 /* NodeModules */ &&
fullPath.charAt(partStart + 1) === "@") {
state = 2 /* Scope */;
}
else {
packageRootIndex = partEnd;
state = 3 /* PackageContent */;
}
break;
case 3 /* PackageContent */:
if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) ===
partStart) {
state = 1 /* NodeModules */;
}
else {
state = 3 /* PackageContent */;
}
break;
}
}
fileNameIndex = partStart;
return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex:
topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex,
packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
}
function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
return ts.firstDefined(rootDirs, function (rootDir) {
var relativePath = getRelativePathIfInDirectory(path, rootDir,
getCanonicalFileName); // TODO: GH#18217
return isPathRelativeToParent(relativePath) ? undefined :
relativePath;
});
}
function removeExtensionAndIndexPostFix(fileName, ending, options) {
if (ts.fileExtensionIs(fileName, ".json" /* Json */))
return fileName;
var noExtension = ts.removeFileExtension(fileName);
switch (ending) {
case 0 /* Minimal */:
return ts.removeSuffix(noExtension, "/index");
case 1 /* Index */:
return noExtension;
case 2 /* JsExtension */:
return noExtension + getJSExtensionForFile(fileName, options);
default:
return ts.Debug.assertNever(ending);
}
}
function getJSExtensionForFile(fileName, options) {
var ext = ts.extensionFromPath(fileName);
switch (ext) {
case ".ts" /* Ts */:
case ".d.ts" /* Dts */:
return ".js" /* Js */;
case ".tsx" /* Tsx */:
return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ :
".js" /* Js */;
case ".js" /* Js */:
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
case ".tsbuildinfo" /* TsBuildInfo */:
return ts.Debug.fail("Extension " + ".tsbuildinfo" /*
TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
}
function getRelativePathIfInDirectory(path, directoryPath,
getCanonicalFileName) {
var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath,
path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
}
function isPathRelativeToParent(path) {
return ts.startsWith(path, "..");
}
})(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
})(ts || (ts = {}));
/*@internal*/
var ts;
(function (ts) {
var sysFormatDiagnosticsHost = ts.sys ? {
getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
getNewLine: function () { return ts.sys.newLine; },
getCanonicalFileName:
ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
} : undefined; // TODO: GH#18217
/**
* Create a function that reports error by writing to the system and handles
the formating of the diagnostic
*/
function createDiagnosticReporter(system, pretty) {
var host = system === ts.sys ? sysFormatDiagnosticsHost : {
getCurrentDirectory: function () { return system.getCurrentDirectory();
},
getNewLine: function () { return system.newLine; },
getCanonicalFileName:
ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
};
if (!pretty) {
return function (diagnostic) { return
system.write(ts.formatDiagnostic(diagnostic, host)); };
}
var diagnostics = new Array(1);
return function (diagnostic) {
diagnostics[0] = diagnostic;
system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host)
+ host.getNewLine());
diagnostics[0] = undefined; // TODO: GH#18217
};
}
ts.createDiagnosticReporter = createDiagnosticReporter;
/**
* @returns Whether the screen was cleared.
*/
function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
if (system.clearScreen &&
!options.preserveWatchOutput &&
!options.extendedDiagnostics &&
!options.diagnostics &&
ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
system.clearScreen();
return true;
}
return false;
}
ts.screenStartingMessageCodes = [
ts.Diagnostics.Starting_compilation_in_watch_mode.code,
ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
];
function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
? newLine + newLine
: newLine;
}
/**
* Get locale specific time based on whether we are in test mode
*/
function getLocaleTimeString(system) {
return !system.now ?
new Date().toLocaleTimeString() :
system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
}
ts.getLocaleTimeString = getLocaleTimeString;
/**
* Create a function that reports watch status by writing to the system and
handles the formating of the diagnostic
*/
function createWatchStatusReporter(system, pretty) {
return pretty ?
function (diagnostic, newLine, options) {
clearScreenIfNotWatchingForFileChanges(system, diagnostic,
options);
var output = "[" +
ts.formatColorAndReset(getLocaleTimeString(system),
ts.ForegroundColorEscapeSequences.Grey) + "] ";
output += "" +
ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine
+ newLine);
system.write(output);
} :
function (diagnostic, newLine, options) {
var output = "";
if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic,
options)) {
output += newLine;
}
output += getLocaleTimeString(system) + " - ";
output += "" +
ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) +
getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
system.write(output);
};
}
ts.createWatchStatusReporter = createWatchStatusReporter;
/** Parses config file using System interface */
function parseConfigFileWithSystem(configFileName, optionsToExtend,
watchOptionsToExtend, system, reportDiagnostic) {
var host = system;
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return
reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
var result = ts.getParsedCommandLineOfConfigFile(configFileName,
optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
return result;
}
ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
function getErrorCountForSummary(diagnostics) {
return ts.countWhere(diagnostics, function (diagnostic) { return
diagnostic.category === ts.DiagnosticCategory.Error; });
}
ts.getErrorCountForSummary = getErrorCountForSummary;
function getWatchErrorSummaryDiagnosticMessage(errorCount) {
return errorCount === 1 ?
ts.Diagnostics.Found_1_error_Watching_for_file_changes :
ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
}
ts.getWatchErrorSummaryDiagnosticMessage =
getWatchErrorSummaryDiagnosticMessage;
function getErrorSummaryText(errorCount, newLine) {
if (errorCount === 0)
return "";
var d = ts.createCompilerDiagnostic(errorCount === 1 ?
ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText,
newLine) + newLine + newLine;
}
ts.getErrorSummaryText = getErrorSummaryText;
function listFiles(program, writeFileName) {
if (program.getCompilerOptions().listFiles ||
program.getCompilerOptions().listFilesOnly) {
ts.forEach(program.getSourceFiles(), function (file) {
writeFileName(file.fileName);
});
}
}
ts.listFiles = listFiles;
/**
* Helper that emit files, report diagnostics and lists emitted and/or source
files depending on compiler options
*/
function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName,
reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)
{
var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
// First get and report any syntactic errors.
var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = allDiagnostics.length;
ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/
undefined, cancellationToken));
// If we didn't have any syntactic errors, then also try getting the global
and
// semantic errors.
if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(allDiagnostics,
program.getOptionsDiagnostics(cancellationToken));
if (!isListFilesOnly) {
ts.addRange(allDiagnostics,
program.getGlobalDiagnostics(cancellationToken));
if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(allDiagnostics,
program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
}
}
}
// Emit and report any errors we ran into.
var emitResult = isListFilesOnly
? { emitSkipped: true, diagnostics: ts.emptyArray }
: program.emit(/*targetSourceFile*/ undefined, writeFile,
cancellationToken, emitOnlyDtsFiles, customTransformers);
var emittedFiles = emitResult.emittedFiles, emitDiagnostics =
emitResult.diagnostics;
ts.addRange(allDiagnostics, emitDiagnostics);
var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
diagnostics.forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
ts.forEach(emittedFiles, function (file) {
var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
writeFileName("TSFILE: " + filepath);
});
listFiles(program, writeFileName);
}
if (reportSummary) {
reportSummary(getErrorCountForSummary(diagnostics));
}
return {
emitResult: emitResult,
diagnostics: diagnostics,
};
}
ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic,
writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles,
customTransformers) {
var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName,
reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers),
emitResult = _a.emitResult, diagnostics = _a.diagnostics;
if (emitResult.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
else if (diagnostics.length > 0) {
// The emitter emitted something, inform the caller if that happened in
the presence
// of diagnostics or not.
return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
}
return ts.ExitStatus.Success;
}
ts.emitFilesAndReportErrorsAndGetExitStatus =
emitFilesAndReportErrorsAndGetExitStatus;
ts.noopFileWatcher = { close: ts.noop };
ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
function createWatchHost(system, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var onWatchStatusChange = reportWatchStatus ||
createWatchStatusReporter(system);
return {
onWatchStatusChange: onWatchStatusChange,
watchFile: ts.maybeBind(system, system.watchFile) ||
ts.returnNoopFileWatcher,
watchDirectory: ts.maybeBind(system, system.watchDirectory) ||
ts.returnNoopFileWatcher,
setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
};
}
ts.createWatchHost = createWatchHost;
ts.WatchType = {
ConfigFile: "Config file",
SourceFile: "Source file",
MissingFile: "Missing file",
WildcardDirectory: "Wild card directory",
FailedLookupLocations: "Failed Lookup Locations",
TypeRoots: "Type roots"
};
function createWatchFactory(host, options) {
var watchLogLevel = host.trace ? options.extendedDiagnostics ?
ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly :
ts.WatchLogLevel.None : ts.WatchLogLevel.None;
var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s)
{ return host.trace(s); }) : ts.noop;
var result = ts.getWatchFactory(watchLogLevel, writeLog);
result.writeLog = writeLog;
return result;
}
ts.createWatchFactory = createWatchFactory;
function createCompilerHostFromProgramHost(host, getCompilerOptions,
directoryStructureHost) {
if (directoryStructureHost === void 0) { directoryStructureHost = host; }
var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
return {
getSourceFile: function (fileName, languageVersion, onError) {
var text;
try {
ts.performance.mark("beforeIORead");
text = host.readFile(fileName, getCompilerOptions().charset);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead",
"afterIORead");
}
catch (e) {
if (onError) {
onError(e.message);
}
text = "";
}
return text !== undefined ? ts.createSourceFile(fileName, text,
languageVersion) : undefined;
},
getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
getDefaultLibFileName: function (options) { return
host.getDefaultLibFileName(options); },
writeFile: writeFile,
getCurrentDirectory: ts.memoize(function () { return
host.getCurrentDirectory(); }),
useCaseSensitiveFileNames: function () { return
useCaseSensitiveFileNames; },
getCanonicalFileName:
ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
getNewLine: function () { return
ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
fileExists: function (f) { return host.fileExists(f); },
readFile: function (f) { return host.readFile(f); },
trace: ts.maybeBind(host, host.trace),
directoryExists: ts.maybeBind(directoryStructureHost,
directoryStructureHost.directoryExists),
getDirectories: ts.maybeBind(directoryStructureHost,
directoryStructureHost.getDirectories),
realpath: ts.maybeBind(host, host.realpath),
getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable)
|| (function () { return ""; }),
createHash: ts.maybeBind(host, host.createHash),
readDirectory: ts.maybeBind(host, host.readDirectory),
};
function writeFile(fileName, text, writeByteOrderMark, onError) {
try {
ts.performance.mark("beforeIOWrite");
// NOTE: If patchWriteFileEnsuringDirectory has been called,
// the host.writeFile will do its own directory creation and
// the ensureDirectoriesExist call will always be redundant.
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); });
ts.performance.mark("afterIOWrite");
ts.performance.measure("I/O Write", "beforeIOWrite",
"afterIOWrite");
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
function setGetSourceFileAsHashVersioned(compilerHost, host) {
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = ts.maybeBind(host, host.createHash) ||
ts.generateDjb2Hash;
compilerHost.getSourceFile = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = originalGetSourceFile.call.apply(originalGetSourceFile,
__spreadArrays([compilerHost], args));
if (result) {
result.version = computeHash(result.text);
}
return result;
};
}
ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or
root file names and options host
*/
function createProgramHost(system, createProgram) {
var getDefaultLibLocation = ts.memoize(function () { return
ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
return {
useCaseSensitiveFileNames: function () { return
system.useCaseSensitiveFileNames; },
getNewLine: function () { return system.newLine; },
getCurrentDirectory: ts.memoize(function () { return
system.getCurrentDirectory(); }),
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return
ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
fileExists: function (path) { return system.fileExists(path); },
readFile: function (path, encoding) { return system.readFile(path,
encoding); },
directoryExists: function (path) { return system.directoryExists(path);
},
getDirectories: function (path) { return
system.getDirectories(path); },
readDirectory: function (path, extensions, exclude, include, depth)
{ return system.readDirectory(path, extensions, exclude, include, depth); },
realpath: ts.maybeBind(system, system.realpath),
getEnvironmentVariable: ts.maybeBind(system,
system.getEnvironmentVariable),
trace: function (s) { return system.write(s + system.newLine); },
createDirectory: function (path) { return system.createDirectory(path);
},
writeFile: function (path, data, writeByteOrderMark) { return
system.writeFile(path, data, writeByteOrderMark); },
createHash: ts.maybeBind(system, system.createHash),
createProgram: createProgram ||
ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
/**
* Creates the watch compiler host that can be extended with config file or
root file names and options host
*/
function createWatchCompilerHost(system, createProgram, reportDiagnostic,
reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine);
};
var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
var newLine = ts.getNewLineCharacter(compilerOptions, function ()
{ return system.newLine; });
emitFilesAndReportErrors(builderProgram, reportDiagnostic,
writeFileName, function (errorCount) { return
result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnost
icMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
};
return result;
}
/**
* Report error and exit
*/
function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
reportDiagnostic(diagnostic);
system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
/**
* Creates the watch compiler host from system for config file in watch mode
*/
function createWatchCompilerHostOfConfigFile(_a) {
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;
var diagnosticReporter = reportDiagnostic ||
createDiagnosticReporter(system);
var host = createWatchCompilerHost(system, createProgram,
diagnosticReporter, reportWatchStatus);
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return
reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
host.configFileName = configFileName;
host.optionsToExtend = optionsToExtend;
host.watchOptionsToExtend = watchOptionsToExtend;
host.extraFileExtensions = extraFileExtensions;
return host;
}
ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
/**
* Creates the watch compiler host from system for compiling root files and
options in watch mode
*/
function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
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;
var host = createWatchCompilerHost(system, createProgram, reportDiagnostic
|| createDiagnosticReporter(system), reportWatchStatus);
host.rootFiles = rootFiles;
host.options = options;
host.watchOptions = watchOptions;
host.projectReferences = projectReferences;
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions =
createWatchCompilerHostOfFilesAndCompilerOptions;
function performIncrementalCompilation(input) {
var system = input.system || ts.sys;
var host = input.host || (input.host =
ts.createIncrementalCompilerHost(input.options, system));
var builderProgram = ts.createIncrementalProgram(input);
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);
if (input.afterProgramEmitAndDiagnostics)
input.afterProgramEmitAndDiagnostics(builderProgram);
return exitStatus;
}
ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
var ts;
(function (ts) {
function readBuilderProgram(compilerOptions, host) {
if (ts.outFile(compilerOptions))
return undefined;
var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
if (!buildInfoPath)
return undefined;
var content = host.readFile(buildInfoPath);
if (!content)
return undefined;
var buildInfo = ts.getBuildInfo(content);
if (buildInfo.version !== ts.version)
return undefined;
if (!buildInfo.program)
return undefined;
return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program,
buildInfoPath, host);
}
ts.readBuilderProgram = readBuilderProgram;
function createIncrementalCompilerHost(options, system) {
if (system === void 0) { system = ts.sys; }
var host = ts.createCompilerHostWorker(options, /*setParentNodes*/
undefined, system);
host.createHash = ts.maybeBind(system, system.createHash);
ts.setGetSourceFileAsHashVersioned(host, system);
ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return
ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
return host;
}
ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
function createIncrementalProgram(_a) {
var rootNames = _a.rootNames, options = _a.options,
configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences =
_a.projectReferences, host = _a.host, createProgram = _a.createProgram;
host = host || createIncrementalCompilerHost(options);
createProgram = createProgram ||
ts.createEmitAndSemanticDiagnosticsBuilderProgram;
var oldProgram = readBuilderProgram(options, host);
return createProgram(rootNames, options, host, oldProgram,
configFileParsingDiagnostics, projectReferences);
}
ts.createIncrementalProgram = createIncrementalProgram;
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system,
createProgram, reportDiagnostic, reportWatchStatus,
projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
if (ts.isArray(rootFilesOrConfigFileName)) {
return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
rootFiles: rootFilesOrConfigFileName,
options: options,
watchOptions: watchOptionsOrExtraFileExtensions,
projectReferences: projectReferencesOrWatchOptionsToExtend,
system: system,
createProgram: createProgram,
reportDiagnostic: reportDiagnostic,
reportWatchStatus: reportWatchStatus,
});
}
else {
return ts.createWatchCompilerHostOfConfigFile({
configFileName: rootFilesOrConfigFileName,
optionsToExtend: options,
watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
extraFileExtensions: watchOptionsOrExtraFileExtensions,
system: system,
createProgram: createProgram,
reportDiagnostic: reportDiagnostic,
reportWatchStatus: reportWatchStatus,
});
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded
from config file/just filenames etc
var missingFilesMap; // Map of file watchers for the missing files
var watchedWildcardDirectories; // map of watchers for the wild card
directories in the config file
var timerToUpdateProgram; // timer callback to recompile the program
var timerToInvalidateFailedLookupResolutions; // timer callback to
invalidate resolutions for changes in failed lookup locations
var sourceFilesCache = new ts.Map(); // Cache that stores the source file
and version info
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
var hasChangedCompilerOptions = false; // True if the compiler options have
changed between compilations
var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
var currentDirectory = host.getCurrentDirectory();
var configFileName = host.configFileName, _a = host.optionsToExtend,
optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend =
host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions,
createProgram = host.createProgram;
var rootFileNames = host.rootFiles, compilerOptions = host.options,
watchOptions = host.watchOptions, projectReferences = host.projectReferences;
var configFileSpecs;
var configFileParsingDiagnostics;
var canConfigFileJsonReportNoInputFiles = false;
var hasChangedConfigFileParsingErrors = false;
var cachedDirectoryStructureHost = configFileName === undefined ? undefined
: ts.createCachedDirectoryStructureHost(host, currentDirectory,
useCaseSensitiveFileNames);
var directoryStructureHost = cachedDirectoryStructureHost || host;
var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host,
directoryStructureHost);
// From tsc we want to get already parsed result and hence check for
rootFileNames
var newLine = updateNewLine();
if (configFileName && host.configFileParsingResult) {
setConfigFileParsingResult(host.configFileParsingResult);
newLine = updateNewLine();
}
reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
if (configFileName && !host.configFileParsingResult) {
newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function
() { return host.getNewLine(); });
ts.Debug.assert(!rootFileNames);
parseConfigFile();
newLine = updateNewLine();
}
var _b = ts.createWatchFactory(host, compilerOptions), watchFile =
_b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory,
writeLog = _b.writeLog;
var getCanonicalFileName =
ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + "
CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
var configFileWatcher;
if (configFileName) {
configFileWatcher = watchFile(host, configFileName,
scheduleProgramReload, ts.PollingInterval.High, watchOptions,
ts.WatchType.ConfigFile);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () {
return compilerOptions; }, directoryStructureHost);
ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return getVersionedSourceFileByPath.apply(void 0,
__spreadArrays([fileName, toPath(fileName)], args));
};
compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
compilerHost.getNewLine = function () { return newLine; };
compilerHost.fileExists = fileExists;
compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
// Members for ResolutionCacheHost
compilerHost.toPath = toPath;
compilerHost.getCompilationSettings = function () { return compilerOptions;
};
compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host,
host.useSourceOfProjectReferenceRedirect);
compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb,
flags) { return watchDirectory(host, dir, cb, flags, watchOptions,
ts.WatchType.FailedLookupLocations); };
compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return
watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
compilerHost.getCachedDirectoryStructureHost = function () { return
cachedDirectoryStructureHost; };
compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations =
scheduleInvalidateResolutionsOfFailedLookupLocations;
compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
compilerHost.fileIsOpen = ts.returnFalse;
compilerHost.getCurrentProgram = getCurrentProgram;
compilerHost.writeLog = writeLog;
// Cache for the module resolution
var resolutionCache = ts.createResolutionCache(compilerHost, configFileName
?
ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName,
currentDirectory)) :
currentDirectory,
/*logChangesWhenResolvingModule*/ false);
// Resolve module using host module resolution strategy if provided
otherwise use resolution cache to resolve module names
compilerHost.resolveModuleNames = host.resolveModuleNames ?
(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return host.resolveModuleNames.apply(host, args);
}) :
(function (moduleNames, containingFile, reusedNames,
redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames,
containingFile, reusedNames, redirectedReference); });
compilerHost.resolveTypeReferenceDirectives =
host.resolveTypeReferenceDirectives ?
(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return host.resolveTypeReferenceDirectives.apply(host, args);
}) :
(function (typeDirectiveNames, containingFile, redirectedReference)
{ return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames,
containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!
host.resolveTypeReferenceDirectives;
builderProgram = readBuilderProgram(compilerOptions, compilerHost);
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
{ getCurrentProgram: getCurrentBuilderProgram, getProgram:
updateProgram, close: close } :
{ getCurrentProgram: getCurrentBuilderProgram, getProgram:
updateProgram, updateRootFileNames: updateRootFileNames, close: close };
function close() {
clearInvalidateResolutionsOfFailedLookupLocations();
resolutionCache.clear();
ts.clearMap(sourceFilesCache, function (value) {
if (value && value.fileWatcher) {
value.fileWatcher.close();
value.fileWatcher = undefined;
}
});
if (configFileWatcher) {
configFileWatcher.close();
configFileWatcher = undefined;
}
if (watchedWildcardDirectories) {
ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
watchedWildcardDirectories = undefined;
}
if (missingFilesMap) {
ts.clearMap(missingFilesMap, ts.closeFileWatcher);
missingFilesMap = undefined;
}
}
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
clearInvalidateResolutionsOfFailedLookupLocations();
var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program &&
ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
resolutionCache.clear();
}
}
// All resolutions are invalid if user provided resolutions
var hasInvalidatedResolution =
resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames,
compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution,
hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
if (hasChangedConfigFileParsingErrors) {
builderProgram = createProgram(/*rootNames*/ undefined,
/*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics,
projectReferences);
hasChangedConfigFileParsingErrors = false;
}
}
else {
createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate && program !== builderProgram) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !
getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
compilerHost.hasChangedAutomaticTypeDirectiveNames =
hasChangedAutomaticTypeDirectiveNames;
builderProgram = createProgram(rootFileNames, compilerOptions,
compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
resolutionCache.finishCachingPerDirectoryResolution();
// Update watches
ts.updateMissingFilePathsWatch(builderProgram.getProgram(),
missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
if (needsUpdateInTypeRootWatch) {
resolutionCache.updateTypeRootsWatch();
}
if (missingFilePathsRequestedForRelease) {
// These are the paths that program creater told us as not in use
any more but were missing on the disk.
// We didnt remove the entry for them from sourceFiles cache so
that we dont have to do File IO,
// if there is already watcher for it (for missing files)
// At this point our watches were updated, hence now we know that
these paths are not tracked and need to be removed
// so that at later time we have correct result of their presence
for (var _i = 0, missingFilePathsRequestedForRelease_1 =
missingFilePathsRequestedForRelease; _i <
missingFilePathsRequestedForRelease_1.length; _i++) {
var missingFilePath =
missingFilePathsRequestedForRelease_1[_i];
if (!missingFilesMap.has(missingFilePath)) {
sourceFilesCache.delete(missingFilePath);
}
}
missingFilePathsRequestedForRelease = undefined;
}
}
function updateRootFileNames(files) {
ts.Debug.assert(!configFileName, "Cannot update root file names with
config file watch mode");
rootFileNames = files;
scheduleProgramUpdate();
}
function updateNewLine() {
return ts.getNewLineCharacter(compilerOptions ||
optionsToExtendForConfigFile, function () { return host.getNewLine(); });
}
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
return typeof hostSourceFile === "boolean";
}
function isFilePresenceUnknownOnHost(hostSourceFile) {
return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
// If file is missing on host from cache, we can definitely say file
doesnt exist
// otherwise we need to ensure from the disk
if (isFileMissingOnHost(sourceFilesCache.get(path))) {
return false;
}
return directoryStructureHost.fileExists(fileName);
}
function getVersionedSourceFileByPath(fileName, path, languageVersion,
onError, shouldCreateNewSourceFile) {
var hostSourceFile = sourceFilesCache.get(path);
// No source file on the host
if (isFileMissingOnHost(hostSourceFile)) {
return undefined;
}
// Create new source file if requested or the versions dont match
if (hostSourceFile === undefined || shouldCreateNewSourceFile ||
isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion,
onError);
if (hostSourceFile) {
if (sourceFile) {
// Set the source file and create file watcher now that
file was present on the disk
hostSourceFile.sourceFile = sourceFile;
hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host,
fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path,
ts.WatchType.SourceFile);
}
}
else {
// There is no source file on host any more, close the
watch, missing file paths will track it
if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
var fileWatcher = watchFilePath(host, fileName,
onSourceFileChange, ts.PollingInterval.Low, watchOptions, path,
ts.WatchType.SourceFile);
sourceFilesCache.set(path, { sourceFile: sourceFile,
version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
sourceFilesCache.set(path, false);
}
}
return sourceFile;
}
return hostSourceFile.sourceFile;
}
function nextSourceFileVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
sourceFilesCache.set(path, { version: false });
}
else {
hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
return !hostSourceFile || !hostSourceFile.version ? undefined :
hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions,
hasSourceFileByPath) {
var hostSourceFileInfo =
sourceFilesCache.get(oldSourceFile.resolvedPath);
// If this is the source file thats in the cache and new program doesnt
need it,
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program
or
// there was version update and new source file was created.
if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if
watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease ||
(missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
}
else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
if (hostSourceFileInfo.fileWatcher) {
hostSourceFileInfo.fileWatcher.close();
}
sourceFilesCache.delete(oldSourceFile.resolvedPath);
if (!hasSourceFileByPath) {
resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
}
}
}
}
function reportWatchDiagnostic(message) {
if (host.onWatchStatusChange) {
host.onWatchStatusChange(ts.createCompilerDiagnostic(message),
newLine, compilerOptions || optionsToExtendForConfigFile);
}
}
function hasChangedAutomaticTypeDirectiveNames() {
return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
}
function clearInvalidateResolutionsOfFailedLookupLocations() {
if (!timerToInvalidateFailedLookupResolutions)
return false;
host.clearTimeout(timerToInvalidateFailedLookupResolutions);
timerToInvalidateFailedLookupResolutions = undefined;
return true;
}
function scheduleInvalidateResolutionsOfFailedLookupLocations() {
if (!host.setTimeout || !host.clearTimeout) {
return
resolutionCache.invalidateResolutionsOfFailedLookupLocations();
}
var pending = clearInvalidateResolutionsOfFailedLookupLocations();
writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled
earlier one" : ""));
timerToInvalidateFailedLookupResolutions =
host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
}
function invalidateResolutionsOfFailedLookup() {
timerToInvalidateFailedLookupResolutions = undefined;
if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
scheduleProgramUpdate();
}
}
// Upon detecting a file change, wait for 250ms and then perform a
recompilation. This gives batch
// operations (such as saving all modified files in an editor) a chance to
complete before we kick
// off a new compilation.
function scheduleProgramUpdate() {
if (!host.setTimeout || !host.clearTimeout) {
return;
}
if (timerToUpdateProgram) {
host.clearTimeout(timerToUpdateProgram);
}
writeLog("Scheduling update");
timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus,
250);
}
function scheduleProgramReload() {
ts.Debug.assert(!!configFileName);
reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
scheduleProgramUpdate();
}
function updateProgramWithWatchStatus() {
timerToUpdateProgram = undefined;
reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_comp
ilation);
updateProgram();
}
function updateProgram() {
switch (reloadLevel) {
case ts.ConfigFileProgramReloadLevel.Partial:
ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
reloadFileNamesFromConfigFile();
break;
case ts.ConfigFileProgramReloadLevel.Full:
ts.perfLogger.logStartUpdateProgram("FullConfigReload");
reloadConfigFile();
break;
default:
ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
synchronizeProgram();
break;
}
ts.perfLogger.logStopUpdateProgram("Done");
return getCurrentBuilderProgram();
}
function reloadFileNamesFromConfigFile() {
writeLog("Reloading new file names and options");
var result = ts.getFileNamesFromConfigSpecs(configFileSpecs,
ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName),
currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
if (ts.updateErrorForNoInputFiles(result,
ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs,
configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
hasChangedConfigFileParsingErrors = true;
}
rootFileNames = result.fileNames;
// Update the program
synchronizeProgram();
}
function reloadConfigFile() {
writeLog("Reloading config file: " + configFileName);
reloadLevel = ts.ConfigFileProgramReloadLevel.None;
if (cachedDirectoryStructureHost) {
cachedDirectoryStructureHost.clearCache();
}
parseConfigFile();
hasChangedCompilerOptions = true;
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
}
function parseConfigFile() {
setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName,
optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/
undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
}
function setConfigFileParsingResult(configFileParseResult) {
rootFileNames = configFileParseResult.fileNames;
compilerOptions = configFileParseResult.options;
watchOptions = configFileParseResult.watchOptions;
configFileSpecs = configFileParseResult.configFileSpecs; // TODO:
GH#18217
projectReferences = configFileParseResult.projectReferences;
configFileParsingDiagnostics =
ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
canConfigFileJsonReportNoInputFiles =
ts.canJsonReportNoInputFiles(configFileParseResult.raw);
hasChangedConfigFileParsingErrors = true;
}
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
if (eventKind === ts.FileWatcherEventKind.Deleted &&
sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
nextSourceFileVersion(path);
// Update the program
scheduleProgramUpdate();
}
function updateCachedSystemWithFile(fileName, path, eventKind) {
if (cachedDirectoryStructureHost) {
cachedDirectoryStructureHost.addOrDeleteFile(fileName, path,
eventKind);
}
}
function watchMissingFilePath(missingFilePath) {
return watchFilePath(host, missingFilePath, onMissingFileChange,
ts.PollingInterval.Medium, watchOptions, missingFilePath,
ts.WatchType.MissingFile);
}
function onMissingFileChange(fileName, eventKind, missingFilePath) {
updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
if (eventKind === ts.FileWatcherEventKind.Created &&
missingFilesMap.has(missingFilePath)) {
missingFilesMap.get(missingFilePath).close();
missingFilesMap.delete(missingFilePath);
// Delete the entry in the source files cache so that new source
file is created
nextSourceFileVersion(missingFilePath);
// When a missing file is created, we should update the graph.
scheduleProgramUpdate();
}
}
function watchConfigFileWildCardDirectories() {
if (configFileSpecs) {
ts.updateWatchingWildcardDirectories(watchedWildcardDirectories ||
(watchedWildcardDirectories = new ts.Map()), new
ts.Map(ts.getEntries(configFileSpecs.wildcardDirectories)),
watchWildcardDirectory);
}
else if (watchedWildcardDirectories) {
ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
}
}
function watchWildcardDirectory(directory, flags) {
return watchDirectory(host, directory, function (fileOrDirectory) {
ts.Debug.assert(!!configFileName);
var fileOrDirectoryPath = toPath(fileOrDirectory);
// Since the file existence changed, update the sourceFiles cache
if (cachedDirectoryStructureHost) {
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory,
fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
if (ts.isIgnoredFileFromWildCardWatching({
watchedDirPath: toPath(directory),
fileOrDirectory: fi