UNPKG

eslint-plugin-kisszaya-fsd-plugin

Version:

Plugin to format code by fsd principles

91 lines (90 loc) 3.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fsdAbsolutePublicApiImports = exports.MessageIds = void 0; const utils_1 = require("@typescript-eslint/utils"); const schema_1 = require("./schema"); const helpers_1 = require("./helpers"); var MessageIds; (function (MessageIds) { MessageIds["ISSUE_ABSOLUTE_IMPORT_SHOULD_BE_FROM_PUBLIC_API"] = "issue:public-api"; })(MessageIds || (exports.MessageIds = MessageIds = {})); const createRule = utils_1.ESLintUtils.RuleCreator((name) => `https://example.com/rule/${name}`); exports.fsdAbsolutePublicApiImports = createRule({ name: "absolute-public-api-imports", meta: { fixable: "code", docs: { description: "Absolute imports should be only from public api, not inside module", }, type: "problem", messages: { [MessageIds.ISSUE_ABSOLUTE_IMPORT_SHOULD_BE_FROM_PUBLIC_API]: "Absolute import should be from public api", }, schema: schema_1.SCHEMA, }, defaultOptions: [], create: (context) => { const alias = context.options[0].alias || ""; const srcPath = context.options[0].srcPath || schema_1.ALIAS_START_PATH; const projectStructure = context.options[0].projectStructure; return { ImportDeclaration(node) { const importPath = node.source.value; const filename = context.physicalFilename; const normalizedFilename = (0, helpers_1.normalizePath)(filename); if (!normalizedFilename.includes(srcPath)) { return; } const checker = new PublicApiImportsChecker(alias, projectStructure); const isAbsolutePath = (0, helpers_1.isAbsolute)({ importPath, alias, projectStructure, }); if (!isAbsolutePath) { return; } const { isViolated, requiredPath } = checker.checkPublicApiImportsViolated({ importPath, }); if (isViolated) { return context.report({ node, messageId: MessageIds.ISSUE_ABSOLUTE_IMPORT_SHOULD_BE_FROM_PUBLIC_API, fix: (fixer) => { return fixer.replaceText(node.source, requiredPath !== null && requiredPath !== void 0 ? requiredPath : ""); }, }); } }, }; }, }); class PublicApiImportsChecker { constructor(alias, projectStructure) { this.alias = alias; this.projectStructure = projectStructure; } checkPublicApiImportsViolated({ importPath }) { const importPathElems = (0, helpers_1.getAbsoluteImportPathElems)({ importPath, alias: this.alias, }); const pattern = (0, helpers_1.getPattern)({ elems: importPathElems, projectStructure: this.projectStructure, }); if (importPathElems.length > pattern.length) { return { isViolated: true, requiredPath: this.getRequiredPath({ pattern, importPathElems }), }; } return { isViolated: false, }; } getRequiredPath({ importPathElems, pattern, }) { return `'${this.alias + importPathElems.slice(0, pattern.length).join("/")}'`; } }