-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
jsx-no-leaked-render.js
204 lines (177 loc) · 7.44 KB
/
jsx-no-leaked-render.js
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
/**
* @fileoverview Prevent problematic leaked values from being rendered
* @author Mario Beltrán
*/
'use strict';
const find = require('es-iterator-helpers/Iterator.prototype.find');
const from = require('es-iterator-helpers/Iterator.from');
const getText = require('../util/eslint').getText;
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');
const variableUtil = require('../util/variable');
const testReactVersion = require('../util/version').testReactVersion;
const isParenthesized = require('../util/ast').isParenthesized;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const messages = {
noPotentialLeakedRender: 'Potential leaked value that might cause unintentionally rendered values or rendering crashes',
};
const COERCE_STRATEGY = 'coerce';
const TERNARY_STRATEGY = 'ternary';
const DEFAULT_VALID_STRATEGIES = [TERNARY_STRATEGY, COERCE_STRATEGY];
const COERCE_VALID_LEFT_SIDE_EXPRESSIONS = ['UnaryExpression', 'BinaryExpression', 'CallExpression'];
const TERNARY_INVALID_ALTERNATE_VALUES = [undefined, null, false];
function trimLeftNode(node) {
// Remove double unary expression (boolean coercion), so we avoid trimming valid negations
if (node.type === 'UnaryExpression' && node.argument.type === 'UnaryExpression') {
return trimLeftNode(node.argument.argument);
}
return node;
}
function getIsCoerceValidNestedLogicalExpression(node) {
if (node.type === 'LogicalExpression') {
return getIsCoerceValidNestedLogicalExpression(node.left) && getIsCoerceValidNestedLogicalExpression(node.right);
}
return COERCE_VALID_LEFT_SIDE_EXPRESSIONS.some((validExpression) => validExpression === node.type);
}
function extractExpressionBetweenLogicalAnds(node) {
if (node.type !== 'LogicalExpression') return [node];
if (node.operator !== '&&') return [node];
return [].concat(
extractExpressionBetweenLogicalAnds(node.left),
extractExpressionBetweenLogicalAnds(node.right)
);
}
function ruleFixer(context, fixStrategy, fixer, reportedNode, leftNode, rightNode) {
const rightSideText = getText(context, rightNode);
if (fixStrategy === COERCE_STRATEGY) {
const expressions = extractExpressionBetweenLogicalAnds(leftNode);
const newText = expressions.map((node) => {
let nodeText = getText(context, node);
if (isParenthesized(context, node)) {
nodeText = `(${nodeText})`;
}
if (node.parent && node.parent.type === 'ConditionalExpression' && node.parent.consequent.value === false) {
return `${getIsCoerceValidNestedLogicalExpression(node) ? '' : '!'}${nodeText}`;
}
return `${getIsCoerceValidNestedLogicalExpression(node) ? '' : '!!'}${nodeText}`;
}).join(' && ');
if (rightNode.parent && rightNode.parent.type === 'ConditionalExpression' && rightNode.parent.consequent.value === false) {
const consequentVal = rightNode.parent.consequent.raw || rightNode.parent.consequent.name;
const alternateVal = rightNode.parent.alternate.raw || rightNode.parent.alternate.name;
if (rightNode.parent.test && rightNode.parent.test.type === 'LogicalExpression') {
return fixer.replaceText(reportedNode, `${newText} ? ${consequentVal} : ${alternateVal}`);
}
return fixer.replaceText(reportedNode, `${newText} && ${alternateVal}`);
}
if (rightNode.type === 'ConditionalExpression' || rightNode.type === 'LogicalExpression') {
return fixer.replaceText(reportedNode, `${newText} && (${rightSideText})`);
}
if (rightNode.type === 'JSXElement') {
const rightSideTextLines = rightSideText.split('\n');
if (rightSideTextLines.length > 1) {
const rightSideTextLastLine = rightSideTextLines[rightSideTextLines.length - 1];
const indentSpacesStart = ' '.repeat(rightSideTextLastLine.search(/\S/));
const indentSpacesClose = ' '.repeat(rightSideTextLastLine.search(/\S/) - 2);
return fixer.replaceText(reportedNode, `${newText} && (\n${indentSpacesStart}${rightSideText}\n${indentSpacesClose})`);
}
}
if (rightNode.type === 'Literal') {
return null;
}
return fixer.replaceText(reportedNode, `${newText} && ${rightSideText}`);
}
if (fixStrategy === TERNARY_STRATEGY) {
let leftSideText = getText(context, trimLeftNode(leftNode));
if (isParenthesized(context, leftNode)) {
leftSideText = `(${leftSideText})`;
}
return fixer.replaceText(reportedNode, `${leftSideText} ? ${rightSideText} : null`);
}
throw new TypeError('Invalid value for "validStrategies" option');
}
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallow problematic leaked values from being rendered',
category: 'Possible Errors',
recommended: false,
url: docsUrl('jsx-no-leaked-render'),
},
messages,
fixable: 'code',
schema: [
{
type: 'object',
properties: {
validStrategies: {
type: 'array',
items: {
enum: [
TERNARY_STRATEGY,
COERCE_STRATEGY,
],
},
uniqueItems: true,
default: DEFAULT_VALID_STRATEGIES,
},
},
additionalProperties: false,
},
],
},
create(context) {
const config = context.options[0] || {};
const validStrategies = new Set(config.validStrategies || DEFAULT_VALID_STRATEGIES);
const fixStrategy = find(from(validStrategies), () => true);
return {
'JSXExpressionContainer > LogicalExpression[operator="&&"]'(node) {
const leftSide = node.left;
const isCoerceValidLeftSide = COERCE_VALID_LEFT_SIDE_EXPRESSIONS
.some((validExpression) => validExpression === leftSide.type);
if (validStrategies.has(COERCE_STRATEGY)) {
if (isCoerceValidLeftSide || getIsCoerceValidNestedLogicalExpression(leftSide)) {
return;
}
const leftSideVar = variableUtil.getVariableFromContext(context, node, leftSide.name);
if (leftSideVar) {
const leftSideValue = leftSideVar.defs
&& leftSideVar.defs.length
&& leftSideVar.defs[0].node.init
&& leftSideVar.defs[0].node.init.value;
if (typeof leftSideValue === 'boolean') {
return;
}
}
}
if (testReactVersion(context, '>= 18') && leftSide.type === 'Literal' && leftSide.value === '') {
return;
}
report(context, messages.noPotentialLeakedRender, 'noPotentialLeakedRender', {
node,
fix(fixer) {
return ruleFixer(context, fixStrategy, fixer, node, leftSide, node.right);
},
});
},
'JSXExpressionContainer > ConditionalExpression'(node) {
if (validStrategies.has(TERNARY_STRATEGY)) {
return;
}
const isValidTernaryAlternate = TERNARY_INVALID_ALTERNATE_VALUES.indexOf(node.alternate.value) === -1;
const isJSXElementAlternate = node.alternate.type === 'JSXElement';
if (isValidTernaryAlternate || isJSXElementAlternate) {
return;
}
report(context, messages.noPotentialLeakedRender, 'noPotentialLeakedRender', {
node,
fix(fixer) {
return ruleFixer(context, fixStrategy, fixer, node, node.test, node.consequent);
},
});
},
};
},
};