UNPKG

eslint-plugin-canonical

Version:
202 lines (201 loc) 8.58 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const node_path_1 = require("node:path"); const recast = __importStar(require("recast")); const utilities_1 = require("../utilities"); const findDirectory_1 = require("../utilities/findDirectory"); const ExportMap_1 = __importDefault(require("./ExportMap")); const findRootPath_1 = require("../utilities/findRootPath"); /** * https://stackoverflow.com/a/45242825/368691 */ const isSubPath = (parent, subject) => { const rel = (0, node_path_1.relative)(parent, subject); return rel && !rel.startsWith('..') && !(0, node_path_1.isAbsolute)(rel); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const ExportMap = ExportMap_1.default; const formatRelativeImport = (currentFilename, importFilename) => { let newImport = (0, node_path_1.relative)((0, node_path_1.dirname)(currentFilename), importFilename); if (!newImport.startsWith('.')) { newImport = './' + newImport; } return newImport.replace(/\.tsx?$/u, ''); }; const findImportSource = (context, moduleExport) => { var _a; const local = moduleExport.local; const modulePath = (_a = moduleExport.getImport()) === null || _a === void 0 ? void 0 : _a.path; if (!modulePath) { return null; } const moduleExports = ExportMap.get(modulePath, context); if (moduleExports.namespace.has(local)) { return { local, path: modulePath, }; } const reexport = moduleExports.reexports.get(local); if (!reexport) { // throw new Error('Re-export not found'); return null; } return findImportSource(context, reexport); }; exports.default = (0, utilities_1.createRule)({ create: (context) => { var _a; const myPath = (_a = context.filename) !== null && _a !== void 0 ? _a : context.getFilename(); // can't cycle-check a non-file if (myPath === '<text>') return {}; const myModuleRoot = (0, findDirectory_1.findDirectory)((0, node_path_1.dirname)(myPath), 'package.json', (0, findRootPath_1.findRootPath)(myPath)); if (!myModuleRoot) { throw new Error('cannot find package.json'); } return { ImportDefaultSpecifier: (node) => { const importDeclarationNode = node.parent; const exportMap = ExportMap.get(importDeclarationNode.source.value, context); if (exportMap === null) { return; } const reexport = exportMap.reexports.get('default'); if (!reexport) { return; } const importSource = findImportSource(context, reexport); if (!importSource) { return; } if (!isSubPath(myModuleRoot, importSource.path)) { return; } const relativeImportPath = formatRelativeImport(myPath, importSource.path); // This is a temporary approach to avoid rewriting imports of packages. // In practice, we want to ensure that we are not importing barrels either. if (relativeImportPath.includes('node_modules')) { return; } const newImport = `import ${node.local.name} from '${relativeImportPath}';`; context.report({ fix(fixer) { return fixer.replaceTextRange(importDeclarationNode.range, newImport); }, messageId: 'noBarrelImport', node, }); }, ImportSpecifier: (node) => { const importDeclarationNode = node.parent; const exportMap = ExportMap.get(importDeclarationNode.source.value, context); if (exportMap === null) { return; } const importedNode = node.imported; if (importedNode.type !== 'Identifier') { throw new Error('Expected identifier'); } const localNode = node.local; if (localNode.type !== 'Identifier') { throw new Error('Expected identifier'); } const reexport = exportMap.reexports.get(importedNode.name); // If it is not re-exported, then it must be defined locally. if (!reexport) { return; } const importSource = findImportSource(context, reexport); if (!importSource) { return; } if (!isSubPath(myModuleRoot, importSource.path)) { return; } const relativeImportPath = formatRelativeImport(myPath, importSource.path); // This is a temporary approach to avoid rewriting imports of packages. // In practice, we want to ensure that we are not importing barrels either. if (relativeImportPath.includes('node_modules')) { return; } const newImport = `import { ${node.importKind === 'type' ? 'type ' : ''}${importSource.local === localNode.name ? importSource.local : `${importSource.local} as ${localNode.name}`} } from '${relativeImportPath}';`; if (importDeclarationNode.specifiers.length === 1) { context.report({ fix(fixer) { return fixer.replaceTextRange(importDeclarationNode.range, newImport); }, messageId: 'noBarrelImport', node, }); } else { context.report({ fix(fixer) { return fixer.replaceTextRange(importDeclarationNode.range, recast.print(Object.assign(Object.assign({}, importDeclarationNode), { // @ts-expect-error TODO specifiers: importDeclarationNode.specifiers.filter((specifier) => specifier !== node) }), { quote: 'single', }).code + '\n' + newImport); }, messageId: 'noBarrelImport', node, }); } }, }; }, defaultOptions: [], meta: { docs: { description: 'Require that imports are made directly from the source', }, fixable: 'code', messages: { noBarrelImport: 'Must not import from a barrel file', }, schema: [], type: 'layout', }, name: 'require-extension', });