-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
254 lines (231 loc) · 7.68 KB
/
index.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
const { browser: browserGlobals, node: nodeGlobals } = require("globals");
const browserGlobalNames = Object.keys(browserGlobals);
const nodeGlobalNames = Object.keys(nodeGlobals);
const browserOnlyGlobals = browserGlobalNames.filter(
(name) => !nodeGlobalNames.includes(name),
);
module.exports = {
rules: {
"no-ssr-browser-globals": {
meta: {
type: "problem",
docs: {
description:
"Disallow browser-specific globals (e.g., `window`, `document`) in SSR contexts.",
category: "Possible Errors",
recommended: true,
},
schema: [
{
type: "object",
properties: {
allowedGlobals: {
type: "array",
items: { type: "string" },
default: [],
},
allowedHooks: {
type: "array",
items: { type: "string" },
default: ["useEffect", "useLayoutEffect"],
},
allowedFunctions: {
type: "array",
items: { type: "string" },
default: ["setTimeout", "setInterval"],
},
conditionCheck: { type: "boolean", default: true },
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || {};
const allowedGlobals = nodeGlobalNames.concat(
options.allowedGlobals || [],
);
const allowedHooks = options.allowedHooks || [
"useEffect",
"useLayoutEffect",
];
const allowedFunctions = options.allowedFunctions || [
"setTimeout",
"setInterval",
"requestAnimationFrame",
];
const conditionCheck = options.conditionCheck !== false;
// Ensure this rule runs only on JSX/TSX files
if (!/\.(jsx|tsx)$/i.test(context.getFilename())) {
return {};
}
/**
* Determines whether the given node is inside a safe client-side context.
* @param {ASTNode} node - The current AST node.
* @returns {boolean} True if the node is in a safe context, false otherwise.
*/
function isSafeContext(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode();
let current = node;
const parent = node.parent;
/**
* ```
* const obj = { location: 'localhost' }; // allowed
* ```
* */
if (
parent.type === "Property" &&
parent.key === node &&
!parent.computed // Static key
) {
return true;
}
/**
* Check for member expressions like `obj.location`
* ```
* const host = location.host; // not allowed
*
* const obj = { location: 'localhost' };
* const host = obj.location; // allowed
* ```
* */
if (
node.parent.type === "MemberExpression" &&
node.parent.property === node
) {
return true;
}
while (current) {
// TS types are allowed
if (
current.type === "TSTypeLiteral" ||
current.type === "TSTypeAnnotation" ||
current.type === "TSTypeReference" ||
current.type === "TSTypeAliasDeclaration"
) {
return true;
}
// Check React hooks like useEffect and useLayoutEffect
if (
current.type === "CallExpression" &&
current.callee.type === "Identifier" &&
allowedHooks.includes(current.callee.name)
) {
return true;
}
// Check browser-specific async functions like setTimeout
if (
current.type === "CallExpression" &&
current.callee.type === "Identifier" &&
allowedFunctions.includes(current.callee.name)
) {
return true;
}
// Check event handlers like onClick or onChange
if (
current.type === "JSXAttribute" &&
current.name.type === "JSXIdentifier"
) {
const attributeName = current.name.name;
/**
* onClick √
* onclick ✗
*/
if (
attributeName.startsWith("on") &&
attributeName[2] === attributeName[2].toUpperCase()
) {
return true;
}
}
if (current.type === "ImportExpression") {
// Check dynamic imports
return true;
}
// Check for window !== 'undefined' condition
if (
conditionCheck &&
current.type === "IfStatement" &&
current.test.type === "BinaryExpression" &&
current.test.operator === "!=="
) {
const left = current.test.left;
const right = current.test.right;
if (left.name === "window" && right.name === "undefined") {
return true;
}
}
const comments = sourceCode.getCommentsBefore(current);
const directComments = comments.filter((comment) => {
return node.loc.start.line - comment.loc.end.line === 1;
});
// Check for client-side annotations
if (
directComments.some(
(comment) => comment.value.trim() === "@client",
)
) {
return true;
}
current = current.parent;
}
return false;
}
/**
* Checks for disallowed usage of browser-specific globals.
* @param {ASTNode} node - The current AST node.
*/
return {
Identifier(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode();
const variablesInScope = sourceCode.getScope(node).variables;
/**
* Check if the identifier is a browser-specific global and it is not declared in the current scope.
*
* For example:
* Location is a browser-only global, so it will be flagged as an error if used in a server-side context.
* But if it is declared in the current scope, it will be allowed.
* ```
* // Allowed
* const location = 'localhost';
*
* // Not allowed
* const value = location.host;
* ```
*/
if (
!(
browserOnlyGlobals.includes(node.name) &&
!variablesInScope.some(
(variable) => variable.name === node.name,
) &&
!allowedGlobals.includes(node.name)
)
) {
return;
}
// Report an error if the node is not in a safe client-side context
if (!isSafeContext(node)) {
context.report({
node,
message: `'${node.name}' is not allowed in a server-side context. Wrap it in a client-side safe context, such as useEffect or an event handler, or mark it with @client annotation.
---------------------------
// @client
const value = location.host;
-----------
`,
});
}
},
};
},
},
},
configs: {
recommended: {
rules: {
"no-ssr-browser-globals": "error",
},
},
},
};