1 import { AST_NODE_TYPES, TSESLint, TSESTree } from "@typescript-eslint/utils"
2 import { createRule } from "../../create-rule"
3 import { isAdminFile } from "../../util/admin-scope"
4
5 type MessageIds = "useImportMetaEnv"
6
7 /**
8 * True when `process` resolves to a local binding (a function param, a
9 * `const process = ...`, an import, etc.) rather than the Node.js global.
10 * In that case `process.env` isn't the Node env object and must not be flagged.
11 */
12 function processBindingIsLocal(scope: TSESLint.Scope.Scope | null): boolean {
13 let current = scope
14 while (current) {
15 const variable = current.variables.find((v) => v.name === "process")
16 if (variable) {
17 // `defs.length > 0` means a real declaration in user code, i.e. a shadow.
18 // The Node global, if present, is a variable with no defs.
19 return variable.defs.length > 0
20 }
21 current = current.upper
22 }
23 return false
24 }
25
26 export const rule = createRule<[], MessageIds>({
27 name: "admin-env-vars-import-meta",
28 meta: {
29 type: "suggestion",
30 docs: {
31 description:
32 "Admin code is bundled for the browser by Vite — use `import.meta.env` instead of `process.env` for environment variables.",
33 },
34 fixable: "code",
35 messages: {
36 useImportMetaEnv:
37 "Admin code runs in the browser via Vite, where `process.env` is undefined. Use `import.meta.env` (e.g. `import.meta.env.VITE_*`) instead.",
38 },
39 schema: [],
40 },
41 defaultOptions: [],
42 create(context) {
43 // Scope to the admin dashboard tree; `process.env` is fine everywhere else
44 // (including API admin routes under `src/api/admin/`).
45 if (!isAdminFile(context.filename)) {
46 return {}
47 }
48
49 return {
50 MemberExpression(node: TSESTree.MemberExpression) {
51 // Match the `process.env` member expression itself (not `process.env.X`,
52 // whose `.object` is this node). Reporting here covers both bare
53 // `process.env` access and any `process.env.FOO` lookup in one place.
54 if (node.computed) {
55 return
56 }
57 if (
58 node.object.type !== AST_NODE_TYPES.Identifier ||
59 node.object.name !== "process"
60 ) {
61 return
62 }
63 if (
64 node.property.type !== AST_NODE_TYPES.Identifier ||
65 node.property.name !== "env"
66 ) {
67 return
68 }
69
70 if (processBindingIsLocal(context.sourceCode.getScope(node))) {
71 return
72 }
73
74 context.report({
75 node,
76 messageId: "useImportMetaEnv",
77 fix(fixer) {
78 return fixer.replaceText(node, "import.meta.env")
79 },
80 })
81 },
82 }
83 },
84 })
85
86 export default rule