Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,24 @@ describe('custom path evaluation works as expected', () => {
expect(evaluateFirstStatement('const x = Math.min(1, 2, 3);', {})).toBe(1);
});

test('Evaluates built-in functions without the Node global alias', () => {
const globalDescriptor = Object.getOwnPropertyDescriptor(
globalThis,
'global',
);
Reflect.deleteProperty(globalThis, 'global');
Comment on lines +127 to +131

try {
expect(
evaluateFirstStatement('const x = Math.max(Number(1), Number(2));', {}),
).toBe(2);
} finally {
if (globalDescriptor) {
Object.defineProperty(globalThis, 'global', globalDescriptor);
}
}
});

test('Evaluates custom functions', () => {
function makeArray(...args) {
return [...args].reverse();
Expand Down
10 changes: 7 additions & 3 deletions packages/@stylexjs/babel-plugin/src/utils/evaluate-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ import fs from 'node:fs';

// This file contains Babels metainterpreter that can evaluate static code.

// This evaluator also ships in a browser bundle, where Node's `global` alias
// does not exist.
const globalObject: any = globalThis;

const VALID_CALLEES = ['String', 'Number', 'Math', 'Object', 'Array'];

// The static methods that may be called on the globals in `VALID_CALLEES`.
Expand Down Expand Up @@ -159,7 +163,7 @@ function isBlockedFunction(fn: mixed): boolean {
Object.getPrototypeOf(callable) === Function ||
// Referenced, never called: this is a value the evaluator refuses to run.
// eslint-disable-next-line no-eval
callable === global.eval
callable === globalObject.eval
);
}

Expand Down Expand Up @@ -1078,7 +1082,7 @@ function _evaluate(path: NodePath<>, state: State): any {
!path.scope.getBinding(callee.node.name) &&
isValidCallee(callee.node.name)
) {
func = global[callee.node.name];
func = globalObject[callee.node.name];
} else if (
callee.isIdentifier() &&
getOwnProperty(state.functions.identifiers, callee.node.name)
Expand All @@ -1103,7 +1107,7 @@ function _evaluate(path: NodePath<>, state: State): any {
isValidCallee(object.node.name) &&
isValidCalleeMethod(object.node.name, property.node.name)
) {
context = global[object.node.name];
context = globalObject[object.node.name];
// @ts-expect-error property may not exist in context object
func = context[property.node.name];
} else {
Expand Down
Loading