notevil

repository·master·Indexed 41 days ago

https://github.com/mmckegg/notevil

A JavaScript library for safely evaluating code using a sandboxed context to prevent access to the global environment. Features include safeEval() for source evaluation and FunctionFactory for creating reusable sandboxed functions.

Tokens
714
Snippets
3
Records
3
Agent score
2%

What's inside notevil

  1. Execute code safely with safeEval()

    master

    Use safeEval(src, parentContext) to evaluate JavaScript source code within a controlled environment. This prevents the code from accessing the global scope or sensitive properties by running it against a sandboxed context. You can optionally provide a parentContext object to act as the base for the sandbox.

    safeEval is also available as the .eval property of the module.

    const safeEval = require('notevil');
    
    // Basic usage
    const result = safeEval('1 + 1');
    
    // Usage with a custom context
    const context = { a: 10 };
    const resultWithContext = safeEval('a + 5', context);
  2. Create sandboxed functions with FunctionFactory

    master

    If you need to execute the same sandboxed code multiple times with different arguments, use FunctionFactory(parentContext). This returns a constructor that creates new functions, each running in a controlled environment derived from the provided parentContext.

    When calling the generated function, the last argument is treated as the source code string, and all preceding arguments are treated as function parameters.

    const { FunctionFactory } = require('notevil');
    
    // Create a factory with a base context
    const MyFunction = FunctionFactory({ multiplier: 2 });
    
    // The last argument is the source code.
    // Preceding arguments are passed as parameters to that code.
    const addAndMultiply = MyFunction('a', 'b', 'return (a + b) * multiplier;');
    
    console.log(addAndMultiply(1, 2)); // Outputs: 6
  3. Use the pre-built Function constructor

    master

    The module exports a pre-instantiated Function object (created via FunctionFactory()). This allows you to create sandboxed functions immediately without manually calling the factory.

    Just like the factory, the last argument passed to the function is the source code string, and all arguments before it are the parameters for that code.

    const { Function } = require('notevil');
    
    // Create a function: params are 'x' and 'y', source is the last arg
    const squareSum = Function('x', 'y', 'return (x * x) + (y * y);');
    
    console.log(squareSum(3, 4)); // Outputs: 25