// Auto-generated from src/ai-service/skills/system/superblocks-api/references/code-blocks.md
// Do not edit directly - edit the .md file instead
export const content = `# JavaScript and Python Code Blocks

Reference documentation for working with JavaScript and Python code blocks in Superblocks APIs.

## JavaScript Block

\`\`\`typescript
import { JavaScript } from "@superblocksteam/library";

new JavaScript("process_data", {
  fn: ({ input }: { input: any }) => {
    // Your JavaScript code here
    return processedResult;
  },
});
\`\`\`

### Key Features

- Full ES2020+ syntax support
- Access to previous block outputs
- Can return any JSON-serializable value
- Runs in Node.js environment

### Common Patterns

\`\`\`typescript
// Data transformation
new JavaScript("transform", {
  fn: ({ users }) =>
    users.output.map((user: any) => ({
      id: user.id,
      displayName: \`\${user.firstName} \${user.lastName}\`,
      email: user.email.toLowerCase(),
    })),
});

// Conditional logic
new JavaScript("validate", {
  fn: ({ data }: { data: any }) => {
    if (!data.email || !data.email.includes("@")) {
      throw new Error("Invalid email address");
    }
    return { valid: true, data };
  },
});

// Aggregation
new JavaScript("aggregate", {
  fn: ({ orders }) => {
    const output = orders.output;
    return {
      totalOrders: output.length,
      totalRevenue: output.reduce((sum: number, o: any) => sum + o.amount, 0),
      averageOrder:
        output.reduce((sum: number, o: any) => sum + o.amount, 0) /
        output.length,
    };
  },
});

// Working with Variables block
new JavaScript("update_state", {
  fn: ({ counter, items, newItem }) => {
    // Variables use .value for reading and .set() for writing
    const currentCount = counter.value;
    const currentItems = items.value;

    items.set([...currentItems, newItem]);
    counter.set(currentCount + 1);

    return { added: newItem, newCount: currentCount + 1 };
  },
});
\`\`\`

### Available Globals

\`\`\`typescript
new JavaScript("with_globals", {
  fn: ({ Global }) => {
    // Global object contains user/org context
    const userId = Global.user.id;
    const userEmail = Global.user.email;
    const userGroups = Global.groups;

    return {
      userId,
      userEmail,
      isAdmin: userGroups.some((g) => g.name === "Admin"),
    };
  },
});
\`\`\`

## Python Block

\`\`\`typescript
import { Python } from "@superblocksteam/library";

new Python("python_transform", {
  code: \`
import json

# Access inputs directly
result = {
    "processed": True,
    "count": len(data)
}

# Return must be JSON serializable
return result
  \`,
});
\`\`\`

### Key Features

- Python 3.x runtime
- Common libraries available (pandas, numpy, etc.)
- Access inputs as Python variables
- Return value must be JSON serializable

### Common Patterns

\`\`\`python
# Data processing with pandas
import pandas as pd

df = pd.DataFrame(users_data)
filtered = df[df['status'] == 'active']
result = filtered.to_dict(orient='records')
return result
\`\`\`

\`\`\`python
# Statistical analysis
import numpy as np

values = [item['amount'] for item in orders_data]
return {
    'mean': float(np.mean(values)),
    'median': float(np.median(values)),
    'std': float(np.std(values))
}
\`\`\`

### Python Variable Access

\`\`\`python
# Inputs are available as Python variables
# Previous block outputs are also available

# Access input parameter
email = input_email  # Direct variable access

# Access previous block output
users = fetch_users  # Output from previous block named 'fetch_users'
\`\`\`

## Choosing JavaScript vs Python

**Use JavaScript when:**

- Simple data transformations
- JSON manipulation
- Working with Superblocks Variables
- Need to use \`.set()\` for state updates

**Use Python when:**

- Complex data analysis (pandas)
- Statistical computations (numpy/scipy)
- Machine learning operations
- Heavy numerical processing

## Error Handling

Both languages throw errors that can be caught with TryCatch:

\`\`\`typescript
new TryCatch("safe_process", {
  try: [
    new JavaScript("risky_operation", {
      fn: ({ data }) => {
        if (!data) throw new Error("Data is required");
        return processData(data);
      },
    }),
  ],
  catch: [
    new JavaScript("handle_error", {
      fn: ({ processError }) => ({
        success: false,
        error: processError.value.message,
      }),
    }),
  ],
  variables: { error: "processError" },
});
\`\`\`

## Processing File Content

When you need to read and process file content (parse CSV, extract text, validate, etc.):

FilePicker files are stored on the orchestrator's file server.

### Methods

- \`readContents(mode?)\` - Synchronous
- \`readContentsAsync(mode?)\` - Asynchronous

### Mode Parameter

- (none) - auto-detects: returns base64 string for binary files, UTF-8 string for text
- \`'raw'\` - returns Buffer in JavaScript, bytes in Python (for direct byte access)
- \`'text'\` - returns UTF-8 string
- \`'binary'\` - returns base64 string

### JavaScript - use await directly

\`\`\`typescript
new JavaScript("parse_csv", {
  fn: async ({ csvFile }) => {
    const file = csvFile.files[0];
    const content = await file.readContentsAsync();
    const headers = content
      .split("\\n")[0]
      .split(",")
      .map((h) => h.trim());
    return { fileName: file.name, headers };
  },
});

// Binary file - use 'raw' mode for byte access
new JavaScript("check_jpeg", {
  fn: async ({ imageFile }) => {
    const buf = await imageFile.files[0].readContentsAsync("raw"); // Buffer
    const isJPEG = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
    return { isJPEG };
  },
});
\`\`\`

### Python - use sync for single file, async for parallel

\`\`\`python
# Single file - use sync (simpler)
content = file.readContents()
rows = content.split('\\n')

# Check file type by magic bytes
raw = file.readContents('raw')
is_pdf = raw[:4] == b'%PDF'

# Multiple files in parallel - use async
import asyncio
async def fetch_all(files):
    return await asyncio.gather(*[f.readContentsAsync() for f in files])
contents = asyncio.run(fetch_all(files))
\`\`\`

## Best Practices

1. **Keep blocks focused** - One logical operation per block
2. **Use descriptive names** - \`calculate_shipping_cost\` not \`calc\`
3. **Type your inputs** - \`({ userId }: { userId: string })\` not \`({ userId })\`
4. **Handle edge cases** - Check for null/undefined/empty arrays
5. **Return clean data** - Only return what's needed downstream
`;
//# sourceMappingURL=code-blocks.generated.js.map