code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) {
var packageJsonPath = ts.combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
var jsonContent;
try {
var jsonText = host.readFile(packageJsonPath);
jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
}
}
}
else {
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host);
}
|
The version of the TypeScript compiler release
|
loadNodeModuleFromDirectory
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function loadModuleFromNodeModules(moduleName, directory, host) {
var failedLookupLocations = [];
directory = ts.normalizeSlashes(directory);
while (true) {
var baseName = ts.getBaseFileName(directory);
if (baseName !== "node_modules") {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations };
}
}
var parentPath = ts.getDirectoryPath(directory);
if (parentPath === directory) {
break;
}
directory = parentPath;
}
return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
}
|
The version of the TypeScript compiler release
|
loadModuleFromNodeModules
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function nameStartsWithDotSlashOrDotDotSlash(name) {
var i = name.lastIndexOf("./", 1);
return i === 0 || (i === 1 && name.charCodeAt(0) === 46 /* dot */);
}
|
The version of the TypeScript compiler release
|
nameStartsWithDotSlashOrDotDotSlash
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
// module names that contain '!' are used to reference resources and are not resolved to actual files on disk
if (moduleName.indexOf("!") != -1) {
return { resolvedModule: undefined, failedLookupLocations: [] };
}
var searchPath = ts.getDirectoryPath(containingFile);
var searchName;
var failedLookupLocations = [];
var referencedSourceFile;
var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions;
while (true) {
searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName));
referencedSourceFile = ts.forEach(extensions, function (extension) {
if (extension === ".tsx" && !compilerOptions.jsx) {
// resolve .tsx files only if jsx support is enabled
// 'logical not' handles both undefined and None cases
return undefined;
}
var candidate = searchName + extension;
if (host.fileExists(candidate)) {
return candidate;
}
else {
failedLookupLocations.push(candidate);
}
});
if (referencedSourceFile) {
break;
}
var parentPath = ts.getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
}
|
The version of the TypeScript compiler release
|
classicNameResolver
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createCompilerHost(options, setParentNodes) {
var existingDirectories = {};
function getCanonicalFileName(fileName) {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
var unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
var start = new Date().getTime();
text = ts.sys.readFile(fileName, options.charset);
ts.ioReadTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode
? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText
: e.message);
}
text = "";
}
return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath) {
if (ts.hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (ts.sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath) {
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
ts.sys.createDirectory(directoryPath);
}
}
function writeFile(fileName, data, writeByteOrderMark, onError) {
try {
var start = new Date().getTime();
ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
ts.sys.writeFile(fileName, data, writeByteOrderMark);
ts.ioWriteTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
var newLine = ts.getNewLineCharacter(options);
return {
getSourceFile: getSourceFile,
getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); },
writeFile: writeFile,
getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }),
useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; },
getCanonicalFileName: getCanonicalFileName,
getNewLine: function () { return newLine; },
fileExists: function (fileName) { return ts.sys.fileExists(fileName); },
readFile: function (fileName) { return ts.sys.readFile(fileName); }
};
}
|
The version of the TypeScript compiler release
|
createCompilerHost
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getCanonicalFileName(fileName) {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
|
The version of the TypeScript compiler release
|
getCanonicalFileName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
var start = new Date().getTime();
text = ts.sys.readFile(fileName, options.charset);
ts.ioReadTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode
? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText
: e.message);
}
text = "";
}
return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
|
The version of the TypeScript compiler release
|
getSourceFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function directoryExists(directoryPath) {
if (ts.hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (ts.sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
|
The version of the TypeScript compiler release
|
directoryExists
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function ensureDirectoriesExist(directoryPath) {
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
ts.sys.createDirectory(directoryPath);
}
}
|
The version of the TypeScript compiler release
|
ensureDirectoriesExist
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function writeFile(fileName, data, writeByteOrderMark, onError) {
try {
var start = new Date().getTime();
ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
ts.sys.writeFile(fileName, data, writeByteOrderMark);
ts.ioWriteTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
|
The version of the TypeScript compiler release
|
writeFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
|
The version of the TypeScript compiler release
|
getPreEmitDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
}
else {
var diagnosticChain = messageText;
var result = "";
var indent = 0;
while (diagnosticChain) {
if (indent) {
result += newLine;
for (var i = 0; i < indent; i++) {
result += " ";
}
}
result += diagnosticChain.messageText;
indent++;
diagnosticChain = diagnosticChain.next;
}
return result;
}
}
|
The version of the TypeScript compiler release
|
flattenDiagnosticMessageText
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createProgram(rootNames, options, host, oldProgram) {
var program;
var files = [];
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var programDiagnostics = ts.createDiagnosticCollection();
var commonSourceDirectory;
var diagnosticsProducingTypeChecker;
var noDiagnosticsTypeChecker;
var classifiableNames;
var skipDefaultLib = options.noLib;
var start = new Date().getTime();
host = host || createCompilerHost(options);
var currentDirectory = host.getCurrentDirectory();
var resolveModuleNamesWorker = host.resolveModuleNames
? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); })
: (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); });
var filesByName = ts.createFileMap();
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined;
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
var oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
ts.forEach(rootNames, function (name) { return processRootFile(name, false); });
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
// processing the root files.
if (!skipDefaultLib) {
processRootFile(host.getDefaultLibFileName(options), true);
}
}
verifyCompilerOptions();
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
ts.programTime += new Date().getTime() - start;
program = {
getRootFileNames: function () { return rootNames; },
getSourceFile: getSourceFile,
getSourceFiles: function () { return files; },
getCompilerOptions: function () { return options; },
getSyntacticDiagnostics: getSyntacticDiagnostics,
getOptionsDiagnostics: getOptionsDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
getSemanticDiagnostics: getSemanticDiagnostics,
getDeclarationDiagnostics: getDeclarationDiagnostics,
getTypeChecker: getTypeChecker,
getClassifiableNames: getClassifiableNames,
getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
getCommonSourceDirectory: function () { return commonSourceDirectory; },
emit: emit,
getCurrentDirectory: function () { return currentDirectory; },
getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }
};
return program;
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
var sourceFile = files_3[_i];
ts.copyMap(sourceFile.classifiableNames, classifiableNames);
}
}
return classifiableNames;
}
function tryReuseStructureFromOldProgram() {
if (!oldProgram) {
return false;
}
ts.Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
var oldRootNames = oldProgram.getRootFileNames();
if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
var modifiedSourceFiles = [];
for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) {
var oldSourceFile = _a[_i];
var newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
newSourceFile.path = oldSourceFile.path;
filePaths.push(newSourceFile.path);
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
return false;
}
// check tripleslash references
if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
// tripleslash references has changed
return false;
}
// check imports
collectExternalModuleReferences(newSourceFile);
if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (resolveModuleNamesWorker) {
var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; });
var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory));
// ensure that module resolution results are still correct
for (var i = 0; i < moduleNames.length; ++i) {
var newResolution = resolutions[i];
var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]);
var resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
modifiedSourceFiles.push(newSourceFile);
}
else {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (var i = 0, len = newSourceFiles.length; i < len; ++i) {
filesByName.set(filePaths[i], newSourceFiles[i]);
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) {
var modifiedFile = modifiedSourceFiles_1[_b];
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
}
function getEmitHost(writeFileCallback) {
return {
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: function () { return currentDirectory; },
getNewLine: function () { return host.getNewLine(); },
getSourceFile: program.getSourceFile,
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); })
};
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
}
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) {
return { diagnostics: [], sourceMaps: undefined, emitSkipped: true };
}
// Create the emit resolver outside of the "emitTime" tracking code below. That way
// any cost associated with it (like type checking) are appropriate associated with
// the type-checking counter.
//
// If the -out option is specified, we should not pass the source file to getEmitResolver.
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
var start = new Date().getTime();
var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.emitTime += new Date().getTime() - start;
return emitResult;
}
function getSourceFile(fileName) {
return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
}
function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
var allDiagnostics = [];
ts.forEach(program.getSourceFiles(), function (sourceFile) {
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken));
});
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getSyntacticDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
function getSemanticDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
function getDeclarationDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
}
function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) {
return sourceFile.parseDiagnostics;
}
function runWithCancellationToken(func) {
try {
return func();
}
catch (e) {
if (e instanceof ts.OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly agressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
}
throw e;
}
}
function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var bindDiagnostics = sourceFile.bindDiagnostics;
var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile);
});
}
function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
if (!ts.isDeclarationFile(sourceFile)) {
var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
var writeFile_1 = function () { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile_1), resolver, sourceFile);
}
});
}
function getOptionsDiagnostics() {
var allDiagnostics = [];
ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());
ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getGlobalDiagnostics() {
var allDiagnostics = [];
ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics());
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
function hasExtension(fileName) {
return ts.getBaseFileName(fileName).indexOf(".") >= 0;
}
function processRootFile(fileName, isDefaultLib) {
processSourceFile(ts.normalizePath(fileName), isDefaultLib);
}
function fileReferenceIsEqualTo(a, b) {
return a.fileName === b.fileName;
}
function moduleNameIsEqualTo(a, b) {
return a.text === b.text;
}
function collectExternalModuleReferences(file) {
if (file.imports) {
return;
}
var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false);
}
file.imports = imports || emptyArray;
return;
function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
if (!collectOnlyRequireCalls) {
switch (node.kind) {
case 222 /* ImportDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 228 /* ExportDeclaration */:
var moduleNameExpr = ts.getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
break;
}
if (!moduleNameExpr.text) {
break;
}
if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
(imports || (imports = [])).push(moduleNameExpr);
}
break;
case 218 /* ModuleDeclaration */:
if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
ts.forEachChild(node.body, function (node) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
});
}
break;
}
}
if (isJavaScriptFile) {
if (ts.isRequireCall(node)) {
(imports || (imports = [])).push(node.arguments[0]);
}
else {
ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); });
}
}
}
}
function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) {
var diagnosticArgument;
var diagnostic;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) {
diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1;
diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"];
}
else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = ts.Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself;
diagnosticArgument = [fileName];
}
}
else {
var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = ts.Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) {
diagnostic = ts.Diagnostics.File_0_not_found;
fileName += ".ts";
diagnosticArgument = [fileName];
}
}
}
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument)));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument)));
}
}
}
function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
}
// Get source file from normalized fileName
function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) {
if (filesByName.contains(normalizedAbsolutePath)) {
var file_1 = filesByName.get(normalizedAbsolutePath);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
return file_1;
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(normalizedAbsolutePath, file);
if (file) {
file.path = normalizedAbsolutePath;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
filesByNameIgnoreCase.set(normalizedAbsolutePath, file);
}
}
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
var basePath = ts.getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
files.unshift(file);
}
else {
files.push(file);
}
}
return file;
}
function processReferencedFiles(file, basePath) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
function getCanonicalFileName(fileName) {
return host.getCanonicalFileName(fileName);
}
function processImportedModules(file, basePath) {
collectExternalModuleReferences(file);
if (file.imports.length) {
file.resolvedModules = {};
var moduleNames = ts.map(file.imports, function (name) { return name.text; });
var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (var i = 0; i < file.imports.length; ++i) {
var resolution = resolutions[i];
ts.setResolvedModule(file, moduleNames[i], resolution);
if (resolution && !options.noResolve) {
var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
if (!ts.isExternalModule(importedFile)) {
var start_2 = ts.getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
else if (importedFile.referencedFiles.length) {
var firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
}
}
}
else {
// no imports - drop cached module resolutions
file.resolvedModules = undefined;
}
return;
}
function computeCommonSourceDirectory(sourceFiles) {
var commonPathComponents;
ts.forEach(files, function (sourceFile) {
// Each file contributes into common source file path
if (ts.isDeclarationFile(sourceFile)) {
return;
}
var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.fileName, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
if (commonPathComponents[i] !== sourcePathComponents[i]) {
if (i === 0) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
return;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
if (!commonPathComponents) {
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
var allFilesBelongToPath = true;
if (sourceFiles) {
var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var sourceFile = sourceFiles_1[_i];
if (!ts.isDeclarationFile(sourceFile)) {
var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
allFilesBelongToPath = false;
}
}
}
}
return allFilesBelongToPath;
}
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
if (options.sourceRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
}
}
if (options.out && options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
return;
}
var languageVersion = options.target || 0 /* ES3 */;
var outFile = options.outFile || options.out;
var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; });
if (options.isolatedModules) {
if (!options.module && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; });
if (firstNonExternalModuleSourceFile) {
var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
}
// Cannot specify module gen target of es6 when below es6
if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir ||
options.sourceRoot ||
options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
// Compute the commonSourceDirectory from the input files
commonSourceDirectory = computeCommonSourceDirectory(files);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += ts.directorySeparator;
}
}
if (options.noEmit) {
if (options.out) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
}
}
|
The version of the TypeScript compiler release
|
createProgram
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
var sourceFile = files_3[_i];
ts.copyMap(sourceFile.classifiableNames, classifiableNames);
}
}
return classifiableNames;
}
|
The version of the TypeScript compiler release
|
getClassifiableNames
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryReuseStructureFromOldProgram() {
if (!oldProgram) {
return false;
}
ts.Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
var oldRootNames = oldProgram.getRootFileNames();
if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
var modifiedSourceFiles = [];
for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) {
var oldSourceFile = _a[_i];
var newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
newSourceFile.path = oldSourceFile.path;
filePaths.push(newSourceFile.path);
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
return false;
}
// check tripleslash references
if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
// tripleslash references has changed
return false;
}
// check imports
collectExternalModuleReferences(newSourceFile);
if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (resolveModuleNamesWorker) {
var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; });
var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory));
// ensure that module resolution results are still correct
for (var i = 0; i < moduleNames.length; ++i) {
var newResolution = resolutions[i];
var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]);
var resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
modifiedSourceFiles.push(newSourceFile);
}
else {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (var i = 0, len = newSourceFiles.length; i < len; ++i) {
filesByName.set(filePaths[i], newSourceFiles[i]);
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) {
var modifiedFile = modifiedSourceFiles_1[_b];
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
}
|
The version of the TypeScript compiler release
|
tryReuseStructureFromOldProgram
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getEmitHost(writeFileCallback) {
return {
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: function () { return currentDirectory; },
getNewLine: function () { return host.getNewLine(); },
getSourceFile: program.getSourceFile,
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); })
};
}
|
The version of the TypeScript compiler release
|
getEmitHost
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
}
|
The version of the TypeScript compiler release
|
getDiagnosticsProducingTypeChecker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
|
The version of the TypeScript compiler release
|
getTypeChecker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
|
The version of the TypeScript compiler release
|
emit
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) {
return { diagnostics: [], sourceMaps: undefined, emitSkipped: true };
}
// Create the emit resolver outside of the "emitTime" tracking code below. That way
// any cost associated with it (like type checking) are appropriate associated with
// the type-checking counter.
//
// If the -out option is specified, we should not pass the source file to getEmitResolver.
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
var start = new Date().getTime();
var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile);
ts.emitTime += new Date().getTime() - start;
return emitResult;
}
|
The version of the TypeScript compiler release
|
emitWorker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSourceFile(fileName) {
return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
}
|
The version of the TypeScript compiler release
|
getSourceFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
var allDiagnostics = [];
ts.forEach(program.getSourceFiles(), function (sourceFile) {
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken));
});
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
|
The version of the TypeScript compiler release
|
getDiagnosticsHelper
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSyntacticDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
|
The version of the TypeScript compiler release
|
getSyntacticDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSemanticDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
|
The version of the TypeScript compiler release
|
getSemanticDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getDeclarationDiagnostics(sourceFile, cancellationToken) {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
}
|
The version of the TypeScript compiler release
|
getDeclarationDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) {
return sourceFile.parseDiagnostics;
}
|
The version of the TypeScript compiler release
|
getSyntacticDiagnosticsForFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function runWithCancellationToken(func) {
try {
return func();
}
catch (e) {
if (e instanceof ts.OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly agressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
}
throw e;
}
}
|
The version of the TypeScript compiler release
|
runWithCancellationToken
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var bindDiagnostics = sourceFile.bindDiagnostics;
var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile);
});
}
|
The version of the TypeScript compiler release
|
getSemanticDiagnosticsForFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
if (!ts.isDeclarationFile(sourceFile)) {
var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
var writeFile_1 = function () { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile_1), resolver, sourceFile);
}
});
}
|
The version of the TypeScript compiler release
|
getDeclarationDiagnosticsForFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getOptionsDiagnostics() {
var allDiagnostics = [];
ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());
ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
|
The version of the TypeScript compiler release
|
getOptionsDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getGlobalDiagnostics() {
var allDiagnostics = [];
ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics());
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
|
The version of the TypeScript compiler release
|
getGlobalDiagnostics
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function hasExtension(fileName) {
return ts.getBaseFileName(fileName).indexOf(".") >= 0;
}
|
The version of the TypeScript compiler release
|
hasExtension
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function processRootFile(fileName, isDefaultLib) {
processSourceFile(ts.normalizePath(fileName), isDefaultLib);
}
|
The version of the TypeScript compiler release
|
processRootFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function fileReferenceIsEqualTo(a, b) {
return a.fileName === b.fileName;
}
|
The version of the TypeScript compiler release
|
fileReferenceIsEqualTo
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function moduleNameIsEqualTo(a, b) {
return a.text === b.text;
}
|
The version of the TypeScript compiler release
|
moduleNameIsEqualTo
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function collectExternalModuleReferences(file) {
if (file.imports) {
return;
}
var isJavaScriptFile = ts.isSourceFileJavaScript(file);
var imports;
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var node = _a[_i];
collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false);
}
file.imports = imports || emptyArray;
return;
function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
if (!collectOnlyRequireCalls) {
switch (node.kind) {
case 222 /* ImportDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 228 /* ExportDeclaration */:
var moduleNameExpr = ts.getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
break;
}
if (!moduleNameExpr.text) {
break;
}
if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
(imports || (imports = [])).push(moduleNameExpr);
}
break;
case 218 /* ModuleDeclaration */:
if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
ts.forEachChild(node.body, function (node) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
});
}
break;
}
}
if (isJavaScriptFile) {
if (ts.isRequireCall(node)) {
(imports || (imports = [])).push(node.arguments[0]);
}
else {
ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); });
}
}
}
}
|
The version of the TypeScript compiler release
|
collectExternalModuleReferences
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) {
if (!collectOnlyRequireCalls) {
switch (node.kind) {
case 222 /* ImportDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 228 /* ExportDeclaration */:
var moduleNameExpr = ts.getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
break;
}
if (!moduleNameExpr.text) {
break;
}
if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) {
(imports || (imports = [])).push(moduleNameExpr);
}
break;
case 218 /* ModuleDeclaration */:
if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
ts.forEachChild(node.body, function (node) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls);
});
}
break;
}
}
if (isJavaScriptFile) {
if (ts.isRequireCall(node)) {
(imports || (imports = [])).push(node.arguments[0]);
}
else {
ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); });
}
}
}
|
The version of the TypeScript compiler release
|
collect
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) {
var diagnosticArgument;
var diagnostic;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) {
diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1;
diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"];
}
else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = ts.Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself;
diagnosticArgument = [fileName];
}
}
else {
var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = ts.Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) {
diagnostic = ts.Diagnostics.File_0_not_found;
fileName += ".ts";
diagnosticArgument = [fileName];
}
}
}
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument)));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument)));
}
}
}
|
The version of the TypeScript compiler release
|
processSourceFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
}
|
The version of the TypeScript compiler release
|
reportFileNamesDifferOnlyInCasingError
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) {
if (filesByName.contains(normalizedAbsolutePath)) {
var file_1 = filesByName.get(normalizedAbsolutePath);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
return file_1;
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(normalizedAbsolutePath, file);
if (file) {
file.path = normalizedAbsolutePath;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
filesByNameIgnoreCase.set(normalizedAbsolutePath, file);
}
}
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
var basePath = ts.getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
files.unshift(file);
}
else {
files.push(file);
}
}
return file;
}
|
The version of the TypeScript compiler release
|
findSourceFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function processReferencedFiles(file, basePath) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
|
The version of the TypeScript compiler release
|
processReferencedFiles
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getCanonicalFileName(fileName) {
return host.getCanonicalFileName(fileName);
}
|
The version of the TypeScript compiler release
|
getCanonicalFileName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function processImportedModules(file, basePath) {
collectExternalModuleReferences(file);
if (file.imports.length) {
file.resolvedModules = {};
var moduleNames = ts.map(file.imports, function (name) { return name.text; });
var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (var i = 0; i < file.imports.length; ++i) {
var resolution = resolutions[i];
ts.setResolvedModule(file, moduleNames[i], resolution);
if (resolution && !options.noResolve) {
var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
if (!ts.isExternalModule(importedFile)) {
var start_2 = ts.getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
else if (importedFile.referencedFiles.length) {
var firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
}
}
}
else {
// no imports - drop cached module resolutions
file.resolvedModules = undefined;
}
return;
}
|
The version of the TypeScript compiler release
|
processImportedModules
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function computeCommonSourceDirectory(sourceFiles) {
var commonPathComponents;
ts.forEach(files, function (sourceFile) {
// Each file contributes into common source file path
if (ts.isDeclarationFile(sourceFile)) {
return;
}
var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.fileName, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
if (commonPathComponents[i] !== sourcePathComponents[i]) {
if (i === 0) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
return;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
if (!commonPathComponents) {
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
}
|
The version of the TypeScript compiler release
|
computeCommonSourceDirectory
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
var allFilesBelongToPath = true;
if (sourceFiles) {
var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var sourceFile = sourceFiles_1[_i];
if (!ts.isDeclarationFile(sourceFile)) {
var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
allFilesBelongToPath = false;
}
}
}
}
return allFilesBelongToPath;
}
|
The version of the TypeScript compiler release
|
checkSourceFilesBelongToPath
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
if (options.sourceRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
}
}
if (options.out && options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
return;
}
var languageVersion = options.target || 0 /* ES3 */;
var outFile = options.outFile || options.out;
var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; });
if (options.isolatedModules) {
if (!options.module && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; });
if (firstNonExternalModuleSourceFile) {
var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
}
// Cannot specify module gen target of es6 when below es6
if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir ||
options.sourceRoot ||
options.mapRoot) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
// Compute the commonSourceDirectory from the input files
commonSourceDirectory = computeCommonSourceDirectory(files);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += ts.directorySeparator;
}
}
if (options.noEmit) {
if (options.out) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
}
|
The version of the TypeScript compiler release
|
verifyCompilerOptions
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
var errors = [];
var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
errors: errors
};
function parseStrings(args) {
var i = 0;
while (i < args.length) {
var s = args[i++];
if (s.charCodeAt(0) === 64 /* at */) {
parseResponseFile(s.slice(1));
}
else if (s.charCodeAt(0) === 45 /* minus */) {
s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase();
// Try to translate short option names to their full equivalents.
if (ts.hasProperty(shortOptionNames, s)) {
s = shortOptionNames[s];
}
if (ts.hasProperty(optionNameMap, s)) {
var opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i++]);
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i++] || "";
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
var map_2 = opt.type;
var key = (args[i++] || "").toLowerCase();
if (ts.hasProperty(map_2, key)) {
options[opt.name] = map_2[key];
}
else {
errors.push(ts.createCompilerDiagnostic(opt.error));
}
}
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s));
}
}
else {
fileNames.push(s);
}
}
}
function parseResponseFile(fileName) {
var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
if (!text) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
return;
}
var args = [];
var pos = 0;
while (true) {
while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
pos++;
if (pos >= text.length)
break;
var start = pos;
if (text.charCodeAt(start) === 34 /* doubleQuote */) {
pos++;
while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
pos++;
if (pos < text.length) {
args.push(text.substring(start + 1, pos));
pos++;
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
}
}
else {
while (text.charCodeAt(pos) > 32 /* space */)
pos++;
args.push(text.substring(start, pos));
}
}
parseStrings(args);
}
}
|
The version of the TypeScript compiler release
|
parseCommandLine
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseStrings(args) {
var i = 0;
while (i < args.length) {
var s = args[i++];
if (s.charCodeAt(0) === 64 /* at */) {
parseResponseFile(s.slice(1));
}
else if (s.charCodeAt(0) === 45 /* minus */) {
s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase();
// Try to translate short option names to their full equivalents.
if (ts.hasProperty(shortOptionNames, s)) {
s = shortOptionNames[s];
}
if (ts.hasProperty(optionNameMap, s)) {
var opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i++]);
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i++] || "";
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
var map_2 = opt.type;
var key = (args[i++] || "").toLowerCase();
if (ts.hasProperty(map_2, key)) {
options[opt.name] = map_2[key];
}
else {
errors.push(ts.createCompilerDiagnostic(opt.error));
}
}
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s));
}
}
else {
fileNames.push(s);
}
}
}
|
The version of the TypeScript compiler release
|
parseStrings
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseResponseFile(fileName) {
var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
if (!text) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
return;
}
var args = [];
var pos = 0;
while (true) {
while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
pos++;
if (pos >= text.length)
break;
var start = pos;
if (text.charCodeAt(start) === 34 /* doubleQuote */) {
pos++;
while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
pos++;
if (pos < text.length) {
args.push(text.substring(start + 1, pos));
pos++;
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
}
}
else {
while (text.charCodeAt(pos) > 32 /* space */)
pos++;
args.push(text.substring(start, pos));
}
}
parseStrings(args);
}
|
The version of the TypeScript compiler release
|
parseResponseFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseConfigFileTextToJson(fileName, jsonText) {
try {
var jsonTextWithoutComments = removeComments(jsonText);
return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
}
}
|
Parse the text of the tsconfig.json file
@param fileName The path to the config file
@param jsonText The text of the config file
|
parseConfigFileTextToJson
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function removeComments(jsonText) {
var output = "";
var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText);
var token;
while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) {
switch (token) {
case 2 /* SingleLineCommentTrivia */:
case 3 /* MultiLineCommentTrivia */:
// replace comments with whitespace to preserve original character positions
output += scanner.getTokenText().replace(/\S/g, " ");
break;
default:
output += scanner.getTokenText();
break;
}
}
return output;
}
|
Remove the comments from a json like text.
Comments can be single line comments (starting with # or //) or multiline comments using / * * /
This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate.
|
removeComments
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseJsonConfigFileContent(json, host, basePath) {
var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors;
return {
options: options,
fileNames: getFileNames(),
errors: errors
};
function getFileNames() {
var fileNames = [];
if (ts.hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); });
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
var name_31 = sysFiles[i];
if (ts.fileExtensionIs(name_31, ".d.ts")) {
var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
fileNames.push(name_31);
}
}
else if (ts.fileExtensionIs(name_31, ".ts")) {
if (!ts.contains(sysFiles, name_31 + "x")) {
fileNames.push(name_31);
}
}
else {
fileNames.push(name_31);
}
}
}
return fileNames;
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
parseJsonConfigFileContent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getFileNames() {
var fileNames = [];
if (ts.hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); });
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
var name_31 = sysFiles[i];
if (ts.fileExtensionIs(name_31, ".d.ts")) {
var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
fileNames.push(name_31);
}
}
else if (ts.fileExtensionIs(name_31, ".ts")) {
if (!ts.contains(sysFiles, name_31 + "x")) {
fileNames.push(name_31);
}
}
else {
fileNames.push(name_31);
}
}
}
return fileNames;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getFileNames
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function convertCompilerOptionsFromJson(jsonOptions, basePath) {
var options = {};
var errors = [];
if (!jsonOptions) {
return { options: options, errors: errors };
}
var optionNameMap = ts.arrayToMap(ts.optionDeclarations, function (opt) { return opt.name; });
for (var id in jsonOptions) {
if (ts.hasProperty(optionNameMap, id)) {
var opt = optionNameMap[id];
var optType = opt.type;
var value = jsonOptions[id];
var expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
var key = value.toLowerCase();
if (ts.hasProperty(optType, key)) {
value = optType[key];
}
else {
errors.push(ts.createCompilerDiagnostic(opt.error));
value = 0;
}
}
if (opt.isFilePath) {
value = ts.normalizePath(ts.combinePaths(basePath, value));
if (value === "") {
value = ".";
}
}
options[opt.name] = value;
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType));
}
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, id));
}
}
return { options: options, errors: errors };
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
convertCompilerOptionsFromJson
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function collectElements(sourceFile) {
var elements = [];
var collapseText = "...";
function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) {
if (hintSpanNode && startElement && endElement) {
var span = {
textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningSpanComments(commentSpan, autoCollapse) {
if (commentSpan) {
var span = {
textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningForLeadingCommentsForNode(n) {
var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (comments) {
var firstSingleLineCommentStart = -1;
var lastSingleLineCommentEnd = -1;
var isFirstSingleLineComment = true;
var singleLineCommentCount = 0;
for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
var currentComment = comments_2[_i];
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === 2 /* SingleLineCommentTrivia */) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
}
else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
}
}
function combineAndAddMultipleSingleLineComments(count, start, end) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
var multipleSingleLineComments = {
pos: start,
end: end,
kind: 2 /* SingleLineCommentTrivia */
};
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node) {
return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */;
}
var depth = 0;
var maxDepth = 20;
function walk(n) {
if (depth > maxDepth) {
return;
}
if (ts.isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case 192 /* Block */:
if (!ts.isFunctionBlock(n)) {
var parent_7 = n.parent;
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent_7.kind === 197 /* DoStatement */ ||
parent_7.kind === 200 /* ForInStatement */ ||
parent_7.kind === 201 /* ForOfStatement */ ||
parent_7.kind === 199 /* ForStatement */ ||
parent_7.kind === 196 /* IfStatement */ ||
parent_7.kind === 198 /* WhileStatement */ ||
parent_7.kind === 205 /* WithStatement */ ||
parent_7.kind === 244 /* CatchClause */) {
addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n));
break;
}
if (parent_7.kind === 209 /* TryStatement */) {
// Could be the try-block, or the finally-block.
var tryStatement = parent_7;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
var span = ts.createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
// Fallthrough.
case 219 /* ModuleBlock */: {
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
case 214 /* ClassDeclaration */:
case 215 /* InterfaceDeclaration */:
case 217 /* EnumDeclaration */:
case 165 /* ObjectLiteralExpression */:
case 220 /* CaseBlock */: {
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case 164 /* ArrayLiteralExpression */:
var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile);
var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
depth++;
ts.forEachChild(n, walk);
depth--;
}
walk(sourceFile);
return elements;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
collectElements
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) {
if (hintSpanNode && startElement && endElement) {
var span = {
textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
addOutliningSpan
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function addOutliningSpanComments(commentSpan, autoCollapse) {
if (commentSpan) {
var span = {
textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
addOutliningSpanComments
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function addOutliningForLeadingCommentsForNode(n) {
var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (comments) {
var firstSingleLineCommentStart = -1;
var lastSingleLineCommentEnd = -1;
var isFirstSingleLineComment = true;
var singleLineCommentCount = 0;
for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
var currentComment = comments_2[_i];
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === 2 /* SingleLineCommentTrivia */) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
}
else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
addOutliningForLeadingCommentsForNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function combineAndAddMultipleSingleLineComments(count, start, end) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
var multipleSingleLineComments = {
pos: start,
end: end,
kind: 2 /* SingleLineCommentTrivia */
};
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
combineAndAddMultipleSingleLineComments
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function autoCollapse(node) {
return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
autoCollapse
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function walk(n) {
if (depth > maxDepth) {
return;
}
if (ts.isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case 192 /* Block */:
if (!ts.isFunctionBlock(n)) {
var parent_7 = n.parent;
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent_7.kind === 197 /* DoStatement */ ||
parent_7.kind === 200 /* ForInStatement */ ||
parent_7.kind === 201 /* ForOfStatement */ ||
parent_7.kind === 199 /* ForStatement */ ||
parent_7.kind === 196 /* IfStatement */ ||
parent_7.kind === 198 /* WhileStatement */ ||
parent_7.kind === 205 /* WithStatement */ ||
parent_7.kind === 244 /* CatchClause */) {
addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n));
break;
}
if (parent_7.kind === 209 /* TryStatement */) {
// Could be the try-block, or the finally-block.
var tryStatement = parent_7;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
var span = ts.createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
// Fallthrough.
case 219 /* ModuleBlock */: {
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
case 214 /* ClassDeclaration */:
case 215 /* InterfaceDeclaration */:
case 217 /* EnumDeclaration */:
case 165 /* ObjectLiteralExpression */:
case 220 /* CaseBlock */: {
var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case 164 /* ArrayLiteralExpression */:
var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile);
var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
depth++;
ts.forEachChild(n, walk);
depth--;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
walk
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
// This means "compare in a case insensitive manner."
var baseSensitivity = { sensitivity: "base" };
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
ts.forEach(program.getSourceFiles(), function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
var nameToDeclarations = sourceFile.getNamedDeclarations();
for (var name_32 in nameToDeclarations) {
var declarations = ts.getProperty(nameToDeclarations, name_32);
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32);
if (!matches) {
continue;
}
for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
var declaration = declarations_6[_i];
// It was a match! If the pattern has dots in it, then also see if the
// declaration container matches as well.
if (patternMatcher.patternContainsDots) {
var containers = getContainers(declaration);
if (!containers) {
return undefined;
}
matches = patternMatcher.getMatches(containers, name_32);
if (!matches) {
continue;
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
}
}
}
});
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
rawItems = rawItems.slice(0, maxResultCount);
}
var items = ts.map(rawItems, createNavigateToItem);
return items;
function allMatchesAreCaseSensitive(matches) {
ts.Debug.assert(matches.length > 0);
// This is a case sensitive match, only if all the submatches were case sensitive.
for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
var match = matches_1[_i];
if (!match.isCaseSensitive) {
return false;
}
}
return true;
}
function getTextOfIdentifierOrLiteral(node) {
if (node) {
if (node.kind === 69 /* Identifier */ ||
node.kind === 9 /* StringLiteral */ ||
node.kind === 8 /* NumericLiteral */) {
return node.text;
}
}
return undefined;
}
function tryAddSingleDeclarationName(declaration, containers) {
if (declaration && declaration.name) {
var text = getTextOfIdentifierOrLiteral(declaration.name);
if (text !== undefined) {
containers.unshift(text);
}
else if (declaration.name.kind === 136 /* ComputedPropertyName */) {
return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true);
}
else {
// Don't know how to add this.
return false;
}
}
return true;
}
// Only added the names of computed properties if they're simple dotted expressions, like:
//
// [X.Y.Z]() { }
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
var text = getTextOfIdentifierOrLiteral(expression);
if (text !== undefined) {
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
if (expression.kind === 166 /* PropertyAccessExpression */) {
var propertyAccess = expression;
if (includeLastPortion) {
containers.unshift(propertyAccess.name.text);
}
return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true);
}
return false;
}
function getContainers(declaration) {
var containers = [];
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
if (declaration.name.kind === 136 /* ComputedPropertyName */) {
if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) {
return undefined;
}
}
// Now, walk up our containers, adding all their names to the container array.
declaration = ts.getContainerNode(declaration);
while (declaration) {
if (!tryAddSingleDeclarationName(declaration, containers)) {
return undefined;
}
declaration = ts.getContainerNode(declaration);
}
return containers;
}
function bestMatchKind(matches) {
ts.Debug.assert(matches.length > 0);
var bestMatchKind = ts.PatternMatchKind.camelCase;
for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) {
var match = matches_2[_i];
var kind = match.kind;
if (kind < bestMatchKind) {
bestMatchKind = kind;
}
}
return bestMatchKind;
}
function compareNavigateToItems(i1, i2) {
// TODO(cyrusn): get the gamut of comparisons that VS already uses here.
// Right now we just sort by kind first, and then by name of the item.
// We first sort case insensitively. So "Aaa" will come before "bar".
// Then we sort case sensitively, so "aaa" will come before "Aaa".
return i1.matchKind - i2.matchKind ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name);
}
function createNavigateToItem(rawItem) {
var declaration = rawItem.declaration;
var container = ts.getContainerNode(declaration);
return {
name: rawItem.name,
kind: ts.getNodeKind(declaration),
kindModifiers: ts.getNodeModifiers(declaration),
matchKind: ts.PatternMatchKind[rawItem.matchKind],
isCaseSensitive: rawItem.isCaseSensitive,
fileName: rawItem.fileName,
textSpan: ts.createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: container && container.name ? container.name.text : "",
containerKind: container && container.name ? ts.getNodeKind(container) : ""
};
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getNavigateToItems
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function allMatchesAreCaseSensitive(matches) {
ts.Debug.assert(matches.length > 0);
// This is a case sensitive match, only if all the submatches were case sensitive.
for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
var match = matches_1[_i];
if (!match.isCaseSensitive) {
return false;
}
}
return true;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
allMatchesAreCaseSensitive
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTextOfIdentifierOrLiteral(node) {
if (node) {
if (node.kind === 69 /* Identifier */ ||
node.kind === 9 /* StringLiteral */ ||
node.kind === 8 /* NumericLiteral */) {
return node.text;
}
}
return undefined;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getTextOfIdentifierOrLiteral
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryAddSingleDeclarationName(declaration, containers) {
if (declaration && declaration.name) {
var text = getTextOfIdentifierOrLiteral(declaration.name);
if (text !== undefined) {
containers.unshift(text);
}
else if (declaration.name.kind === 136 /* ComputedPropertyName */) {
return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true);
}
else {
// Don't know how to add this.
return false;
}
}
return true;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
tryAddSingleDeclarationName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
var text = getTextOfIdentifierOrLiteral(expression);
if (text !== undefined) {
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
if (expression.kind === 166 /* PropertyAccessExpression */) {
var propertyAccess = expression;
if (includeLastPortion) {
containers.unshift(propertyAccess.name.text);
}
return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true);
}
return false;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
tryAddComputedPropertyName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getContainers(declaration) {
var containers = [];
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
if (declaration.name.kind === 136 /* ComputedPropertyName */) {
if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) {
return undefined;
}
}
// Now, walk up our containers, adding all their names to the container array.
declaration = ts.getContainerNode(declaration);
while (declaration) {
if (!tryAddSingleDeclarationName(declaration, containers)) {
return undefined;
}
declaration = ts.getContainerNode(declaration);
}
return containers;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getContainers
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function bestMatchKind(matches) {
ts.Debug.assert(matches.length > 0);
var bestMatchKind = ts.PatternMatchKind.camelCase;
for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) {
var match = matches_2[_i];
var kind = match.kind;
if (kind < bestMatchKind) {
bestMatchKind = kind;
}
}
return bestMatchKind;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
bestMatchKind
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function compareNavigateToItems(i1, i2) {
// TODO(cyrusn): get the gamut of comparisons that VS already uses here.
// Right now we just sort by kind first, and then by name of the item.
// We first sort case insensitively. So "Aaa" will come before "bar".
// Then we sort case sensitively, so "aaa" will come before "Aaa".
return i1.matchKind - i2.matchKind ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name);
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
compareNavigateToItems
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createNavigateToItem(rawItem) {
var declaration = rawItem.declaration;
var container = ts.getContainerNode(declaration);
return {
name: rawItem.name,
kind: ts.getNodeKind(declaration),
kindModifiers: ts.getNodeModifiers(declaration),
matchKind: ts.PatternMatchKind[rawItem.matchKind],
isCaseSensitive: rawItem.isCaseSensitive,
fileName: rawItem.fileName,
textSpan: ts.createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: container && container.name ? container.name.text : "",
containerKind: container && container.name ? ts.getNodeKind(container) : ""
};
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createNavigateToItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getNavigationBarItems(sourceFile) {
// If the source file has any child items, then it included in the tree
// and takes lexical ownership of all other top-level items.
var hasGlobalNode = false;
return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem);
function getIndent(node) {
// If we have a global node in the tree,
// then it adds an extra layer of depth to all subnodes.
var indent = hasGlobalNode ? 1 : 0;
var current = node.parent;
while (current) {
switch (current.kind) {
case 218 /* ModuleDeclaration */:
// If we have a module declared as A.B.C, it is more "intuitive"
// to say it only has a single layer of depth
do {
current = current.parent;
} while (current.kind === 218 /* ModuleDeclaration */);
// fall through
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
case 213 /* FunctionDeclaration */:
indent++;
}
current = current.parent;
}
return indent;
}
function getChildNodes(nodes) {
var childNodes = [];
function visit(node) {
switch (node.kind) {
case 193 /* VariableStatement */:
ts.forEach(node.declarationList.declarations, visit);
break;
case 161 /* ObjectBindingPattern */:
case 162 /* ArrayBindingPattern */:
ts.forEach(node.elements, visit);
break;
case 228 /* ExportDeclaration */:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
if (node.exportClause) {
ts.forEach(node.exportClause.elements, visit);
}
break;
case 222 /* ImportDeclaration */:
var importClause = node.importClause;
if (importClause) {
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
childNodes.push(importClause);
}
// Handle named bindings in imports e.g.:
// import * as NS from "mod";
// import {a, b as B} from "mod";
if (importClause.namedBindings) {
if (importClause.namedBindings.kind === 224 /* NamespaceImport */) {
childNodes.push(importClause.namedBindings);
}
else {
ts.forEach(importClause.namedBindings.elements, visit);
}
}
}
break;
case 163 /* BindingElement */:
case 211 /* VariableDeclaration */:
if (ts.isBindingPattern(node.name)) {
visit(node.name);
break;
}
// Fall through
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
case 218 /* ModuleDeclaration */:
case 213 /* FunctionDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 226 /* ImportSpecifier */:
case 230 /* ExportSpecifier */:
childNodes.push(node);
break;
}
}
//for (let i = 0, n = nodes.length; i < n; i++) {
// let node = nodes[i];
// if (node.kind === SyntaxKind.ClassDeclaration ||
// node.kind === SyntaxKind.EnumDeclaration ||
// node.kind === SyntaxKind.InterfaceDeclaration ||
// node.kind === SyntaxKind.ModuleDeclaration ||
// node.kind === SyntaxKind.FunctionDeclaration) {
// childNodes.push(node);
// }
// else if (node.kind === SyntaxKind.VariableStatement) {
// childNodes.push.apply(childNodes, (<VariableStatement>node).declarations);
// }
//}
ts.forEach(nodes, visit);
return sortNodes(childNodes);
}
function getTopLevelNodes(node) {
var topLevelNodes = [];
topLevelNodes.push(node);
addTopLevelNodes(node.statements, topLevelNodes);
return topLevelNodes;
}
function sortNodes(nodes) {
return nodes.slice(0).sort(function (n1, n2) {
if (n1.name && n2.name) {
return ts.getPropertyNameForPropertyNameNode(n1.name).localeCompare(ts.getPropertyNameForPropertyNameNode(n2.name));
}
else if (n1.name) {
return 1;
}
else if (n2.name) {
return -1;
}
else {
return n1.kind - n2.kind;
}
});
}
function addTopLevelNodes(nodes, topLevelNodes) {
nodes = sortNodes(nodes);
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
var node = nodes_4[_i];
switch (node.kind) {
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
topLevelNodes.push(node);
break;
case 218 /* ModuleDeclaration */:
var moduleDeclaration = node;
topLevelNodes.push(node);
addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes);
break;
case 213 /* FunctionDeclaration */:
var functionDeclaration = node;
if (isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes);
}
break;
}
}
}
function isTopLevelFunctionDeclaration(functionDeclaration) {
if (functionDeclaration.kind === 213 /* FunctionDeclaration */) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) {
// Proper function declarations can only have identifier names
if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) {
return true;
}
// Or if it is not parented by another function. i.e all functions
// at module scope are 'top level'.
if (!ts.isFunctionBlock(functionDeclaration.parent)) {
return true;
}
}
}
return false;
}
function getItemsWorker(nodes, createItem) {
var items = [];
var keyToItem = {};
for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
var child = nodes_5[_i];
var item = createItem(child);
if (item !== undefined) {
if (item.text.length > 0) {
var key = item.text + "-" + item.kind + "-" + item.indent;
var itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
merge(itemWithSameName, item);
}
else {
keyToItem[key] = item;
items.push(item);
}
}
}
}
return items;
}
function merge(target, source) {
// First, add any spans in the source to the target.
ts.addRange(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
target.childItems = [];
}
// Next, recursively merge or add any children in the source as appropriate.
outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) {
var sourceChild = _a[_i];
for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) {
var targetChild = _c[_b];
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
merge(targetChild, sourceChild);
continue outer;
}
}
// Didn't find a match, just add this child to the list.
target.childItems.push(sourceChild);
}
}
}
function createChildItem(node) {
switch (node.kind) {
case 138 /* Parameter */:
if (ts.isBindingPattern(node.name)) {
break;
}
if ((node.flags & 1022 /* Modifier */) === 0) {
return undefined;
}
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement);
case 145 /* GetAccessor */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement);
case 146 /* SetAccessor */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement);
case 149 /* IndexSignature */:
return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement);
case 247 /* EnumMember */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 147 /* CallSignature */:
return createItem(node, "()", ts.ScriptElementKind.callSignatureElement);
case 148 /* ConstructSignature */:
return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement);
case 141 /* PropertyDeclaration */:
case 140 /* PropertySignature */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 213 /* FunctionDeclaration */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement);
case 211 /* VariableDeclaration */:
case 163 /* BindingElement */:
var variableDeclarationNode;
var name_33;
if (node.kind === 163 /* BindingElement */) {
name_33 = node.name;
variableDeclarationNode = node;
// binding elements are added only for variable declarations
// bubble up to the containing variable declaration
while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) {
variableDeclarationNode = variableDeclarationNode.parent;
}
ts.Debug.assert(variableDeclarationNode !== undefined);
}
else {
ts.Debug.assert(!ts.isBindingPattern(node.name));
variableDeclarationNode = node;
name_33 = node.name;
}
if (ts.isConst(variableDeclarationNode)) {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement);
}
else if (ts.isLet(variableDeclarationNode)) {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement);
}
else {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement);
}
case 144 /* Constructor */:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
case 230 /* ExportSpecifier */:
case 226 /* ImportSpecifier */:
case 221 /* ImportEqualsDeclaration */:
case 223 /* ImportClause */:
case 224 /* NamespaceImport */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias);
}
return undefined;
function createItem(node, name, scriptElementKind) {
return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]);
}
}
function isEmpty(text) {
return !text || text.trim() === "";
}
function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) {
if (childItems === void 0) { childItems = []; }
if (indent === void 0) { indent = 0; }
if (isEmpty(text)) {
return undefined;
}
return {
text: text,
kind: kind,
kindModifiers: kindModifiers,
spans: spans,
childItems: childItems,
indent: indent,
bolded: false,
grayed: false
};
}
function createTopLevelItem(node) {
switch (node.kind) {
case 248 /* SourceFile */:
return createSourceFileItem(node);
case 214 /* ClassDeclaration */:
return createClassItem(node);
case 217 /* EnumDeclaration */:
return createEnumItem(node);
case 215 /* InterfaceDeclaration */:
return createIterfaceItem(node);
case 218 /* ModuleDeclaration */:
return createModuleItem(node);
case 213 /* FunctionDeclaration */:
return createFunctionItem(node);
}
return undefined;
function getModuleName(moduleDeclaration) {
// We want to maintain quotation marks.
if (moduleDeclaration.name.kind === 9 /* StringLiteral */) {
return getTextOfNode(moduleDeclaration.name);
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) {
moduleDeclaration = moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
return result.join(".");
}
function createModuleItem(node) {
var moduleName = getModuleName(node);
var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem);
return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createFunctionItem(node) {
if (node.body && node.body.kind === 192 /* Block */) {
var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem);
return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
return undefined;
}
function createSourceFileItem(node) {
var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
var rootName = ts.isExternalModule(node)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\""
: "<global>";
return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems);
}
function createClassItem(node) {
var childItems;
if (node.members) {
var constructor = ts.forEach(node.members, function (member) {
return member.kind === 144 /* Constructor */ && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
var nodes = removeDynamicallyNamedProperties(node);
if (constructor) {
ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); }));
}
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createEnumItem(node) {
var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createIterfaceItem(node) {
var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
}
function removeComputedProperties(node) {
return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; });
}
/**
* Like removeComputedProperties, but retains the properties with well known symbol names
*/
function removeDynamicallyNamedProperties(node) {
return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); });
}
function getInnermostModule(node) {
while (node.body.kind === 218 /* ModuleDeclaration */) {
node = node.body;
}
return node;
}
function getNodeSpan(node) {
return node.kind === 248 /* SourceFile */
? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd())
: ts.createTextSpanFromBounds(node.getStart(), node.getEnd());
}
function getTextOfNode(node) {
return ts.getTextOfNodeFromSourceText(sourceFile.text, node);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getNavigationBarItems
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getIndent(node) {
// If we have a global node in the tree,
// then it adds an extra layer of depth to all subnodes.
var indent = hasGlobalNode ? 1 : 0;
var current = node.parent;
while (current) {
switch (current.kind) {
case 218 /* ModuleDeclaration */:
// If we have a module declared as A.B.C, it is more "intuitive"
// to say it only has a single layer of depth
do {
current = current.parent;
} while (current.kind === 218 /* ModuleDeclaration */);
// fall through
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
case 213 /* FunctionDeclaration */:
indent++;
}
current = current.parent;
}
return indent;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getIndent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getChildNodes(nodes) {
var childNodes = [];
function visit(node) {
switch (node.kind) {
case 193 /* VariableStatement */:
ts.forEach(node.declarationList.declarations, visit);
break;
case 161 /* ObjectBindingPattern */:
case 162 /* ArrayBindingPattern */:
ts.forEach(node.elements, visit);
break;
case 228 /* ExportDeclaration */:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
if (node.exportClause) {
ts.forEach(node.exportClause.elements, visit);
}
break;
case 222 /* ImportDeclaration */:
var importClause = node.importClause;
if (importClause) {
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
childNodes.push(importClause);
}
// Handle named bindings in imports e.g.:
// import * as NS from "mod";
// import {a, b as B} from "mod";
if (importClause.namedBindings) {
if (importClause.namedBindings.kind === 224 /* NamespaceImport */) {
childNodes.push(importClause.namedBindings);
}
else {
ts.forEach(importClause.namedBindings.elements, visit);
}
}
}
break;
case 163 /* BindingElement */:
case 211 /* VariableDeclaration */:
if (ts.isBindingPattern(node.name)) {
visit(node.name);
break;
}
// Fall through
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
case 218 /* ModuleDeclaration */:
case 213 /* FunctionDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 226 /* ImportSpecifier */:
case 230 /* ExportSpecifier */:
childNodes.push(node);
break;
}
}
//for (let i = 0, n = nodes.length; i < n; i++) {
// let node = nodes[i];
// if (node.kind === SyntaxKind.ClassDeclaration ||
// node.kind === SyntaxKind.EnumDeclaration ||
// node.kind === SyntaxKind.InterfaceDeclaration ||
// node.kind === SyntaxKind.ModuleDeclaration ||
// node.kind === SyntaxKind.FunctionDeclaration) {
// childNodes.push(node);
// }
// else if (node.kind === SyntaxKind.VariableStatement) {
// childNodes.push.apply(childNodes, (<VariableStatement>node).declarations);
// }
//}
ts.forEach(nodes, visit);
return sortNodes(childNodes);
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getChildNodes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function visit(node) {
switch (node.kind) {
case 193 /* VariableStatement */:
ts.forEach(node.declarationList.declarations, visit);
break;
case 161 /* ObjectBindingPattern */:
case 162 /* ArrayBindingPattern */:
ts.forEach(node.elements, visit);
break;
case 228 /* ExportDeclaration */:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
if (node.exportClause) {
ts.forEach(node.exportClause.elements, visit);
}
break;
case 222 /* ImportDeclaration */:
var importClause = node.importClause;
if (importClause) {
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
childNodes.push(importClause);
}
// Handle named bindings in imports e.g.:
// import * as NS from "mod";
// import {a, b as B} from "mod";
if (importClause.namedBindings) {
if (importClause.namedBindings.kind === 224 /* NamespaceImport */) {
childNodes.push(importClause.namedBindings);
}
else {
ts.forEach(importClause.namedBindings.elements, visit);
}
}
}
break;
case 163 /* BindingElement */:
case 211 /* VariableDeclaration */:
if (ts.isBindingPattern(node.name)) {
visit(node.name);
break;
}
// Fall through
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
case 218 /* ModuleDeclaration */:
case 213 /* FunctionDeclaration */:
case 221 /* ImportEqualsDeclaration */:
case 226 /* ImportSpecifier */:
case 230 /* ExportSpecifier */:
childNodes.push(node);
break;
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
visit
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTopLevelNodes(node) {
var topLevelNodes = [];
topLevelNodes.push(node);
addTopLevelNodes(node.statements, topLevelNodes);
return topLevelNodes;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getTopLevelNodes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function sortNodes(nodes) {
return nodes.slice(0).sort(function (n1, n2) {
if (n1.name && n2.name) {
return ts.getPropertyNameForPropertyNameNode(n1.name).localeCompare(ts.getPropertyNameForPropertyNameNode(n2.name));
}
else if (n1.name) {
return 1;
}
else if (n2.name) {
return -1;
}
else {
return n1.kind - n2.kind;
}
});
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
sortNodes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function addTopLevelNodes(nodes, topLevelNodes) {
nodes = sortNodes(nodes);
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
var node = nodes_4[_i];
switch (node.kind) {
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 215 /* InterfaceDeclaration */:
topLevelNodes.push(node);
break;
case 218 /* ModuleDeclaration */:
var moduleDeclaration = node;
topLevelNodes.push(node);
addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes);
break;
case 213 /* FunctionDeclaration */:
var functionDeclaration = node;
if (isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes);
}
break;
}
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
addTopLevelNodes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isTopLevelFunctionDeclaration(functionDeclaration) {
if (functionDeclaration.kind === 213 /* FunctionDeclaration */) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) {
// Proper function declarations can only have identifier names
if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) {
return true;
}
// Or if it is not parented by another function. i.e all functions
// at module scope are 'top level'.
if (!ts.isFunctionBlock(functionDeclaration.parent)) {
return true;
}
}
}
return false;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
isTopLevelFunctionDeclaration
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getItemsWorker(nodes, createItem) {
var items = [];
var keyToItem = {};
for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
var child = nodes_5[_i];
var item = createItem(child);
if (item !== undefined) {
if (item.text.length > 0) {
var key = item.text + "-" + item.kind + "-" + item.indent;
var itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
merge(itemWithSameName, item);
}
else {
keyToItem[key] = item;
items.push(item);
}
}
}
}
return items;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getItemsWorker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function merge(target, source) {
// First, add any spans in the source to the target.
ts.addRange(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
target.childItems = [];
}
// Next, recursively merge or add any children in the source as appropriate.
outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) {
var sourceChild = _a[_i];
for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) {
var targetChild = _c[_b];
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
merge(targetChild, sourceChild);
continue outer;
}
}
// Didn't find a match, just add this child to the list.
target.childItems.push(sourceChild);
}
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
merge
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createChildItem(node) {
switch (node.kind) {
case 138 /* Parameter */:
if (ts.isBindingPattern(node.name)) {
break;
}
if ((node.flags & 1022 /* Modifier */) === 0) {
return undefined;
}
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement);
case 145 /* GetAccessor */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement);
case 146 /* SetAccessor */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement);
case 149 /* IndexSignature */:
return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement);
case 247 /* EnumMember */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 147 /* CallSignature */:
return createItem(node, "()", ts.ScriptElementKind.callSignatureElement);
case 148 /* ConstructSignature */:
return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement);
case 141 /* PropertyDeclaration */:
case 140 /* PropertySignature */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement);
case 213 /* FunctionDeclaration */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement);
case 211 /* VariableDeclaration */:
case 163 /* BindingElement */:
var variableDeclarationNode;
var name_33;
if (node.kind === 163 /* BindingElement */) {
name_33 = node.name;
variableDeclarationNode = node;
// binding elements are added only for variable declarations
// bubble up to the containing variable declaration
while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) {
variableDeclarationNode = variableDeclarationNode.parent;
}
ts.Debug.assert(variableDeclarationNode !== undefined);
}
else {
ts.Debug.assert(!ts.isBindingPattern(node.name));
variableDeclarationNode = node;
name_33 = node.name;
}
if (ts.isConst(variableDeclarationNode)) {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement);
}
else if (ts.isLet(variableDeclarationNode)) {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement);
}
else {
return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement);
}
case 144 /* Constructor */:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
case 230 /* ExportSpecifier */:
case 226 /* ImportSpecifier */:
case 221 /* ImportEqualsDeclaration */:
case 223 /* ImportClause */:
case 224 /* NamespaceImport */:
return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias);
}
return undefined;
function createItem(node, name, scriptElementKind) {
return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]);
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createChildItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createItem(node, name, scriptElementKind) {
return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]);
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isEmpty(text) {
return !text || text.trim() === "";
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
isEmpty
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) {
if (childItems === void 0) { childItems = []; }
if (indent === void 0) { indent = 0; }
if (isEmpty(text)) {
return undefined;
}
return {
text: text,
kind: kind,
kindModifiers: kindModifiers,
spans: spans,
childItems: childItems,
indent: indent,
bolded: false,
grayed: false
};
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getNavigationBarItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createTopLevelItem(node) {
switch (node.kind) {
case 248 /* SourceFile */:
return createSourceFileItem(node);
case 214 /* ClassDeclaration */:
return createClassItem(node);
case 217 /* EnumDeclaration */:
return createEnumItem(node);
case 215 /* InterfaceDeclaration */:
return createIterfaceItem(node);
case 218 /* ModuleDeclaration */:
return createModuleItem(node);
case 213 /* FunctionDeclaration */:
return createFunctionItem(node);
}
return undefined;
function getModuleName(moduleDeclaration) {
// We want to maintain quotation marks.
if (moduleDeclaration.name.kind === 9 /* StringLiteral */) {
return getTextOfNode(moduleDeclaration.name);
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) {
moduleDeclaration = moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
return result.join(".");
}
function createModuleItem(node) {
var moduleName = getModuleName(node);
var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem);
return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createFunctionItem(node) {
if (node.body && node.body.kind === 192 /* Block */) {
var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem);
return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
return undefined;
}
function createSourceFileItem(node) {
var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
var rootName = ts.isExternalModule(node)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\""
: "<global>";
return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems);
}
function createClassItem(node) {
var childItems;
if (node.members) {
var constructor = ts.forEach(node.members, function (member) {
return member.kind === 144 /* Constructor */ && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
var nodes = removeDynamicallyNamedProperties(node);
if (constructor) {
ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); }));
}
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createEnumItem(node) {
var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
function createIterfaceItem(node) {
var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createTopLevelItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getModuleName(moduleDeclaration) {
// We want to maintain quotation marks.
if (moduleDeclaration.name.kind === 9 /* StringLiteral */) {
return getTextOfNode(moduleDeclaration.name);
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) {
moduleDeclaration = moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
return result.join(".");
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
getModuleName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createModuleItem(node) {
var moduleName = getModuleName(node);
var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem);
return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createModuleItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createFunctionItem(node) {
if (node.body && node.body.kind === 192 /* Block */) {
var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem);
return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
return undefined;
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createFunctionItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createSourceFileItem(node) {
var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
var rootName = ts.isExternalModule(node)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\""
: "<global>";
return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems);
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createSourceFileItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createClassItem(node) {
var childItems;
if (node.members) {
var constructor = ts.forEach(node.members, function (member) {
return member.kind === 144 /* Constructor */ && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
var nodes = removeDynamicallyNamedProperties(node);
if (constructor) {
ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); }));
}
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createClassItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createEnumItem(node) {
var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createEnumItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createIterfaceItem(node) {
var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node));
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
createIterfaceItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function removeComputedProperties(node) {
return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; });
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
removeComputedProperties
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getInnermostModule(node) {
while (node.body.kind === 218 /* ModuleDeclaration */) {
node = node.body;
}
return node;
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
getInnermostModule
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getNodeSpan(node) {
return node.kind === 248 /* SourceFile */
? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd())
: ts.createTextSpanFromBounds(node.getStart(), node.getEnd());
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
getNodeSpan
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTextOfNode(node) {
return ts.getTextOfNodeFromSourceText(sourceFile.text, node);
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
getTextOfNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) {
return {
kind: kind,
punctuationStripped: punctuationStripped,
isCaseSensitive: isCaseSensitive,
camelCaseWeight: camelCaseWeight
};
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
createPatternMatch
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createPatternMatcher(pattern) {
// We'll often see the same candidate string many times when searching (For example, when
// we see the name of a module that is used everywhere, or the name of an overload). As
// such, we cache the information we compute about the candidate for the life of this
// pattern matcher so we don't have to compute it multiple times.
var stringToWordSpans = {};
pattern = pattern.trim();
var fullPatternSegment = createSegment(pattern);
var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); });
var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid);
return {
getMatches: getMatches,
getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern,
patternContainsDots: dotSeparatedSegments.length > 1
};
// Quick checks so we can bail out when asked to match a candidate.
function skipMatch(candidate) {
return invalidPattern || !candidate;
}
function getMatchesForLastSegmentOfPattern(candidate) {
if (skipMatch(candidate)) {
return undefined;
}
return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments));
}
function getMatches(candidateContainers, candidate) {
if (skipMatch(candidate)) {
return undefined;
}
// First, check that the last part of the dot separated pattern matches the name of the
// candidate. If not, then there's no point in proceeding and doing the more
// expensive work.
var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments));
if (!candidateMatch) {
return undefined;
}
candidateContainers = candidateContainers || [];
// -1 because the last part was checked against the name, and only the rest
// of the parts are checked against the container.
if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
// There weren't enough container parts to match against the pattern parts.
// So this definitely doesn't match.
return undefined;
}
// So far so good. Now break up the container for the candidate and check if all
// the dotted parts match up correctly.
var totalMatch = candidateMatch;
for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) {
var segment = dotSeparatedSegments[i];
var containerName = candidateContainers[j];
var containerMatch = matchSegment(containerName, segment);
if (!containerMatch) {
// This container didn't match the pattern piece. So there's no match at all.
return undefined;
}
ts.addRange(totalMatch, containerMatch);
}
// Success, this symbol's full name matched against the dotted name the user was asking
// about.
return totalMatch;
}
function getWordSpans(word) {
if (!ts.hasProperty(stringToWordSpans, word)) {
stringToWordSpans[word] = breakIntoWordSpans(word);
}
return stringToWordSpans[word];
}
function matchTextChunk(candidate, chunk, punctuationStripped) {
var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
if (index === 0) {
if (chunk.text.length === candidate.length) {
// a) Check if the part matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.text);
}
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
if (isLowercase) {
if (index > 0) {
// c) If the part is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of some
// word part. That way we don't match something like 'Class' when the user types 'a'.
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
var span = wordSpans_1[_i];
if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
/*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
}
}
}
}
else {
// d) If the part was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
if (candidate.indexOf(chunk.text) > 0) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ true);
}
}
if (!isLowercase) {
// e) If the part was not entirely lowercase, then attempt a camel cased match as well.
if (chunk.characterSpans.length > 0) {
var candidateParts = getWordSpans(candidate);
var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false);
if (camelCaseWeight !== undefined) {
return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight);
}
camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true);
if (camelCaseWeight !== undefined) {
return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ false, /*camelCaseWeight:*/ camelCaseWeight);
}
}
}
if (isLowercase) {
// f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
// We could check every character boundary start of the candidate for the pattern. However, that's
// an m * n operation in the wost case. Instead, find the first instance of the pattern
// substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
// filter the list based on a substring that starts on a capital letter and also with a lowercase one.
// (Pattern: fogbar, Candidate: quuxfogbarFogBar).
if (chunk.text.length < candidate.length) {
if (index > 0 && isUpperCaseLetter(candidate.charCodeAt(index))) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ false);
}
}
}
return undefined;
}
function containsSpaceOrAsterisk(text) {
for (var i = 0; i < text.length; i++) {
var ch = text.charCodeAt(i);
if (ch === 32 /* space */ || ch === 42 /* asterisk */) {
return true;
}
}
return false;
}
function matchSegment(candidate, segment) {
// First check if the segment matches as is. This is also useful if the segment contains
// characters we would normally strip when splitting into parts that we also may want to
// match in the candidate. For example if the segment is "@int" and the candidate is
// "@int", then that will show up as an exact match here.
//
// Note: if the segment contains a space or an asterisk then we must assume that it's a
// multi-word segment.
if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) {
var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false);
if (match) {
return [match];
}
}
// The logic for pattern matching is now as follows:
//
// 1) Break the segment passed in into words. Breaking is rather simple and a
// good way to think about it that if gives you all the individual alphanumeric words
// of the pattern.
//
// 2) For each word try to match the word against the candidate value.
//
// 3) Matching is as follows:
//
// a) Check if the word matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
//
// b) Check if the word is a prefix of the candidate, in a case insensitive or
// sensitive manner. If it does, return that there was a prefix match.
//
// c) If the word is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of
// some word part. That way we don't match something like 'Class' when the user
// types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
// 'a').
//
// d) If the word was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
//
// e) If the word was not entirely lowercase, then attempt a camel cased match as
// well.
//
// f) The word is all lower case. Is it a case insensitive substring of the candidate starting
// on a part boundary of the candidate?
//
// Only if all words have some sort of match is the pattern considered matched.
var subWordTextChunks = segment.subWordTextChunks;
var matches = undefined;
for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
var subWordTextChunk = subWordTextChunks_1[_i];
// Try to match the candidate with this word
var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true);
if (!result) {
return undefined;
}
matches = matches || [];
matches.push(result);
}
return matches;
}
function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) {
var patternPartStart = patternSpan ? patternSpan.start : 0;
var patternPartLength = patternSpan ? patternSpan.length : pattern.length;
if (patternPartLength > candidateSpan.length) {
// Pattern part is longer than the candidate part. There can never be a match.
return false;
}
if (ignoreCase) {
for (var i = 0; i < patternPartLength; i++) {
var ch1 = pattern.charCodeAt(patternPartStart + i);
var ch2 = candidate.charCodeAt(candidateSpan.start + i);
if (toLowerCase(ch1) !== toLowerCase(ch2)) {
return false;
}
}
}
else {
for (var i = 0; i < patternPartLength; i++) {
var ch1 = pattern.charCodeAt(patternPartStart + i);
var ch2 = candidate.charCodeAt(candidateSpan.start + i);
if (ch1 !== ch2) {
return false;
}
}
}
return true;
}
function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
var chunkCharacterSpans = chunk.characterSpans;
// Note: we may have more pattern parts than candidate parts. This is because multiple
// pattern parts may match a candidate part. For example "SiUI" against "SimpleUI".
// We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U
// and I will both match in UI.
var currentCandidate = 0;
var currentChunkSpan = 0;
var firstMatch = undefined;
var contiguous = undefined;
while (true) {
// Let's consider our termination cases
if (currentChunkSpan === chunkCharacterSpans.length) {
// We did match! We shall assign a weight to this
var weight = 0;
// Was this contiguous?
if (contiguous) {
weight += 1;
}
// Did we start at the beginning of the candidate?
if (firstMatch === 0) {
weight += 2;
}
return weight;
}
else if (currentCandidate === candidateParts.length) {
// No match, since we still have more of the pattern to hit
return undefined;
}
var candidatePart = candidateParts[currentCandidate];
var gotOneMatchThisCandidate = false;
// Consider the case of matching SiUI against SimpleUIElement. The candidate parts
// will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si'
// against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to
// still keep matching pattern parts against that candidate part.
for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
if (gotOneMatchThisCandidate) {
// We've already gotten one pattern part match in this candidate. We will
// only continue trying to consumer pattern parts if the last part and this
// part are both upper case.
if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
break;
}
}
if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
break;
}
gotOneMatchThisCandidate = true;
firstMatch = firstMatch === undefined ? currentCandidate : firstMatch;
// If we were contiguous, then keep that value. If we weren't, then keep that
// value. If we don't know, then set the value to 'true' as an initial match is
// obviously contiguous.
contiguous = contiguous === undefined ? true : contiguous;
candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
}
// Check if we matched anything at all. If we didn't, then we need to unset the
// contiguous bit if we currently had it set.
// If we haven't set the bit yet, then that means we haven't matched anything so
// far, and we don't want to change that.
if (!gotOneMatchThisCandidate && contiguous !== undefined) {
contiguous = false;
}
// Move onto the next candidate.
currentCandidate++;
}
}
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
createPatternMatcher
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function skipMatch(candidate) {
return invalidPattern || !candidate;
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
skipMatch
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getMatchesForLastSegmentOfPattern(candidate) {
if (skipMatch(candidate)) {
return undefined;
}
return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments));
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
getMatchesForLastSegmentOfPattern
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.