|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Get the current file layer. |
| 5 | + * |
| 6 | + * @example |
| 7 | + * ```js |
| 8 | + * getCurrentFileLayer('src/shared/ui/button.tsx'); |
| 9 | + * // => 'shared' |
| 10 | + * |
| 11 | + * getCurrentFileLayer('src/entities/theme/model/use-dark.ts'); |
| 12 | + * // => 'entities' |
| 13 | + * ``` |
| 14 | + */ |
| 15 | +function getCurrentFileLayer(currentFilePath) { |
| 16 | + const normalizedPath = currentFilePath.replace(/\\/g, '/'); |
| 17 | + const projectPath = normalizedPath?.split('src')[1]; |
| 18 | + const segments = projectPath?.split('/'); |
| 19 | + |
| 20 | + return segments?.[1]; |
| 21 | +} |
| 22 | + |
| 23 | +exports.create = function create(context) { |
| 24 | + const { alias = '' } = context.options[0] ?? {}; |
| 25 | + |
| 26 | + const layers = { |
| 27 | + background: ['background', 'widgets', 'features', 'entities', 'shared'], |
| 28 | + contentScripts: ['contentScripts', 'widgets', 'features', 'entities', 'shared'], |
| 29 | + options: ['options', 'widgets', 'features', 'entities', 'shared'], |
| 30 | + widgets: ['features', 'entities', 'shared'], |
| 31 | + features: ['entities', 'shared'], |
| 32 | + entities: ['entities', 'shared'], |
| 33 | + shared: ['shared'], |
| 34 | + }; |
| 35 | + |
| 36 | + const availableLayers = Object.keys(layers); |
| 37 | + |
| 38 | + const getImportLayer = (value) => { |
| 39 | + const importPath = alias ? value.replace(new RegExp(`^${alias}/`), '') : value; |
| 40 | + const segments = importPath.split('/'); |
| 41 | + |
| 42 | + return segments.find((segment) => availableLayers.includes(segment)); |
| 43 | + }; |
| 44 | + |
| 45 | + /** |
| 46 | + * @example |
| 47 | + * // src/shared/ui/button.tsx |
| 48 | + * import a from '../lib/env'; |
| 49 | + * import a1 from '~/shared/lib/env'; |
| 50 | + * import b from './label'; |
| 51 | + * import b1 from '~/shared/ui/label'; |
| 52 | + * import z from '../../entities/...'; // trigger error! |
| 53 | + * import z1 from '~/entities/...'; // trigger error! |
| 54 | + */ |
| 55 | + return { |
| 56 | + ImportDeclaration(node) { |
| 57 | + const { value } = node.source; |
| 58 | + const currentFileLayer = getCurrentFileLayer(context.getFilename()); |
| 59 | + const importLayer = getImportLayer(value); |
| 60 | + |
| 61 | + if (!importLayer) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + const isAllowed = layers[currentFileLayer].includes(importLayer); |
| 66 | + |
| 67 | + if (!isAllowed) { |
| 68 | + context.report({ |
| 69 | + node, |
| 70 | + message: `Importing from "${importLayer}" is not allowed in the current layer "${currentFileLayer}".`, |
| 71 | + }); |
| 72 | + } |
| 73 | + }, |
| 74 | + }; |
| 75 | +}; |
0 commit comments