> ## Documentation Index
> Fetch the complete documentation index at: https://docs.buntime.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# One-Shot Execution

> Execute code without persistent state

## 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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
const result = await client.execute({
  sessionId: session.id,
  code: `
    const text = "Contact us at support@buntime.sh or sales@buntime.sh";
    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

```typescript theme={null}
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

```typescript theme={null}
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: 'alice@example.com',
      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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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:

```typescript theme={null}
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:

```bash theme={null}
# 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

<AccordionGroup>
  <Accordion icon="clock" title="Set short TTLs">
    For one-shot executions, use a short TTL (5-10 minutes) to automatically clean up sessions.

    ```typescript theme={null}
    const session = await client.sessions.create({ ttl: 300 }); // 5 minutes
    ```
  </Accordion>

  <Accordion icon="broom" title="Always clean up">
    Delete sessions when done to free resources immediately.

    ```typescript theme={null}
    try {
      const result = await client.execute({ ... });
    } finally {
      await client.sessions.delete({ sessionId: session.id });
    }
    ```
  </Accordion>

  <Accordion icon="gauge" title="Check exit codes">
    Always verify the execution succeeded before using results.

    ```typescript theme={null}
    if (result.exitCode === 0) {
      console.log('Success:', result.stdout);
    } else {
      console.error('Failed:', result.stderr);
    }
    ```
  </Accordion>

  <Accordion icon="shield" title="Handle errors gracefully">
    Wrap risky operations in try-catch blocks in your code.

    ```typescript theme={null}
    code: `
      try {
        // Your code here
      } catch (error) {
        console.error('Error:', error.message);
        process.exit(1);
      }
    `
    ```
  </Accordion>
</AccordionGroup>

## Common Use Cases

<CardGroup cols={2}>
  <Card title="Data Transformation" icon="arrows-rotate">
    Convert between formats (JSON, CSV, XML)
  </Card>

  <Card title="Quick Calculations" icon="calculator">
    Mathematical operations and statistics
  </Card>

  <Card title="API Testing" icon="flask">
    Test external APIs and parse responses
  </Card>

  <Card title="String Processing" icon="text">
    Text manipulation and regex operations
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Multi-file Projects" icon="folder" href="/guides/multi-file-projects">
    Learn how to build complex applications
  </Card>

  <Card title="Execute API" icon="code" href="/api-reference/execution/execute">
    View complete execution options
  </Card>

  <Card title="Sessions" icon="server" href="/concepts/sessions">
    Understand session lifecycle
  </Card>

  <Card title="AI Integration" icon="brain" href="/guides/ai-integration">
    Use buntime.sh with AI agents
  </Card>
</CardGroup>
