@fold-run/runtime
v0.2.1
Published
Runtime SDK for fold.run functions — typed context, bindings, and handler helpers
Readme
@fold-run/runtime
Runtime SDK for 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.
npm install -D @fold-run/runtimeQuick start
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:
fold deploy function.tsdefineHandler
Wraps your function and provides a typed FoldContext as the single argument.
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
ctx.json(data, status?) // application/json
ctx.text(body, status?) // text/plain
ctx.stream(generator) // text/event-stream (SSE)Request helpers
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 headerBackground work
ctx.waitUntil(promise) // Extend request lifetime for async workBindings
Attach bindings to your function via the fold.run dashboard (Functions > Bindings) or fold.json. They become available on ctx:
// 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: '[email protected]' });
// 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:
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:
const apiKey = ctx.env.THIRD_PARTY_API_KEY;
const baseUrl = ctx.env.BASE_URL ?? 'https://api.example.com';Local development
fold dev function.tsfold 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:
# 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:3000TypeScript
@fold-run/runtime ships full TypeScript types. No extra setup required.
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true
}
}