# Script Runtime

How each language wrapper receives input, runs user code, and prints the result.

## Input Injection

The handler writes `{"code": ..., "input": ...}` as JSON to the wrapper's stdin. The wrapper parses the `input` string as JSON and exposes it through two globals:

| Global | Content |
|--------|---------|
| `event` | The parsed `input`; `{}` when `input` is empty |
| `input` | The same object as `event` |

When `input` is not valid JSON, the wrapper writes to stderr and exits with code 1.

## Per-language Behavior

| Language | Runtime | Execution | Result Output |
|----------|---------|-----------|---------------|
| Python | `python3 -u` | Indents the code into `__user_main__()` so top-level `return` works | Prints `json.dumps(return value)` to stdout; prints nothing if not serializable |
| JavaScript | `node` | Wraps the code in an `async function` and runs it with `vm.Script` in the global context; `await` works | Prints `JSON.stringify` of the return value when it is not `undefined` |
| TypeScript | `tsx` | Transpiles with `esbuild.transformSync` (`loader: ts`, `format: cjs`, `target: node18`), then runs like JavaScript | Prints `JSON.stringify` of the top-level `return` value or global `result` |

## Examples

```python
total = sum(event["items"])
print("summing", len(event["items"]))
return {"total": total}
```

```javascript
const res = await Promise.resolve(event.a * 2);
return { doubled: res };
```

```typescript
interface User { name: string; age: number }
const adults = (event.users as User[]).filter(u => u.age >= 18);
return adults.map(u => u.name);
```

Intermediate `print` / `console.log` output is ignored in non-stream mode (only the last valid JSON line counts) and becomes `log` events in stream mode.

## Error Handling

- Exceptions are written to stderr (`Error: ...`) and the wrapper exits with code 1.
- Non-stream mode: HTTP 500 with `failed to run: <error>`.
- Stream mode: any stderr output kills the process immediately and emits an `error` event; warnings that third-party packages print to stderr trigger it too.

## Related Pages

- [Responses and SSE](/responses)
- [Sandbox](/sandbox)
