{"id":16262,"library":"uvm","title":"UVM (Universal Virtual Machine)","description":"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.","status":"active","version":"4.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/postmanlabs/uvm","tags":["javascript","vm","worker","contextify","postman"],"install":[{"cmd":"npm install uvm","lang":"bash","label":"npm"},{"cmd":"yarn add uvm","lang":"bash","label":"yarn"},{"cmd":"pnpm add uvm","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For modern Node.js environments (>=18) and browser bundlers, ESM import is the preferred method for the main UVM object. The library is dual-published or transpiled to support both, but ESM is recommended for new projects.","wrong":"const uvm = require('uvm');","symbol":"uvm","correct":"import uvm from 'uvm';"},{"note":"CommonJS `require` is supported, as shown in the README, for compatibility with older Node.js projects or specific build setups. Use this if your project does not support ESM.","wrong":"import uvm from 'uvm';","symbol":"uvm","correct":"const uvm = require('uvm');"},{"note":"`spawn` is a static method of the default `uvm` export, not a named export itself. It's the primary function for creating new isolated virtual machine contexts.","wrong":"import { spawn } from 'uvm';","symbol":"spawn","correct":"import uvm from 'uvm';\nconst context = uvm.spawn({ /* options */ });"}],"quickstart":{"code":"import uvm from 'uvm';\n\nconst context = uvm.spawn({\n    bootCode: `\n        // Code running inside the isolated VM/Worker context\n        bridge.on('loopback', function (data) {\n            console.log(`VM received: ${data}`);\n            bridge.dispatch('loopback', data + ' World!');\n        });\n        // Example of handling potential errors inside the VM\n        try {\n            // Some potentially error-prone code\n            // throw new Error('Simulated VM error');\n        } catch (e) {\n            bridge.dispatch('error', e.message);\n        }\n    `\n});\n\ncontext.on('loopback', function (data) {\n    console.log(`Main context received: ${data}`); // Expected: Hello World!\n});\n\ncontext.on('error', function (errorMessage) {\n    console.error(`VM Error: ${errorMessage}`);\n});\n\ncontext.dispatch('loopback', 'Hello');\n\n// To demonstrate cleanup (important for resource management)\nsetTimeout(() => {\n    console.log('Disconnecting UVM context...');\n    context.disconnect();\n}, 1000);\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Review the official GitHub release notes for your target version. Update import statements (`require` to `import`) and ensure your Node.js environment meets the `engines.node` requirement (>=18 for v4.x). Verify data serialization for cross-context communication.","message":"UVM `v3.x` and `v4.x` likely introduced breaking changes related to ESM support and Node.js Worker Threads APIs. Projects upgrading from older `v2.x` versions, especially those relying solely on CommonJS or targeting older Node.js versions, may require code adjustments. Always consult the GitHub releases for specific upgrade guides.","severity":"breaking","affected_versions":">=3.0"},{"fix":"Ensure all data passed via `bridge.dispatch` or in `bootCode` options consists of primitive values, plain objects, arrays, or other structured clone algorithm compatible types. Avoid passing functions, DOM elements, or class instances directly.","message":"Data passed between the main context and the spawned UVM context (Node.js Worker Thread or Web Worker) must be serializable. Complex objects, functions, or non-primitive data types might not transfer correctly or may throw serialization errors.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Explicitly pass any necessary configuration, initial data, or environment variables to the UVM context via the `spawn` options or by dispatching events after the context has booted. Understand that functions and objects cannot be directly shared, only their serializable data representations.","message":"The code executed within the UVM `bootCode` runs in an isolated scope. It does not have direct access to variables or globals from the main application context unless explicitly passed during `spawn` or through the `bridge` mechanism. This isolation is by design for security and stability but can be a source of confusion.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"For highly critical security requirements, consider additional layers of security like running worker processes with restrictive permissions, using containerization, or specialized sandboxing solutions (e.g., `vm2`, though it has also faced vulnerabilities). Do not solely rely on UVM for absolute security against untrusted code.","message":"While UVM provides an isolated environment, it's not a complete security sandbox for running arbitrary, malicious untrusted code, especially in Node.js. Node.js's native `vm` module and `worker_threads` have known limitations regarding true sandboxing against sophisticated attacks.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"If your project is ESM, change `const uvm = require('uvm');` to `import uvm from 'uvm';`. Ensure your `package.json` has `\"type\": \"module\"` or use `.mjs` file extensions for ESM.","cause":"Attempting to use CommonJS `require` syntax in an ESM module context when `uvm` is imported as an ESM module, or when the project is configured for ESM-only.","error":"TypeError: require is not a function"},{"fix":"Before dispatching data across the `bridge`, ensure that the data is structured clone algorithm compatible. Convert complex objects into plain JavaScript objects (POJOs), serialize functions to strings, or extract only necessary primitive values.","cause":"Attempting to pass a non-serializable object (e.g., a DOM element, a function, or a complex class instance) across the UVM bridge to or from a Web Worker.","error":"Uncaught DOMException: Failed to execute 'postMessage' on 'Worker': An object could not be cloned."},{"fix":"Ensure that `bridge.on` and `bridge.dispatch` calls are exclusively within the `bootCode` string provided to `uvm.spawn`, which defines the code to run inside the isolated VM/Worker. The main context interacts via `context.on` and `context.dispatch`.","cause":"This error typically occurs if `bridge.on` or `bridge.dispatch` is called outside the `bootCode` context or before the UVM context has fully initialized and established its `bridge` object.","error":"ReferenceError: bridge is not defined"}],"ecosystem":"npm"}