|
| 1 | +import { ESLintUtils, ASTUtils } from "@typescript-eslint/utils"; |
| 2 | +import type { TSESTree as AST } from "@typescript-eslint/types"; |
| 3 | + |
| 4 | +type Fn = |
| 5 | + | AST.FunctionDeclaration |
| 6 | + | AST.ArrowFunctionExpression |
| 7 | + | AST.FunctionExpression; |
| 8 | + |
| 9 | +export const rule = ESLintUtils.RuleCreator.withoutDocs({ |
| 10 | + create(context) { |
| 11 | + let depth = 1; |
| 12 | + let disabledDepth: number | false = false; |
| 13 | + |
| 14 | + function EnterFn() { |
| 15 | + depth++; |
| 16 | + } |
| 17 | + function ExitFn() { |
| 18 | + depth--; |
| 19 | + if (disabledDepth !== false && disabledDepth > depth) { |
| 20 | + disabledDepth = false; |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return { |
| 25 | + CallExpression(node) { |
| 26 | + const directCallee = |
| 27 | + node.callee.type === "Identifier" ? node.callee |
| 28 | + : node.callee.type === "MemberExpression" ? node.callee.property |
| 29 | + : null; |
| 30 | + |
| 31 | + if ( |
| 32 | + directCallee?.type === "Identifier" && |
| 33 | + directCallee.name === "disableActEnvironment" |
| 34 | + ) { |
| 35 | + if (disabledDepth === false) { |
| 36 | + disabledDepth = depth; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + if ( |
| 41 | + directCallee?.type === "Identifier" && |
| 42 | + (directCallee.name === "takeRender" || |
| 43 | + directCallee.name === "takeSnapshot") |
| 44 | + ) { |
| 45 | + if (disabledDepth === false) { |
| 46 | + context.report({ |
| 47 | + messageId: "missingDisableActEnvironment", |
| 48 | + node: node, |
| 49 | + }); |
| 50 | + } |
| 51 | + } |
| 52 | + }, |
| 53 | + ArrowFunctionExpression: EnterFn, |
| 54 | + FunctionExpression: EnterFn, |
| 55 | + FunctionDeclaration: EnterFn, |
| 56 | + "ArrowFunctionExpression:exit": ExitFn, |
| 57 | + "FunctionExpression:exit": ExitFn, |
| 58 | + "FunctionDeclaration:exit": ExitFn, |
| 59 | + }; |
| 60 | + }, |
| 61 | + meta: { |
| 62 | + messages: { |
| 63 | + missingDisableActEnvironment: |
| 64 | + "Tests using a render stream should call `disableActEnvironment`.", |
| 65 | + }, |
| 66 | + type: "problem", |
| 67 | + schema: [], |
| 68 | + }, |
| 69 | + defaultOptions: [], |
| 70 | +}); |
| 71 | + |
| 72 | +function findParentFunction(node: AST.Node): Fn | undefined { |
| 73 | + let parentFunction: AST.Node | undefined = node; |
| 74 | + while ( |
| 75 | + parentFunction != null && |
| 76 | + parentFunction.type !== "FunctionDeclaration" && |
| 77 | + parentFunction.type !== "FunctionExpression" && |
| 78 | + parentFunction.type !== "ArrowFunctionExpression" |
| 79 | + ) { |
| 80 | + parentFunction = parentFunction.parent; |
| 81 | + } |
| 82 | + return parentFunction; |
| 83 | +} |
0 commit comments