Skip to main content

Overview

The buntime.sh TypeScript SDK provides a type-safe, modern interface for interacting with the buntime.sh API. Built with TypeScript, fully async/await compatible, and designed for both Node.js and Bun runtimes.

Why Use the SDK?

Type Safety

Full TypeScript support with autocomplete and type checking

Error Handling

Structured error types with helpful messages

Automatic Retries

Built-in retry logic for transient failures

Streaming Support

Stream execution output in real-time

Installation

bun add buntime.sh

Quick Start

import { Buntime } from 'buntime.sh';

// Initialize the client
const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY
});

// Create a session
const session = await client.sessions.create();

// Execute code
const result = await client.execute({
  sessionId: session.id,
  code: `
    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce((a, b) => a + b, 0);
    console.log('Sum:', sum);
  `
});

console.log(result.stdout); // "Sum: 15"

Client Configuration

Basic Configuration

const client = new Buntime({
  apiKey: 'your_api_key_here'
});

Advanced Configuration

const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY,
  baseUrl: 'https://api.buntime.sh', // Custom API URL
  timeout: 60000, // Request timeout in ms (default: 30000)
  maxRetries: 3, // Max retry attempts (default: 2)
  retryDelay: 1000, // Initial retry delay in ms (default: 1000)
  onRetry: (error, attempt) => {
    console.log(`Retry attempt ${attempt}:`, error.message);
  }
});

Core Concepts

Sessions

Sessions are isolated execution environments. Create a session once and reuse it across multiple executions:
// Create a session
const session = await client.sessions.create({
  ttl: 3600, // 1 hour
  metadata: {
    userId: 'user_123',
    purpose: 'data-processing'
  }
});

// Use the session multiple times
await client.execute({
  sessionId: session.id,
  code: 'console.log("First execution");'
});

await client.execute({
  sessionId: session.id,
  code: 'console.log("Second execution");'
});

// Clean up when done
await client.sessions.delete({ sessionId: session.id });

Execution

Execute code or commands in a session:
// Execute inline code
const result = await client.execute({
  sessionId: session.id,
  code: 'console.log("Hello, World!");'
});

// Execute a command
const result = await client.execute({
  sessionId: session.id,
  command: 'bun run index.ts'
});

// Execute with files
const result = await client.execute({
  sessionId: session.id,
  files: [
    { path: 'utils.ts', content: 'export const add = (a, b) => a + b;' },
    { path: 'main.ts', content: 'import { add } from "./utils"; console.log(add(2, 3));' }
  ],
  command: 'bun run main.ts'
});

Files

Manage files in a session:
// Write a file
await client.files.write({
  sessionId: session.id,
  path: 'data.json',
  content: JSON.stringify({ key: 'value' })
});

// Read a file
const content = await client.files.read({
  sessionId: session.id,
  path: 'data.json'
});

// List files
const files = await client.files.list({
  sessionId: session.id
});

Error Handling

The SDK throws typed errors that you can catch and handle:
import { Buntime, BuntimeError } from 'buntime.sh';

const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY });

try {
  const result = await client.execute({
    sessionId: 'invalid_session',
    code: 'console.log("test");'
  });
} catch (error) {
  if (error instanceof BuntimeError) {
    console.error('Buntime error:', error.code);
    console.error('Message:', error.message);
    console.error('Status:', error.status);
    console.error('Details:', error.details);
    
    // Handle specific error types
    switch (error.code) {
      case 'session_not_found':
        console.log('Session expired or deleted');
        break;
      case 'rate_limit_exceeded':
        console.log('Rate limited. Retry after:', error.retryAfter);
        break;
      case 'execution_timeout':
        console.log('Code took too long to execute');
        break;
      default:
        console.log('Unknown error');
    }
  } else {
    // Network error or other unexpected error
    console.error('Unexpected error:', error);
  }
}

Complete Example

Here’s a full example showing common SDK patterns:
import { Buntime } from 'buntime.sh';

