@@ -208,11 +208,40 @@ const create = Components.detect(
208
208
// @ts -expect-error
209
209
const name = node . object . name ;
210
210
const scopeType = context . getScope ( ) . type ;
211
- if (
211
+
212
+ // check if the window usage is behind a typeof window === 'undefined' check
213
+ const conditionalExpressionNode = node . parent ?. parent ;
214
+ const isWindowCheck =
215
+ conditionalExpressionNode ?. type === "ConditionalExpression" &&
216
+ conditionalExpressionNode . test ?. type === "BinaryExpression" &&
217
+ conditionalExpressionNode . test . left ?. type === "UnaryExpression" &&
218
+ conditionalExpressionNode . test . left . operator === "typeof" &&
219
+ conditionalExpressionNode . test . left . argument ?. type === "Identifier" &&
220
+ conditionalExpressionNode . test . left . argument ?. name === "window" &&
221
+ conditionalExpressionNode . test . right ?. type === "Literal" &&
222
+ conditionalExpressionNode . test . right . value === "undefined" ;
223
+
224
+ // checks to see if it's `typeof window !== 'undefined'` or `typeof window === 'undefined'`
225
+ const isNegatedWindowCheck =
226
+ isWindowCheck &&
227
+ conditionalExpressionNode . test ?. type === "BinaryExpression" &&
228
+ conditionalExpressionNode . test . operator === "!==" ;
229
+
230
+ // checks to see if window is being accessed safely behind a window check
231
+ const isSafelyBehindWindowCheck =
232
+ ( isWindowCheck &&
233
+ ! isNegatedWindowCheck &&
234
+ conditionalExpressionNode . alternate === node ?. parent ) ||
235
+ ( isNegatedWindowCheck &&
236
+ conditionalExpressionNode . consequent === node ?. parent ) ;
237
+
238
+ if (
212
239
undeclaredReferences . has ( name ) &&
213
240
browserOnlyGlobals . has ( name ) &&
214
- ( scopeType === "module" || ! ! util . getParentComponent ( node ) )
241
+ ( scopeType === "module" || ! ! util . getParentComponent ( node ) ) &&
242
+ ! isSafelyBehindWindowCheck
215
243
) {
244
+ // console.log(name, node.object)
216
245
instances . push ( name ) ;
217
246
reportMissingDirective ( "addUseClientBrowserAPI" , node . object ) ;
218
247
}
0 commit comments