1 | "use strict";
|
2 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3 | if (k2 === undefined) k2 = k;
|
4 | Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
5 | }) : (function(o, m, k, k2) {
|
6 | if (k2 === undefined) k2 = k;
|
7 | o[k2] = m[k];
|
8 | }));
|
9 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
10 | Object.defineProperty(o, "default", { enumerable: true, value: v });
|
11 | }) : function(o, v) {
|
12 | o["default"] = v;
|
13 | });
|
14 | var __importStar = (this && this.__importStar) || function (mod) {
|
15 | if (mod && mod.__esModule) return mod;
|
16 | var result = {};
|
17 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
18 | __setModuleDefault(result, mod);
|
19 | return result;
|
20 | };
|
21 | Object.defineProperty(exports, "__esModule", { value: true });
|
22 | const utils_1 = require("@typescript-eslint/utils");
|
23 | const util = __importStar(require("../util"));
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | exports.default = util.createRule({
|
41 | name: 'prefer-optional-chain',
|
42 | meta: {
|
43 | type: 'suggestion',
|
44 | docs: {
|
45 | description: 'Prefer using concise optional chain expressions instead of chained logical ands',
|
46 | recommended: false,
|
47 | suggestion: true,
|
48 | },
|
49 | hasSuggestions: true,
|
50 | messages: {
|
51 | preferOptionalChain: "Prefer using an optional chain expression instead, as it's more concise and easier to read.",
|
52 | optionalChainSuggest: 'Change to an optional chain.',
|
53 | },
|
54 | schema: [],
|
55 | },
|
56 | defaultOptions: [],
|
57 | create(context) {
|
58 | const sourceCode = context.getSourceCode();
|
59 | return {
|
60 | [[
|
61 | 'LogicalExpression[operator="&&"] > Identifier',
|
62 | 'LogicalExpression[operator="&&"] > MemberExpression',
|
63 | 'LogicalExpression[operator="&&"] > ChainExpression > MemberExpression',
|
64 | 'LogicalExpression[operator="&&"] > BinaryExpression[operator="!=="]',
|
65 | 'LogicalExpression[operator="&&"] > BinaryExpression[operator="!="]',
|
66 | ].join(',')](initialIdentifierOrNotEqualsExpr) {
|
67 | var _a;
|
68 |
|
69 | const initialExpression = (((_a = initialIdentifierOrNotEqualsExpr.parent) === null || _a === void 0 ? void 0 : _a.type) ===
|
70 | utils_1.AST_NODE_TYPES.ChainExpression
|
71 | ? initialIdentifierOrNotEqualsExpr.parent.parent
|
72 | : initialIdentifierOrNotEqualsExpr.parent);
|
73 | if (initialExpression.left !== initialIdentifierOrNotEqualsExpr) {
|
74 |
|
75 | return;
|
76 | }
|
77 | if (!isValidChainTarget(initialIdentifierOrNotEqualsExpr, true)) {
|
78 | return;
|
79 | }
|
80 |
|
81 | let previous = initialExpression;
|
82 | let current = initialExpression;
|
83 | let previousLeftText = getText(initialIdentifierOrNotEqualsExpr);
|
84 | let optionallyChainedCode = previousLeftText;
|
85 | let expressionCount = 1;
|
86 | while (current.type === utils_1.AST_NODE_TYPES.LogicalExpression) {
|
87 | if (!isValidChainTarget(current.right,
|
88 |
|
89 | expressionCount === 1)) {
|
90 | break;
|
91 | }
|
92 | const leftText = previousLeftText;
|
93 | const rightText = getText(current.right);
|
94 |
|
95 | const matchRegex = new RegExp(`^${
|
96 | // escape regex characters
|
97 | leftText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^a-zA-Z0-9_$]`);
|
98 | if (!matchRegex.test(rightText) &&
|
99 |
|
100 | leftText !== rightText) {
|
101 | break;
|
102 | }
|
103 |
|
104 | if (rightText !== leftText) {
|
105 | expressionCount += 1;
|
106 | previousLeftText = rightText;
|
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 | const diff = rightText.replace(leftText, '');
|
137 | if (diff.startsWith('?')) {
|
138 |
|
139 | optionallyChainedCode += diff;
|
140 | }
|
141 | else {
|
142 | const needsDot = diff.startsWith('(') || diff.startsWith('[');
|
143 | optionallyChainedCode += `?${needsDot ? '.' : ''}${diff}`;
|
144 | }
|
145 | }
|
146 | previous = current;
|
147 | current = util.nullThrows(current.parent, util.NullThrowsReasons.MissingParent);
|
148 | }
|
149 | if (expressionCount > 1) {
|
150 | if (previous.right.type === utils_1.AST_NODE_TYPES.BinaryExpression) {
|
151 |
|
152 | optionallyChainedCode += ` ${previous.right.operator} ${sourceCode.getText(previous.right.right)}`;
|
153 | }
|
154 | context.report({
|
155 | node: previous,
|
156 | messageId: 'preferOptionalChain',
|
157 | suggest: [
|
158 | {
|
159 | messageId: 'optionalChainSuggest',
|
160 | fix: (fixer) => [
|
161 | fixer.replaceText(previous, optionallyChainedCode),
|
162 | ],
|
163 | },
|
164 | ],
|
165 | });
|
166 | }
|
167 | },
|
168 | };
|
169 | function getText(node) {
|
170 | if (node.type === utils_1.AST_NODE_TYPES.BinaryExpression) {
|
171 | return getText(
|
172 |
|
173 | node.left);
|
174 | }
|
175 | if (node.type === utils_1.AST_NODE_TYPES.CallExpression) {
|
176 | const calleeText = getText(
|
177 |
|
178 | node.callee);
|
179 |
|
180 |
|
181 |
|
182 | const closingParenToken = util.nullThrows(sourceCode.getLastToken(node), util.NullThrowsReasons.MissingToken('closing parenthesis', node.type));
|
183 | const openingParenToken = util.nullThrows(sourceCode.getFirstTokenBetween(node.callee, closingParenToken, util.isOpeningParenToken), util.NullThrowsReasons.MissingToken('opening parenthesis', node.type));
|
184 | const argumentsText = sourceCode.text.substring(openingParenToken.range[0], closingParenToken.range[1]);
|
185 | return `${calleeText}${argumentsText}`;
|
186 | }
|
187 | if (node.type === utils_1.AST_NODE_TYPES.Identifier) {
|
188 | return node.name;
|
189 | }
|
190 | if (node.type === utils_1.AST_NODE_TYPES.ThisExpression) {
|
191 | return 'this';
|
192 | }
|
193 | if (node.type === utils_1.AST_NODE_TYPES.ChainExpression) {
|
194 | if (node.expression.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) {
|
195 |
|
196 | return '';
|
197 | }
|
198 | return getText(node.expression);
|
199 | }
|
200 | return getMemberExpressionText(node);
|
201 | }
|
202 | |
203 |
|
204 |
|
205 | function getMemberExpressionText(node) {
|
206 | let objectText;
|
207 |
|
208 | switch (node.object.type) {
|
209 | case utils_1.AST_NODE_TYPES.CallExpression:
|
210 | case utils_1.AST_NODE_TYPES.Identifier:
|
211 | objectText = getText(node.object);
|
212 | break;
|
213 | case utils_1.AST_NODE_TYPES.MemberExpression:
|
214 | objectText = getMemberExpressionText(node.object);
|
215 | break;
|
216 | case utils_1.AST_NODE_TYPES.ThisExpression:
|
217 | objectText = getText(node.object);
|
218 | break;
|
219 |
|
220 | default:
|
221 | throw new Error(`Unexpected member object type: ${node.object.type}`);
|
222 | }
|
223 | let propertyText;
|
224 | if (node.computed) {
|
225 |
|
226 | switch (node.property.type) {
|
227 | case utils_1.AST_NODE_TYPES.Identifier:
|
228 | propertyText = getText(node.property);
|
229 | break;
|
230 | case utils_1.AST_NODE_TYPES.Literal:
|
231 | case utils_1.AST_NODE_TYPES.TemplateLiteral:
|
232 | propertyText = sourceCode.getText(node.property);
|
233 | break;
|
234 | case utils_1.AST_NODE_TYPES.MemberExpression:
|
235 | propertyText = getMemberExpressionText(node.property);
|
236 | break;
|
237 |
|
238 | default:
|
239 | throw new Error(`Unexpected member property type: ${node.object.type}`);
|
240 | }
|
241 | return `${objectText}${node.optional ? '?.' : ''}[${propertyText}]`;
|
242 | }
|
243 | else {
|
244 |
|
245 | switch (node.property.type) {
|
246 | case utils_1.AST_NODE_TYPES.Identifier:
|
247 | propertyText = getText(node.property);
|
248 | break;
|
249 |
|
250 | default:
|
251 | throw new Error(`Unexpected member property type: ${node.object.type}`);
|
252 | }
|
253 | return `${objectText}${node.optional ? '?.' : '.'}${propertyText}`;
|
254 | }
|
255 | }
|
256 | },
|
257 | });
|
258 | const ALLOWED_MEMBER_OBJECT_TYPES = new Set([
|
259 | utils_1.AST_NODE_TYPES.CallExpression,
|
260 | utils_1.AST_NODE_TYPES.Identifier,
|
261 | utils_1.AST_NODE_TYPES.MemberExpression,
|
262 | utils_1.AST_NODE_TYPES.ThisExpression,
|
263 | ]);
|
264 | const ALLOWED_COMPUTED_PROP_TYPES = new Set([
|
265 | utils_1.AST_NODE_TYPES.Identifier,
|
266 | utils_1.AST_NODE_TYPES.Literal,
|
267 | utils_1.AST_NODE_TYPES.MemberExpression,
|
268 | utils_1.AST_NODE_TYPES.TemplateLiteral,
|
269 | ]);
|
270 | const ALLOWED_NON_COMPUTED_PROP_TYPES = new Set([
|
271 | utils_1.AST_NODE_TYPES.Identifier,
|
272 | ]);
|
273 | function isValidChainTarget(node, allowIdentifier) {
|
274 | if (node.type === utils_1.AST_NODE_TYPES.ChainExpression) {
|
275 | return isValidChainTarget(node.expression, allowIdentifier);
|
276 | }
|
277 | if (node.type === utils_1.AST_NODE_TYPES.MemberExpression) {
|
278 | const isObjectValid = ALLOWED_MEMBER_OBJECT_TYPES.has(node.object.type) &&
|
279 |
|
280 | isValidChainTarget(node.object, true);
|
281 | const isPropertyValid = node.computed
|
282 | ? ALLOWED_COMPUTED_PROP_TYPES.has(node.property.type) &&
|
283 |
|
284 | (node.property.type === utils_1.AST_NODE_TYPES.MemberExpression
|
285 | ? isValidChainTarget(node.property, allowIdentifier)
|
286 | : true)
|
287 | : ALLOWED_NON_COMPUTED_PROP_TYPES.has(node.property.type);
|
288 | return isObjectValid && isPropertyValid;
|
289 | }
|
290 | if (node.type === utils_1.AST_NODE_TYPES.CallExpression) {
|
291 | return isValidChainTarget(node.callee, allowIdentifier);
|
292 | }
|
293 | if (allowIdentifier &&
|
294 | (node.type === utils_1.AST_NODE_TYPES.Identifier ||
|
295 | node.type === utils_1.AST_NODE_TYPES.ThisExpression)) {
|
296 | return true;
|
297 | }
|
298 | |
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 | if (node.type === utils_1.AST_NODE_TYPES.BinaryExpression &&
|
306 | ['!==', '!='].includes(node.operator) &&
|
307 | isValidChainTarget(node.left, allowIdentifier)) {
|
308 | if (node.right.type === utils_1.AST_NODE_TYPES.Identifier &&
|
309 | node.right.name === 'undefined') {
|
310 | return true;
|
311 | }
|
312 | if (node.right.type === utils_1.AST_NODE_TYPES.Literal &&
|
313 | node.right.value === null) {
|
314 | return true;
|
315 | }
|
316 | }
|
317 | return false;
|
318 | }
|
319 |
|
\ | No newline at end of file |