JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 294
  • Score
    100M100P100Q89866F
  • License MIT

A JavaScript SDK for executing multi-language code in controlled sandboxes, supporting both synchronous and asynchronous modes, as well as multi-language kernels (Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash)

Package Exports

  • @scalebox/sdk
  • @scalebox/sdk/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@scalebox/sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Scalebox JavaScript SDK

npm version npm downloads npm bundle size License: MIT TypeScript Node.js Build Status Coverage PRs Welcome

A JavaScript SDK for executing multi-language code in controlled sandboxes, supporting both synchronous and asynchronous modes, as well as multi-language kernels (Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash). Comprehensive real-world test cases and scripts are provided.

中文文档

Features

  • Multi-language kernels: Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash
  • Synchronous Sandbox and asynchronous AsyncSandbox execution
  • Persistent context: Retain variables/state across multiple executions
  • Callback subscriptions: stdout, stderr, results, and errors
  • Rich result formats: text, html, markdown, svg, png, jpeg, pdf, latex, json, javascript, chart, data, and more
  • Real-world testing: Comprehensive coverage with synchronous/asynchronous and multi-language examples

Requirements

  • Node.js 18+
  • Access to Scalebox environment or local service

Installation

npm yarn pnpm

# Using npm
npm install @scalebox/sdk

# Using yarn
yarn add @scalebox/sdk

# Using pnpm
pnpm add @scalebox/sdk

Configuration

Environment Variables

The SDK supports reading configuration from environment variables or .env file:

Variable Required Description Default
SCALEBOX_API_KEY Yes* API key for authentication -
SCALEBOX_ACCESS_TOKEN Yes* Access token (alternative to API key) -
SCALEBOX_API_URL No API endpoint URL https://api.scalebox.dev
SCALEBOX_DOMAIN No Custom domain for sandboxes -

*Either SCALEBOX_API_KEY or SCALEBOX_ACCESS_TOKEN must be provided.

Example Configuration

Using environment variables:

export SCALEBOX_API_KEY=your_api_key_here
export SCALEBOX_API_URL=https://api.scalebox.dev  # optional

Using .env file:

# .env
SCALEBOX_API_KEY=your_api_key_here
SCALEBOX_API_URL=https://api.scalebox.dev  # optional

Using code configuration:

import { Sandbox } from '@scalebox/sdk'

const sandbox = await Sandbox.create('code-interpreter', {
  apiKey: 'your_api_key_here',
  apiUrl: 'https://api.scalebox.dev'  // optional
})

Quick Start

import { Sandbox } from '@scalebox/sdk'

const sandbox = await Sandbox.create('code-interpreter', {
  timeoutMs: 300000, // 5 minutes
  metadata: { test: 'example' }
})

// Check sandbox status
const isRunning = await sandbox.isRunning()
console.log('Sandbox is running:', isRunning)

// Get sandbox information
// ⚠️ Note: getInfo() returns public sandbox metadata
// Internal properties like envdAccessToken and sandboxDomain are excluded for security
// Use sandbox.sandboxId, sandbox.sandboxDomain directly if needed
const info = await sandbox.getInfo()
console.log('Sandbox info:', info)

// Filesystem operations
const files = await sandbox.files.list("/")
console.log('Files:', files)

// Command execution
const result = await sandbox.commands.run('echo "Hello World"')
console.log('Command output:', result.stdout)

// Cleanup
await sandbox.kill()

Quick Start (Code Interpreter)

import { CodeInterpreter } from '@scalebox/sdk'

async function main() {
    // ✅ Recommended: Use CodeInterpreter.create() static method
    const interpreter = await CodeInterpreter.create({
        templateId: 'code-interpreter'
    })
    
    const exec = await interpreter.runCode("print('hello from interpreter')", { language: "python" })
    console.log(exec.logs.stdout)
    
    await interpreter.close()
}

main()

API Examples

Sandbox Management

import { Sandbox } from '@scalebox/sdk'

// Create sandbox
const sandbox = await Sandbox.create('code-interpreter', {
  timeoutMs: 300000,
  metadata: { project: 'my-app' },
  envs: { NODE_ENV: 'production' }
})

// Connect to existing sandbox
const connectedSandbox = await Sandbox.connect('sandbox-id')

// List all sandboxes
const paginator = Sandbox.list()
while (paginator.hasNext) {
  const sandboxes = await paginator.nextItems()
  console.log(sandboxes)
}

// Sandbox operations
await sandbox.setTimeout(600000) // 10 minutes
await sandbox.betaPause() // Pause sandbox
await sandbox.kill() // Close sandbox

Filesystem Operations

// Read file
const content = await sandbox.files.read('/path/to/file.txt')

// Write file
await sandbox.files.write('/path/to/file.txt', 'Hello World')

// List directory
const files = await sandbox.files.list('/home/user')

// Create directory
await sandbox.files.makeDir('/home/user/newdir')

// Move file
await sandbox.files.move('/old/path', '/new/path')

// Remove file
await sandbox.files.remove('/path/to/file.txt')

Command Execution

// Execute command synchronously
const result = await sandbox.commands.run('ls -la')
console.log(result.stdout)
console.log(result.stderr)
console.log(result.exitCode)

// Execute command in background
const handle = await sandbox.commands.run('long-running-command', {
  background: true
})

// Wait for command to complete
const finalResult = await handle.wait()

// Kill command
await handle.kill()