async function processData() {
  const client = new Buntime({
    apiKey: process.env.BUNTIME_API_KEY
  });

  try {
    // Create a session for this workflow
    console.log('Creating session...');
    const session = await client.sessions.create({
      ttl: 3600,
      metadata: {
        workflow: 'data-processing',
        timestamp: new Date().toISOString()
      }
    });
    console.log('Session created:', session.id);

    // Write data files
    console.log('Writing files...');
    await client.files.write({
      sessionId: session.id,
      path: 'data.csv',
      content: 'name,age\nAlice,30\nBob,25\nCharlie,35'
    });

    // Write processing script
    await client.files.write({
      sessionId: session.id,
      path: 'process.ts',
      content: `
        const csv = await Bun.file('data.csv').text();
        const lines = csv.trim().split('\\n');
        const headers = lines[0].split(',');
        
        const data = lines.slice(1).map(line => {
          const values = line.split(',');
          return {
            name: values[0],
            age: parseInt(values[1])
          };
        });
        
        const avgAge = data.reduce((sum, person) => sum + person.age, 0) / data.length;
        console.log('Average age:', avgAge);
        
        const sorted = data.sort((a, b) => b.age - a.age);
        console.log('Oldest:', sorted[0].name);
      `
    });

    // Execute the script
    console.log('Processing data...');
    const result = await client.execute({
      sessionId: session.id,
      command: 'bun run process.ts',
      timeout: 60
    });

    console.log('Output:', result.stdout);
    console.log('Execution time:', result.executionTime, 'ms');
    console.log('Memory used:', (result.memoryUsed / 1024 / 1024).toFixed(2), 'MB');

    // List all files created
    const files = await client.files.list({ sessionId: session.id });
    console.log('Files in session:', files.map(f => f.path));

    // Clean up
    await client.sessions.delete({ sessionId: session.id });
    console.log('Session deleted');

  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

processData();

TypeScript Types

The SDK exports all types for your convenience:
import type {
  Session,
  ExecuteRequest,
  ExecuteResponse,
  File,
  FileListResponse,
  BuntimeError,
  BuntimeConfig,
  ResourceLimits,
  SessionMetadata
} from 'buntime.sh';

// Use types in your code
const config: BuntimeConfig = {
  apiKey: process.env.BUNTIME_API_KEY!,
  timeout: 30000
};

const executeParams: ExecuteRequest = {
  sessionId: 'ses_123',
  code: 'console.log("hello");'
};

Best Practices

Never hardcode your API key. Use environment variables or a secrets manager.
const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY
});
Create a session once and reuse it for multiple operations rather than creating a new session for each execution.
const session = await client.sessions.create();

// Good: Multiple executions in same session
await client.execute({ sessionId: session.id, code: '...' });
await client.execute({ sessionId: session.id, code: '...' });
Always delete sessions when you’re done to free resources.
try {
  const session = await client.sessions.create();
  // ... use session
} finally {
  await client.sessions.delete({ sessionId: session.id });
}
Use try-catch blocks and check for specific error types.
try {
  await client.execute({ ... });
} catch (error) {
  if (error instanceof BuntimeError) {
    // Handle buntime-specific errors
  }
}
Check execution metrics to optimize performance.
const result = await client.execute({ ... });
console.log('Execution time:', result.executionTime);
console.log('Memory used:', result.memoryUsed);

Framework Integration

Express

import express from 'express';
import { Buntime } from 'buntime.sh';

const app = express();
const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY });

app.post('/execute', async (req, res) => {
  try {
    const { sessionId, code } = req.body;
    const result = await client.execute({ sessionId, code });
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Next.js API Route

import { Buntime } from 'buntime.sh';
import type { NextApiRequest, NextApiResponse } from 'next';

const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY! });

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { sessionId, code } = req.body;
    const result = await client.execute({ sessionId, code });
    return res.status(200).json(result);
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
}

Next Steps

Questions? Join our Discord community or check out the GitHub repository.