eslint-plugin-immutablejs
Version:
ESLint rules for projects using Immutable.js
112 lines (91 loc) • 3.75 kB
JavaScript
;
var IMMUTABLE_IMPORT_NAME = 'immutable';
function importIncludesType(_ref, type) {
var _ref$specifiers = _ref.specifiers;
var specifiers = _ref$specifiers === undefined ? [] : _ref$specifiers;
return specifiers.some(function (specifier) {
return specifier.type === 'ImportSpecifier' && specifier.imported.name === type;
});
}
function importIsImmutable(importDeclaration) {
return importDeclaration.source.value === IMMUTABLE_IMPORT_NAME;
}
function defaultImportName(_ref2) {
var _ref2$specifiers = _ref2.specifiers;
var specifiers = _ref2$specifiers === undefined ? [] : _ref2$specifiers;
var specifier = specifiers.find(function (specifier) {
return specifier.type === 'ImportDefaultSpecifier';
});
return specifier && specifier.local.name;
}
function objPatternIncludes(_ref3, key) {
var _ref3$properties = _ref3.properties;
var properties = _ref3$properties === undefined ? [] : _ref3$properties;
return properties.some(function (prop) {
return prop.key.name === key;
});
}
module.exports = function (context) {
var hasMapImport = false;
var hasSetImport = false;
var immutableAlias = '';
return {
ImportDeclaration: function ImportDeclaration(node) {
if (!importIsImmutable(node)) return;
if (importIncludesType(node, 'Map')) {
hasMapImport = true;
}
if (importIncludesType(node, 'Set')) {
hasSetImport = true;
}
immutableAlias = defaultImportName(node) || immutableAlias;
},
CallExpression: function CallExpression(_ref4) {
var callee = _ref4.callee;
var parent = _ref4.parent;
var _ref4$arguments = _ref4.arguments;
var args = _ref4$arguments === undefined ? [] : _ref4$arguments;
// var immutable = require('immutable');
if (callee.name === 'require' && parent.type === 'VariableDeclarator' && args[0] && args[0].value === IMMUTABLE_IMPORT_NAME) {
immutableAlias = parent.id.name;;
}
},
VariableDeclarator: function VariableDeclarator(node) {
if (node.init && node.init.type === 'MemberExpression' && node.init.object.name === immutableAlias && ['Map', 'Set'].some(function (name) {
return name === node.id.name;
})) {
if (node.init.property.name === 'Map') {
hasMapImport = true;
}
if (node.init.property.name === 'Set') {
hasSetImport = true;
}
};
if (node.id.type === 'ObjectPattern' && node.init && node.init.name === immutableAlias) {
var includesMap = objPatternIncludes(node.id, 'Map');
var includesSet = objPatternIncludes(node.id, 'Set');
if (includesMap) {
hasMapImport = true;
}
if (includesSet) {
hasSetImport = true;
}
}
},
Identifier: function Identifier(node) {
if (node.parent.type === 'ImportSpecifier') return;
if (node.name === 'Map' && !hasMapImport) {
context.report({
message: 'Native ES6 Map is not allowed. Use Immutable.Map()',
node: node
});
}
if (node.name === 'Set' && !hasSetImport) {
context.report({
message: 'Native ES6 Set is not allowed. Use Immutable.Set()',
node: node
});
}
}
};
};