### Run Hono Example App Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Run the example Hono application to test the setup. This command starts the example server. ```bash bun example:hono ``` -------------------------------- ### Install and Run Development Server Source: https://github.com/ephor/vision/blob/main/apps/docs/README.md Use these commands to install project dependencies and start the development server. Open http://localhost:3000 in your browser. ```bash bun install bun dev ``` -------------------------------- ### Clone and Run Vision Examples Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/index.mdx Clone the Vision repository, navigate to the examples directory, install dependencies, and run the development server. Access the dashboard at http://localhost:9500. ```bash git clone https://github.com/ephor/vision cd vision/examples/vision bun install && bun dev # Open http://localhost:9500 ``` -------------------------------- ### Quick Start Example Source: https://github.com/ephor/vision/blob/main/packages/adapter-express/README.md A basic example demonstrating how to integrate the Vision middleware and Zod validation into an Express.js application. ```APIDOC ## Quick Start ```typescript import express from 'express' import { visionMiddleware, enableAutoDiscovery, zValidator } from '@getvision/adapter-express' import { z } from 'zod' const app = express() // Add Vision middleware (development only) if (process.env.NODE_ENV === 'development') { app.use(visionMiddleware({ port: 9500 })) } // JSON parser app.use(express.json()) // Your routes app.get('/users', (req, res) => { res.json({ users: [] }) }) // Zod validation (typed + auto-documented in Vision) const createUser = z.object({ name: z.string().min(1).describe('Full name'), email: z.string().email().describe('Email'), age: z.number().int().positive().optional().describe('Age (optional)'), }) app.post('/users', zValidator('body', createUser), (req, res) => { res.status(201).json(req.body) }) // Enable auto-discovery after routes if (process.env.NODE_ENV === 'development') { // Auto-group routes by first path segment (Users, Root, etc.) enableAutoDiscovery(app) // Or provide manual services grouping with glob-like patterns // e.g. `/users/*` → "Users" service // `/auth/*` → "Auth" service // Unmatched → "Uncategorized" // // enableAutoDiscovery(app, { services: [ // { name: 'Users', description: 'User management', routes: ['/users/*'] }, // { name: 'Auth', routes: ['/auth/*'] } // ]}) } app.listen(3000) ``` Visit `http://localhost:9500` to see the dashboard! 🎉 ``` -------------------------------- ### Install Dependencies and Run Dev Server Source: https://github.com/ephor/vision/blob/main/examples/hono/README.md Installs project dependencies, pushes the database schema, and starts the development server. Access the API at http://localhost:3000, Vision Dashboard at http://localhost:9500, and Drizzle Studio at http://localhost:4983. ```bash bun install bun run db:push bun dev ``` -------------------------------- ### Install Vision Server for New Projects Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/why-vision.mdx Install the Vision server package using npm when starting a new project with Vision. ```bash npm install @getvision/server ``` -------------------------------- ### Complete Vision Adapter Example for Hono Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/adapters/hono.mdx A full example demonstrating Vision adapter setup, route definition, Zod validation, and database interaction with Vision spans. ```typescript import { serve } from '@hono/node-server' import { Hono } from 'hono' import { z } from 'zod' import { visionAdapter, enableAutoDiscovery, useVisionSpan, zValidator } from '@getvision/adapter-hono' import { db } from './db' import { users } from './db/schema' const app = new Hono() // Vision setup app.use('*', visionAdapter({ service: { name: 'my-api', version: '1.0.0', }, })) enableAutoDiscovery(app) // Schemas const createUserSchema = z.object({ name: z.string().min(1).describe('User full name'), email: z.string().email().describe('User email address'), }) // Routes app.get('/users', async (c) => { const withSpan = useVisionSpan() const allUsers = withSpan('db.query', { 'db.table': 'users', }, () => { return db.select().from(users).all() }) return c.json(allUsers) }) app.post('/users', zValidator('json', createUserSchema), async (c) => { const body = c.req.valid('json') const withSpan = useVisionSpan() const newUser = withSpan('db.insert', { 'db.table': 'users', }, () => { return db.insert(users).values(body).returning().get() }) return c.json(newUser, 201) } ) serve(app) ``` -------------------------------- ### Running the Vision Server Example Source: https://github.com/ephor/vision/blob/main/packages/server/README.md These bash commands demonstrate how to execute the provided Vision Server example. You can run it from the project root using 'bun run example:server' or navigate to the example directory and use 'bun run dev'. ```bash # From project root bun run example:server # Or directly cd examples/vision bun run dev ``` -------------------------------- ### Basic Vision Server Setup Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/index.mdx Initializes a Vision server with a user module and starts listening on port 3000. Requires @getvision/server and zod. ```typescript import { createVision, createModule } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .get( '/:id', ({ params, span }) => { return span('db.select', { 'db.table': 'users' }, () => getUser(params.id)) }, { params: z.object({ id: z.string() }) } ) const app = createVision({ service: { name: 'My API' } }).use(usersModule) app.listen(3000) ``` -------------------------------- ### Install Fastify Adapter Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/adapters/fastify.mdx Install the Fastify adapter using bun or npm. ```bash bun add @getvision/adapter-fastify # or npm i @getvision/adapter-fastify ``` -------------------------------- ### Install @getvision/adapter-fastify Source: https://github.com/ephor/vision/blob/main/packages/adapter-fastify/README.md Install the Fastify adapter and the Zod type provider for schema validation. ```bash bun add @getvision/adapter-fastify fastify-type-provider-zod # or npm install @getvision/adapter-fastify fastify-type-provider-zod ``` -------------------------------- ### Install @getvision/core Source: https://github.com/ephor/vision/blob/main/packages/core/README.md Install the core package using pnpm. ```bash pnpm add @getvision/core ``` -------------------------------- ### Add Example Script to Root package.json Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Add a script to the root `package.json` to easily run examples for a specific framework adapter. ```json { "scripts": { "example:my-framework": "bun --filter my-framework-example dev" } } ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/ephor/vision/blob/main/examples/nextjs/README.md Command to start the Next.js development server with the Vision example. It also provides the URLs for the Next.js application and the Vision Dashboard. ```bash bun --filter nextjs-vision-example dev # Next.js: http://localhost:3100 # Vision Dashboard: http://localhost:9500 (starts on first API hit) ``` -------------------------------- ### Clone and Install Vision Project Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Steps to clone the Vision repository and install its dependencies using Bun. Ensure Bun is installed and the lockfile is frozen for consistent installations. ```bash git clone https://github.com/ephor/vision.git cd vision bun install --frozen-lockfile ``` -------------------------------- ### Starting Server with app.listen Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/server/migration.mdx Starts the Elysia server on the specified port. The `onStart` hook is automatically awaited internally. ```typescript app.listen(3000) ``` -------------------------------- ### Install Hono Adapter Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/adapters/hono.mdx Install the Hono adapter package using Bun. ```bash bun add @getvision/adapter-hono ``` -------------------------------- ### Install Vision Server Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/server/index.mdx Install Vision Server along with Elysia and Zod using Bun. ```bash bun add @getvision/server elysia zod ``` -------------------------------- ### View Request Trace Example Source: https://github.com/ephor/vision/blob/main/examples/express/README.md After making a request, view the trace in the Vision Dashboard. This example shows a typical trace for a GET /users request, including database calls. ```text GET /users (35ms) ├── http.request (35ms) │ └── db.select (8ms) │ └── db.table: "users" │ └── db.system: "mock" ``` -------------------------------- ### Start New API with Elysia and Vision Source: https://github.com/ephor/vision/blob/main/README.md Set up a new API project from scratch using Elysia, Vision server, and Zod for validation. Install necessary packages with `bun add`. The `createVision` function initializes the server, and `createModule` defines API endpoints with validation. ```bash bun add @getvision/server elysia zod ``` ```typescript import { createVision, createModule } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .post( '/', async ({ body }) => ({ id: crypto.randomUUID(), ...body }), { body: z.object({ name: z.string(), email: z.string().email() }) } ) createVision({ service: { name: 'My API' } }) .use(usersModule) .listen(3000) // Dashboard at http://localhost:9500 ``` -------------------------------- ### Run Documentation Development Server Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Start the documentation site development server to preview changes. ```bash bun docs:dev ``` -------------------------------- ### Install Vision Server Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/quickstart.mdx Install the Vision Server package and Zod for schema validation using Bun. ```bash bun add @getvision/server zod ``` -------------------------------- ### Installation Source: https://github.com/ephor/vision/blob/main/packages/adapter-express/README.md Install the @getvision/adapter-express package using your preferred package manager. ```APIDOC ## Installation ```bash bun add @getvision/adapter-express # or npm install @getvision/adapter-express ``` ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Install project dependencies using Bun. Ensure you have Node.js 20+ or Bun installed. ```bash bun install ``` -------------------------------- ### Install Express Adapter Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/adapters/express.mdx Install the Vision adapter for Express using npm or bun. ```bash bun add @getvision/adapter-express # or npm i @getvision/adapter-express ``` -------------------------------- ### Start Server Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Start the Vision server on a specified port. ```APIDOC ## `app.start(port, options?)` ### Description Start the server (convenience method). ### Parameters #### Path Parameters - **port** (number) - Required - The port to start the server on. - **options** (object) - Optional - Server start options. - **hostname** (string) - Optional - The hostname to bind to. ### Request Example ```typescript await app.start(3000) // or await app.start(3000, { hostname: '0.0.0.0' }) ``` ``` -------------------------------- ### Basic API Endpoints with Vision Source: https://github.com/ephor/vision/blob/main/examples/fastify/README.md Example API endpoints for a Fastify application integrated with Vision. These demonstrate common operations like getting users, creating, updating, and deleting them, all of which will be traced by Vision. ```bash # Get API info curl http://localhost:3000/ # List users curl http://localhost:3000/users # Get user by ID (multiple spans) curl http://localhost:3000/users/1 # Create user (with validation) curl -X POST http://localhost:3000/users \ -H "Content-Type: application/json" \ -d '{"name":"Alice Smith","email":"alice@example.com","age":25}' # Update user curl -X PUT http://localhost:3000/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"Alice Updated"}' # Delete user curl -X DELETE http://localhost:3000/users/1 ``` -------------------------------- ### Installing Vision Framework Adapters Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/index.mdx Installs the adapter for Hono, Fastify, or Express to integrate Vision with existing frameworks. Choose the adapter that matches your project's framework. ```bash bun add @getvision/adapter-hono # or adapter-fastify, adapter-express ``` -------------------------------- ### Test Changes with Example App Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Run the example Hono application to test your recent changes. This command is used after making modifications to the core or adapters. ```bash pnpm example:hono ``` -------------------------------- ### Install @getvision/adapter-hono Source: https://github.com/ephor/vision/blob/main/packages/adapter-hono/README.md Use pnpm to add the adapter to your project dependencies. ```bash pnpm add @getvision/adapter-hono ``` -------------------------------- ### Changeset File Example Source: https://github.com/ephor/vision/blob/main/CLAUDE.md An example of a Changeset file, specifying the packages affected and the type of version bump (minor/patch) along with a summary of changes. ```markdown --- "@getvision/core": minor "@getvision/adapter-express": patch --- Add support for custom trace metadata and fix Express middleware ordering ``` -------------------------------- ### Start Vision Dashboard Server Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/api-reference.mdx Call `vision.start()` to launch the dashboard server. Ensure this is awaited before proceeding. ```typescript await vision.start() console.log('Vision running at http://localhost:9500') ``` -------------------------------- ### Install Vision Adapter for Fastify Source: https://github.com/ephor/vision/blob/main/examples/fastify/README.md Install the Vision Fastify adapter using npm. This is the first step to integrate Vision into your Fastify application. ```bash npm install @getvision/adapter-fastify ``` -------------------------------- ### Start Vision Server Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Start the Vision server on a specified port, with optional hostname configuration. This is a convenience method for launching the application. ```typescript await app.start(3000) // or await app.start(3000, { hostname: '0.0.0.0' }) ``` -------------------------------- ### Install Vision Adapter for Express Source: https://github.com/ephor/vision/blob/main/examples/express/README.md Install the Vision adapter for Express using npm. This is the first step to integrating Vision into your application. ```bash npm install @getvision/adapter-express ``` -------------------------------- ### Complete Elysia Application Example Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/server/modules.mdx A comprehensive example demonstrating the integration of modules, event definitions, cron jobs, route handling, and validation within an Elysia application. ```typescript import { createVision, createModule, defineEvents, defineCrons, rateLimit } from '@getvision/server' import { z } from 'zod' const User = z.object({ id: z.string(), name: z.string(), email: z.string().email() }) const usersModule = createModule({ prefix: '/users' }) .use( defineEvents({ 'user/created': { schema: z.object({ userId: z.string(), email: z.string().email() }), handler: async (event) => { console.log('[welcome email] →', event.email) }, }, }) ) .use( defineCrons({ 'daily-digest': { schedule: '0 9 * * *', handler: async () => { console.log('sending daily digest') }, }, }) ) .get('/', ({ span }) => span('db.select', {}, () => ({ users: [{ id: '1', name: 'Alice', email: 'alice@example.com' }], })) ) .post( '/', async ({ body, emit, span }) => { const user = span('db.insert', {}, () => ({ id: crypto.randomUUID(), ...body })) await emit('user/created', { userId: user.id, email: user.email }) return user }, { body: z.object({ name: z.string().min(1), email: z.string().email() }), response: User, beforeHandle: [rateLimit({ requests: 5, window: '15m' })], } ) const app = createVision({ service: { name: 'My API', version: '1.0.0' }, pubsub: { devMode: true }, }).use(usersModule) app.listen(3000) export type AppType = typeof app ``` -------------------------------- ### New Adapter package.json Configuration Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Example `package.json` for a new adapter. It specifies dependencies on the core Vision package and peer dependencies on the framework it adapts. ```json { "name": "@getvision/adapter-yourframework", "version": "0.0.1", "type": "module", "dependencies": { "@getvision/core": "workspace:*" }, "peerDependencies": { "yourframework": "^1.0.0" } } ``` -------------------------------- ### Build and Run Vision Project Scripts Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Common scripts for building, testing, and running the Vision project. Use 'bun run build' for all packages, 'bun run test' for tests, and specific 'bun example:*' commands to run individual examples. ```bash bun run build bun run dev bun run test bun run lint bun run format ``` ```bash bun example:hono bun example:express bun example:fastify bun example:server ``` ```bash bun docs:dev bun docs:build ``` ```bash bun run changeset bun run ci:version bun run release ``` -------------------------------- ### Install Vision Adapter for Hono Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/why-vision.mdx Install the Vision adapter for Hono using npm. This is the first step to integrating Vision into your Hono application. ```bash npm install @getvision/adapter-hono ``` -------------------------------- ### Raw Log Message Example Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/features/logs.mdx This is an example of a raw log message before Vision's smart cleanup is applied. It includes key-value pairs that Vision will later extract and display as inline badges. ```text INF request completed code=200 duration=131ms path=/users/1 ``` -------------------------------- ### VisionCore Methods Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/api-reference.mdx Methods for managing traces and starting the dashboard server. ```APIDOC ## VisionCore Methods ### Description Methods for managing traces and starting the dashboard server. ### Methods #### `vision.createTrace(metadata)` ##### Description Create a new trace. ##### Parameters - **metadata** (object) - Required - Metadata for the trace. - **method** (string) - Optional - HTTP method. - **path** (string) - Optional - Request path. - **timestamp** (number) - Required - Timestamp of trace creation. ##### Request Example ```typescript const trace = vision.createTrace({ method: 'GET', path: '/users', timestamp: Date.now(), }) ``` #### `vision.addSpan(traceId, span)` ##### Description Add a span to an existing trace. ##### Parameters - **traceId** (string) - Required - The ID of the trace to add the span to. - **span** (object) - Required - The span object. - **name** (string) - Required - The name of the span. - **startTime** (number) - Required - The start time of the span. - **duration** (number) - Optional - The duration of the span. - **attributes** (object) - Optional - Key-value attributes for the span. ##### Request Example ```typescript vision.addSpan(traceId, { name: 'db.query', startTime: Date.now(), duration: 50, attributes: { 'db.table': 'users', }, }) ``` #### `vision.completeTrace(traceId, metadata)` ##### Description Complete a trace. ##### Parameters - **traceId** (string) - Required - The ID of the trace to complete. - **metadata** (object) - Optional - Metadata for completing the trace. - **statusCode** (number) - Optional - The HTTP status code of the response. - **duration** (number) - Optional - The total duration of the trace. - **response** (any) - Optional - The response object. ##### Request Example ```typescript vision.completeTrace(traceId, { statusCode: 200, duration: 150, response: { data: '...' }, }) ``` #### `vision.start()` ##### Description Start the dashboard server. ##### Request Example ```typescript await vision.start() console.log('Vision running at http://localhost:9500') ``` ``` -------------------------------- ### Vision UI Log Message Example Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/features/logs.mdx This example shows how a raw log message is transformed in the Vision UI. Key-value pairs like `code=200` and `duration=131ms` are extracted and displayed as stylish inline badges. ```text INF request completed [code=200] [duration=131ms] [path=/users/1] ``` -------------------------------- ### Drizzle Integration - Auto-Start Studio Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Configure Vision Server to automatically start Drizzle Studio. ```APIDOC ## Drizzle Integration Vision Server automatically detects and integrates with Drizzle ORM. ### Auto-Start Drizzle Studio ### Request Example ```typescript const app = new Vision({ service: { name: 'My API', integrations: { database: 'sqlite://./dev.db' }, drizzle: { autoStart: true, // Start Drizzle Studio automatically port: 4983 // Default: 4983 } } }) ``` **What happens:** 1. ✅ Detects `drizzle.config.ts` in your project 2. ✅ Auto-starts Drizzle Studio on port 4983 3. ✅ Displays in Vision Dashboard → Integrations 4. ✅ Links to https://local.drizzle.studio ``` -------------------------------- ### Start Adapter Development Watch Mode Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Navigate to the adapter-hono package directory and run the development command to enable watch mode for the Hono.js adapter. ```bash cd packages/adapter-hono pnpm dev ``` -------------------------------- ### Basic Hono App Setup with Vision Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/adapters/hono.mdx Integrate the Vision adapter into a Hono application and enable automatic route discovery. ```typescript import { Hono } from 'hono' import { visionAdapter, enableAutoDiscovery } from '@getvision/adapter-hono' const app = new Hono() app.use('*', visionAdapter()) enableAutoDiscovery(app) export default app ``` -------------------------------- ### Create a Basic Vision Server with Modules Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Set up a Vision Server instance, define modules with routes and events, and start the server. Automatic tracing and a dashboard are enabled by default. ```typescript import { createVision, createModule, defineEvents } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .use( defineEvents({ 'user/created': { schema: z.object({ userId: z.string(), email: z.string().email() }), handler: async (event) => { console.log('[welcome email] →', event.email) }, }, }) ) .get('/', ({ span }) => { const users = span('db.select', { 'db.table': 'users' }, () => [ { id: '1', name: 'Alice' }, ]) return { users } }) .post( '/', async ({ body, emit }) => { const id = crypto.randomUUID() await emit('user/created', { userId: id, email: body.email }) return { id, ...body } }, { body: z.object({ name: z.string(), email: z.string().email() }) } ) const app = createVision({ service: { name: 'My API', version: '1.0.0' }, vision: { enabled: true }, pubsub: { devMode: true }, }) .use(usersModule) .listen(3000) ``` -------------------------------- ### Express Quick Start with Vision Source: https://github.com/ephor/vision/blob/main/packages/adapter-express/README.md Integrate Vision middleware, JSON parsing, define routes, and enable Zod validation and auto-discovery for development. ```typescript import express from 'express' import { visionMiddleware, enableAutoDiscovery, zValidator } from '@getvision/adapter-express' import { z } from 'zod' const app = express() // Add Vision middleware (development only) if (process.env.NODE_ENV === 'development') { app.use(visionMiddleware({ port: 9500 })) } // JSON parser app.use(express.json()) // Your routes app.get('/users', (req, res) => { res.json({ users: [] }) }) // Zod validation (typed + auto-documented in Vision) const createUser = z.object({ name: z.string().min(1).describe('Full name'), email: z.string().email().describe('Email'), age: z.number().int().positive().optional().describe('Age (optional)'), }) app.post('/users', zValidator('body', createUser), (req, res) => { res.status(201).json(req.body) }) // Enable auto-discovery after routes if (process.env.NODE_ENV === 'development') { // Auto-group routes by first path segment (Users, Root, etc.) enableAutoDiscovery(app) // Or provide manual services grouping with glob-like patterns // e.g. `/users/*` → "Users" service // `/auth/*` → "Auth" service // Unmatched → "Uncategorized" // // enableAutoDiscovery(app, { services: [ // { name: 'Users', description: 'User management', routes: ['/users/*'] }, // { name: 'Auth', routes: ['/auth/*'] } // ]}) } app.listen(3000) ``` -------------------------------- ### Define Product Endpoint with Vision Source: https://github.com/ephor/vision/blob/main/examples/vision/README.md This snippet demonstrates how to define a GET endpoint for products using Vision Server. Ensure you have the '@getvision/server' package installed. ```typescript import { Vision } from '@getvision/server' const app = new Vision() app.service('products') .endpoint('GET', '/', {...}, listProducts) export default app ``` -------------------------------- ### Example API Endpoints with Curl Source: https://github.com/ephor/vision/blob/main/examples/express/README.md A collection of curl commands to interact with the Express API, demonstrating various operations like getting, creating, updating, and deleting users. ```bash # Get API info curl http://localhost:3000/ ``` ```bash # List users curl http://localhost:3000/users ``` ```bash # Get user by ID curl http://localhost:3000/users/1 ``` ```bash # Create user (with validation) curl -X POST http://localhost:3000/users \ -H "Content-Type: application/json" \ -d '{"name":"Alice","email":"alice@example.com"}' ``` ```bash # Update user curl -X PUT http://localhost:3000/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"Alice Updated"}' ``` ```bash # Delete user curl -X DELETE http://localhost:3000/users/1 ``` -------------------------------- ### Define User Service Endpoint Source: https://github.com/ephor/vision/blob/main/examples/vision/README.md Example of defining a GET endpoint for a user service using the Vision Server's service builder pattern. Includes input/output schemas and a handler with built-in span tracking. ```typescript app.service('users') .endpoint('GET', '/users/:id', { input: z.object({ id: z.string() }), output: z.object({ id: z.string(), name: z.string() }) }, async ({ id }, c) => { // c.span() is built in - no imports needed const user = c.span('db.select', { 'db.table': 'users' }, () => { return db.select().from(users).where(eq(users.id, id)) }) return user }) ``` -------------------------------- ### Build Documentation Site Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Build the static assets for the documentation site. ```bash bun docs:build ``` -------------------------------- ### Create Vision Server Application with Modules Source: https://context7.com/ephor/vision/llms.txt Use `createVision` to set up a Vision Server application. This example demonstrates defining modules with routes, events, cron jobs, and integrating validation schemas. It also shows how to configure service details, Vision's observability settings, and pub/sub behavior. ```typescript import { createVision, createModule, defineEvents, defineCrons, rateLimit } from '@getvision/server' import { z } from 'zod' // Define a module with routes, events, and cron jobs const usersModule = createModule({ prefix: '/users' }) .use( defineEvents({ 'user/created': { schema: z.object({ userId: z.string(), email: z.string().email() }), description: 'User account created', handler: async (event) => { console.log('Send welcome email to:', event.email) }, }, }) ) .use( defineCrons({ 'daily-cleanup': { schedule: '0 0 * * *', handler: async () => { console.log('Running daily cleanup') }, }, }) ) .get( '/', ({ span }) => { const users = span('db.select', { 'db.table': 'users' }, () => [ { id: '1', name: 'Alice', email: 'alice@example.com' }, ]) return { users } }, { response: z.object({ users: z.array(z.object({ id: z.string(), name: z.string(), email: z.string() })) }) } ) .post( '/', async ({ body, emit, span, addContext }) => { addContext({ 'user.email': body.email }) const user = span('db.insert', { 'db.table': 'users' }, () => ({ id: crypto.randomUUID(), ...body, })) await emit('user/created', { userId: user.id, email: user.email }) return user }, { body: z.object({ name: z.string().min(1), email: z.string().email() }), beforeHandle: [rateLimit({ requests: 5, window: '15m' })], } ) // Create and configure the Vision app const app = createVision({ service: { name: 'My API', version: '1.0.0', description: 'My awesome API', integrations: { database: 'postgresql://localhost/mydb', }, drizzle: { autoStart: true, port: 4983, }, }, vision: { enabled: true, port: 9500, maxTraces: 1000, maxLogs: 10000, }, pubsub: { devMode: true, // In-memory queue, no Redis required }, }) .use(usersModule) app.listen(3000) // API: http://localhost:3000 // Dashboard: http://localhost:9500 export type AppType = typeof app // For Eden Treaty typed RPC client ``` -------------------------------- ### Create a Vision Server App with Modules Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/server/index.mdx Set up a Vision Server application using modules for organizing routes and events. This example defines a users module with event handling and GET/POST routes, then integrates it into the main application. ```typescript import { createVision, createModule, defineEvents } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .use( defineEvents({ 'user/created': { schema: z.object({ userId: z.string(), email: z.string().email() }), handler: async (event) => { console.log('[welcome email] →', event.email) }, }, }) ) .get('/', ({ span }) => { const users = span('db.select', { 'db.table': 'users' }, () => [ { id: '1', name: 'Alice' }, ]) return { users } }) .post( '/', async ({ body, emit }) => { const id = crypto.randomUUID() await emit('user/created', { userId: id, email: body.email }) return { id, ...body } }, { body: z.object({ name: z.string(), email: z.string().email() }), } ) const app = createVision({ service: { name: 'My API', version: '1.0.0' }, pubsub: { devMode: true }, }).use(usersModule) app.listen(3000) /** Eden Treaty client type — export for the frontend. */ export type AppType = typeof app ``` -------------------------------- ### Initialize Vision Server App Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Create a new Vision app instance with detailed service, vision, and pubsub configurations. Includes settings for database, Redis, Drizzle Studio, and Vision dashboard. ```typescript const app = new Vision({ service: { name: 'My API', version: '1.0.0', description: 'Optional description', integrations: { database: 'postgresql://localhost/mydb', // Optional redis: 'redis://localhost:6379' // Optional }, drizzle: { autoStart: true, // Auto-start Drizzle Studio port: 4983 // Drizzle Studio port } }, vision: { enabled: true, // Enable/disable dashboard port: 9500, // Dashboard port maxTraces: 1000, // Max traces to store maxLogs: 10000, // Max logs to store logging: true // Console logging }, pubsub: { devMode: true, // In-memory BullMQ for local dev redis: { host: 'localhost', port: 6379, password: 'your-password', // Connection settings to prevent timeouts keepAlive: 30000, // Keep connection alive (30s) maxRetriesPerRequest: null, // Required null for BullMQ enableReadyCheck: true, // Check Redis is ready connectTimeout: 10000, // Connection timeout (10s) enableOfflineQueue: true // Queue commands when offline }, // BullMQ options queue: { defaultJobOptions: { lockDuration: 300000, // 5 minutes stalledInterval: 300000, maxStalledCount: 1, removeOnComplete: 1000, removeOnFail: 1000, } }, worker: { lockDuration: 300000, }, queueEvents: { stalledInterval: 300000, } } }) ``` -------------------------------- ### Get VisionCore Instance Source: https://github.com/ephor/vision/blob/main/packages/server/README.md Get the VisionCore instance to access tracers and other core functionalities. ```APIDOC ## `app.getVision()` ### Description Get the VisionCore instance. ### Request Example ```typescript const vision = app.getVision() const tracer = vision.getTracer() ``` ``` -------------------------------- ### Invalid Request Example Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/features/schemas.mdx An example of an invalid request payload that fails validation due to incorrect data types or values. ```json { "email": "not-an-email", "age": -5 } ``` -------------------------------- ### Start Core Development Watch Mode Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Navigate to the core package directory and run the development command to enable watch mode for the core WebSocket server and tracing. ```bash cd packages/core pnpm dev ``` -------------------------------- ### Basic Vision Server Setup Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/quickstart.mdx Create a simple Vision Server app with a basic module for handling user data. This includes defining parameters and response schemas using Zod. ```typescript import { createVision, createModule } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .get( '/:id', ({ params }) => ({ id: params.id, name: 'John Doe', email: 'john@example.com', }), { params: z.object({ id: z.string() }), response: z.object({ id: z.string(), name: z.string(), email: z.string(), }), } ) const app = createVision({ service: { name: 'My API', version: '1.0.0', description: 'My awesome API', }, }).use(usersModule) app.listen(3000) /** Eden Treaty type for typed RPC on the client. */ export type AppType = typeof app ``` -------------------------------- ### Example API Response Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/features/api-explorer.mdx This is an example of a formatted JSON response that would be displayed in the API Explorer's Response Viewer after calling an API. ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "age": 30, "createdAt": "2025-10-05T23:00:00Z" } ``` -------------------------------- ### Build Project for Production Source: https://github.com/ephor/vision/blob/main/apps/docs/README.md Execute this command to build the static site for the Vision project. The output will be generated in the `out/` directory. ```bash bun build ``` -------------------------------- ### Advanced Vision Server Setup with Events Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/index.mdx Sets up a Vision server with a user module that defines and emits custom events ('user/created'). It also includes database insertion and context addition. Requires @getvision/server and zod. ```typescript import { createVision, createModule, defineEvents } from '@getvision/server' import { z } from 'zod' const usersModule = createModule({ prefix: '/users' }) .use( defineEvents({ 'user/created': { schema: z.object({ userId: z.string(), email: z.string().email() }), handler: async (event) => console.log('welcome →', event.email), }, }) ) .post( '/', async ({ body, addContext, emit, span }) => { addContext({ 'user.email': body.email }) const user = span('db.insert', { 'db.table': 'users' }, () => ({ id: crypto.randomUUID(), ...body, })) await emit('user/created', { userId: user.id, email: user.email }) return user }, { body: z.object({ name: z.string().min(1), email: z.string().email() }), } ) const app = createVision({ service: { name: 'My API' } }).use(usersModule) app.listen(3000) export type AppType = typeof app // ← Eden Treaty type for the client ``` -------------------------------- ### Example Request Body for POST /users Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/features/api-explorer.mdx This is an example of a request body that can be edited in the API Explorer's Request Body Editor for a POST /users endpoint. ```json { "name": "John Doe", "email": "john@example.com", "age": 30 } ``` -------------------------------- ### Deploy to Cloudflare Pages Source: https://github.com/ephor/vision/blob/main/apps/docs/README.md Build the project and upload the generated `out/` directory to Cloudflare Pages for deployment. Automatic GitHub integration is also available. ```bash bun build # Upload out/ directory to Cloudflare Pages ``` -------------------------------- ### Add New Documentation File Source: https://github.com/ephor/vision/blob/main/apps/docs/README.md Follow these steps to create a new documentation file using MDX format. Ensure to update frontmatter and regenerate types. ```yaml --- title: Page Title description: Page description --- ``` -------------------------------- ### getVisionInstance() Source: https://github.com/ephor/vision/blob/main/packages/adapter-express/README.md Get the global Vision instance. ```APIDOC ## `getVisionInstance()` Get the global Vision instance. **Returns:** `VisionCore | null` ``` -------------------------------- ### Create New Adapter Package Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Create a new directory for a custom adapter package. This is the first step in creating a new adapter for a different framework. ```bash mkdir -p packages/adapter-yourframework ``` -------------------------------- ### Trace Waterfall for Get User Request Source: https://github.com/ephor/vision/blob/main/examples/hono/README.md This trace waterfall illustrates the breakdown of a GET /users/1 request, showing that the database query took 12ms out of a total of 45ms. This helps identify performance bottlenecks within the request lifecycle. ```text GET /users/1 (45ms) ├── http.request (45ms) │ └── db.select (12ms) │ └── db.table: "users" │ └── db.system: "sqlite" ``` -------------------------------- ### Initialize and Use VisionCore Source: https://github.com/ephor/vision/blob/main/packages/core/README.md Initialize the VisionCore instance with options, set application status, create and complete traces, and broadcast events. ```typescript import { VisionCore } from '@getvision/core' // Create Vision instance const vision = new VisionCore({ port: 9500, maxTraces: 1000, }) // Set app status vision.setAppStatus({ running: true, pid: process.pid, metadata: { name: 'My App', framework: 'hono', }, }) // Create and complete traces const trace = vision.createTrace('GET', '/api/users') // ... handle request ... vision.completeTrace(trace.id, 200, 150) // Broadcast events vision.broadcast({ type: 'log.stdout', data: { message: 'Server started', timestamp: Date.now() }, }) ``` -------------------------------- ### Initialize VisionCore Instance Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/api-reference.mdx Instantiate the main VisionCore class to manage traces and serve the dashboard. Configure the dashboard port and the maximum number of traces to store in memory. ```typescript import { VisionCore } from '@getvision/core' const vision = new VisionCore({ port: 9500, maxTraces: 1000, }) ``` -------------------------------- ### Get Users API Source: https://github.com/ephor/vision/blob/main/packages/adapter-fastify/README.md This API endpoint retrieves a list of users. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users ### Response #### Success Response (200) - **users** (array) - A list of user objects. #### Response Example { "users": [] } ``` -------------------------------- ### Explicitly Readying App in Serverless Environments Source: https://github.com/ephor/vision/blob/main/apps/docs/content/docs/server/migration.mdx Ensures the Elysia app is ready before handling requests in serverless or edge environments by calling `ready(app)`. This is crucial as `onStart` hooks do not fire automatically in these contexts. ```typescript // instrumentation.ts export async function register() { if (process.env.NEXT_RUNTIME !== 'nodejs') return const [{ ready }, { app }] = await Promise.all([ import('@getvision/server'), import('./src/vision'), ]) await ready(app) } ``` -------------------------------- ### getVisionContext Usage Source: https://github.com/ephor/vision/blob/main/packages/adapter-fastify/README.md Example of using `getVisionContext` to retrieve the current Vision context. ```APIDOC ## `getVisionContext()` Get current Vision context. **Returns:** `{ vision: VisionCore, traceId: string, rootSpanId: string }` ```typescript import { getVisionContext } from '@getvision/adapter-fastify' app.get('/debug', async (request, reply) => { const { vision, traceId } = getVisionContext() return { traceId } }) ``` ``` -------------------------------- ### Arktype Schema Definition Source: https://github.com/ephor/vision/blob/main/packages/core/src/validation/README.md Example of defining a schema using the Arktype library. ```typescript import { type } from 'arktype' const schema = type({ name: "string" }) ``` -------------------------------- ### Valibot Schema Definition Source: https://github.com/ephor/vision/blob/main/packages/core/src/validation/README.md Example of defining a schema using the Valibot library. ```typescript import * as v from 'valibot' const schema = v.object({ name: v.string() }) ``` -------------------------------- ### Zod Schema Definition Source: https://github.com/ephor/vision/blob/main/packages/core/src/validation/README.md Example of defining a schema using the Zod library. ```typescript import { z } from 'zod' const schema = z.object({ name: z.string() }) ``` -------------------------------- ### Fastify Quick Start with Vision Source: https://github.com/ephor/vision/blob/main/packages/adapter-fastify/README.md Set up a Fastify application with Vision plugin, Zod validation, and basic routes. Ensure to register the Vision plugin only in development environments. ```typescript import Fastify from 'fastify' import { visionPlugin, enableAutoDiscovery } from '@getvision/adapter-fastify' import { z } from 'zod' import { serializerCompiler, validatorCompiler, type ZodTypeProvider } from 'fastify-type-provider-zod' const app = Fastify() // Add Zod validator and serializer app.setValidatorCompiler(validatorCompiler) app.setSerializerCompiler(serializerCompiler) // Register Vision plugin (development only) if (process.env.NODE_ENV === 'development') { await app.register(visionPlugin, { port: 9500 }) } // Routes app.get('/users', async (request, reply) => { return { users: [] } }) // Zod validation with Fastify type provider const CreateUserSchema = z.object({ name: z.string().min(1).describe('Full name'), email: z.string().email().describe('Email'), age: z.number().int().positive().optional().describe('Age (optional)'), }) app.withTypeProvider().post('/users', { schema: { body: CreateUserSchema } }, async (request, reply) => { return { id: 1, ...request.body } }) // Enable auto-discovery after routes if (process.env.NODE_ENV === 'development') { enableAutoDiscovery(app) } await app.listen({ port: 3000 }) ``` -------------------------------- ### Run Linting Source: https://github.com/ephor/vision/blob/main/CONTRIBUTING.md Execute the linting process using Bun to check code quality and style. This should be run before committing changes. ```bash bun lint ``` -------------------------------- ### useVisionSpan Usage Source: https://github.com/ephor/vision/blob/main/packages/adapter-fastify/README.md Example of using `useVisionSpan` to create custom spans for operations within a request. ```APIDOC ## `useVisionSpan()` Get span helper for current request. Child spans are automatically parented to the root `http.request` span for the current request. **Returns:** `(name, attributes, fn) => result` ```typescript import { useVisionSpan } from '@getvision/adapter-fastify' const withSpan = useVisionSpan() const result = withSpan('operation.name', { 'attr.key': 'value' }, () => { // Your operation return result }) ``` ``` -------------------------------- ### New Package package.json Configuration Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Define the metadata, scripts, and dependencies for a new package. Ensure correct naming and workspace configurations. ```json { "name": "@getvision/my-package", "version": "0.0.1", "type": "module", "types": "dist/index.d.ts", "module": "dist/index.js", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } }, "scripts": { "dev": "tsc --watch", "build": "tsc", "test": "bun test", "lint": "eslint . --max-warnings 0" }, "dependencies": { "@getvision/core": "workspace:*" }, "devDependencies": { "@repo/eslint-config": "workspace:*", "@repo/typescript-config": "workspace:*", "@types/node": "^20.14.9", "typescript": "5.9.3" } } ``` -------------------------------- ### Console Interceptor Example Source: https://github.com/ephor/vision/blob/main/CLAUDE.md Demonstrates how console logs are automatically captured and associated with the current trace. ```typescript // Automatically captures and links to current trace console.log('Processing user request') // Linked to trace console.error('Database error', { userId: 123 }) // Linked with context ```