open-index/open-npm huggingface dataset:
npm package: @ricsam/isolate-core
Description: Core utilities and class builder for isolated-vm V8 sandbox bindings
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-core

Core utilities and Web Streams API for isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-core
```

## Usage

```typescript
import { setupCore } from "@ricsam/isolate-core";

const handle = await setupCore(context);
```

## Injected Globals

- `ReadableStream`, `WritableStream`, `TransformStream`
- `ReadableStreamDefaultReader`, `WritableStreamDefaultWriter`
- `Blob`, `File`
- `URL`, `URLSearchParams`
- `DOMException`
- `DOMParser`
- `Node`, `Document`, `DocumentFragment`, `DocumentType`, `Element`, `Attr`, `Text`, `Comment`
- `Event`, `EventTarget`, `CustomEvent`
- `AbortController`, `AbortSignal`
- `TextEncoder`, `TextDecoder`

## Usage in Isolate

```javascript
// Streams
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue("chunk1");
    controller.enqueue("chunk2");
    controller.close();
  }
});

const reader = stream.getReader();
const { value, done } = await reader.read();

// Blob
const blob = new Blob(["hello", " ", "world"], { type: "text/plain" });
const text = await blob.text(); // "hello world"

// File
const file = new File(["content"], "file.txt", { type: "text/plain" });
console.log(file.name); // "file.txt"
```

## License

MIT
npm package: @ricsam/isolate-crypto
Description: Web Crypto API implementation for isolated-vm V8 sandbox
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-crypto

Web Crypto API implementation for isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-crypto
```

## Usage

```typescript
import { setupCrypto } from "@ricsam/isolate-crypto";

const handle = await setupCrypto(context);
```

## Injected Globals

- `crypto.getRandomValues(array)` - Fill a TypedArray with random bytes
- `crypto.randomUUID()` - Generate a random UUID v4
- `crypto.subtle` - SubtleCrypto interface for cryptographic operations

## Usage in Isolate

```javascript
// Generate random bytes
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);

// Generate UUID
const uuid = crypto.randomUUID();
console.log(uuid); // "550e8400-e29b-41d4-a716-446655440000"

// Hash data with SHA-256
const data = new TextEncoder().encode("Hello, World!");
const hash = await crypto.subtle.digest("SHA-256", data);

// Generate encryption key
const key = await crypto.subtle.generateKey(
  { name: "AES-GCM", length: 256 },
  true,
  ["encrypt", "decrypt"]
);

// Encrypt data
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
  { name: "AES-GCM", iv },
  key,
  data
);

// Decrypt data
const decrypted = await crypto.subtle.decrypt(
  { name: "AES-GCM", iv },
  key,
  encrypted
);
```

## SubtleCrypto Methods

| Method | Description |
|--------|-------------|
| `digest` | Generate hash (SHA-256, SHA-384, SHA-512) |
| `generateKey` | Generate symmetric or asymmetric keys |
| `sign` / `verify` | Sign and verify data (HMAC, ECDSA) |
| `encrypt` / `decrypt` | Encrypt and decrypt data (AES-GCM, AES-CBC) |
| `importKey` / `exportKey` | Import/export keys (raw, jwk, pkcs8, spki) |
| `deriveBits` / `deriveKey` | Derive keys (PBKDF2, ECDH) |
| `wrapKey` / `unwrapKey` | Wrap/unwrap keys for secure transport |

**See also:** [MDN Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)

## License

MIT
npm package: @ricsam/isolate-encoding
Description: Base64 encoding APIs (atob, btoa) for isolated-vm V8 sandbox
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-encoding

Base64 encoding and decoding via `atob` and `btoa` for isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-encoding
```

## Usage

```typescript
import { setupEncoding } from "@ricsam/isolate-encoding";

const handle = await setupEncoding(context);
```

## Injected Globals

- `atob(encodedData)` - Decode a Base64-encoded string
- `btoa(stringToEncode)` - Encode a string to Base64

## Usage in Isolate

```javascript
// Encode string to Base64
const encoded = btoa("Hello, World!");
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode Base64 to string
const decoded = atob("SGVsbG8sIFdvcmxkIQ==");
console.log(decoded); // "Hello, World!"

// Common use case: encoding JSON for transport
const data = { user: "john", token: "abc123" };
const base64Data = btoa(JSON.stringify(data));

// Decode it back
const originalData = JSON.parse(atob(base64Data));
```

## Error Handling

```javascript
// btoa throws for characters outside Latin1 range (0-255)
try {
  btoa("Hello 世界"); // Throws DOMException
} catch (e) {
  console.error("Cannot encode non-Latin1 characters");
}

