Sval JavaScript Interpreter

0.6.12 · active · verified Sun Apr 19

Sval is a JavaScript interpreter written entirely in JavaScript, leveraging the Acorn parser to support modern ECMAScript features while maintaining compatibility with ES5 environments. As of version 0.6.12, it provides robust capabilities for executing JavaScript code in either an isolated sandbox or an invasive mode, depending on user requirements. This flexibility makes it particularly useful for environments where native `eval`, `setTimeout`, or `new Function` might be disabled or restricted due to security policies. The package is actively maintained, with frequent updates addressing bug fixes and dependency bumps, ensuring ongoing support for new JavaScript syntax and improved stability. Key differentiators include its ability to run cutting-edge ES features on older runtimes and its explicit support for both script and module source types, alongside TypeScript type definitions for enhanced developer experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a `Sval` interpreter instance, configure it with options, import host functions and variables, and execute a JavaScript string in a sandboxed environment.

import Sval from 'sval';

const interpreter = new Sval({
  ecmaVer: 'latest', // Support latest ECMAScript features
  sourceType: 'script', // Treat code as a standard script
  sandBox: true, // Run code in an isolated environment (recommended)
});

// Import host-environment variables or modules into the interpreter's scope
interpreter.import({
  log: console.log,
  greet: (name: string) => `Hello, ${name} from interpreter!`,
});

try {
  // Execute JavaScript code as a string
  interpreter.run(`
    const message = greet('Sval User');
    log(message);
    
    const sum = (a, b) => a + b;
    log('2 + 3 =', sum(2, 3));

    // Accessing built-in globals like Math
    log('Math.PI =', Math.PI);
  `);
} catch (error) {
  console.error('Interpreter Error:', error);
}

view raw JSON →