| 1 | import { |
| 2 | isParenthesizedExpression, |
| 3 | isTSAsExpression, |
| 4 | isTSNonNullExpression, |
| 5 | isTSSatisfiesExpression, |
| 6 | isTSTypeAssertion, |
| 7 | isTypeCastExpression, |
| 8 | } from "@babel/types"; |
| 9 | |
| 10 | import type * as t from "@babel/types"; |
| 11 | import type { NodePath } from "@babel/traverse"; |
| 12 | |
| 13 | export type TransparentExprWrapper = |
| 14 | | t.TSAsExpression |
| 15 | | t.TSSatisfiesExpression |
| 16 | | t.TSTypeAssertion |
| 17 | | t.TSNonNullExpression |
| 18 | | t.TypeCastExpression |
| 19 | | t.ParenthesizedExpression; |
| 20 | |
| 21 | // A transparent expression wrapper is an AST node that most plugins will wish |
| 22 | // to skip, as its presence does not affect the behaviour of the code. This |
| 23 | // includes expressions used for types, and extra parenthesis. For example, in |
| 24 | // (a as any)(), this helper can be used to skip the TSAsExpression when |
| 25 | // determining the callee. |
| 26 | export function isTransparentExprWrapper( |
| 27 | node: t.Node, |
| 28 | ): node is TransparentExprWrapper { |
| 29 | return ( |
| 30 | isTSAsExpression(node) || |
| 31 | isTSSatisfiesExpression(node) || |
| 32 | isTSTypeAssertion(node) || |
| 33 | isTSNonNullExpression(node) || |
| 34 | isTypeCastExpression(node) || |
| 35 | isParenthesizedExpression(node) |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | export function skipTransparentExprWrappers( |
| 40 | path: NodePath<t.Expression>, |
| 41 | ): NodePath<t.Expression> { |
| 42 | while (isTransparentExprWrapper(path.node)) { |
| 43 | path = path.get("expression"); |
| 44 | } |
| 45 | return path; |
| 46 | } |
| 47 | |
| 48 | export function skipTransparentExprWrapperNodes( |
| 49 | node: t.Expression | t.Super, |
| 50 | ): t.Expression | t.Super { |
| 51 | while (isTransparentExprWrapper(node)) { |
| 52 | node = node.expression; |
| 53 | } |
| 54 | return node; |
| 55 | } |