// atob throws for invalid Base64
try {
  atob("not valid base64!!!");
} catch (e) {
  console.error("Invalid Base64 string");
}
```

## License

MIT
npm package: @ricsam/isolate-fs
Description: File system API implementation for isolated-vm V8 sandbox
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-fs

File System Access API (OPFS-compatible) for isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-fs
```

## Usage

```typescript
import { setupFs } from "@ricsam/isolate-fs";

const handle = await setupFs(context, {
  // Return a FileSystemHandler for the given directory path
  getDirectory: async (path) => {
    // Validate path access
    if (!path.startsWith("/allowed")) {
      throw new Error("Access denied");
    }
    return createNodeFileSystemHandler(`./sandbox${path}`);
  },
});
```

## Injected Globals

- `getDirectory(path)` - Entry point for file system access
- `FileSystemDirectoryHandle`, `FileSystemFileHandle`
- `FileSystemWritableFileStream`

## Usage in Isolate

```javascript
// Get directory handle
const root = await getDirectory("/data");

// Read a file
const fileHandle = await root.getFileHandle("config.json");
const file = await fileHandle.getFile();
const text = await file.text();
const config = JSON.parse(text);

// Write a file
const outputHandle = await root.getFileHandle("output.txt", { create: true });
const writable = await outputHandle.createWritable();
await writable.write("Hello, World!");
await writable.close();

// Directory operations
const subDir = await root.getDirectoryHandle("subdir", { create: true });
await root.removeEntry("old-file.txt");
await root.removeEntry("old-dir", { recursive: true });

// Iterate directory
for await (const [name, handle] of root.entries()) {
  console.log(name, handle.kind); // "file" or "directory"
}
```

## License

MIT
npm package: @ricsam/isolate-path
Description: POSIX path utilities (join, resolve, dirname, basename, etc.) for isolated-vm V8 sandbox
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-path

Node.js-compatible path utilities for POSIX paths in isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-path
```

## Usage

```typescript
import { setupPath } from "@ricsam/isolate-path";

// Default: uses "/" as working directory
const handle = await setupPath(context);

// Custom working directory for path.resolve()
const handle = await setupPath(context, { cwd: "/home/user/project" });
```

## Options

- `cwd` - Current working directory for `path.resolve()`. Defaults to `"/"`.

## Injected Globals

- `path.join(...paths)` - Join path segments
- `path.resolve(...paths)` - Resolve to absolute path (uses configured `cwd` as base)
- `path.normalize(path)` - Normalize a path
- `path.basename(path, ext?)` - Get file name
- `path.dirname(path)` - Get directory name
- `path.extname(path)` - Get file extension
- `path.isAbsolute(path)` - Check if path is absolute
- `path.parse(path)` - Parse into components
- `path.format(obj)` - Format from components
- `path.relative(from, to)` - Get relative path
- `path.sep` - Path separator (`/`)
- `path.delimiter` - Path delimiter (`:`)
- `path.posix` - Alias to `path` (POSIX-only implementation)

## Usage in Isolate

```javascript
// Join paths
path.join('/foo', 'bar', 'baz'); // "/foo/bar/baz"
path.join('foo', 'bar', '..', 'baz'); // "foo/baz"

// Resolve to absolute (relative paths use configured cwd)
path.resolve('foo/bar'); // Uses cwd + "/foo/bar"
path.resolve('/foo', 'bar'); // "/foo/bar" (absolute paths ignore cwd)

// Parse and format
const parsed = path.parse('/foo/bar/baz.txt');
// { root: "/", dir: "/foo/bar", base: "baz.txt", ext: ".txt", name: "baz" }

path.format({ dir: '/foo/bar', base: 'baz.txt' }); // "/foo/bar/baz.txt"

// Other utilities
path.basename('/foo/bar/baz.txt'); // "baz.txt"
path.dirname('/foo/bar/baz.txt'); // "/foo/bar"
path.extname('file.tar.gz'); // ".gz"
path.isAbsolute('/foo'); // true
```

## License

MIT
npm package: @ricsam/isolate-protocol
Description: Binary protocol for communication between isolate daemon and client
Author: ricsam
Latest version: 0.1.23

# @ricsam/isolate-protocol

Binary protocol for daemon-client communication. Uses MessagePack for efficient serialization.

## Installation

```bash
npm add @ricsam/isolate-protocol
```

## Frame Format

```
┌──────────┬──────────┬─────────────────┐
│ Length   │ Type     │ Payload         │
│ (4 bytes)│ (1 byte) │ (MessagePack)   │
└──────────┴──────────┴─────────────────┘
```

## Features

- MessagePack serialization (5-10x faster than JSON)
- Request/response correlation via request IDs
- Bidirectional callbacks for console, fetch, and fs operations
- Streaming support for large request/response bodies
- Event streaming for Playwright console logs and network activity

## Playwright Contract Notes

The shared runtime contract is handler-first:

- `playwright.handler` is the public integration point
- convenience helpers (for example `defaultPlaywrightHandler(page)`) live in
  `@ricsam/isolate-playwright`
- page-mode options are intentionally not part of the protocol's public
  runtime options shape

## Usage

```typescript
import {
  createFrameParser,
  buildFrame,
  MessageType,
  type CreateRuntimeRequest,
  type ResponseOk,
} from "@ricsam/isolate-protocol";

