Skip to main content

Overview

One-shot execution is the simplest way to use buntime.sh. Perfect for quick calculations, data transformations, or testing code snippets without needing persistent state.

When to Use One-Shot Execution

Use one-shot execution when you need to:
  • ✅ Run quick calculations or algorithms
  • ✅ Test a code snippet
  • ✅ Process data without saving files
  • ✅ Verify API responses
  • ✅ Run independent tasks
Don’t use it when you need:
  • ❌ Files to persist between executions
  • ❌ Multiple related code executions
  • ❌ Long-running processes
  • ❌ Stateful operations

Quick Example

import { Buntime } from 'buntime.sh';

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

// Create a session
const session = await client.sessions.create({ ttl: 300 }); // 5 minutes

// 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"

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

Simple Calculations

Mathematical Operations

const result = await client.execute({
  sessionId: session.id,
  code: `
    function fibonacci(n) {
      if (n <= 1) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    console.log(fibonacci(10));
  `
});

console.log(result.stdout); // "55"

Statistical Analysis

const result = await client.execute({
  sessionId: session.id,
  code: `
    const data = [23, 45, 67, 12, 89, 34, 56, 78];
    
    const mean = data.reduce((a, b) => a + b) / data.length;
    const sorted = [...data].sort((a, b) => a - b);
    const median = sorted[Math.floor(sorted.length / 2)];
    const max = Math.max(...data);
    const min = Math.min(...data);
    
    console.log(JSON.stringify({
      mean,
      median,
      max,
      min,
      count: data.length
    }, null, 2));
  `
});

console.log(result.stdout);

String Processing

Text Transformation

const result = await client.execute({
  sessionId: session.id,
  code: `
    const text = "hello world from buntime";
    
    const capitalized = text.split(' ')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
    
    console.log('Original:', text);
    console.log('Capitalized:', capitalized);
    console.log('Word count:', text.split(' ').length);
  `
});

Regular Expressions

const result = await client.execute({
  sessionId: session.id,
  code: `
    const text = "Contact us at [email protected] or [email protected]";
    const emails = text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/g);
    
    console.log('Found emails:', JSON.stringify(emails));
  `
});

Array and Object Operations

Array Manipulation

const result = await client.execute({
  sessionId: session.id,
  code: `
    const users = [
      { name: 'Alice', age: 30, city: 'NYC' },
      { name: 'Bob', age: 25, city: 'LA' },
      { name: 'Charlie', age: 35, city: 'NYC' }
    ];
    
    // Filter users from NYC
    const nycUsers = users.filter(u => u.city === 'NYC');
    
    // Get average age
    const avgAge = users.reduce((sum, u) => sum + u.age, 0) / users.length;
    
    // Sort by age
    const sorted = [...users].sort((a, b) => b.age - a.age);
    
    console.log('NYC users:', nycUsers.length);
    console.log('Average age:', avgAge);
    console.log('Oldest:', sorted[0].name);
  `
});

Data Validation

Schema Validation with Zod

const result = await client.execute({
  sessionId: session.id,
  code: `
    import { z } from 'zod';
    
    const UserSchema = z.object({
      name: z.string().min(1),
      email: z.string().email(),
      age: z.number().min(0).max(120)
    });
    
    const validData = {
      name: 'Alice',
      email: '[email protected]',
      age: 30
    };
    
    const invalidData = {
      name: '',
      email: 'not-an-email',
      age: 150
    };
    
    try {
      UserSchema.parse(validData);
      console.log('Valid data passed');
    } catch (error) {
      console.log('Valid data failed:', error.message);
    }
    
    try {
      UserSchema.parse(invalidData);
      console.log('Invalid data passed');
    } catch (error) {
      console.log('Invalid data failed (expected)');
    }
  `
});

API Requests

Fetch External Data

const result = await client.execute({
  sessionId: session.id,
  code: `
    const response = await fetch('https://api.github.com/users/github');
    const data = await response.json();
    
    console.log('User:', data.name);
    console.log('Public repos:', data.public_repos);
    console.log('Followers:', data.followers);
  `
});

POST Request

const result = await client.execute({
  sessionId: session.id,
  code: `
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title: 'Test Post',
        body: 'This is a test from buntime.sh',
        userId: 1
      })
    });
    
    const data = await response.json();
    console.log('Created post ID:', data.id);
  `
});

Date and Time Operations

const result = await client.execute({
  sessionId: session.id,
  code: `
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const daysDiff = (date1, date2) => {
      const diffTime = Math.abs(date2 - date1);
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    };
    
    const futureDate = new Date('2025-12-31');
    const daysUntil = daysDiff(now, futureDate);
    
    console.log('Today:', now.toISOString());
    console.log('Tomorrow:', tomorrow.toISOString());
    console.log('Days until 2025:', daysUntil);
  `
});

Error Handling

Always check the exit code and stderr:
const result = await client.execute({
  sessionId: session.id,
  code: `
    try {
      const data = JSON.parse('invalid json');
      console.log(data);
    } catch (error) {
      console.error('Error:', error.message);
      process.exit(1);
    }
  `
});

if (result.exitCode !== 0) {
  console.log('Code failed with error:', result.stderr);
} else {
  console.log('Output:', result.stdout);
}

Using REST API Directly

For one-shot executions, you can use the REST API without an SDK:
# Create session
SESSION_ID=$(curl -s -X POST https://api.buntime.sh/sessions/create \
  -H "Authorization: Bearer $BUNTIME_API_KEY" \
  | jq -r '.sessionId')

# Execute code
curl -X POST https://api.buntime.sh/execute \
  -H "Authorization: Bearer $BUNTIME_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"sessionId\": \"$SESSION_ID\",
    \"code\": \"console.log('Hello from buntime!')\"
  }"

# Delete session
curl -X DELETE https://api.buntime.sh/sessions/$SESSION_ID \
  -H "Authorization: Bearer $BUNTIME_API_KEY"

Best Practices

For one-shot executions, use a short TTL (5-10 minutes) to automatically clean up sessions.
const session = await client.sessions.create({ ttl: 300 }); // 5 minutes
Delete sessions when done to free resources immediately.
try {
  const result = await client.execute({ ... });
} finally {
  await client.sessions.delete({ sessionId: session.id });
}
Always verify the execution succeeded before using results.
if (result.exitCode === 0) {
  console.log('Success:', result.stdout);
} else {
  console.error('Failed:', result.stderr);
}
Wrap risky operations in try-catch blocks in your code.
code: `
  try {
    // Your code here
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
`

Common Use Cases

Data Transformation

Convert between formats (JSON, CSV, XML)

Quick Calculations

Mathematical operations and statistics

API Testing

Test external APIs and parse responses

String Processing

Text manipulation and regex operations

Next Steps