eslint-plugin-sonarjs
Version:
168 lines (167 loc) • 7.46 kB
JavaScript
;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S9150/javascript
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;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const ast_js_1 = require("../helpers/ast.js");
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const location_js_1 = require("../helpers/location.js");
const vue_js_1 = require("../helpers/vue.js");
const meta = __importStar(require("./generated-meta.js"));
const messages = {
replaceMixin: 'Replace this mixin with a Vue composable.',
mixinDefinedHere: 'Mixin defined here. Extract it into a composable.',
};
const MIXINS_PROPERTY_NAME = 'mixins';
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta),
create(context) {
if ((0, vue_js_1.isVue2OrEarlier)(context)) {
return {};
}
return {
ObjectExpression(node) {
const mixinsProperty = findMixinsProperty(node);
if (!mixinsProperty) {
return;
}
const mixinsArray = resolveMixinsArray(context, mixinsProperty.value);
if (!mixinsArray) {
return;
}
const secondaries = getMixinIdentifiers(mixinsArray)
.map(identifier => resolveMixinSecondaryLocation(context, identifier))
.filter((location) => location !== undefined);
(0, location_js_1.report)(context, { message: messages.replaceMixin, node: mixinsProperty }, secondaries);
},
};
},
};
/**
* Looks for a `mixins` key directly declared on the object literal. Properties merged in through
* a spread element are intentionally not followed: the spread source, if it is itself an object
* literal declaring `mixins`, is visited and reported on its own as an `ObjectExpression`.
*/
function findMixinsProperty(node) {
return node.properties.find((property) => property.type === 'Property' &&
// a computed identifier key, e.g. `{ [mixins]: [...] }`, reads a variable named `mixins`
// rather than declaring a `mixins` property, so it's excluded here. A computed string
// literal key, e.g. `{ ['mixins']: [...] }`, does mean the same thing as a plain `mixins:`
// key, so it's still accepted by the isStringLiteral() branch below regardless of `computed`.
((!property.computed && (0, ast_js_1.isIdentifier)(property.key, MIXINS_PROPERTY_NAME)) ||
((0, ast_js_1.isStringLiteral)(property.key) && property.key.value === MIXINS_PROPERTY_NAME)));
}
/**
* Vue's `mixins` option is always an array. Requiring the property's value to be one (or to
* resolve to one through a local variable) filters out unrelated, non-Vue uses of a `mixins` key
* that couldn't be a real mixins list, e.g. `{ mixins: "hey" }`.
*/
function resolveMixinsArray(context, value) {
return value.type === 'ArrayExpression'
? value
: (0, ast_js_1.getValueOfExpression)(context, value, 'ArrayExpression');
}
/**
* Best-effort extraction of the mixin identifiers out of the `mixins` array, so their source can
* be pointed at as a secondary location. Only plain identifiers are considered; spreads, call
* expressions and other dynamic shapes are skipped, and simply yield no secondary location for
* that element (the primary issue is unaffected).
*/
function getMixinIdentifiers(mixinsArray) {
return mixinsArray.elements.filter((element) => element?.type === 'Identifier');
}
/**
* Resolves a mixin identifier to where it comes from, so it can be highlighted as a secondary
* location:
* - imported from another module: the import specifier, naming the module (we cannot point into
* the other file, secondary locations are scoped to the current file).
* - declared as a local object literal (optionally wrapped in a single-argument call such as
* `defineComponent({...})`): the object literal itself.
* - anything else (ambiguous/unresolvable references): no secondary location.
*/
function resolveMixinSecondaryLocation(context, identifier) {
const variable = (0, ast_js_1.getVariableFromName)(context, identifier.name, identifier);
const definition = variable?.defs[0];
if (!definition) {
return undefined;
}
if (definition.type === 'ImportBinding') {
const source = definition.parent.source?.value;
if (typeof source !== 'string') {
return undefined;
}
return (0, location_js_1.toSecondaryLocation)(definition.node, `Mixin imported from '${source}'.`);
}
if (definition.type === 'Variable') {
const declarator = definition.node;
const objectExpression = unwrapToObjectExpression(declarator.init);
return (0, location_js_1.toSecondaryLocation)(objectExpression ?? declarator, messages.mixinDefinedHere);
}
return undefined;
}
/**
* Unwraps a variable initializer down to the object literal it holds, following at most one
* single-argument call (e.g. `defineComponent({...})`).
*/
function unwrapToObjectExpression(node) {
if (!node) {
return undefined;
}
if (node.type === 'ObjectExpression') {
return node;
}
if (node.type === 'CallExpression' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'ObjectExpression') {
return node.arguments[0];
}
return undefined;
}