|
| 1 | +/** |
| 2 | + * @fileoverview Rule to disallow using optional chaining - because this is transpiled into verbose code. |
| 3 | + * @author Francesco Novy |
| 4 | + * |
| 5 | + * Based on https://github.com/facebook/lexical/pull/3233 |
| 6 | + */ |
| 7 | +'use strict'; |
| 8 | + |
| 9 | +// ------------------------------------------------------------------------------ |
| 10 | +// Rule Definition |
| 11 | +// ------------------------------------------------------------------------------ |
| 12 | + |
| 13 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 14 | +module.exports = { |
| 15 | + meta: { |
| 16 | + type: 'problem', |
| 17 | + docs: { |
| 18 | + description: 'disallow usage of optional chaining', |
| 19 | + category: 'Best Practices', |
| 20 | + recommended: true, |
| 21 | + }, |
| 22 | + messages: { |
| 23 | + forbidden: 'Avoid using optional chaining', |
| 24 | + }, |
| 25 | + fixable: null, |
| 26 | + schema: [], |
| 27 | + }, |
| 28 | + |
| 29 | + create(context) { |
| 30 | + const sourceCode = context.getSourceCode(); |
| 31 | + |
| 32 | + /** |
| 33 | + * Checks if the given token is a `?.` token or not. |
| 34 | + * @param {Token} token The token to check. |
| 35 | + * @returns {boolean} `true` if the token is a `?.` token. |
| 36 | + */ |
| 37 | + function isQuestionDotToken(token) { |
| 38 | + return ( |
| 39 | + token.value === '?.' && |
| 40 | + (token.type === 'Punctuator' || // espree has been parsed well. |
| 41 | + // [email protected] doesn't parse "?." tokens well. Therefore, get the string from the source code and check it. |
| 42 | + sourceCode.getText(token) === '?.') |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + return { |
| 47 | + 'CallExpression[optional=true]'(node) { |
| 48 | + context.report({ |
| 49 | + messageId: 'forbidden', |
| 50 | + node: sourceCode.getTokenAfter(node.callee, isQuestionDotToken), |
| 51 | + }); |
| 52 | + }, |
| 53 | + 'MemberExpression[optional=true]'(node) { |
| 54 | + context.report({ |
| 55 | + messageId: 'forbidden', |
| 56 | + node: sourceCode.getTokenAfter(node.object, isQuestionDotToken), |
| 57 | + }); |
| 58 | + }, |
| 59 | + }; |
| 60 | + }, |
| 61 | +}; |
0 commit comments