summaryrefslogtreecommitdiffstats
path: root/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-globalThis-modification.js
blob: f14fdcd7952d7a3b7c243cae0d3ccc536248d086 (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
/**
 * @fileoverview Enforce the standard object name for
 * ChromeUtils.defineESMGetters
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

"use strict";

function isIdentifier(node, id) {
  return node.type === "Identifier" && node.name === id;
}

function calleeToString(node) {
  if (node.type === "Identifier") {
    return node.name;
  }

  if (node.type === "MemberExpression" && !node.computed) {
    return calleeToString(node.object) + "." + node.property.name;
  }

  return "???";
}

module.exports = {
  meta: {
    docs: {
      url: "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/rules/reject-globalThis-modification.html",
    },
    messages: {
      rejectModifyGlobalThis:
        "`globalThis` shouldn't be modified. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.",
      rejectPassingGlobalThis:
        "`globalThis` shouldn't be passed to function that can modify it. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.",
    },
    schema: [],
    type: "problem",
  },

  create(context) {
    return {
      AssignmentExpression(node) {
        let target = node.left;
        while (target.type === "MemberExpression") {
          target = target.object;
        }
        if (isIdentifier(target, "globalThis")) {
          context.report({
            node,
            messageId: "rejectModifyGlobalThis",
          });
        }
      },
      CallExpression(node) {
        const calleeStr = calleeToString(node.callee);
        if (calleeStr.endsWith(".deserialize")) {
          return;
        }

        for (const arg of node.arguments) {
          if (isIdentifier(arg, "globalThis")) {
            context.report({
              node,
              messageId: "rejectPassingGlobalThis",
            });
          }
        }
      },
    };
  },
};