tslint-folders
Version:
Custom TSLint rules for checking imports between packages and their folders, and generating relevant diagrams.
64 lines (63 loc) • 3.18 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbsoluteImportResolver = exports.IS_DEBUG_ENABLED = void 0;
var fs_1 = require("fs");
var path = require("path");
var DirUtils_1 = require("./DirUtils");
var PackageConfigHelper_1 = require("./PackageConfigHelper");
exports.IS_DEBUG_ENABLED = false;
// Resolves an absolute file path, to a 'package' path, as specified in tsconfig.json
var AbsoluteImportResolver;
(function (AbsoluteImportResolver) {
function removeTrailingSlashStarFrom(packagePath) {
return packagePath.replace(/\/\*$/, "");
}
function resolvePathToPackageName(filePath, tsConfig, config) {
if (tsConfig.paths) {
var packageNames = Object.keys(tsConfig.paths);
var resolvedToPackageName_1 = null;
packageNames.forEach(function (packageName) {
var paths = tsConfig.paths[packageName].map(removeTrailingSlashStarFrom);
if (paths.some(function (partialPath) {
var absolutePaths = tsConfig.include
.map(function (include) {
var joined = path.join(tsConfig.baseUrl, include, partialPath);
return DirUtils_1.DirUtils.convertWindowsToUnix(joined); // needs to be Unix style, to handle multicomponent paths like 'my-editor/api'
})
.filter(function (p) { return (0, fs_1.existsSync)(p); });
return absolutePaths.some(function (abs) { return filePath.startsWith(abs); });
})) {
if (resolvedToPackageName_1 && exports.IS_DEBUG_ENABLED) {
console.warn("Multiple configured paths matching to path '".concat(filePath, "'"));
}
else {
resolvedToPackageName_1 = removeTrailingSlashStarFrom(packageName);
}
}
});
if (resolvedToPackageName_1) {
return resolvedToPackageName_1;
}
}
// Fallback, in case 'paths' not set, or incomplete:
return resolvePathToPackageNameViaSplitting(filePath, config);
}
AbsoluteImportResolver.resolvePathToPackageName = resolvePathToPackageName;
function resolvePathToPackageNameViaSplitting(pathToSplit, config) {
var dirs = DirUtils_1.DirUtils.splitPath(pathToSplit);
var packageName = null;
dirs.forEach(function (dir) {
if (PackageConfigHelper_1.PackageConfigHelper.hasPackage(config, dir)) {
if (packageName === null) {
// take the 1st recognised folder:
packageName = dir;
}
else if (exports.IS_DEBUG_ENABLED) {
// this can occur with package names like 'utils'
console.warn("import has more than one recognised package: [".concat(packageName, ",").concat(dir, "]"));
}
}
});
return packageName;
}
})(AbsoluteImportResolver = exports.AbsoluteImportResolver || (exports.AbsoluteImportResolver = {}));
;