UVM (Universal Virtual Machine)

4.0.1 · active · verified Tue Apr 21

UVM (Universal Virtual Machine) is a JavaScript library designed to provide a consistent API for executing code in isolated contexts, leveraging Node.js Worker Threads and Web Workers in browser environments. This abstraction simplifies cross-context communication via an event emitter-based bridge, enabling developers to run potentially untrusted or computationally intensive code without blocking the main thread. Currently at version 4.0.1 (last published 10 months ago, as of current date), the library appears to be actively maintained. Its key differentiator lies in offering a 'universal' approach to sandboxed code execution, providing a unified development experience across different JavaScript runtimes, making it suitable for applications requiring secure and efficient off-main-thread processing. The project originates from Postman Labs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an isolated UVM context, send data to it, receive data back using an event emitter bridge, and handle basic lifecycle events including disconnection for resource management. It showcases cross-context communication between the main process/thread and the UVM sandbox.

import uvm from 'uvm';

const context = uvm.spawn({
    bootCode: `
        // Code running inside the isolated VM/Worker context
        bridge.on('loopback', function (data) {
            console.log(`VM received: ${data}`);
            bridge.dispatch('loopback', data + ' World!');
        });
        // Example of handling potential errors inside the VM
        try {
            // Some potentially error-prone code
            // throw new Error('Simulated VM error');
        } catch (e) {
            bridge.dispatch('error', e.message);
        }
    `
});

context.on('loopback', function (data) {
    console.log(`Main context received: ${data}`); // Expected: Hello World!
});

context.on('error', function (errorMessage) {
    console.error(`VM Error: ${errorMessage}`);
});

context.dispatch('loopback', 'Hello');

// To demonstrate cleanup (important for resource management)
setTimeout(() => {
    console.log('Disconnecting UVM context...');
    context.disconnect();
}, 1000);

view raw JSON →