UNPKG

2.05 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow use of Object.prototype builtins on objects
3 * @author Andrew Levine
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const astUtils = require("./utils/ast-utils");
12
13//------------------------------------------------------------------------------
14// Rule Definition
15//------------------------------------------------------------------------------
16
17module.exports = {
18 meta: {
19 type: "problem",
20
21 docs: {
22 description: "disallow calling some `Object.prototype` methods directly on objects",
23 category: "Possible Errors",
24 recommended: true,
25 url: "https://eslint.org/docs/rules/no-prototype-builtins"
26 },
27
28 schema: [],
29
30 messages: {
31 prototypeBuildIn: "Do not access Object.prototype method '{{prop}}' from target object."
32 }
33 },
34
35 create(context) {
36 const DISALLOWED_PROPS = [
37 "hasOwnProperty",
38 "isPrototypeOf",
39 "propertyIsEnumerable"
40 ];
41
42 /**
43 * Reports if a disallowed property is used in a CallExpression
44 * @param {ASTNode} node The CallExpression node.
45 * @returns {void}
46 */
47 function disallowBuiltIns(node) {
48
49 const callee = astUtils.skipChainExpression(node.callee);
50
51 if (callee.type !== "MemberExpression") {
52 return;
53 }
54
55 const propName = astUtils.getStaticPropertyName(callee);
56
57 if (propName !== null && DISALLOWED_PROPS.indexOf(propName) > -1) {
58 context.report({
59 messageId: "prototypeBuildIn",
60 loc: callee.property.loc,
61 data: { prop: propName },
62 node
63 });
64 }
65 }
66
67 return {
68 CallExpression: disallowBuiltIns
69 };
70 }
71};