unbound-method.js
10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const tsutils = __importStar(require("tsutils"));
const ts = __importStar(require("typescript"));
const util = __importStar(require("../util"));
/**
* The following is a list of exceptions to the rule
* Generated via the following script.
* This is statically defined to save making purposely invalid calls every lint run
* ```
SUPPORTED_GLOBALS.flatMap(namespace => {
const object = window[namespace];
return Object.getOwnPropertyNames(object)
.filter(
name =>
!name.startsWith('_') &&
typeof object[name] === 'function',
)
.map(name => {
try {
const x = object[name];
x();
} catch (e) {
if (e.message.includes("called on non-object")) {
return `${namespace}.${name}`;
}
}
});
}).filter(Boolean);
* ```
*/
const nativelyNotBoundMembers = new Set([
'Promise.all',
'Promise.race',
'Promise.resolve',
'Promise.reject',
'Promise.allSettled',
'Object.defineProperties',
'Object.defineProperty',
'Reflect.defineProperty',
'Reflect.deleteProperty',
'Reflect.get',
'Reflect.getOwnPropertyDescriptor',
'Reflect.getPrototypeOf',
'Reflect.has',
'Reflect.isExtensible',
'Reflect.ownKeys',
'Reflect.preventExtensions',
'Reflect.set',
'Reflect.setPrototypeOf',
]);
const SUPPORTED_GLOBALS = [
'Number',
'Object',
'String',
'RegExp',
'Symbol',
'Array',
'Proxy',
'Date',
'Infinity',
'Atomics',
'Reflect',
'console',
'Math',
'JSON',
'Intl',
];
const nativelyBoundMembers = SUPPORTED_GLOBALS.map(namespace => {
if (!(namespace in global)) {
// node.js might not have namespaces like Intl depending on compilation options
// https://nodejs.org/api/intl.html#intl_options_for_building_node_js
return [];
}
const object = global[namespace];
return Object.getOwnPropertyNames(object)
.filter(name => !name.startsWith('_') &&
typeof object[name] === 'function')
.map(name => `${namespace}.${name}`);
})
.reduce((arr, names) => arr.concat(names), [])
.filter(name => !nativelyNotBoundMembers.has(name));
const isNotImported = (symbol, currentSourceFile) => {
const { valueDeclaration } = symbol;
if (!valueDeclaration) {
// working around https://github.com/microsoft/TypeScript/issues/31294
return false;
}
return (!!currentSourceFile &&
currentSourceFile !== valueDeclaration.getSourceFile());
};
const getNodeName = (node) => node.type === experimental_utils_1.AST_NODE_TYPES.Identifier ? node.name : null;
const getMemberFullName = (node) => `${getNodeName(node.object)}.${getNodeName(node.property)}`;
exports.default = util.createRule({
name: 'unbound-method',
meta: {
docs: {
category: 'Best Practices',
description: 'Enforces unbound methods are called with their expected scope',
recommended: 'error',
requiresTypeChecking: true,
},
messages: {
unbound: 'Avoid referencing unbound methods which may cause unintentional scoping of `this`.',
},
schema: [
{
type: 'object',
properties: {
ignoreStatic: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
type: 'problem',
},
defaultOptions: [
{
ignoreStatic: false,
},
],
create(context, [{ ignoreStatic }]) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const currentSourceFile = parserServices.program.getSourceFile(context.getFilename());
return {
MemberExpression(node) {
if (isSafeUse(node)) {
return;
}
const objectSymbol = checker.getSymbolAtLocation(parserServices.esTreeNodeToTSNodeMap.get(node.object));
if (objectSymbol &&
nativelyBoundMembers.includes(getMemberFullName(node)) &&
isNotImported(objectSymbol, currentSourceFile)) {
return;
}
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const symbol = checker.getSymbolAtLocation(originalNode);
if (symbol && isDangerousMethod(symbol, ignoreStatic)) {
context.report({
messageId: 'unbound',
node,
});
}
},
'VariableDeclarator, AssignmentExpression'(node) {
const [idNode, initNode] = node.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator
? [node.id, node.init]
: [node.left, node.right];
if (initNode && idNode.type === experimental_utils_1.AST_NODE_TYPES.ObjectPattern) {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(initNode);
const rightSymbol = checker.getSymbolAtLocation(tsNode);
const initTypes = checker.getTypeAtLocation(tsNode);
const notImported = rightSymbol && isNotImported(rightSymbol, currentSourceFile);
idNode.properties.forEach(property => {
if (property.type === experimental_utils_1.AST_NODE_TYPES.Property &&
property.key.type === experimental_utils_1.AST_NODE_TYPES.Identifier) {
if (notImported &&
util.isIdentifier(initNode) &&
nativelyBoundMembers.includes(`${initNode.name}.${property.key.name}`)) {
return;
}
const symbol = initTypes.getProperty(property.key.name);
if (symbol && isDangerousMethod(symbol, ignoreStatic)) {
context.report({
messageId: 'unbound',
node,
});
}
}
});
}
},
};
},
});
function isDangerousMethod(symbol, ignoreStatic) {
var _a, _b;
const { valueDeclaration } = symbol;
if (!valueDeclaration) {
// working around https://github.com/microsoft/TypeScript/issues/31294
return false;
}
switch (valueDeclaration.kind) {
case ts.SyntaxKind.PropertyDeclaration:
return (((_a = valueDeclaration.initializer) === null || _a === void 0 ? void 0 : _a.kind) ===
ts.SyntaxKind.FunctionExpression);
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.MethodSignature: {
const decl = valueDeclaration;
const firstParam = decl.parameters[0];
const thisArgIsVoid = (firstParam === null || firstParam === void 0 ? void 0 : firstParam.name.kind) === ts.SyntaxKind.Identifier &&
(firstParam === null || firstParam === void 0 ? void 0 : firstParam.name.escapedText) === 'this' &&
((_b = firstParam === null || firstParam === void 0 ? void 0 : firstParam.type) === null || _b === void 0 ? void 0 : _b.kind) === ts.SyntaxKind.VoidKeyword;
return (!thisArgIsVoid &&
!(ignoreStatic &&
tsutils.hasModifier(valueDeclaration.modifiers, ts.SyntaxKind.StaticKeyword)));
}
}
return false;
}
function isSafeUse(node) {
const parent = node.parent;
switch (parent === null || parent === void 0 ? void 0 : parent.type) {
case experimental_utils_1.AST_NODE_TYPES.IfStatement:
case experimental_utils_1.AST_NODE_TYPES.ForStatement:
case experimental_utils_1.AST_NODE_TYPES.MemberExpression:
case experimental_utils_1.AST_NODE_TYPES.SwitchStatement:
case experimental_utils_1.AST_NODE_TYPES.UpdateExpression:
case experimental_utils_1.AST_NODE_TYPES.WhileStatement:
return true;
case experimental_utils_1.AST_NODE_TYPES.CallExpression:
return parent.callee === node;
case experimental_utils_1.AST_NODE_TYPES.ConditionalExpression:
return parent.test === node;
case experimental_utils_1.AST_NODE_TYPES.TaggedTemplateExpression:
return parent.tag === node;
case experimental_utils_1.AST_NODE_TYPES.UnaryExpression:
// the first case is safe for obvious
// reasons. The second one is also fine
// since we're returning something falsy
return ['typeof', '!', 'void', 'delete'].includes(parent.operator);
case experimental_utils_1.AST_NODE_TYPES.BinaryExpression:
return ['instanceof', '==', '!=', '===', '!=='].includes(parent.operator);
case experimental_utils_1.AST_NODE_TYPES.AssignmentExpression:
return parent.operator === '=' && node === parent.left;
case experimental_utils_1.AST_NODE_TYPES.ChainExpression:
case experimental_utils_1.AST_NODE_TYPES.TSNonNullExpression:
case experimental_utils_1.AST_NODE_TYPES.TSAsExpression:
case experimental_utils_1.AST_NODE_TYPES.TSTypeAssertion:
return isSafeUse(parent);
case experimental_utils_1.AST_NODE_TYPES.LogicalExpression:
if (parent.operator === '&&' && parent.left === node) {
// this is safe, as && will return the left if and only if it's falsy
return true;
}
// in all other cases, it's likely the logical expression will return the method ref
// so make sure the parent is a safe usage
return isSafeUse(parent);
}
return false;
}
//# sourceMappingURL=unbound-method.js.map