summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/tools/eslint/src/use-using.ts
blob: 0c727a4334349fb71b974f088179077846e7299b (plain)
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
/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import {ESLintUtils, TSESTree} from '@typescript-eslint/utils';

const usingSymbols = ['ElementHandle', 'JSHandle'];

const createRule = ESLintUtils.RuleCreator(name => {
  return `https://github.com/puppeteer/puppeteer/tree/main/tools/eslint/${name}.js`;
});

const useUsingRule = createRule<[], 'useUsing' | 'useUsingFix'>({
  name: 'use-using',
  meta: {
    docs: {
      description: "Requires 'using' for element/JS handles.",
      requiresTypeChecking: true,
    },
    hasSuggestions: true,
    messages: {
      useUsing: "Use 'using'.",
      useUsingFix: "Replace with 'using' to ignore.",
    },
    schema: [],
    type: 'problem',
  },
  defaultOptions: [],
  create(context) {
    const services = ESLintUtils.getParserServices(context);
    const checker = services.program.getTypeChecker();

    return {
      VariableDeclaration(node): void {
        if (['using', 'await using'].includes(node.kind) || node.declare) {
          return;
        }
        for (const declaration of node.declarations) {
          if (declaration.id.type === TSESTree.AST_NODE_TYPES.Identifier) {
            const tsNode = services.esTreeNodeToTSNodeMap.get(declaration.id);
            const type = checker.getTypeAtLocation(tsNode);
            let isElementHandleReference = false;
            if (type.isUnionOrIntersection()) {
              for (const member of type.types) {
                if (
                  member.symbol !== undefined &&
                  usingSymbols.includes(member.symbol.escapedName as string)
                ) {
                  isElementHandleReference = true;
                  break;
                }
              }
            } else {
              isElementHandleReference =
                type.symbol !== undefined
                  ? usingSymbols.includes(type.symbol.escapedName as string)
                  : false;
            }
            if (isElementHandleReference) {
              context.report({
                node: declaration.id,
                messageId: 'useUsing',
                suggest: [
                  {
                    messageId: 'useUsingFix',
                    fix(fixer) {
                      return fixer.replaceTextRange(
                        [node.range[0], node.range[0] + node.kind.length],
                        'using'
                      );
                    },
                  },
                ],
              });
            }
          }
        }
      },
    };
  },
});

export = useUsingRule;