Pseudo-Terminal Operations

// Start pseudo-terminal
const pty = await sandbox.pty.start({
  cwd: '/home/user',
  envs: { PATH: '/usr/bin:/bin' }
})

// Send data
await pty.send('echo "Hello from PTY"')

// Wait for output
await pty.wait()

Multi-Language Examples

  • Python: language: "python"
  • R: language: "r"
  • Node.js: language: "nodejs"
  • Deno/TypeScript: language: "typescript"
  • Java (IJAVA/pure Java): language: "ijava" or language: "java"
  • Bash: language: "bash"

Example (Node.js):

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()
const code = `
console.log("Hello from Node.js!");
const x = 1 + 2; console.log(\`x=\${x}\`);
`
const result = await sbx.runCode(code, { language: "nodejs" })
console.log(result.logs.stdout)

Example (R):

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()
const code = `
print("Hello from R!")
x <- mean(c(1,2,3,4,5))
print(paste("mean:", x))
`
const res = await sbx.runCode(code, { language: "r" })
console.log(res.logs.stdout)

Example (Deno/TypeScript):

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()
const ts = `
console.log("Hello from Deno/TypeScript!")
const nums: number[] = [1,2,3]
console.log(nums.reduce((a,b)=>a+b, 0))
`
const res = await sbx.runCode(ts, { language: "typescript" })
console.log(res.logs.stdout)

Example (Java/IJAVA):

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()
const code = `
System.out.println("Hello from IJAVA!");
int a = 10, b = 20; System.out.println(a + b);
`
const res = await sbx.runCode(code, { language: "java" })
console.log(res.logs.stdout)

Example (Bash):

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()
const res = await sbx.runCode("echo 'Hello from Bash'", { language: "bash" })
console.log(res.logs.stdout)

Context Management

Context allows reusing variables/state across multiple executions using real gRPC service:

import { CodeInterpreter } from '@scalebox/sdk'

// ✅ Recommended: Use static create method
const interpreter = await CodeInterpreter.create()

// Create context (using gRPC)
const ctx = await interpreter.createCodeContext({ language: "python", cwd: "/tmp" })

await interpreter.runCode("counter = 0", { language: "python", context: ctx })
await interpreter.runCode("counter += 1; print(counter)", { language: "python", context: ctx })

// Destroy context (using gRPC)
await interpreter.destroyContext(ctx)

// Manage multiple contexts
const pythonCtx = await interpreter.createCodeContext({ language: "python" })
const jsCtx = await interpreter.createCodeContext({ language: "nodejs" })

console.log('Active contexts:', interpreter.getContexts().length)

Callbacks (Optional)

import { Sandbox } from '@scalebox/sdk'

const sbx = await Sandbox.create()

function onStdout(msg) {
    console.log("STDOUT:", msg.content)
}

function onStderr(msg) {
    console.log("STDERR:", msg.content)
}

function onResult(res) {
    console.log("RESULT formats:", Object.keys(res.formats))
}

function onError(err) {
    console.log("ERROR:", err.name, err.value)
}

await sbx.runCode(
    "print('with callbacks')",
    { 
        language: "python",
        onStdout,
        onStderr,
        onResult,
        onError
    }
)

Result Formats

Result may contain the following data fields:

  • text, html, markdown, svg, png, jpeg, pdf, latex
  • jsonData, javascript, data, chart
  • executionCount, isMainResult, extra

You can view available formats via Object.keys(result.formats).

Running Tests

The test/ directory contains comprehensive real-world use cases covering:

  • Synchronous and asynchronous comprehensive use cases
  • Multi-language kernels (Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash)
  • Context management, callbacks, and result formats
# Run all tests
npm test

# Run specific tests
npm run test:integration

Troubleshooting

  • Import/dependency errors: Ensure dependencies are properly installed
  • External kernels unavailable: Ensure environment has corresponding language runtime (R/Node/Deno/JDK) installed and backend has enabled the kernel
  • Timeout/network: Check network and backend service reachability, increase timeout/requestTimeout if necessary

Tech Stack

Python R JavaScript TypeScript Java Bash

Platform Support

Linux macOS Windows Docker

Automated Release Process

This project uses semantic-release for fully automated version management and releases.

📝 Commit Conventions

Use Conventional Commits specification:

# New feature (automatically publish minor version)
git commit -m "feat: add new authentication method"

# Bug fix (automatically publish patch version)
git commit -m "fix: resolve timeout issue in sandbox"

# Breaking change (automatically publish major version)
git commit -m "feat!: breaking change in API"

# Documentation update (does not trigger release)
git commit -m "docs: update installation guide"

# Performance optimization (automatically publish patch version)
git commit -m "perf: optimize memory usage"

🚀 Release Process

  1. Commit code using standardized commit message
  2. Push to main branch
  3. CI automatically handles:
    • ✅ Analyze commit messages to determine version type
    • ✅ Automatically update version number
    • ✅ Generate CHANGELOG.md
    • ✅ Create Git tag
    • ✅ Publish to npm
    • ✅ Create GitHub Release

📋 Version Rules

Commit Type Version Increment Example
feat: minor (0.1.0) New feature
fix: patch (0.0.1) Bug fix
perf: patch (0.0.1) Performance optimization
feat!: major (1.0.0) Breaking change
docs: - Documentation update
chore: - Build/tools
test: - Testing related

License

This project is licensed under the MIT License.