npm package: @fold-run/runtime
Description: Runtime SDK for fold.run functions — typed context, bindings, and handler helpers
Latest version: 0.2.1

# @fold-run/runtime

Runtime SDK for [fold.run](https://fold.run) functions. Provides typed context, platform binding helpers, and the `defineHandler` entry point.

Install as a dev dependency for type hints — the implementation is injected by the platform at deploy time.

```bash
npm install -D @fold-run/runtime
```

---

## Quick start

```ts
import { defineHandler } from '@fold-run/runtime';

export default defineHandler(async (ctx) => {
  const name = ctx.query('name') ?? 'world';
  return ctx.json({ message: `Hello, ${name}!` });
});
```

Deploy with the CLI:

```bash
fold deploy function.ts
```

---

## `defineHandler`

Wraps your function and provides a typed `FoldContext` as the single argument.

```ts
import { defineHandler } from '@fold-run/runtime';

// Simple handler
export default defineHandler(async (ctx) => {
  return ctx.text('ok');
});

// With scheduled handler
export default defineHandler({
  fetch: async (ctx) => ctx.json({ status: 'ok' }),
  scheduled: async (ctx, event) => {
    console.log('cron fired:', event.cron);
  },
});
```

---

## `FoldContext`

| Property | Type | Description |
|---|---|---|
| `ctx.request` | `Request` | Incoming HTTP request |
| `ctx.kv` | `FoldKV` | Key-value store |
| `ctx.db` | `FoldDB` | SQL database |
| `ctx.storage` | `FoldStorage` | Object storage |
| `ctx.ai` | `FoldAI` | AI model inference |
| `ctx.queue` | `FoldQueue` | Message queue |
| `ctx.vectorize` | `FoldVectorize` | Vector index for embeddings |
| `ctx.env` | `Record<string, string>` | Plain-text env vars and secrets |
| `ctx.tenantId` | `string \| undefined` | Current tenant identifier |

### Response helpers

```ts
ctx.json(data, status?)   // application/json
ctx.text(body, status?)   // text/plain
ctx.stream(generator)     // text/event-stream (SSE)
```

### Request helpers

```ts
const body = await ctx.body<MyType>()   // Parse JSON body
const name = ctx.query('name')          // URL search param
const all = ctx.queries()               // All search params
const auth = ctx.header('authorization') // Request header
```

### Background work

```ts
ctx.waitUntil(promise)   // Extend request lifetime for async work
```

---

## Bindings

Attach bindings to your function via the fold.run dashboard (Functions > Bindings) or `fold.json`. They become available on `ctx`:

```ts
// KV store
const value = await ctx.kv.get('my-key');
await ctx.kv.put('my-key', 'hello');
await ctx.kv.delete('my-key');
const { keys } = await ctx.kv.list({ prefix: 'user:' });

// SQL database
const row = await ctx.db.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();
const { results } = await ctx.db.prepare('SELECT * FROM users').all();
await ctx.db.prepare('INSERT INTO users (id, name) VALUES (?, ?)').bind(id, name).run();

// Object storage
await ctx.storage.put('file.txt', body);
const obj = await ctx.storage.get('file.txt');
await ctx.storage.delete('file.txt');
const { objects } = await ctx.storage.list({ prefix: 'uploads/' });

// Queue
await ctx.queue.send({ type: 'email', to: 'user@example.com' });

// Vector index
await ctx.vectorize.upsert([{ id: 'doc-1', values: embedding }]);
const { matches } = await ctx.vectorize.query(embedding, { topK: 5 });
```

Accessing a binding that hasn't been attached will throw a clear error with instructions.

---

## AI inference

Use fold.run model names — the platform resolves them to the underlying model at runtime:

```ts
const result = await ctx.ai.run('@fold/meta/llama-3.1-8b-instruct', {
  prompt: 'Summarize this text: ...',
});

// Streaming
return ctx.stream(async function* () {
  const stream = await ctx.ai.run('@fold/meta/llama-3.1-8b-instruct', { prompt, stream: true });
  for await (const chunk of stream) {
    yield `data: ${JSON.stringify(chunk)}\n\n`;
  }
});
```

---

## Env vars and secrets

Set plain-text env vars and secrets via `fold env set` or the dashboard. Access them on `ctx.env`:

```ts
const apiKey = ctx.env.THIRD_PARTY_API_KEY;
const baseUrl = ctx.env.BASE_URL ?? 'https://api.example.com';
```

---

## Local development

```bash
fold dev function.ts
```

`fold dev` automatically injects a dev shim for `@fold-run/runtime` — no platform connection needed. Bindings (`ctx.kv`, `ctx.db`, etc.) are in-memory stubs.

Pass env vars for local testing:

```bash
# From a .env file (auto-loaded from cwd)
echo "API_KEY=test-key" > .env
fold dev function.ts

# Or inline
fold dev function.ts -e API_KEY=test-key -e BASE_URL=http://localhost:3000
```

---

## TypeScript

`@fold-run/runtime` ships full TypeScript types. No extra setup required.

```json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true
  }
}
```