// Build a frame to send
const request: CreateRuntimeRequest = {
  type: MessageType.CREATE_RUNTIME,
  requestId: 1,
  options: { memoryLimitMB: 128 },
};
const frame = buildFrame(request);

// Parse incoming frames
const parser = createFrameParser();
for (const { message } of parser.feed(data)) {
  if (message.type === MessageType.RESPONSE_OK) {
    console.log("Response:", (message as ResponseOk).data);
  }
}
```

## License

MIT
npm package: @ricsam/isolate-server
Description: Reusable lifecycle manager for namespaced isolate runtimes and entry-module startup
Author: ricsam
Latest version: 0.2.10

# @ricsam/isolate-server

Reusable server lifecycle manager for `@ricsam/isolate-client` runtimes.

`IsolateServer` wraps namespaced runtime lifecycle (`start`, `reload`, `close`) and provides a stable
`fetch` proxy that can auto-start from the last successful configuration.

## Installation

```bash
npm add @ricsam/isolate-server
```

## Usage

```ts
import { IsolateServer } from "@ricsam/isolate-server";
import { connect } from "@ricsam/isolate-client";

const connection = await connect({ socket: "/tmp/isolate.sock" });

const server = new IsolateServer({
  namespaceId: "project/main",
  getConnection: async () => connection,
});

await server.start({
  entry: "server.js",
  runtimeOptions: {
    moduleLoader: (specifier) => {
      if (specifier === "server.js") {
        return {
          code: `serve({ fetch: () => new Response("ok") });`,
          resolveDir: "/",
        };
      }
      throw new Error(`Unknown module: ${specifier}`);
    },
  },
});

const response = await server.fetch.dispatchRequest(new Request("http://localhost/"));
console.log(await response.text()); // "ok"

await server.reload();
await server.close();
```

## API

- `start(options)` configures and starts the runtime (idempotent when already running).
- `reload()` hard-disposes the current runtime and starts a fresh runtime with the last start options.
- `close()` disposes current runtime (idempotent).
- `getRuntime()` returns the active runtime or `null`.
- `fetch.*` proxies to runtime fetch methods and auto-starts after an initial `start()`.
npm package: @ricsam/isolate-test-utils
Description: Utilities for isolated-vm - run JavaScript in a sandboxed V8 environment with web-standard APIs
Author: ricsam
Latest version: 0.1.28

# @ricsam/isolate-test-utils

Testing utilities for isolated-vm V8 sandbox development.

## Installation

```bash
npm add @ricsam/isolate-test-utils
```

## Usage

```typescript
import { createRuntimeTestContext } from "@ricsam/isolate-test-utils";

// Create a test context with all APIs set up
const ctx = await createRuntimeTestContext({ fs: true });

// Set up mock response for fetch
ctx.setMockResponse({ status: 200, body: '{"data": "test"}' });

// Run code
await ctx.context.eval(`
  (async () => {
    console.log("Starting fetch...");
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log("Got data:", data);
  })()
`, { promise: true });

// Check captured logs
console.log(ctx.logs);
// [{ level: "log", stdout: "Starting fetch..." }, ...]

// Check captured fetch calls
console.log(ctx.fetchCalls);
// [{ url: "https://api.example.com/data", method: "GET", headers: [...] }]

// Cleanup
ctx.dispose();
```

## RuntimeTestContext

```typescript
interface RuntimeTestContext {
  isolate: ivm.Isolate;
  context: ivm.Context;
  tick(ms?: number): Promise<void>;
  dispose(): void;
  logs: Array<{ level: string; stdout: string }>;
  fetchCalls: Array<{ url: string; method: string; headers: [string, string][] }>;
  setMockResponse(response: MockResponse): void;
  mockFs: MockFileSystem;
}

