npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@aiconnect/codelets-runner

v0.2.0

Published

Minimal, secure runtime for executing untrusted JavaScript codelets with vm2 sandboxing

Readme

@aiconnect/codelets-runner

Minimal, secure runtime for executing untrusted JavaScript codelets with vm2 sandboxing.

Overview

The Codelets Runner provides a safe, isolated environment for executing small JavaScript code snippets ("codelets") with:

  • vm2-based sandboxing: Default-deny security policy
  • Timeout enforcement: Prevents infinite loops (default: 2000ms)
  • Console capture: Captures console.log/info/warn/error with timestamps
  • Structured error handling: Standardized error codes and sanitized messages
  • TypeScript-first: Full type safety with ESM + CJS support

Installation

npm install @aiconnect/codelets-runner

Basic Usage

import { runCodelet } from '@aiconnect/codelets-runner';

// Define a codelet (must export async function main)
const codeletSource = {
  type: 'string' as const,
  code: `
    export async function main(input, { logger }) {
      logger.info('Processing input:', input);
      return { result: input.value * 2 };
    }
  `
};

// Run the codelet
const result = await runCodelet(codeletSource, {
  input: { value: 21 },
  timeout_ms: 2000
});

if (result.ok) {
  console.log('Result:', result.value); // { result: 42 }
  console.log('Logs:', result.logs);
} else {
  console.error('Error:', result.error);
}

API

runCodelet(source, options)

Executes a codelet and returns a result.

Parameters:

  • source: CodeletSource - The codelet source code
    • type: 'string' - Only string sources supported in MVP
    • code: string - JavaScript code that exports async function main(input, helpers)
    • export_name?: string - Name of exported function (default: 'main')
  • options: CodeletRunOptions - Execution options
    • input?: unknown - Input data passed to codelet
    • timeout_ms?: number - Timeout in milliseconds (default: 2000)
    • globals?: Record<string, unknown> - Read-only global variables

Returns: Promise<CodeletResult>

  • ok: boolean - Whether execution succeeded
  • value?: unknown - Return value if successful
  • error?: CodeletError - Error details if failed
  • logs: ConsoleLog[] - Captured console output (max 100 logs)
  • duration_ms: number - Execution time in milliseconds

createCodeletRunner()

Creates a reusable runner instance (factory function).

import { createCodeletRunner } from '@aiconnect/codelets-runner';

const runner = createCodeletRunner();
const result = await runner.run(source, options);
runner.dispose(); // Clean up resources

Codelet Signature

All codelets must export a main function with this signature:

export async function main(input: unknown, helpers: { logger: Logger }): Promise<unknown> {
  // Your code here
  return result;
}

Helpers (MVP):

  • logger.info(message) - Log info message
  • logger.warn(message) - Log warning message
  • logger.error(message) - Log error message

Error Codes

  • TIMEOUT - Execution exceeded timeout
  • SYNTAX_ERROR - Invalid JavaScript syntax
  • RUNTIME_ERROR - Unhandled exception in codelet
  • POLICY_VIOLATION - Attempted disallowed capability (require, eval, etc.)

Compatibility

| Component | Version/Support | |-----------|----------------| | Node.js | >= 18.x | | Module Systems | ESM and CJS (via package.json exports) | | TypeScript | >= 4.5 (optional, types included) | | vm2 | 3.10.0 (pinned) |

Known Issues and Limitations

vm2 Timeout Limitations

⚠️ Important: vm2's timeout mechanism has significant limitations and cannot interrupt:

  • Tight synchronous loops: while(true) {}, tight for loops without async yields
  • Native timer functions: setTimeout(), setInterval(), setImmediate() (run outside VM control)
  • Native function calls: Frequent calls to Date.now(), Math.random(), etc. may not be interrupted

Example of non-interruptible code:

// This CANNOT be interrupted by vm2 timeout - will hang indefinitely
export async function main(input) {
  while (true) {} // Infinite loop
}

// This ALSO cannot be interrupted - setTimeout runs outside VM
export async function main(input) {
  await new Promise(r => setTimeout(r, 60000));
}

Workaround: Always run the codelet runner with external process monitoring:

  • Docker: --cpus="0.5" --memory="512m" --pids-limit=100
  • Kubernetes: resources.limits.cpu and resources.limits.memory
  • systemd: CPUQuota=50% and MemoryLimit=512M
  • Node.js: --max-old-space-size=512

See Integration Guide for detailed examples.

No Memory Limits

The runner does not enforce memory limits in this MVP. Memory-bound codelets can cause OOM (Out of Memory) errors. Use external resource limits (see above).

CPU-Bound Codelets

Avoid running CPU-intensive codelets without external safeguards. The sandbox provides execution isolation but not resource isolation.

Operational Recommendations

For Production Deployments:

  1. Always use external resource limits (Docker/K8s/systemd)
  2. Monitor execution metrics: CPU, memory, duration, error rates
  3. Set appropriate timeouts: 2-5 seconds for most use cases
  4. Alert on anomalies: Frequent timeouts may indicate malicious codelets

See the Integration Guide for comprehensive operational guidance.

Security & Limitations (MVP)

Security Policy (Default-Deny):

  • No require() or module imports
  • No network access
  • No filesystem access
  • No eval() or dynamic code generation
  • Frozen global scope

MVP Limitations:

  • JavaScript-only (no TypeScript transpilation)
  • String sources only (no file or module loading)
  • No memory limits (timeout only)
  • No allowlist support (all capabilities denied)
  • Basic error sanitization (regex-based path stripping)
  • Console capture limited to 100 logs per execution

Dependencies:

Monitoring: Actively monitor vm2 security advisories. See project SECURITY.md for CVE tracking.

Post-MVP Features

The following features are deferred to future releases:

  • Policy allowlists (require, env, network)
  • Deterministic execution (seeded PRNG, controllable clock)
  • Memory and CPU limits
  • Observable execution (metrics, events)
  • Context pooling
  • Alternative sandbox adapters (node:vm, isolated-vm)
  • Advanced helpers (env, random, now, fetch)

License

MIT