interface MockResponse {
  status?: number;
  body?: string;
  headers?: Record<string, string>;
}
```

## Options

```typescript
interface RuntimeTestContextOptions {
  fs?: boolean; // Enable file system APIs with mock file system
}
```

## License

MIT
npm package: @ricsam/isolate-timers
Description: Timer APIs (setTimeout, setInterval, clearTimeout, clearInterval) for isolated-vm V8 sandbox
Author: ricsam
Latest version: 0.1.19

# @ricsam/isolate-timers

Timer APIs with real-time execution for isolated-vm V8 sandbox.

## Installation

```bash
npm add @ricsam/isolate-timers
```

## Usage

```typescript
import { setupTimers } from "@ricsam/isolate-timers";

const handle = await setupTimers(context);

// Timers fire automatically based on real time
// Clear all pending timers if needed
handle.clearAll();

// Dispose when done
handle.dispose();
```

## Injected Globals

- `setTimeout(callback, ms, ...args)` - Schedule delayed execution
- `setInterval(callback, ms, ...args)` - Schedule repeated execution
- `clearTimeout(id)` - Cancel a timeout
- `clearInterval(id)` - Cancel an interval

## Usage in Isolate

```javascript
// One-shot timer - fires automatically after 1 second
const timeoutId = setTimeout(() => {
  console.log("Fired after 1 second!");
}, 1000);

// Repeating timer - fires automatically every 100ms
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log("Tick", count);
  if (count >= 5) {
    clearInterval(intervalId);
  }
}, 100);

// Cancel a timer
clearTimeout(timeoutId);
```

## Handle API

```typescript
interface TimersHandle {
  /** Clear all pending timers */
  clearAll(): void;
  /** Dispose the timers handle */
  dispose(): void;
}
```

## License

MIT
npm package: @ricsam/isolate-types
Description: Type definition strings and type-checking utilities for isolated-vm V8 sandbox APIs
Author: ricsam
Latest version: 0.1.16

# @ricsam/isolate-types

Type definitions and type-checking utilities for isolate user code.

## Installation

```bash
npm add @ricsam/isolate-types
```

## Type Checking Isolate Code

Validate TypeScript/JavaScript code that will run inside the isolate before execution using `ts-morph`:

```typescript
import { typecheckIsolateCode } from "@ricsam/isolate-types";

const result = typecheckIsolateCode(`
  serve({
    fetch(request, server) {
      const url = new URL(request.url);

      if (url.pathname === "/ws") {
        server.upgrade(request, { data: { userId: 123 } });
        return new Response(null, { status: 101 });
      }

      return Response.json({ message: "Hello!" });
    },
    websocket: {
      message(ws, message) {
        ws.send("Echo: " + message);
      }
    }
  });
`, { include: ["core", "fetch"] });

if (!result.success) {
  console.error("Type errors found:");
  for (const error of result.errors) {
    console.error(`  Line ${error.line}: ${error.message}`);
  }
}
```

## Options

| Option | Description |
|--------|-------------|
| `include` | Which package types to include: `"core"`, `"fetch"`, `"fs"`, `"console"`, `"encoding"`, `"timers"`, `"testEnvironment"`, `"playwright"` (default: `["core", "fetch", "fs"]`) |
| `compilerOptions` | Additional TypeScript compiler options |
| `libraryTypes` | External library type definitions for import resolution |

## Using with Tests

```typescript
import { describe, expect, test } from "node:test";
import { typecheckIsolateCode } from "@ricsam/isolate-types";

describe("Isolate code validation", () => {
  test("server code is type-safe", () => {
    const result = typecheckIsolateCode(userProvidedCode, {
      include: ["fetch"]
    });
    expect(result.success).toBe(true);
  });
});
```

## Type Definition Strings

The type definitions are exported as strings for custom use cases:

```typescript
import {
  CORE_TYPES,       // ReadableStream, Blob, File, URL, etc.
  CONSOLE_TYPES,    // console.log, console.time, etc.
  CRYPTO_TYPES,     // crypto.subtle, CryptoKey, etc.
  ENCODING_TYPES,   // atob, btoa
  FETCH_TYPES,      // fetch, Request, Response, serve, etc.
  FS_TYPES,         // getDirectory, FileSystemHandle, etc.
  PATH_TYPES,       // path.join, path.resolve, etc.
  TEST_ENV_TYPES,   // describe, it, expect, etc.
  TIMERS_TYPES,     // setTimeout, setInterval, etc.
  PLAYWRIGHT_TYPES, // page, context, browser, Locator, etc.
  TYPE_DEFINITIONS  // All types as { core, fetch, fs, playwright, ... }
} from "@ricsam/isolate-types";

// Use with your own ts-morph project
project.createSourceFile("isolate-globals.d.ts", FETCH_TYPES);
```

## License

MIT