# BareJS (`barejs`) — AI Quick Reference (`llms.txt`) > BareJS is a batteries-included, JIT-compiled TypeScript web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `33 KB`, zero `node:*` / zero external imports), **AWS Lambda**, **Cloudflare Pages**, **Netlify**, and **Meta Frameworks** (Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start via `new BareJS({ prefix: '/api' })` + `export const GET = app.fetch`) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)**, official AI Agent Skill (`bunx skills add xarhang/bareJS`), and **511 tests across 38 files verified in CI (Bun, Node.js 20/22, Deno 2)**. ## 0. Complete Export & Subpath Index (Check Here First!) - `barejs` (core): `BareJS`, `BareRouter`, `Context`, `Type`/`T`/`TypeBox`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `isTokenRevoked`, `Hash`/`Password`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck`, `generateOpenAPISpec`, `renderDocsHTML` (router supports `:param`, optional `:param?`, regex `:id{[0-9]+}`, and `*` wildcards) - `barejs/node`: Node.js `>= 20` build (same exports + native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` / `ws` / `@node-rs/argon2`) - `barejs/edge` (`33 KB`): Zero-`node:*`, zero-external-dep Edge build (Cloudflare Workers, Vercel Edge, Deno Deploy) - `barejs/html` (`1.3 KB`): `html`, `raw`, `escapeHtml`, `type HtmlString` - `barejs/etag` (`2.4 KB`): `etag`, `type EtagOptions` - `barejs/cache` (`2.2 KB`): `cache`, `type CacheOptions` - `barejs/jsx` / `barejs/jsx-runtime` (`4.5 KB`): `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse` - `barejs/ssg` (`2.1 KB`): `toSSG`, `type ToSSGOptions`, `type ToSSGResult` - `barejs/aws-lambda` (`3.0 KB`): `awsLambda`, `handle`, `type AwsLambdaEvent`, `type AwsLambdaResult` - `barejs/cloudflare-pages` (`768 B`): `handle`, `cloudflarePages` (`export const onRequest = handle(app)`) - `barejs/netlify` (`752 B`): `handle`, `netlify` (`export default handle(app)`) ## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge) ```bash bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebSockets.js, Deno) bun create barejs my-app --bun # --bun | --node | --node-uws | --deno ``` ```ts import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy // Optional { poolSize, prefix } (or numeric poolSize 0..65536, default 1024): lazy bounded LIFO Context pool + optional base path prefix (e.g. `new BareJS({ prefix: '/api' })` or `app.basePath('/api')`) const app = new BareJS(); // Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams) app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name })); app.get('/ping', () => 'pong'); app.get('/logo', () => file('public/logo.png')); // Or file(ctx.params.name, { root: './uploads', download: true }) app.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; }); // Pull-based ReadableStream backpressure // Wildcard catch-all route (`ctx.params['*']`) app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] })); // Native TLS works across Bun, uWebSockets.js (SSLApp), and Node https: app.listen(3000); // or app.listen(8443, '0.0.0.0', false, { tls: { keyFileName, certFileName } }) ``` ## 2. Routing, Plugins & Unified Schema Validation Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.all`, `app.basePath(prefix)`, `app.group(prefix, fn)`, `app.route(prefix, router)`, `app.use(mwOrRouterOrPlugin)`. Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`): ```ts app.post('/users/:id', { detail: { summary: 'Update user', description: 'Updates user profile', tags: ['Users'] }, params: Type.Object({ id: Type.Integer() }), query: Type.Object({ active: Type.Optional(Type.Boolean()) }), headers: Type.Object({ 'x-client': Type.Optional(Type.String()) }), body: Type.Object({ name: Type.String({ minLength: 1 }) }), response: Type.Object({ id: Type.Number(), name: Type.String() }), // Recursive JIT projector auto-strips undeclared fields (e.g. password_hash)! maxBodySize: 1024 * 1024 // default 1MB (returns 413 on overflow) }, (ctx: Context) => ({ id: ctx.params.id, // auto-coerced to number active: ctx.query.active, // auto-coerced to boolean name: ctx.body.name, password_hash: 'secret' // automatically stripped before sending to client! })); ``` Supports **Standard Schema v1** (`~standard` — Valibot, ArkType, Zod 4, Effect; sync & async fail-closed), **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`). ### Modular Routers & Plugins ```ts // Sub-router const api = new BareRouter(); api.get('/items', () => []); // Modular sub-routers preserve full bareClient() type inference across prefixes: const api = new BareRouter().get('/items', () => []); const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api) ``` ## 3. Context (`ctx`) & Testing (`app.request`) - `await app.request('/items', { method: 'POST', body: JSON.stringify({ name: 'a' }) })`: Ergonomic in-memory helper (normalizes relative paths to `http://localhost` and delegates to `app.fetch`). - `ctx.req`: Raw incoming Bun `Request`. - `ctx.params`: Route params (`Record`, including `ctx.params['*']` for wildcards). - `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support. - `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit. - `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type). - `ctx.uploadStream({ maxFileSize, maxFiles, maxFieldSize, allowedTypes })`: True streaming `multipart/form-data` async generator yielding `{ type: 'field', fieldName, value }` and `{ type: 'file', fieldName, filename, safeName, contentType, stream }` (`ReadableStream`, $O(\text{chunk})$ memory). - `ctx.cookies`: Lazy parsed request cookies (`Record`). - `await ctx.setCookie(name, value, { secret?, httpOnly?, sameSite?, secure?, maxAge?, expires?, domain?, path? })`: Defaults to `HttpOnly; SameSite=Lax; Path=/`. Pass `secret` for HMAC-SHA256 signing. - `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing. - `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`). - `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`. - `ctx.ip`: Client IP from `x-forwarded-for` (first non-empty), `x-real-ip`, `cf-connecting-ip` (only when `trustProxy` is enabled), else peer IP or `'127.0.0.1'`. - `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`. - `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map` (automatically cleared on pool release). - **Response Helpers (Hono / Express style):** - `ctx.status(code)` (chainable) - `ctx.setHeader(name, val)` (chainable, copy-on-write safe) - `ctx.json(data)` -> `application/json` - `ctx.send(message, extra?)` -> `{ status: 'success' | 'error', msg: message, ...extra }` - `ctx.html(html, status?)` -> `text/html; charset=utf-8` - `ctx.text(text, status?)` -> `text/plain; charset=utf-8` - `ctx.redirect(url, status = 302)` -> `Location: url` - `ctx.problem(status, detailOrOpts?)` -> RFC 9457 `application/problem+json` (auto `title` & `instance`, supports extension fields) - `ctx.defer(fn)` -> Registers LIFO request-scoped cleanup callback (runs after handler finishes, even on error; 0 overhead when unused) - `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` -> `text/event-stream` ## 4. Context Enrichment (`app.derive`) & Plugin Deduplication ```ts const derivedApp = app.derive((ctx) => ({ requestTime: Date.now(), tenant: ctx.req.headers.get('x-tenant') || 'public' })); ``` Derived properties are attached directly onto `ctx` with TypeScript inference (`Bare`), automatically dispose values implementing `Symbol.asyncDispose` / `Symbol.dispose` after the handler finishes, and clean up when `Context` returns to the pool. Named plugins (`{ name, seed?, install }`) and sub-apps (`new BareJS({ name, seed })`) are automatically deduplicated when mounted via `.use()` or `.route()`. ## 5. Built-in Security Middlewares, Pluggable Redis Store, Compression & Static Cache ```ts import { cors, csrf, timeout, rateLimit, securityHeaders, idempotency, createSingleflight, redisStore, compress, bareAuth, createToken, basicAuth, hasRole, revokeToken, Hash, staticFile } from 'barejs'; // Optional shared Redis store (compatible with Bun.redis and ioredis) const store = redisStore(Bun.redis, { prefix: 'myapp:' }); app.use(securityHeaders()); app.use(cors({ origin: ['https://app.example.com'], credentials: true })); app.use(csrf({ allowedOrigins: ['https://app.example.com'], requireToken: true })); app.use(timeout(10_000, { status: 408, message: 'Timed out' })); app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip app.use(rateLimit({ windowMs: 60_000, max: 100, store })); // Omit store for zero-overhead in-memory Map app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } })); // Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true) app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store, keyScope: (ctx) => ctx.user?.id }), (ctx) => ({ paid: true })); // Thundering-herd / Cache-stampede request coalescer const sf = createSingleflight(); app.get('/report', () => sf('report-key', async () => ({ total: 100 }))); // Auth & Hashing (HS256 sync fast-path + RS256/ES256/JWKS async verification + revocationStore) const hash = await Hash.make('password'); // Argon2id (64MB default) const ok = await Hash.verify('password', hash); const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET!); app.get('/admin', bareAuth({ secret: process.env.JWT_SECRET!, revocationStore: store }), hasRole('admin'), (ctx) => ctx.user); app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user); ``` ## 6. Real-Time, RPC, OpenAPI & Client - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })` (Native on Bun, built-in RFC 6455 or optional `ws` on Node.js, `Deno.upgradeWebSocket` on Deno) - **SSE**: `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` (works across Bun, Node.js, Deno) - **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes) - **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`) - **Type-Safe Client & Chained RPC (`bareClient` / `bareTreaty`, URL or Zero-Network In-Memory `app`)**: - Network: `const api = bareClient('http://localhost:3000');` - In-Memory (SSR / Unit Tests): `const api = bareClient(app); await api.get('/users/:id', { params: { id: 1 } });` - Non-Throwing Result Union: `const res = await api.safe.get('/users/:id', { params: { id: 1 } }); // { ok: true, data } | { ok: false, error, status }` - Chained Proxy RPC & Typed WebSockets: `const treaty = bareTreaty(app); await treaty.users({ id: 1 }).get(); const ws = treaty.ws.chat.subscribe();` ## 7. Lifecycle & Error Handling ```ts app.onStart(() => console.log('Server started')); app.onDrain(async () => console.log('Draining...')); // Also triggered by IPC DRAIN_REQUEST app.onStop(async () => await db.close()); app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId })); app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' })); await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners ``` > **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`). ## 8. Optional Subpaths, Macros & Observability - **MCP Server (`barejs/mcp`)**: `app.use(mcp({ path: '/mcp', name: 'my-mcp' }))` — auto-exposes BareJS routes & schemas as MCP (2025-03-26 Streamable HTTP) tools and executes `tools/call` in-memory via `app.fetch()` with auth header forwarding. - **Live Visual DevTools (`barejs/devtools`)**: `app.use(devtools({ path: '/__bare' }))` — live dark-mode dashboard, SSE request waterfall, per-route p50/p95/p99 latency, redacted headers, and SSRF-safe replay (auto-disabled in `NODE_ENV=production`). - **Background Job Queue (`barejs/queue`)**: `const q = createQueue({ concurrency: 4, retries: 3 }); q.process('email', fn); q.enqueue('email', payload, { delayMs });` — exponential backoff, Dead-Letter Queue, and graceful `q.stop()`. - **Signed Webhooks (`barejs/webhooks`)**: `app.post('/webhooks', verifyWebhook({ secret, toleranceSec: 300 }), handler)` + `sendWebhook(url, payload, { secret, retries: 3 })` — Web Crypto HMAC-SHA256, replay window, secret rotation. - **Prometheus Metrics (`barejs/metrics`)**: `app.use(metrics('/metrics'))` — exports `http_requests_total`, `http_request_duration_seconds`, `http_requests_in_flight`, and custom counters/gauges with ID/UUID path normalization. - **AI / LLM Streaming (`barejs/ai`)**: `aiStream(async (emit) => { emit.text('Hi'); emit.done(); })` + `parseOpenAISSE(stream)` — structured SSE events with automatic `AbortSignal` cancellation on client disconnect. - **Client Disconnect & Streaming RPC**: `ctx.signal` / `ctx.onAbort(cb)` on `Context` & `EdgeContext`; `bareTreaty(app, { transformer: bareTransformer })` preserves `Date`/`Map`/`Set`/`BigInt`/`RegExp`/`URL` and decodes `text/event-stream` responses as `AsyncIterable` with `options.signal`. - **OpenTelemetry OTLP (`barejs/otel`)**: `app.use(otel({ url, serviceName, headers }))` — zero-dep OTLP/HTTP JSON (`v1/traces`) batch exporter. - **Unified Store (`barejs/store`)**: `memoryStore()`, `sqliteStore(db)`, `upstashStore({ url, token })`, `kvStore(env.KV)` + bridges `toRateLimitStore()`, `toCacheStore()`, `toIdempotencyStore()` for distributed `rateLimit()`, `cache()`, `idempotency()`, and workflows. - **Durable Workflows (`barejs/workflow`)**: `defineWorkflow(name, async (input, step) => { await step.run(...); await step.sleep(...); await step.waitForEvent(...); }, { store })` — crash-resumable idempotent step replay. - **HTML Templates (`barejs/html`, `649 B`)**: `html\`

Hello ${name}

${raw('✓')}\`.toResponse()` — auto-escapes XSS, supports nested `html`, arrays, and falsy values. - **Dynamic ETag (`barejs/etag`, `1.8 KB`)**: `app.use(etag())` (weak `Bun.hash`/FNV-1a default) or `etag({ weak: false })` (strong SHA-256) with `304 Not Modified`. - **AWS Lambda (`barejs/aws-lambda`, `2.4 KB`)**: `export const handler = awsLambda(app)` (alias `handle`) — supports API Gateway v1, v2, ALB, `Set-Cookie`, and binary base64. - **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro({ auth: { beforeHandle, resolve } }); app.use(plugin).get('/me', { auth: 'admin' }, handler);` - **Cookie & Per-Status Response Schemas**: `RouteSchemas` supports `cookies` validation and `response: { 200: OkSchema, 404: ErrSchema }` (reflected in OpenAPI 3.1 & `bareTreaty`). - **Observability (`tracing`, `serverTiming`)**: `app.use(tracing({ serverTiming: 'app', onSpan }))` — zero-dep W3C `traceparent` + `Server-Timing` header. --- # BareJS Comprehensive Guide Complete examples covering project scaffolding (`create-barejs`), validation, cookies, file uploads, security middlewares, `app.derive()`, `app.macro()`, real-time APIs, OpenAPI 3.1, JSON-RPC 2.0, and production hardening. --- ## 0. Project Scaffolding ([`create-barejs`](https://github.com/xarhang/create-barejs)) Create a production-ready BareJS app (pre-configured with JSON logging, `securityHeaders()`, `healthcheck()`, and OpenAPI 3.1 `/docs`) for **Bun**, **Node.js**, **Node.js + `uWebSockets.js`**, or **Deno**: ```bash # Interactive prompt bun create barejs my-app # Or pick a runtime directly bun create barejs my-bun-app --bun bun create barejs my-node-app --node bun create barejs my-uws-app --node-uws bun create barejs my-deno-app --deno ``` ### AI Agent Skill (Claude Code, Cursor, Codex, OpenCode) Install the official BareJS skill so your AI coding agent knows every BareJS API, subpath, and best practice: ```bash bunx skills add xarhang/bareJS # or: npx skills add xarhang/bareJS ``` --- ## 1. Unified Route Validation & Auto-Coercion (`body`, `query`, `params`, `headers`) Pass a schema object directly before your handler. BareJS automatically coerces numeric and boolean strings in `params` and `query`, enforces `maxBodySize` (`413 Payload Too Large`), and registers the route in OpenAPI `/docs`. ```typescript import { BareJS, Type, Z, native, type Context } from 'barejs'; const app = new BareJS(); // Declarative RouteSchemas (works with TypeBox, Zod, or Native JSON Schema) app.post('/orders/:orderId', { detail: { summary: 'Create Order', tags: ['Orders'] }, params: Type.Object({ orderId: Type.Integer() }), // "42" -> 42 query: Type.Object({ notify: Type.Optional(Type.Boolean()) }), // "true" -> true headers: Type.Object({ 'x-api-version': Type.Optional(Type.String()) }), body: Type.Object({ item: Type.String({ minLength: 1 }), qty: Type.Integer({ minimum: 1 }) }), // Response schema automatically strips undeclared secret fields (e.g. internal_cost) response: Type.Object({ orderId: Type.Number(), notify: Type.Optional(Type.Boolean()), body: Type.Object({ item: Type.String(), qty: Type.Number() }) }), maxBodySize: 512 * 1024 // 512 KB limit (returns 413 if exceeded) }, (ctx: Context) => ({ orderId: ctx.params.orderId, // number notify: ctx.query.notify, // boolean | undefined body: ctx.body, // validated body internal_cost: 9999 // automatically stripped before sending to client })); // Standalone middleware validators are also supported: app.post('/zod', Z.object({ email: Z.string().email() }), (ctx) => ctx.body); app.post('/native', native({ properties: { title: { type: 'string' }, priority: { type: 'number' } }, required: ['title'] // 'priority' is optional }), (ctx) => ctx.body); ``` --- ## 2. Cookies, HMAC Signed Cookies & Safe File Uploads ```typescript // HMAC-SHA256 Signed Cookies (HttpOnly & SameSite=Lax by default) app.post('/session', async (ctx) => { await ctx.setCookie('session_id', 'user_42', { secret: process.env.COOKIE_SECRET!, httpOnly: true, secure: true, sameSite: 'Strict', maxAge: 3600 }); return { loggedIn: true }; }); app.get('/session', async (ctx) => { const userId = await ctx.getSignedCookie('session_id', process.env.COOKIE_SECRET!); if (!userId) return ctx.status(401).json({ error: 'Invalid or tampered cookie' }); return { userId }; }); // Safe Multipart File Upload (enforces size, file count, MIME allowlist & filename sanitization) app.post('/upload', async (ctx) => { const { fields, files } = await ctx.upload({ maxFileSize: 5 * 1024 * 1024, // 5 MB -> 413 if exceeded maxFiles: 3, // -> 413 if exceeded allowedTypes: ['image/png', 'image/jpeg', 'application/pdf'] // -> 415 if unsupported }); return { fields, uploaded: files.map((f) => ({ safeName: f.safeName, size: f.size, type: f.type })) }; }); // True Streaming Multipart Upload (constant O(chunk) memory for large files) app.post('/upload-stream', async (ctx) => { const uploaded: string[] = []; for await (const part of ctx.uploadStream({ maxFileSize: 500 * 1024 * 1024 })) { if (part.type === 'file' && part.stream) { await Bun.write(`./uploads/${part.safeName}`, new Response(part.stream)); uploaded.push(part.safeName!); } } return { uploaded }; }); ``` --- ## 3. Production Security Suite, Idempotency & Singleflight ```typescript import { BareJS, securityHeaders, cors, csrf, timeout, rateLimit, idempotency, createSingleflight, redisStore, compress, bareAuth, createToken, hasRole, Hash, staticFile } from 'barejs'; const app = new BareJS(); const SECRET = process.env.JWT_SECRET || 'super-secret-key'; const store = redisStore(Bun.redis, { prefix: 'myapp:' }); // Optional: omit for in-memory Map app.use(securityHeaders()); app.use(cors({ origin: ['https://app.example.com'], credentials: true })); app.use(csrf({ allowedOrigins: ['https://app.example.com'] })); app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); app.use(rateLimit({ windowMs: 60_000, max: 100, store })); app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } })); // Payment/Order Double-Charge Protection (Idempotency-Key header) app.post('/payments', idempotency({ ttlMs: 86_400_000, store }), async (ctx) => { const body = await ctx.jsonBody(); return { chargeId: 'ch_101', amount: body.amount, status: 'paid' }; }); // Cache-Stampede / Thundering-Herd Request Coalescing const singleflight = createSingleflight(); app.get('/reports/daily', async () => { return singleflight.do('daily-report', async () => ({ revenue: 125_000, generatedAt: Date.now() })); }); // Argon2id Password Hashing & JWT Creation app.post('/login', async (ctx) => { const { password } = await ctx.jsonBody(); const hash = await Hash.make(password); const valid = await Hash.verify(password, hash); if (!valid) return ctx.status(401).send('Invalid credentials'); const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET); return { token }; }); // Protect routes with constant-time HS256 JWT or asymmetric RS256/ES256/JWKS app.get('/admin', bareAuth({ secret: SECRET, revocationStore: store }), hasRole('admin'), (ctx) => ({ user: ctx.user, requestId: ctx.requestId })); app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user); ``` --- ## 4. Type-Safe Context Derivation (`app.derive`), Plugins & Lifecycle Hooks ```typescript // Enrich ctx with full TypeScript inference (auto-cleaned on pool release) const appWithContext = app.derive((ctx) => ({ requestTime: Date.now(), traceId: ctx.requestId })); appWithContext.get('/trace', (ctx) => ({ traceId: ctx.traceId, // typed as string requestTime: ctx.requestTime // typed as number })); // Register a modular plugin app.use({ name: 'health-plugin', install(instance) { instance.get('/healthz', (ctx: any) => ({ ok: true, traceId: ctx.traceId })); } }); // Server Lifecycle & Error Masking app.onStart(() => console.log('Database ready')); app.onDrain(async () => console.log('Draining in-flight requests...')); app.onStop(async () => console.log('Cleaned up resources')); app.onError((err, ctx) => ctx.status(err.status || 500).json({ status: 'error', message: err.message, requestId: ctx.requestId })); ``` --- ## 5. Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client ```typescript import { BareJS, BareRouter, bareClient, Type } from 'barejs'; const usersRouter = new BareRouter().get('/users/:id', { params: Type.Object({ id: Type.Integer() }), query: Type.Object({ full: Type.Optional(Type.Boolean()) }), }, (ctx) => ({ id: ctx.params.id, full: ctx.query.full })); const app = new BareJS().route('/api', usersRouter); // Native Bun WebSocket (or `ws` peer dep on Node.js) app.ws('/ws/chat', { open: (ws) => ws.send('connected'), message: (ws, msg) => ws.send(`echo: ${msg}`) }); // Server-Sent Events (SSE) app.get('/events', (ctx) => ctx.sse(async (send) => { send({ step: 1, msg: 'streaming...' }, 'progress', '1'); })); // JSON-RPC 2.0 Endpoint (single, batch & notifications) app.rpc('/rpc', { add: ({ a, b }: { a: number; b: number }) => a + b }); // Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs) app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' }); // Ergonomic in-memory test helper const res = await app.request('/api/users/42?full=true'); // Type-Safe Client (Zero-Network In-Memory for tests/SSR OR Network URL) const inMemoryClient = bareClient(app); const localRes = await inMemoryClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } }); const httpClient = bareClient('http://localhost:3000'); const remoteRes = await httpClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } }); ``` --- ## 6. Production Observability, Hooks & Zero-Trust Hardening ```typescript import { BareJS, healthcheck, bareAuth, revokeToken, staticFile } from 'barejs'; const app = new BareJS() // Trust only your internal load balancer CIDRs (prevents X-Forwarded-For spoofing) .trustProxy(['10.0.0.0/8', '127.0.0.1']) // Built-in structured JSON access logging (or pass custom onLog callback) .useLog({ format: 'json' }) // Zero-overhead request/response lifecycle hooks .onRequest((ctx) => ctx.set('startedAt', performance.now())) .onResponse((ctx, res) => { const ms = (performance.now() - (ctx.get('startedAt') ?? 0)).toFixed(2); console.log(`[${ctx.requestId}] ${ctx.req.method} ${res.status} (${ms}ms)`); }) .use(healthcheck({ path: '/health', readyPath: '/ready', version: '1.0.0', checks: { db: async () => true } })) // Serve frontend SPA with automatic index.html fallback & production metadata cache .use(staticFile('public', { spa: true, maxAge: 3600 })) .use(bareAuth({ secret: process.env.JWT_SECRET!, isRevoked: async (payload) => isBlockedInRedis(payload.jti) })); revokeToken('compromised-jti-123', 3600_000); // OpenAPI 3.1 auto-detects bareAuth (bearerAuth) & basicAuth schemes automatically app.docs({ title: 'Production API', version: '1.0.0' }); // Enforce server-level maxRequestBodySize (default: 10MB) app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 }); ``` --- ## 7. Multi-Core Clustering (`listenCluster`) & Node.js `uWebSockets.js` Driver BareJS runs natively on **Bun**, **Node.js**, and **Deno**. On Node.js, installing `uWebSockets.js` automatically enables BareJS's built-in `uWebSockets.js` driver (with streaming backpressure, native WebSocket pub/sub, and graceful `drain()`): ```typescript import { BareJS } from 'barejs'; const app = new BareJS(); app.get('/ping', () => 'pong'); app.ws('/ws/room', { open(ws) { ws.subscribe('lobby'); }, message(ws, msg) { ws.publish('lobby', msg); } }); // One-line multi-core clustering with optional native TLS (Bun, uWS.SSLApp, or Node https) app.listenCluster(8443, 4, '0.0.0.0', { engine: 'auto', // 'auto' | 'uws' | 'http' (Node.js) tls: { keyFileName: '/certs/server.key', certFileName: '/certs/server.crt' } }); ``` --- ## 8. Zero-Node Edge Runtime (`barejs/edge`) Deploy directly to **Cloudflare Workers**, **Vercel Edge**, **Deno Deploy**, or **Fastly Compute** with zero `node:*` imports: ```typescript import { BareJS, cors, securityHeaders, createSingleflight } from 'barejs/edge'; const sf = createSingleflight(); const app = new BareJS<{ API_KEY: string }>() .use(securityHeaders()) .use(cors({ origin: '*' })) .get('/ping', () => 'pong') .get('/users/:id', (ctx) => ({ id: ctx.params.id, region: ctx.req.headers.get('cf-ipcountry'), hasKey: Boolean(ctx.env.API_KEY) })) .get('/cached', () => sf.do('report', async () => ({ generatedAt: Date.now() }))); export default app; ``` --- ## 9. Optional Modular Subpaths (`barejs/html`, `barejs/etag`, `barejs/cache`, `barejs/aws-lambda`) Import standalone subpaths individually: ### XSS-Safe HTML Templates (`barejs/html` — `649 B`) ```typescript import { BareJS } from 'barejs'; import { html, raw } from 'barejs/html'; const app = new BareJS().get('/profile', (ctx) => { const name = ctx.query.name || 'Guest'; const badge = raw('✓'); return html`

Hello ${name}

${badge}`.toResponse(); }); ``` ### Dynamic API ETag Middleware (`barejs/etag` — `1.8 KB`) ```typescript import { BareJS } from 'barejs'; import { etag } from 'barejs/etag'; // Weak FNV-1a 64-bit ETag by default (zero-async), or { weak: false } for strong SHA-256 const app = new BareJS() .use(etag()) .get('/items', () => ({ items: [1, 2, 3] })); ``` ### Edge Cache & `Cache-Control` Middleware (`barejs/cache` — `1.6 KB`) ```typescript import { BareJS } from 'barejs/edge'; import { cache } from 'barejs/cache'; // Sets Cache-Control / Vary and caches GET/HEAD via Web Cache API (caches.default) const app = new BareJS() .use(cache({ cacheControl: 'public, max-age=60, stale-while-revalidate=30', vary: 'Accept-Encoding' })) .get('/feed', () => ({ updatedAt: Date.now() })); ``` ### AWS Lambda, Cloudflare Pages & Netlify Adapters ```typescript import { BareJS } from 'barejs/edge'; import { awsLambda } from 'barejs/aws-lambda'; import { handle as cfPages } from 'barejs/cloudflare-pages'; import { handle as netlify } from 'barejs/netlify'; const app = new BareJS() .get('/animals/:type?', (ctx) => ({ type: ctx.params.type ?? 'all' })) .get('/users/:id{[0-9]+}', (ctx) => ({ id: Number(ctx.params.id) })); export const handler = awsLambda(app); // AWS Lambda (API Gateway v1/v2 & ALB) export const onRequest = cfPages(app); // Cloudflare Pages Functions export default netlify(app); // Netlify Functions v2 ``` ### JSX Streaming SSR (`barejs/jsx`) & Static Site Generation (`barejs/ssg`) ```typescript import { BareJS } from 'barejs'; import { jsx, Suspense, streamResponse } from 'barejs/jsx'; import { toSSG } from 'barejs/ssg'; const Slow = async () => jsx('p', { children: 'Loaded asynchronously!' }); const app = new BareJS() .get('/', () => streamResponse( jsx(Suspense, { fallback: jsx('p', { children: 'Loading...' }), children: jsx(Slow, null) }) )); // Pre-render static GET routes to ./static at build time: await toSSG(app, { dir: './static', routes: ['/'] }); ``` --- ## 9. Production Kit Subpaths (`mcp`, `devtools`, `queue`, `webhooks`, `metrics`, `ai`) & Request Cleanup All modules below are standalone zero-dependency subpaths (0 bytes in core/edge when unused): ### Request Cleanup (`ctx.defer`, `Symbol.asyncDispose`) & RFC 9457 (`ctx.problem`) ```typescript import { BareJS } from 'barejs'; const app = new BareJS() .derive(() => ({ tx: { query: (sql: string) => sql, async [Symbol.asyncDispose]() { /* auto-closed after handler completes */ } } })) .get('/users/:id', (ctx) => { ctx.defer(() => { /* LIFO cleanup, runs even if handler throws */ }); if (ctx.params.id === '0') { return ctx.problem(404, { code: 'USER_NOT_FOUND', detail: 'User does not exist' }); } return { id: ctx.params.id }; }); ``` ### 1-Line MCP Server (`barejs/mcp`) & Live DevTools (`barejs/devtools`) ```typescript import { BareJS, Type } from 'barejs'; import { mcp } from 'barejs/mcp'; import { devtools } from 'barejs/devtools'; const app = new BareJS() .use(devtools({ path: '/__bare' })) // Auto-disabled in NODE_ENV=production .post('/orders', { body: Type.Object({ item: Type.String(), qty: Type.Integer() }), detail: { summary: 'Create a new order' } }, (ctx) => ({ created: ctx.body })) .use(mcp({ path: '/mcp', name: 'orders-mcp' })); // Exposes POST /orders as an MCP Tool! ``` ### Background Queue (`barejs/queue`), Signed Webhooks (`barejs/webhooks`), Prometheus (`barejs/metrics`) & AI Streaming (`barejs/ai`) ```typescript import { BareJS } from 'barejs'; import { createQueue } from 'barejs/queue'; import { verifyWebhook, sendWebhook } from 'barejs/webhooks'; import { metrics } from 'barejs/metrics'; import { aiStream } from 'barejs/ai'; const jobs = createQueue({ concurrency: 4, retries: 3 }); jobs.process<{ email: string }>('welcome', async (p) => { /* send email */ }); const prom = metrics({ path: '/metrics', prefix: 'myapp_' }); const app = new BareJS() .use(prom) .post('/webhooks/stripe', verifyWebhook({ secret: process.env.WEBHOOK_SECRET!, toleranceSec: 300 }), (ctx) => { jobs.enqueue('welcome', { email: ctx.body.email }); return { received: true }; }) .get('/ai/chat', () => aiStream(async (emit) => { emit.text('Hello from BareJS AI!'); emit.done(); })) .onStop(() => jobs.stop()); ``` ### Client Disconnect (`ctx.signal`), Typed SSE RPC & Rich Type Transformer (`bareTransformer`) ```typescript import { BareJS, bareTreaty, bareTransformer } from 'barejs'; const app = new BareJS() .get('/stream', (ctx) => { ctx.onAbort(() => console.log('Client disconnected')); return ctx.sse<{ step: number; at: Date }>((async function* () { yield { data: bareTransformer.serialize({ step: 1, at: new Date() }) }; yield { data: bareTransformer.serialize({ step: 2, at: new Date() }) }; })()); }); const client = bareTreaty(app, { transformer: bareTransformer }); const res = await client.stream.get(); if (res.ok) { for await (const chunk of res.data) { // chunk is compile-time typed as { step: number; at: Date }! console.log(chunk.step, chunk.at.toISOString()); } } ``` ### OpenTelemetry OTLP (`barejs/otel`), Unified Store (`barejs/store`) & Durable Workflows (`barejs/workflow`) ```typescript import { BareJS, rateLimit, idempotency } from 'barejs'; import { otel } from 'barejs/otel'; import { cache } from 'barejs/cache'; import { upstashStore, toRateLimitStore, toCacheStore, toIdempotencyStore } from 'barejs/store'; import { defineWorkflow } from 'barejs/workflow'; const store = upstashStore({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN! }); const orderFlow = defineWorkflow('order-flow', async (input: { id: string }, step) => { const charge = await step.run('charge', () => ({ ok: true, id: input.id })); await step.sleep('wait', 5000); const approval = await step.waitForEvent<{ approvedBy: string }>('approval', 'order.approved'); return { charge, approval }; }, { store }); const app = new BareJS() .use(otel({ url: 'https://otlp.example.com/v1/traces', serviceName: 'orders-api' })) .use(rateLimit({ max: 100, windowMs: 60_000, store: toRateLimitStore(store) })) .get('/catalog', cache({ cache: toCacheStore(store, 60_000), cacheControl: 'public, max-age=60' }), () => ({ items: [] })) .post('/orders', idempotency({ store: toIdempotencyStore(store) }), async (ctx) => { return orderFlow.start({ id: ctx.body.id }); }); ``` --- # BareJS API & Configuration Reference ## 1. `Context` (`ctx`) Reference Every route handler and middleware receives a pooled `Context` (or `EdgeContext` in `barejs/edge`). | Method / Property | Signature / Default | Description | | :--- | :--- | :--- | | `ctx.req` | `Request` | Raw incoming Web Standard `Request`. | | `ctx.params` | `Record` | Route parameters (`:id`, `:id{[0-9]+}`, `:type?`, or `ctx.params['*']`). Inferred automatically at compile time from the route path literal. | | `ctx.query` | `Record` | Lazy, prototype-pollution-safe parsed query parameters. | | `ctx.getQuery(k)` / `ctx.queryAll(k)` | `string \| undefined` / `string[]` | Safe single-key lookup or all repeated query values in order. | | `ctx.body` | `any` (typed when schema present) | Validated & parsed request body (when route schema is attached). | | `await ctx.jsonBody(maxBytes?)` | `default: 1_048_576` (1 MB) | Parses & caches JSON body; enforces `413 Payload Too Large` on oversized payloads. | | `await ctx.upload(opts?)` | `{ maxFileSize?, maxFiles?, allowedTypes? }` | Safe `multipart/form-data` upload parser (default 5 MB/file, 10 files). | | `ctx.uploadStream(opts?)` | `AsyncGenerator` | Streaming `multipart/form-data` parser (`ReadableStream` per file part, $O(\text{chunk})$ memory). | | `ctx.cookies` | `Record` | Lazy parsed request cookies (null-prototype object). | | `await ctx.setCookie(k, v, opts?)` | `HttpOnly; SameSite=Lax` default | Sets a cookie; optional `{ secret, maxAge, expires, path, domain, secure, httpOnly, sameSite }`. | | `await ctx.getSignedCookie(k, secret)` | `Promise` | Constant-time HMAC-SHA256 signed cookie verification. | | `ctx.deleteCookie(k, opts?)` | `this` | Expires a cookie immediately (`Max-Age=0`). | | `ctx.user` | `AuthUser \| undefined` | Authenticated user payload attached by `bareAuth` or `basicAuth`. | | `ctx.requestId` | `string` | Incoming `x-request-id` header or generated UUIDv4. | | `ctx.ip` | `string` | Client IP from forwarded headers (when `trustProxy` is enabled) or socket peer IP. | | `ctx.signal` | `AbortSignal` | Lazy `AbortSignal` that fires when the client disconnects or aborts (0 ns overhead when unused). | | `ctx.onAbort(cb)` | `() => void` | Registers a client-disconnect listener; returns an unsubscribe function. | | `ctx.defer(fn)` | `this` | Registers a request-scoped LIFO cleanup callback executed after the handler completes (even on thrown errors). | | `ctx.status(code)` | `this` | Sets HTTP response status code (chainable). | | `ctx.setHeader(name, value)` | `this` | Sets response header (chainable, CRLF-guarded, copy-on-write safe). | | `ctx.json(data)` | `Response` | Returns `application/json` response. | | `ctx.problem(status, detailOrOpts?)` | `Response` | RFC 9457 `application/problem+json` response with auto `title`, `instance`, extension members, and CORS/cookie preservation. | | `ctx.send(msg, extra?)` | `Response` | Returns standardized `{ status, msg, ...extra }` JSON response. | | `ctx.html(html, status?)` | `Response` | Returns `text/html; charset=utf-8` response. | | `ctx.text(text, status?)` | `Response` | Returns `text/plain; charset=utf-8` response. | | `ctx.redirect(url, status?)` | `Response` | Returns HTTP redirect response (default `302`). | | `ctx.sse(source)` | `SseResponse` | Streams Server-Sent Events (`text/event-stream`); typed as `AsyncIterable` in `bareTreaty`. | | `ctx.set(k, v)` / `ctx.get(k)` | `void` / `any` | Per-request key-value storage (cleared automatically on pool release). | --- ## 2. `BareJS` Application & Routing Methods | Method | Options / Signature | Description | | :--- | :--- | :--- | | `new BareJS(opts?)` | `{ prefix?: string, poolSize?: number }` | Creates an app with optional base path prefix (e.g. `'/api'`) and Context pool size (`0..65536`, default `1024`). | | `app.basePath(prefix)` | `this` | Fluent alias for setting a route prefix (also supported on `BareEdge`). | | `app.get / post / put / patch / delete / options / head / all` | `(path, [schemas \| ...mws], handler)` | Registers typed HTTP routes; supports static, `:param`, `:param?`, `:id{[0-9]+}`, and `*` wildcards. | | `app.group(prefix, ...mws, cb)` | `this` | Groups routes under a shared prefix and middleware stack (inherits macros & merges `.ws()` routes). | | `app.route(prefix, router)` / `app.use(plugin)` | `this` | Mounts sub-routers or plugins with automatic `name` + `seed` deduplication. | | `app.derive(fn)` | `BareJS` | Injects per-request derived properties into `ctx`; auto-disposes `Symbol.asyncDispose` / `Symbol.dispose` values after response. | | `app.macro({ [name]: { beforeHandle?, resolve? } })` | `BareJS<..., Macros>` | Registers declarative per-route macros inherited across plugins and groups. | | `app.ws(path, handlers)` | `{ body?, query?, headers?, open?, message?, close?, drain? }` | Native WebSocket route with fail-closed validation and pub/sub (`subscribe`, `unsubscribe`, `publish`). | | `app.docs(path?, opts?)` | `{ title?, version?, description?, jsonPath? }` | Mounts auto-generated OpenAPI 3.1 JSON + Scalar UI (auto-detects auth schemes & per-status responses). | | `app.rpc(path, procedures)` | `this` | Mounts a JSON-RPC 2.0 endpoint supporting single and batch calls. | | `app.cron(name, schedule, fn)` | `this` | Registers an overlap-locked scheduled task (auto-stopped on `app.stop()`). | | `app.onRequest(fn)` / `app.onResponse(fn)` | `this` | Global request/response lifecycle hooks (0 ns overhead when unused). | | `app.onError(fn)` / `app.setNotFound(fn)` | `this` | Custom error handler and 404 handler (both chainable). | | `app.onStart(fn)` / `app.onDrain(fn)` / `app.onStop(fn)` | `this` | Server startup, graceful in-flight drain, and shutdown hooks. | | `app.trustProxy(val)` | `boolean \| string[]` | Enables forwarded IP resolution; accepts CIDR/IP allowlist (e.g. `['10.0.0.0/8', '127.0.0.1']`). | | `app.useLog(opts)` | `boolean \| { format?: 'pretty' \| 'json', onLog? }` | Built-in request logger. | | `app.listen(port?, host?, reusePort?, opts?)` | `{ engine?: 'auto' \| 'uws' \| 'http', tls?, maxRequestBodySize?, trustProxy? }` | Starts the HTTP/WebSocket server on Bun, Node.js (`uWebSockets.js` / `node:http`), or Deno. | | `app.listenCluster(port?, workers?, host?, opts?)` | Same as `listen()` | Spawns multi-core workers (`reusePort` on Bun or `node:cluster` on Node.js) with TLS support. | | `app.fetch(req, peerIp?)` / `app.request(path, init?)` | `Promise` | Web Standard Fetch handler (for Next.js/Astro/Workers/Lambda) and in-memory test helper. | --- ## 3. Built-In Security & Resilience Middleware Options ### `bareAuth(options)` | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `secret` | `string \| Uint8Array` | — | HMAC secret for `HS256` tokens (min 32 chars recommended). | | `publicKey` / `jwksUri` | `string \| CryptoKey` | — | Public key or remote JWKS endpoint for `RS256` / `ES256` verification. | | `issuer` / `audience` | `string \| string[]` | — | Optional `iss` and `aud` claim validation. | | `cookieName` | `string` | — | Also read JWT from an `HttpOnly` cookie if `Authorization` header is absent. | | `revocationStore` | `RevocationStore` | — | Optional store (`isRevoked(jti)`) for immediate token revocation. | ### `cors(options)` | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `origin` | `string \| string[] \| RegExp \| (origin: string) => boolean` | `'*'` | Allowed origin(s); automatically appends `Vary: Origin` for non-wildcard origins. | | `methods` | `string[]` | `['GET','POST','PUT','PATCH','DELETE','OPTIONS']` | Allowed HTTP methods. | | `credentials` | `boolean` | `false` | Sets `Access-Control-Allow-Credentials: true` (blocked when `origin: '*'`). | | `maxAge` | `number` | `86400` | Preflight cache duration in seconds. | ### `rateLimit(options)` | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `max` | `number` | `100` | Maximum requests per window. | | `windowMs` | `number` | `60_000` | Window size in milliseconds. | | `keyGenerator` | `(ctx: Context) => string` | `(ctx) => ctx.ip` | Custom bucket key (e.g. API key, user ID, route). | | `maxEntries` | `number` | `10_000` | Bounded in-memory LRU cap. | | `store` | `RateLimitStore` | in-memory | Distributed store (use `toRateLimitStore(store)` from `barejs/store` or `redisStore()`). | ### `idempotency(options)` | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `headerName` | `string` | `'idempotency-key'` | Header carrying the caller's idempotency key. | | `ttlMs` | `number` | `300_000` | Replay cache TTL in ms (5 minutes). | | `maxKeys` | `number` | `10_000` | Bounded in-memory LRU cap. | | `store` | `IdempotencyStore` | in-memory | Distributed store (use `toIdempotencyStore(store)` from `barejs/store` or `redisStore()`). | | `keyScope` | `(ctx: Context) => string \| undefined` | SHA-256 of Auth/Cookie | Isolates keys per caller to prevent cross-user replay. | ### `csrf(options)` & `circuitBreaker(options)` & `compress(options)` - **`csrf({ allowedOrigins?, ignoreMethods?, cookieName?, headerName?, requireToken?, allowMissingOrigin? })`**: Origin/Fetch-Metadata CSRF guard for state-changing requests (`POST`/`PUT`/`PATCH`/`DELETE`). - **`circuitBreaker({ failureThreshold?: 5, resetTimeoutMs?: 30_000 })`**: `CLOSED → OPEN → HALF_OPEN` resilience guard returning `503` when open. - **`compress({ threshold?: 1024 })`**: Compresses text/JSON responses with `zstd`, `br`, or `gzip`; skips binary MIME types (`image/*`, `video/*`, `audio/*`, `font/*`, `application/zip`, `application/pdf`) and SSE streams. --- ## 4. `bareTreaty` & `bareClient` RPC Reference ```typescript import { bareTreaty, bareClient, bareTransformer } from 'barejs'; const api = bareTreaty('https://api.example.com', { headers: { authorization: 'Bearer ...' }, transformer: bareTransformer, // preserves Date, Map, Set, BigInt, RegExp, URL (or pass superjson) fetch: customFetch }); ``` | Feature | Usage | | :--- | :--- | | **Discriminated Result** | `const res = await api.users({ id: 42 }).get(); if (res.ok) res.data; else res.error;` | | **Abort / Timeout** | `await api.reports.get({ signal: AbortSignal.timeout(5000) })` | | **Typed SSE Streaming** | Routes returning `ctx.sse(...)` unwrap to `AsyncIterable` (`for await (const chunk of res.data)`). | | **Typed WebSockets** | `const ws = api.chat.subscribe({ query: { room: 'general' } }); ws.onMessage((m) => ...);` | | **In-Memory Testing** | `bareTreaty(app)` executes requests in-memory via `app.fetch()` with zero network sockets. | --- ## 5. Optional Modular Subpaths (0 Bytes in Core When Unused) | Subpath | Bundle Size | Exports & Key Options | | :--- | :---: | :--- | | `barejs/edge` | `39 KB` | `BareEdge` (`BareJS`), `bareClient`, `bareTreaty`, `bareTransformer`, `cors`, `securityHeaders`, `rateLimit`, `timeout`, `circuitBreaker`, `healthcheck`, `logger`, `etag`, `cache`. Zero `node:*` imports. | | `barejs/mcp` | `11 KB` | `mcp({ path?: '/mcp', name?, version?, include?, exclude?, authHeaderPassthrough?: true })` — Auto-discovers routes & schemas as MCP `2025-03-26` tools; executes in-memory via `app.fetch()`. | | `barejs/devtools` | `8.4 KB` | `devtools({ path?: '/__bare', maxEntries?: 200, redactHeaders?, enabled? })` — Dark-mode Request Inspector, SSE waterfall, p50/p95/p99 latency profiler, SSRF-safe replay; auto-disabled in `NODE_ENV=production`. | | `barejs/queue` | `2.8 KB` | `createQueue({ concurrency?: 4, retries?: 3, backoffMs?: 100, maxBackoffMs?: 30_000, maxQueueSize?: 10_000, onDeadLetter? })` — Compile-time typed `.process(name, fn)` / `.enqueue(name, payload)`, delayed jobs, DLQ, `drain()`, `stop()`. | | `barejs/webhooks` | `3.7 KB` | `verifyWebhook({ secret: string \| string[], headerName?: 'x-bare-signature', toleranceSec?: 300 })`, `signWebhookPayload(payload, secret)`, `sendWebhook(url, payload, { secret, retries?, backoffMs? })`. | | `barejs/metrics` | `3.5 KB` | `metrics({ path?: '/metrics', prefix?: '', includeDefaultLabels? })` — Prometheus text exporter (`http_requests_total`, `http_request_duration_seconds`, `http_requests_in_flight`) + `incCounter()`, `setGauge()`. | | `barejs/ai` | `2.5 KB` | `aiStream(async (emit) => { emit.text(); emit.json(); emit.toolCall(); emit.toolResult(); emit.usage(); emit.done(); })` + `parseOpenAISSE(stream)` with client-disconnect `AbortSignal`. | | `barejs/otel` | `3.5 KB` | `otel({ url, serviceName?, serviceVersion?, headers?, batchSize?: 32, flushIntervalMs?: 5000 })`, `createOtlpExporter(opts)` — OTLP/HTTP JSON (`v1/traces`) exporter for Grafana/Datadog/Honeycomb/Jaeger. | | `barejs/store` | `5.4 KB` | `memoryStore({ maxEntries? })`, `sqliteStore(db, { tableName? })`, `upstashStore({ url, token, prefix? })`, `kvStore(binding, { prefix? })` + bridges `toRateLimitStore()`, `toCacheStore()`, `toIdempotencyStore()`. | | `barejs/workflow` | `5.0 KB` | `defineWorkflow(name, async (input, step) => ..., { store?, ttlMs? })` — `step.run(id, fn)`, `step.sleep(id, ms)`, `step.waitForEvent(id, eventName)`, `start()`, `resume()`, `sendEvent()`, `status()`. | | `barejs/html` | `649 B` | `html\`...\``, `raw(str)`, `escapeHtml(str)`, `.toResponse()`. | | `barejs/etag` | `1.8 KB` | `etag({ weak?: true })` — Weak (`Bun.hash`/FNV-1a) or strong (SHA-256) ETag + `304 Not Modified`. | | `barejs/cache` | `2.2 KB` | `cache({ cacheControl?, vary?, cacheName?, cache?, keyGenerator?, wait?, cacheableStatuses? })`. | | `barejs/jsx` | `4.5 KB` | `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse`. | | `barejs/ssg` | `2.1 KB` | `toSSG(app, { dir?, routes?, concurrency? })` — Build-time Static Site Generator with path-traversal guard. | | `barejs/aws-lambda` | `3.0 KB` | `awsLambda(app)` / `handle(app)` — API Gateway v1/v2 & ALB, cookies, binary base64. | | `barejs/cloudflare-pages` | `768 B` | `cloudflarePages(app)` / `handle(app)` — Cloudflare Pages Functions `onRequest` adapter. | | `barejs/netlify` | `752 B` | `netlify(app)` / `handle(app)` — Netlify Functions v2 adapter. | --- ## 6. Performance & Environment Configuration | Variable / File | Default | Description | | :--- | :--- | :--- | | `bare.config.ts` | Optional | Centralized config for `port` and Argon2id/scrypt `hash` parameters. | | `poolSize` | `1024` | `new BareJS({ poolSize })` — maximum released `Context` instances retained in the bounded LIFO pool (`0..65536`; `0` disables pooling). | | `NODE_ENV` | `development` | Set to `production` to mask 500 stack traces, disable the startup banner, enable `staticFile` metadata caching, auto-disable `barejs/devtools`, and disable the dev-mode UAF Proxy guard. | | `BARE_DEBUG_UAF` | `0` | Set to `1` to explicitly enable the Context Use-After-Free Proxy detector outside `NODE_ENV=development`. | --- # BareJS Production Cookbook & Recipes Copy-pasteable, production-hardened patterns using BareJS built-in APIs and zero-dependency subpaths. --- ## 1. JWT Authentication + RBAC Macro + Revocation ```typescript import { BareJS, bareAuth, createToken, Hash, Type } from 'barejs'; const SECRET = process.env.JWT_SECRET!; const revoked = new Set(); const app = new BareJS() .macro({ requireRole: { beforeHandle: (ctx, role: 'admin' | 'editor') => { if (!ctx.user) return ctx.problem(401, 'Authentication required'); if (ctx.user.role !== role && ctx.user.role !== 'admin') { return ctx.problem(403, `Requires ${role} role`); } } } }) .post('/auth/login', { body: Type.Object({ email: Type.String({ format: 'email' }), password: Type.String({ minLength: 8 }) }) }, async (ctx) => { const valid = await Hash.verify(ctx.body.password, storedPasswordHash); if (!valid) return ctx.problem(401, 'Invalid credentials'); const token = await createToken({ sub: 'u_1', role: 'admin', jti: crypto.randomUUID() }, SECRET, { expiresIn: '15m' }); await ctx.setCookie('session', token, { httpOnly: true, secure: true, sameSite: 'Lax', maxAge: 900 }); return { token }; }) .group('/admin', bareAuth({ secret: SECRET, cookieName: 'session', revocationStore: { revoke: (jti) => { revoked.add(jti); }, isRevoked: (jti) => revoked.has(jti) } }), (r) => { r.delete('/users/:id', { requireRole: 'admin' }, (ctx) => ({ deleted: ctx.params.id })); }); ``` --- ## 2. Database Connection Scoping with `ctx.defer()` & `Symbol.asyncDispose` Never leak DB connections or transactions even when a handler throws: ```typescript import { BareJS } from 'barejs'; const app = new BareJS() .derive(async () => { const conn = await pool.acquire(); return { db: conn, // Automatically invoked AFTER the handler finishes (or throws)! [Symbol.asyncDispose]: async () => { await conn.release(); } }; }) .post('/transfer', async (ctx) => { const tx = await ctx.db.begin(); let committed = false; ctx.defer(async () => { if (!committed) await tx.rollback(); }); await tx.exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1'); await tx.exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2'); await tx.commit(); committed = true; return { ok: true }; }); ``` --- ## 3. AI Chat API + MCP Server + Live DevTools Expose your existing REST routes to Claude / Cursor via MCP and inspect live latency at `/__bare`: ```typescript import { BareJS, Type } from 'barejs'; import { mcp } from 'barejs/mcp'; import { devtools } from 'barejs/devtools'; import { aiStream } from 'barejs/ai'; const app = new BareJS() .use(devtools({ path: '/__bare' })) // auto-disabled when NODE_ENV=production .get('/weather/:city', { detail: { summary: 'Get current weather for a city' } }, (ctx) => ({ city: ctx.params.city, tempC: 30 })) .post('/ai/chat', { body: Type.Object({ prompt: Type.String() }) }, (ctx) => aiStream(async (emit) => { // Aborts automatically if the user clicks Stop const res = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', signal: emit.signal, headers: { authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 'content-type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4o-mini', stream: true, messages: [{ role: 'user', content: ctx.body.prompt }] }) }); emit.text('Streaming response...'); emit.done(); }) ) .use(mcp({ path: '/mcp', name: 'my-assistant' })); app.listen(3000); ``` --- ## 4. Distributed Rate-Limiting, Caching & Idempotency with `barejs/store` Switch seamlessly from local dev (`memoryStore()` / `sqliteStore(db)`) to multi-region production (`upstashStore()` / `kvStore(env.KV)`): ```typescript import { BareJS, rateLimit, idempotency } from 'barejs'; import { cache } from 'barejs/cache'; import { upstashStore, toRateLimitStore, toCacheStore, toIdempotencyStore } from 'barejs/store'; const store = upstashStore({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN! }); const app = new BareJS() .use(rateLimit({ max: 120, windowMs: 60_000, store: toRateLimitStore(store) })) .get('/products', cache({ cache: toCacheStore(store, 60_000), cacheControl: 'public, max-age=60' }), () => ({ items: [] })) .post('/payments', idempotency({ store: toIdempotencyStore(store), ttlMs: 300_000 }), (ctx) => ({ charged: true })); ``` --- ## 5. Durable Multi-Step Order Workflow + Signed Webhooks Persist completed steps so a server crash never double-charges a customer: ```typescript import { BareJS } from 'barejs'; import { memoryStore } from 'barejs/store'; import { defineWorkflow } from 'barejs/workflow'; import { verifyWebhook } from 'barejs/webhooks'; const store = memoryStore(); // swap for sqliteStore(db) or upstashStore(...) in production const orderWorkflow = defineWorkflow('order-fulfillment', async (input: { orderId: string }, step) => { const receipt = await step.run('charge-card', () => ({ receiptId: `rcpt_${input.orderId}` })); const approval = await step.waitForEvent<{ approvedBy: string }>('wait-fraud-check', 'fraud.cleared'); const tracking = await step.run('dispatch', () => ({ trackingId: `TRK_${input.orderId}`, by: approval.approvedBy })); return { receipt, tracking }; }, { store }); const app = new BareJS() .post('/orders/:id', (ctx) => orderWorkflow.start({ orderId: ctx.params.id }, { runId: ctx.params.id })) .post('/webhooks/fraud', verifyWebhook({ secret: process.env.WEBHOOK_SECRET! }), async (ctx) => { const { orderId, approvedBy } = ctx.body; return orderWorkflow.sendEvent(orderId, 'fraud.cleared', { approvedBy }); }); ``` --- ## 6. Observability: OpenTelemetry OTLP + Prometheus Metrics ```typescript import { BareJS } from 'barejs'; import { otel } from 'barejs/otel'; import { metrics } from 'barejs/metrics'; const otelMw = otel({ url: process.env.OTLP_URL || 'http://localhost:4318/v1/traces', serviceName: 'billing-api', headers: { authorization: `Bearer ${process.env.OTLP_TOKEN}` } }); const app = new BareJS() .use(otelMw) .use(metrics({ path: '/metrics', prefix: 'billing_' })) .get('/health', () => ({ ok: true })) .onStop(() => otelMw.stop()); ``` --- ## 7. Multi-Core TLS Cluster + Graceful Shutdown ```typescript import { BareJS, healthcheck } from 'barejs'; const app = new BareJS() .use(healthcheck({ path: '/healthz' })) .onDrain(async () => { /* stop accepting background jobs */ }) .onStop(async () => { /* close DB pools */ }); app.listenCluster(8443, undefined, '0.0.0.0', { engine: 'auto', // Bun native -> uWebSockets.js -> node:http tls: { keyFileName: '/etc/certs/server.key', certFileName: '/etc/certs/server.crt' } }); ``` --- ## 8. Troubleshooting & FAQ - **Why is `ctx.body` `undefined`?** `ctx.body` is automatically populated when you attach a route schema (`{ body: ... }`). On schema-less routes, call `await ctx.jsonBody()` (enforces 1 MB limit) or `await ctx.req.json()`. - **Why did `barejs/devtools` return `404` in production?** `devtools()` automatically disables itself when `NODE_ENV=production` for security. Pass `devtools({ enabled: true })` only if you explicitly protect `/__bare` behind auth/VPN. - **Why did `barejs/edge` fail to import `node:fs`?** `barejs/edge` is intentionally zero-Node (`39 KB`) for Cloudflare Workers / Vercel Edge / Deno Deploy. Use `barejs` (or `barejs/node`) for Node/Bun server APIs like `file()` or `staticFile()`. - **How do I avoid `Context` Use-After-Free in background tasks?** `Context` instances are pooled and reset after the response is sent. Read any needed values (`const ip = ctx.ip; const body = ctx.body;`) before starting detached background work (`queue.enqueue(...)`). --- # Migration Guide — Express, Hono & ElysiaJS to BareJS This guide shows 1-to-1 equivalents for migrating existing **Express**, **Hono**, or **ElysiaJS** applications to **BareJS**. --- ## 1. Migrating from Express.js | Concept | Express.js | BareJS | | :--- | :--- | :--- | | App creation | `const app = express()` | `const app = new BareJS()` | | JSON body parsing | `app.use(express.json())` | Built-in (`ctx.body` with schema, or `await ctx.jsonBody()`) | | Route params | `req.params.id` | `ctx.params.id` (compile-time typed!) | | Query params | `req.query.page` | `ctx.query.page` / `ctx.getQuery('page')` | | Send JSON | `res.status(201).json(data)` | `ctx.status(201).json(data)` or return `{ ... }` directly | | Error response | `res.status(404).json({ error })` | `ctx.problem(404, 'User not found')` (RFC 9457) | | Middleware | `(req, res, next) => { ... next(); }` | `async (ctx, next) => { ... return next(); }` | | Router / Prefix | `app.use('/api', router)` | `app.route('/api', router)` or `app.group('/api', (r) => ...)` | | Security headers | `helmet()` | `securityHeaders()` (built-in) | | Rate limiting | `express-rate-limit` | `rateLimit({ max: 100, windowMs: 60_000 })` (built-in) | | Error middleware | `app.use((err, req, res, next) => ...)` | `app.onError((err, ctx) => ctx.problem(500, err.message))` | | Start server | `app.listen(3000)` | `app.listen(3000)` (or `app.listenCluster(3000)` for multi-core) | ### Express → BareJS Example ```typescript import { BareJS, cors, securityHeaders, rateLimit, Type } from 'barejs'; const app = new BareJS() .use(securityHeaders(), cors({ origin: 'https://app.example.com' }), rateLimit({ max: 100 })) .get('/users/:id', (ctx) => ({ id: ctx.params.id })) .post('/users', { body: Type.Object({ name: Type.String(), email: Type.String({ format: 'email' }) }) }, (ctx) => ctx.status(201).json({ created: ctx.body })) .onError((err, ctx) => ctx.problem(500, err.message)); app.listen(3000); ``` --- ## 2. Migrating from Hono | Concept | Hono | BareJS | | :--- | :--- | :--- | | Node / Bun / Deno app | `new Hono()` | `new BareJS()` | | Edge Worker app | `new Hono()` | `import { BareJS } from 'barejs/edge'; new BareJS()` (`39 KB`, zero deps) | | Base path | `app.basePath('/api')` | `app.basePath('/api')` or `new BareJS({ prefix: '/api' })` | | JSON response | `c.json({ ok: true }, 201)` | `ctx.status(201).json({ ok: true })` | | Validation | `@hono/zod-validator` | Built-in Standard Schema v1 (Zod, Valibot, ArkType), TypeBox & JSON Schema | | OpenAPI / Swagger | `@hono/zod-openapi` + `@scalar/hono-api-reference` | Built-in `app.docs('/docs')` | | Typed RPC | `hc(url)` | `bareTreaty(url)` (with typed SSE `AsyncIterable` & `bareTransformer`) | | HTML templates | `hono/html` | `barejs/html` (`649 B`) | | JSX SSR & Suspense | `hono/jsx` | `barejs/jsx` (`4.5 KB`) | | ETag / Cache | `hono/etag`, `hono/cache` | `barejs/etag` (`1.8 KB`), `barejs/cache` (`2.2 KB`) | | SSG | `hono/ssg` | `barejs/ssg` (`2.1 KB`) | | AWS Lambda / CF Pages / Netlify | `hono/aws-lambda`, etc. | `barejs/aws-lambda`, `barejs/cloudflare-pages`, `barejs/netlify` | | Client disconnect | Manual `c.req.raw.signal` | `ctx.signal` / `ctx.onAbort(cb)` | | Response validation & secret stripping | Not built-in | Built-in `response` schema strips unknown/secret fields automatically | ### Hono → BareJS Example ```typescript import { BareJS, bareTreaty, bareTransformer } from 'barejs'; import { z } from 'zod'; const app = new BareJS({ prefix: '/api' }) .post('/tasks', { body: z.object({ title: z.string().min(1) }), response: z.object({ id: z.string(), title: z.string() }) // strips any extra fields! }, (ctx) => ({ id: crypto.randomUUID(), title: ctx.body.title, internalNote: 'stripped!' })) .docs('/docs'); // End-to-end typed client (works in-memory for tests or over HTTP) const client = bareTreaty(app, { transformer: bareTransformer }); const res = await client.api.tasks.post({ body: { title: 'Ship v1' } }); ``` --- ## 3. Migrating from ElysiaJS | Concept | ElysiaJS | BareJS | | :--- | :--- | :--- | | App & Schema | `new Elysia().post('/x', handler, { body: t.Object(...) })` | `new BareJS().post('/x', { body: Type.Object(...) }, handler)` | | Handler argument | `({ params, body, query, status }) => ...` | `(ctx) => ...` (`ctx.params`, `ctx.body`, `ctx.query`, `ctx.status()`) | | Derive / Resolve | `app.derive(...)` | `app.derive(...)` (plus automatic `Symbol.asyncDispose` cleanup!) | | Macros | `app.macro({ auth: ... })` | `app.macro({ auth: { beforeHandle, resolve } })` | | Plugin deduplication | `new Elysia({ name, seed })` | `plugin = { name, seed, install(app) {} }` or `router.pluginName` | | OpenAPI UI | `@elysiajs/openapi` | Built-in `app.docs('/docs')` | | Typed RPC | `@elysiajs/eden` (`treaty(url)`) | Built-in `bareTreaty(url)` | | Node.js acceleration | `@elysiajs/node` | Built-in `uWebSockets.js` auto-detection (`engine: 'auto'`) + `node:http` fallback | | Edge / Cloudflare Workers | Adapter required | Native `barejs/edge` (`39 KB`, zero `node:*` imports) | | MCP Server | Community plugin | Built-in `barejs/mcp` (`11 KB`, zero deps) | | OpenTelemetry | `@elysiajs/opentelemetry` | Built-in `barejs/otel` (`3.5 KB`, zero deps) | | Request cleanup | Manual `try/finally` | `ctx.defer(fn)` + `Symbol.asyncDispose` | ### ElysiaJS → BareJS Example ```typescript import { BareJS, bareAuth, Type } from 'barejs'; const app = new BareJS() .macro({ auth: { beforeHandle: (ctx) => { if (!ctx.user) return ctx.problem(401, 'Unauthorized'); }, resolve: (ctx) => ({ userId: ctx.user!.sub as string }) } }) .use(bareAuth({ secret: process.env.JWT_SECRET! })) .get('/me', { auth: true }, (ctx) => ({ userId: ctx.userId })); ``` --- # External Integrations Because BareJS is built on Web Standard `Request` (`ctx.req`) and `Response`, most modern TypeScript ecosystem libraries plug in directly in 1–5 lines without framework-specific adapters. --- ## 1. Better-Auth Mount Better-Auth's Web Standard `handler(req)` directly on `/api/auth/*`: ```typescript import { BareJS } from 'barejs'; import { auth } from './auth'; // betterAuth({ ... }) const app = new BareJS(); app.all('/api/auth/*', (ctx) => auth.handler(ctx.req)); // Optional: protect routes using Better-Auth session app.derive(async (ctx) => { const session = await auth.api.getSession({ headers: ctx.req.headers }); return { session }; }); ``` --- ## 2. GraphQL Yoga Mount GraphQL Yoga's `yoga.fetch(req)` directly on `/graphql`: ```typescript import { BareJS } from 'barejs'; import { createSchema, createYoga } from 'graphql-yoga'; const yoga = createYoga({ schema: createSchema({ typeDefs: `type Query { hello: String }`, resolvers: { Query: { hello: () => 'Hello from BareJS + Yoga!' } } }) }); const app = new BareJS(); app.all('/graphql', (ctx) => yoga.fetch(ctx.req)); ``` --- ## 3. Auth0 (Built-in JWKS Verification — Zero Extra SDK) BareJS's built-in `bareAuth` supports `RS256` / `ES256` with automatic JWKS fetching, key rotation caching, and `issuer` / `audience` checks: ```typescript import { BareJS, bareAuth } from 'barejs'; const app = new BareJS(); app.group('/api', bareAuth({ algorithms: ['RS256'], jwksUri: 'https://YOUR_TENANT.auth0.com/.well-known/jwks.json', issuer: 'https://YOUR_TENANT.auth0.com/', audience: 'https://api.example.com' }), (api) => { api.get('/profile', (ctx) => ({ user: ctx.user })); }); ``` --- ## 4. Clerk (`@clerk/backend` or Built-in JWKS) Use `@clerk/backend`'s `authenticateRequest(ctx.req)` or BareJS's built-in `bareAuth({ jwksUri })`: ```typescript import { BareJS } from 'barejs'; import { createClerkClient } from '@clerk/backend'; const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! }); const app = new BareJS(); app.group('/api', async (ctx, next) => { const requestState = await clerk.authenticateRequest(ctx.req); if (!requestState.isSignedIn) { return ctx.status(401).json({ error: 'Unauthorized' }); } ctx.set('auth', requestState.toAuth()); return next(); }, (api) => { api.get('/me', (ctx) => ({ auth: ctx.get('auth') })); }); ``` --- ## 5. Sentry (`@sentry/bun` / `@sentry/node`) `@sentry/bun` and `@sentry/node` instrument the runtime HTTP server automatically. Add `app.onError()` to capture handled/unhandled route errors with `requestId` context: ```typescript import * as Sentry from '@sentry/bun'; // or '@sentry/node' import { BareJS } from 'barejs'; Sentry.init({ dsn: process.env.SENTRY_DSN }); const app = new BareJS(); app.onError((err, ctx) => { Sentry.captureException(err, { extra: { requestId: ctx.requestId, url: ctx.req.url, method: ctx.req.method } }); return ctx.status(err.status || 500).json({ error: 'Internal Server Error', requestId: ctx.requestId }); }); ``` --- ## 6. OpenTelemetry (`@opentelemetry/api`) `@opentelemetry/instrumentation-http` captures HTTP spans at the runtime layer. Add a lightweight middleware to attach route metadata and `requestId`: ```typescript import { trace, SpanStatusCode } from '@opentelemetry/api'; import { BareJS } from 'barejs'; const tracer = trace.getTracer('barejs-app'); const app = new BareJS(); app.use(async (ctx, next) => { return tracer.startActiveSpan(`${ctx.req.method} ${new URL(ctx.req.url).pathname}`, async (span) => { span.setAttribute('http.request_id', ctx.requestId); try { const res = await next(); if (res instanceof Response) span.setAttribute('http.status_code', res.status); return res; } catch (err: any) { span.recordException(err); span.setStatus({ code: SpanStatusCode.ERROR }); throw err; } finally { span.end(); } }); }); ``` --- ## 7. Meta Frameworks (Next.js, Astro, SvelteKit, Nuxt, Remix, SolidStart, TanStack Start) Because `app.fetch` (and `BareEdge.fetch` in `barejs/edge`) is a Web Standard `(req: Request) => Response | Promise` handler and safely ignores non-string framework context arguments, you can mount a BareJS API inside any Web Standard meta framework using `new BareJS({ prefix: '/api' })` or `new BareJS().basePath('/api')`. ### Next.js (App Router) Mount a catch-all API route at `app/api/[[...slug]]/route.ts`: ```typescript import { BareJS, Type } from 'barejs'; const app = new BareJS({ prefix: '/api' }) .get('/health', () => ({ ok: true })) .post( '/echo', { body: Type.Object({ message: Type.String() }) }, (ctx) => ({ echoed: ctx.body.message }) ); export type App = typeof app; export const GET = app.fetch; export const POST = app.fetch; export const PUT = app.fetch; export const PATCH = app.fetch; export const DELETE = app.fetch; export const OPTIONS = app.fetch; export const HEAD = app.fetch; ``` > **Edge Runtime:** If you export `export const runtime = 'edge';` in Next.js, import `BareEdge` from `'barejs/edge'` instead of `'barejs'` (`new BareEdge({ prefix: '/api' })`). Use `bareTreaty` from Client or Server Components for end-to-end type safety: ```typescript import { bareTreaty } from 'barejs'; import type { App } from '@/app/api/[[...slug]]/route'; const api = bareTreaty('/api'); const { data } = await api.echo.post({ body: { message: 'hello' } }); ``` ### Astro Create `src/pages/api/[...slug].ts`: ```typescript import type { APIRoute } from 'astro'; import { BareJS } from 'barejs'; const app = new BareJS({ prefix: '/api' }) .get('/hello', () => ({ message: 'Hello from BareJS + Astro!' })); export const ALL: APIRoute = ({ request }) => app.fetch(request); ``` ### SvelteKit Create `src/routes/api/[...slug]/+server.ts`: ```typescript import type { RequestHandler } from './$types'; import { BareJS } from 'barejs'; const app = new BareJS({ prefix: '/api' }) .get('/hello', () => ({ message: 'Hello from BareJS + SvelteKit!' })); export const fallback: RequestHandler = ({ request }) => app.fetch(request); ``` ### Nuxt 3 / Nitro Create `server/api/[...].ts`: ```typescript import { defineEventHandler, toWebRequest } from 'h3'; import { BareJS } from 'barejs'; const app = new BareJS({ prefix: '/api' }) .get('/hello', () => ({ message: 'Hello from BareJS + Nuxt!' })); export default defineEventHandler((event) => app.fetch(toWebRequest(event))); ``` ### Remix / React Router v7 / SolidStart / TanStack Start Forward the Web Standard `request` directly to `app.fetch(request)` in any catch-all API route: ```typescript // Remix / React Router v7 — app/routes/api.$.ts import { BareJS } from 'barejs'; const app = new BareJS({ prefix: '/api' }) .get('/hello', () => ({ message: 'Hello from BareJS!' })); export const loader = ({ request }: { request: Request }) => app.fetch(request); export const action = ({ request }: { request: Request }) => app.fetch(request); ``` --- ## 8. ORMs (Prisma, Drizzle, Kysely, TypeORM) Inject your ORM client via module scope or `app.derive()`, declare `response` schemas to strip internal columns automatically, and close connections cleanly in `app.onStop()`: ### Prisma (`@prisma/client`) ```typescript import { BareJS, Type } from 'barejs'; import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); const UserPublic = Type.Object({ id: Type.Integer(), email: Type.String(), name: Type.String() }); const app = new BareJS() .get('/users/:id{[0-9]+}', { params: Type.Object({ id: Type.Integer() }), response: { 200: UserPublic, 404: Type.Object({ error: Type.String() }) } }, async (ctx) => { const user = await prisma.user.findUnique({ where: { id: ctx.params.id } }); if (!user) { ctx.status(404); return { error: 'Not found' }; } return user; // passwordHash / undeclared fields are automatically stripped }) .onStop(async () => { await prisma.$disconnect(); }); ``` ### Drizzle ORM (`drizzle-orm`) ```typescript import { BareJS, Type } from 'barejs'; import { drizzle } from 'drizzle-orm/node-postgres'; // or 'drizzle-orm/bun-sqlite' | 'drizzle-orm/mysql2' import { eq } from 'drizzle-orm'; import { Pool } from 'pg'; import { users } from './schema'; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const db = drizzle(pool); const app = new BareJS() .get('/users/:id{[0-9]+}', { params: Type.Object({ id: Type.Integer() }) }, async (ctx) => { const [row] = await db.select().from(users).where(eq(users.id, ctx.params.id)); if (!row) return ctx.status(404).json({ error: 'Not found' }); return row; }) .onStop(async () => { await pool.end(); }); ``` ### Kysely (`kysely`) ```typescript import { BareJS } from 'barejs'; import { Kysely, PostgresDialect } from 'kysely'; import { Pool } from 'pg'; const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }) }) }); const app = new BareJS() .get('/products', () => db.selectFrom('products').selectAll().execute()) .onStop(async () => { await db.destroy(); }); ``` ### TypeORM (`typeorm`) ```typescript import 'reflect-metadata'; import { BareJS } from 'barejs/node'; import { DataSource } from 'typeorm'; import { Order } from './entities/Order'; const dataSource = new DataSource({ type: 'postgres', // 'mysql' | 'oracle' | 'sqlite' url: process.env.DATABASE_URL, entities: [Order] }); await dataSource.initialize(); const app = new BareJS() .get('/orders', () => dataSource.getRepository(Order).find()) .onStop(async () => { if (dataSource.isInitialized) await dataSource.destroy(); }); ``` --- ## 9. Native Database Drivers (PostgreSQL, MySQL, Oracle, SQLite, MongoDB, Redis) ### PostgreSQL (`Bun.sql` / `postgres` / `pg`) ```typescript // Bun native SQL (zero external driver): import { sql } from 'bun'; import { BareJS } from 'barejs'; const app = new BareJS() .get('/users', async () => await sql`SELECT id, email FROM users LIMIT 50`); // Or Node.js / Bun with `pg`: // import { Pool } from 'pg'; // const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20 }); // app.get('/users', async () => (await pool.query('SELECT id, email FROM users LIMIT 50')).rows); // app.onStop(() => pool.end()); ``` ### MySQL / MariaDB (`mysql2/promise`) ```typescript import { BareJS, Type } from 'barejs'; import mysql from 'mysql2/promise'; const pool = mysql.createPool({ uri: process.env.MYSQL_URL, connectionLimit: 20 }); const app = new BareJS() .get('/orders/:id{[0-9]+}', { params: Type.Object({ id: Type.Integer() }) }, async (ctx) => { const [rows] = await pool.execute('SELECT id, total FROM orders WHERE id = ?', [ctx.params.id]); return rows; }) .onStop(() => pool.end()); ``` ### Oracle Database (`oracledb` — Thin Mode, Zero Instant Client) ```typescript import { BareJS, Type } from 'barejs/node'; import oracledb from 'oracledb'; oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT; const pool = await oracledb.createPool({ user: process.env.ORACLE_USER, password: process.env.ORACLE_PASSWORD, connectString: process.env.ORACLE_CONNECT_STRING, // e.g. 'localhost:1521/FREEPDB1' poolMin: 2, poolMax: 20 }); const app = new BareJS() .get('/employees/:id{[0-9]+}', { params: Type.Object({ id: Type.Integer() }) }, async (ctx) => { const conn = await pool.getConnection(); try { const result = await conn.execute( 'SELECT employee_id, first_name, email FROM employees WHERE employee_id = :id', { id: ctx.params.id } ); return result.rows ?? []; } finally { await conn.close(); } }) .onStop(async () => { await pool.close(10); }); ``` ### SQLite (`bun:sqlite` / `better-sqlite3`), MongoDB & Redis - **SQLite (`bun:sqlite`):** `const db = new Database('app.db'); db.run('PRAGMA journal_mode = WAL');` (see [`examples/sqlite-rest-api.ts`](../examples/sqlite-rest-api.ts)). - **MongoDB (`mongodb`):** `const client = new MongoClient(process.env.MONGO_URL!); await client.connect(); app.onStop(() => client.close());` - **Redis (`Bun.redis` / `ioredis`):** BareJS includes `redisStore(client, { prefix })` out of the box for distributed `rateLimit()`, `idempotency()`, and `bareAuth()` token revocation. --- ## 10. Frontend SSR, SPA & Full-Stack Patterns - **Next.js / Astro / SvelteKit / Nuxt / Remix SSR:** Mount `export const GET = app.fetch` (Section 7) and call `bareTreaty(app)` in Server Components / loaders for **zero-network in-process typed RPC** during SSR, and `bareTreaty('/api')` in the browser. - **Vite / React / Vue / Svelte SPA:** Serve the built frontend bundle with `app.use(staticFile('./dist', { spa: true, etag: true }))` alongside your `/api/*` routes. - **Zero-Bundle Server-Rendered HTML & Streaming SSR:** - Lightweight templates / HTMX: `import { html, raw } from 'barejs/html';` - Component SSR + streaming ``: `import { jsx, Suspense, streamResponse } from 'barejs/jsx';` - Pre-rendered static sites: `import { toSSG } from 'barejs/ssg';` --- --- name: barejs description: Build fast, type-safe backend APIs, WebSockets, SSR, Edge Workers, and serverless apps with BareJS across Bun, Node.js (uWebSockets.js), Deno 2, Edge, AWS Lambda, Cloudflare Pages, and Netlify. Use when creating, editing, testing, or debugging BareJS applications. --- # BareJS Agent Skill Use this skill whenever working on a project that uses **BareJS** (`barejs`). ## 1. Entrypoints & Modular Subpaths (Check Exports First) Never install redundant third-party packages for features BareJS already ships: | Import Path | Use For | Key Exports | | :--- | :--- | :--- | | `barejs` | Bun & Deno core | `BareJS`, `BareRouter`, `Context`, `Type`/`T`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `Hash`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck` | | `barejs/node` | Node.js `>= 20` | Same exports + `node:http`, native RFC 6455 WS, `scrypt`, auto-detected `uWebSockets.js` (`engine: 'uws'`) | | `barejs/edge` | Edge Workers (`33 KB`, zero `node:*`, zero external deps) | `BareJS`, `BareEdge`, Web Crypto auth/cookies, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `idempotency`, `circuitBreaker`, `createSingleflight`, `tracing`, `html`, `etag` | | `barejs/html` | XSS-safe HTML templates | `html`, `raw`, `escapeHtml` (`.toResponse()`) | | `barejs/etag` | Dynamic API ETag + `304` | `etag({ weak?: boolean })` | | `barejs/cache` | `Cache-Control` + Web Cache API | `cache({ cacheControl?, vary?, cacheName?, cache? })` | | `barejs/jsx` | JSX/TSX SSR + streaming `` | `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse` (also `barejs/jsx-runtime`) | | `barejs/ssg` | Build-time Static Site Generator | `toSSG(app, { dir?, routes?, dirIndex? })` | | `barejs/aws-lambda` | AWS Lambda (API GW v1/v2 & ALB) | `awsLambda(app)` / `handle(app)` | | `barejs/cloudflare-pages` | Cloudflare Pages Functions | `handle(app)` (`export const onRequest = handle(app)`) | | `barejs/netlify` | Netlify Functions v2 | `handle(app)` (`export default handle(app)`) | ## 2. Scaffolding & Setup ```bash bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWS, Deno) bun create barejs my-app --bun # --bun | --node | --node-uws | --deno ``` ## 3. Routing, Validation & Secret Stripping - Always chain route methods (`.get()`, `.post()`, `.use()`, `.derive()`, `.macro()`, `.route()`) on `new BareJS()` when you want end-to-end `bareTreaty` / `bareClient` type inference. - Supported path patterns: static (`/users`), named params (`/users/:id`), optional params (`/animals/:type?`, `/posts/:year?/:month?`), regex-constrained params (`/users/:id{[0-9]+}` with automatic fall-through to `/users/:slug`), and wildcards (`/files/*` → `ctx.params['*']`). - Pass a `RouteSchemas` object directly before the handler. Supports **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect), **TypeBox** (`Type`/`t`), **Zod**, or **Native JSON Schema** (`native()`): ```ts import { BareJS, Type, type Context } from 'barejs'; const app = new BareJS() .post('/orders/:id{[0-9]+}', { detail: { summary: 'Create order', tags: ['Orders'] }, params: Type.Object({ id: Type.Integer() }), query: Type.Object({ dryRun: Type.Optional(Type.Boolean()) }), cookies: Type.Object({ session: Type.Optional(Type.String()) }), body: Type.Object({ item: Type.String({ minLength: 1 }), qty: Type.Integer({ minimum: 1 }) }), response: { 200: Type.Object({ id: Type.Number(), item: Type.String(), qty: Type.Number() }), 404: Type.Object({ error: Type.String() }) }, stripUnknown: true, maxBodySize: 1024 * 1024 }, (ctx: Context) => ({ id: ctx.params.id, // auto-coerced to number ...ctx.body, internal_cost: 9999 // automatically stripped by declared response schema! })) .docs('/docs', { title: 'Orders API', version: '1.0.0' }); ``` ## 4. End-to-End Type-Safe RPC (`bareTreaty` & `bareClient`) ```ts import { bareTreaty, bareClient } from 'barejs'; // Zero-network in-memory (great for tests & SSR) OR remote URL: const api = bareTreaty(app); // or bareTreaty('https://api.example.com') const { data, error, status } = await api.orders({ id: 42 }).post({ body: { item: 'book', qty: 2 }, headers: { Authorization: `Bearer ${token}`, 'Idempotency-Key': 'req-1' } }); // Typed WebSocket client: const ws = api.ws.chat.subscribe(); // Non-throwing client alternative: const client = bareClient(app); const res = await client.safe.get('/orders/:id', { params: { id: 42 } }); ``` > **Type Inference Note:** Use the 3-arg `.post(path, schemas, handler)` form to preserve full `bareTreaty` types; mount cross-cutting middleware (`idempotency()`, `bareAuth()`) via `.use()` or `app.group()` rather than extra per-route middleware args. ## 5. Modular Plugins, `app.derive()` & `app.macro()` `app.macro()` takes a **single object map** (`{ macroName: { beforeHandle?, resolve? } }`), NOT 2 arguments: ```ts const authPlugin = new BareJS({ name: 'auth-plugin', seed: 'v1' }) // deduplicated if .use()'d multiple times .macro({ auth: { beforeHandle: (ctx: Context, role: string) => ctx.user?.role === role ? undefined : ctx.problem(403, { code: 'FORBIDDEN', detail: 'Insufficient role' }) } }); const app = new BareJS() .use(authPlugin) .derive((ctx) => ({ tenant: ctx.req.headers.get('x-tenant') ?? 'public' })) .get('/public', (ctx) => { ctx.defer(() => { /* LIFO request cleanup (also auto-runs Symbol.asyncDispose on derived values) */ }); return { ok: true }; }) // Scope bareAuth() to protected groups/routes so /docs and public routes stay accessible: .group('/admin', bareAuth({ secret: process.env.JWT_SECRET! }), (g) => { g.get('/me', { auth: 'admin' }, (ctx) => ({ tenant: ctx.tenant, user: ctx.user })); }); ``` ## 6. Security, Resilience & Observability ```ts import { BareJS, securityHeaders, cors, csrf, rateLimit, timeout, idempotency, createSingleflight, circuitBreaker, compress, bareAuth, createToken, basicAuth, hasRole, Hash, tracing, healthcheck, redisStore } from 'barejs'; import { etag } from 'barejs/etag'; // Sign HS256 JWT (async): const token = await createToken( { id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET! ); const store = redisStore(Bun.redis, { prefix: 'app:' }); // optional shared Redis store const sf = createSingleflight(); const app = new BareJS() .use(securityHeaders(), cors({ origin: ['https://app.example.com'], credentials: true })) .use(tracing(), compress(), etag()) .use(rateLimit({ windowMs: 60_000, max: 100, store })) .use(healthcheck()) // healthcheck() returns a BarePlugin -> mount via .use(), NOT .get() // idempotency() reads `Idempotency-Key` header by default (replays cached response + X-Idempotent-Replayed: true) .post('/pay', idempotency({ ttlMs: 86_400_000, store }), () => ({ paid: true })) // createSingleflight() returns Promise<{ data, shared }> .get('/report', async () => (await sf('report', async () => ({ total: 100 }))).data) .get('/upstream', circuitBreaker({ failureThreshold: 3, resetTimeoutMs: 5_000 }), () => ({ ok: true })) // basicAuth() uses `{ user, pass }` (NOT username/password) .get('/metrics', basicAuth({ user: 'ops', pass: process.env.OPS_PASS! }), () => 'ok'); ``` ## 7. Files, Streaming, WebSockets, JSX, Edge & Meta Frameworks - **1-line file serving (with root jail):** `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))` - **Static files:** `app.use(staticFile('./public', { spa: true }))` (middleware — mount via `.use()`, not `.get()`) - **Generator streaming:** `app.get('/stream', async function* () { yield 'chunk-1\n'; yield 'chunk-2\n'; })` - **SSE:** `app.get('/events', (ctx) => ctx.sse(async (send) => { send({ ok: true }, 'ping'); }))` - **Typed WebSockets:** `app.ws('/ws/:room', { body: MsgSchema, open(ws) { ws.subscribe(ws.data.params.room); }, message(ws, data) { ... } })` - **JSX Streaming SSR:** `import { jsx, Suspense, streamResponse } from 'barejs/jsx'` - **Edge Workers:** `import { BareJS } from 'barejs/edge'; export default app;` - **Meta Frameworks (Next.js App Router, Astro, SvelteKit, Nuxt 3, Remix):** - `const app = new BareJS({ prefix: '/api' }).get('/hello', () => ({ ok: true }));` (or `new BareJS().basePath('/api')`) - `export const GET = app.fetch; export const POST = app.fetch;` (`app.fetch` safely ignores non-string framework `context` 2nd arg) - **AWS Lambda:** `import { awsLambda } from 'barejs/aws-lambda'; export const handler = awsLambda(app);` - **Cloudflare Pages:** `import { handle } from 'barejs/cloudflare-pages'; export const onRequest = handle(app);` - **Netlify:** `import { handle } from 'barejs/netlify'; export default handle(app);` - **MCP Server (AI Agents):** `import { mcp } from 'barejs/mcp'; app.use(mcp({ path: '/mcp', name: 'my-mcp' }));` — auto-exposes routes & schemas as MCP tools. - **Live Visual DevTools:** `import { devtools } from 'barejs/devtools'; app.use(devtools());` — live UI at `/__bare` (auto-disabled in `NODE_ENV=production`). - **Background Job Queue:** `import { createQueue } from 'barejs/queue'; const q = createQueue({ concurrency: 4, retries: 3 });` (drain in `app.onStop(() => q.stop())`). - **Signed Webhooks:** `import { verifyWebhook, sendWebhook } from 'barejs/webhooks';` — HMAC-SHA256 verification, replay window, secret rotation, and retrying dispatcher. - **Prometheus Metrics:** `import { metrics } from 'barejs/metrics'; app.use(metrics('/metrics'));` — exports Prometheus counters & histograms with ID/UUID path normalization. - **AI / LLM Streaming:** `import { aiStream, parseOpenAISSE } from 'barejs/ai';` — typed SSE streaming (`text`, `tool_call`, `usage`, `done`) with automatic `AbortSignal` on disconnect. - **Client Disconnect & Typed SSE/Transformer RPC:** `ctx.signal` / `ctx.onAbort(cb)`; `bareTreaty(app, { transformer: bareTransformer })` preserves `Date`/`Map`/`Set`/`BigInt` and decodes SSE as `AsyncIterable`. - **OpenTelemetry OTLP:** `import { otel, createOtlpExporter } from 'barejs/otel';` — zero-dep OTLP/HTTP JSON trace exporter for Grafana/Datadog/Honeycomb. - **Distributed Store:** `import { memoryStore, sqliteStore, upstashStore, kvStore, toRateLimitStore, toCacheStore, toIdempotencyStore } from 'barejs/store';` — unified `BareStore` for `rateLimit()`, `cache()`, `idempotency()`, and durable workflows. - **Durable Workflows:** `import { defineWorkflow } from 'barejs/workflow';` — crash-resumable `step.run()`, `step.sleep()`, and `step.waitForEvent()` backed by `BareStore`. ## 8. Cookies, Uploads, Sub-Routers, JSON-RPC 2.0, Cron & Lifecycle - **Signed Cookies:** `await ctx.setCookie('sid', 'val', { secret, httpOnly: true, sameSite: 'Lax', maxAge: 3600 })`, `await ctx.getSignedCookie('sid', secret)`, `ctx.deleteCookie('sid')`. - **File Uploads:** - Buffered: `const { fields, files } = await ctx.upload({ maxFileSize: 10e6, maxFiles: 5, allowedTypes: ['image/png'] });` — each item has `f.safeName` and `f.file` (`File`, e.g. `await Bun.write(dest, f.file)`). - Streaming ($O(\text{chunk})$ memory): `for await (const part of ctx.uploadStream({ maxFileSize: 100e6 })) { if (part.type === 'file') { /* part.stream */ } }` - **Sub-Routers & Route Groups:** - `const v1 = new BareRouter().get('/items', () => []); const typed = app.route('/api/v1', v1);` - `app.group('/admin', bareAuth({ secret }), (g) => { g.get('/stats', { auth: 'admin' }, () => ({ ok: true })); });` - **JSON-RPC 2.0:** `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b }, { maxBatchSize: 100 })` - **Overlap-Safe Cron:** `app.cron('cleanup', 60_000, async () => { /* ... */ })` (auto-cleared on `app.stop()`). - **Lifecycle, Error Handling, TLS & Cluster:** - `app.onRequest(fn)` / `app.onResponse(fn)` / `app.onStart(fn)` / `app.onDrain(fn)` / `app.onStop(fn)` - `app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId }))` - `app.setNotFound(() => ({ status: 404, message: 'Not Found' }))` (chainable) - `app.trustProxy(['10.0.0.0/8', '127.0.0.1'])` (enables `ctx.ip` from `x-forwarded-for` only from trusted CIDRs) - `const server = app.listen(0)` returns the underlying server (`server.port` for ephemeral test ports); `await app.stop()` cleans up server & cron timers. - `await app.listenCluster(8443, undefined, '0.0.0.0', { engine: 'auto', tls: { keyFileName, certFileName } })` ## 9. Testing, Common Mistakes (Do / Don't) & Production Rules | Don't (Express / Hono / Elysia habit) | Do (Correct BareJS) | | :--- | :--- | | `app.macro('auth', { beforeHandle })` (2 args) | `app.macro({ auth: { beforeHandle } })` (single object map) | | `basicAuth({ username, password })` | `basicAuth({ user, pass })` | | `app.get('/health', healthcheck())` | `app.use(healthcheck())` (`healthcheck()` is a `BarePlugin`) | | `app.setNotFound((ctx) => ctx.status(404)...)` | `app.setNotFound(() => ({ status: 404, message: 'Not Found' }))` (takes **0 args**, no `ctx`!) | | `ctx.json(data, 201)` | `ctx.status(201).json(data)` (`ctx.json` takes 1 arg) | | `return ctx.status(201).json(obj)` on response-schema routes | `ctx.status(201); return obj;` (returning a `Response` bypasses secret stripping!) | | `app.use('/api', authMw)` (Express prefix mw) | `app.group('/api', authMw, (g) => { ... })` or `app.route('/api', subRouter)` | | `app.use(bareAuth(...))` globally when `/docs` is public | Mount `bareAuth(...)` on protected groups/routes so `/docs` & public routes stay open | | `await ctx.req.json()` when `body` schema is set | Read `ctx.body` directly (already validated, coerced & stripped) | | `app.get('/a', h1); app.get('/b', h2);` (unchained) | Chain `const app = new BareJS().get('/a', h1).get('/b', h2)` for `bareTreaty` types | | `import { BareJS } from 'barejs'` on Node.js / Edge | Use `'barejs/node'` on Node.js `>= 20`, `'barejs/edge'` on Workers/Edge | | `setTimeout(() => console.log(ctx.ip), 100)` | Copy `const ip = ctx.ip` before returning (`ctx` is LIFO-pooled) | | `npm install helmet cors express-rate-limit` | Use built-in `securityHeaders()`, `cors()`, `rateLimit()`, `timeout(ms)` from `'barejs'` | - **TSX with `barejs/jsx`:** Set `"jsx": "react-jsx", "jsxImportSource": "barejs"` in `tsconfig.json` for `.tsx` files (`` and `async` components are supported). - **ORMs & Databases (Prisma, Drizzle, Kysely, TypeORM, PostgreSQL, MySQL, Oracle `oracledb`, SQLite, MongoDB):** Inject via module scope or `app.derive()`, declare `response` schemas to strip secret columns, and always close pools in `app.onStop(async () => ...)` — see `docs/integrations.md`. - **In-memory testing:** Use `await app.request('/path', { method: 'POST', body: JSON.stringify(...) })` or `bareTreaty(app)` — no port binding needed. - **Production mode:** Always set `NODE_ENV=production` to enable static route fast-paths, disable dev UAF Proxy overhead, mask 500 stack traces, and enable `staticFile` metadata caching. - **Full reference:** See `https://xarhang.github.io/bareJS/llms.txt` or `https://xarhang.github.io/bareJS/llms-full.txt`. --- # Runnable Examples ## examples/aws-lambda.ts ```typescript /** * AWS Lambda Example (API Gateway HTTP API v2, REST API v1 & ALB) * Export `handler` in your Lambda bundle (~2.4 KB adapter, zero core bloat) */ import { BareJS, cors, securityHeaders } from 'barejs/edge'; import { etag } from 'barejs/etag'; import { awsLambda } from 'barejs/aws-lambda'; const app = new BareJS() .use(securityHeaders(), cors(), etag()) .get('/hello/:name', (ctx) => ({ message: `Hello, ${ctx.params.name}!`, requestId: ctx.requestId })) .post('/echo', async (ctx) => ({ received: await ctx.jsonBody() })); export const handler = awsLambda(app); ``` ## examples/cloudflare-worker.ts ```typescript /** * Cloudflare Workers / Vercel Edge / Deno Deploy Example (Zero node:* imports) * Deploy with: wrangler deploy examples/cloudflare-worker.ts */ import { BareJS, cors, securityHeaders, tracing } from 'barejs/edge'; import { cache } from 'barejs/cache'; import { etag } from 'barejs/etag'; interface Env { API_KEY: string; } const app = new BareJS() .use(securityHeaders(), cors({ origin: '*' }), tracing()) .get('/health', () => ({ ok: true, runtime: 'edge' })) .get( '/v1/config', cache({ cacheControl: 'public, max-age=60, stale-while-revalidate=30', vary: 'Accept-Encoding' }), etag(), (ctx) => ({ region: ctx.req.headers.get('cf-ipcountry') ?? 'unknown', hasKey: Boolean(ctx.env?.API_KEY) }) ); export default app; ``` ## examples/durable-workflow.ts ```typescript /** * BareJS Example: Durable Multi-Step Workflow with Crash-Resumable Replay & Events * Run: bun run examples/durable-workflow.ts */ import { memoryStore } from '../src/utils/store'; import { defineWorkflow } from '../src/utils/workflow'; const store = memoryStore(); // Swap for sqliteStore(db) or upstashStore(...) in production const orderFlow = defineWorkflow( 'order-fulfillment', async (input: { orderId: string; amount: number }, step) => { const payment = await step.run('charge-card', () => { console.log(`Charging $${input.amount} for ${input.orderId}`); return { receiptId: `rcpt_${input.orderId}`, paid: true }; }); await step.sleep('fraud-cooldown', 20); const approval = await step.waitForEvent<{ approvedBy: string }>('wait-approval', 'order.approved'); const shipment = await step.run('ship', () => ({ tracking: `TRK_${input.orderId}`, approvedBy: approval.approvedBy })); return { payment, shipment }; }, { store } ); const paused = await orderFlow.start({ orderId: 'ORD-42', amount: 199 }, { runId: 'ORD-42' }); console.log('Workflow paused:', paused.status, paused.waitingFor); const completed = await orderFlow.sendEvent('ORD-42', 'order.approved', { approvedBy: 'alice' }); console.log('Workflow completed:', completed.status, completed.output); ``` ## examples/mcp-and-devtools.ts ```typescript /** * BareJS Example: 1-Line MCP Server + Live Visual DevTools UI * Run: bun run examples/mcp-and-devtools.ts * Open: http://localhost:3000/__bare (DevTools) & http://localhost:3000/mcp (MCP Streamable HTTP) */ import { BareJS, Type } from '../src/index'; import { mcp } from '../src/utils/mcp'; import { devtools } from '../src/utils/devtools'; const notes: Array<{ id: number; title: string; body: string }> = [ { id: 1, title: 'Welcome', body: 'Try calling this API from Claude or Cursor via /mcp!' } ]; const app = new BareJS() .use(devtools({ path: '/__bare' })) .get('/notes', { detail: { summary: 'List all notes' } }, () => ({ notes })) .post('/notes', { body: Type.Object({ title: Type.String({ minLength: 1 }), body: Type.String() }), detail: { summary: 'Create a new note' } }, (ctx) => { const note = { id: notes.length + 1, ...ctx.body }; notes.push(note); return ctx.status(201).json(note); }) .use(mcp({ path: '/mcp', name: 'notes-mcp' })); app.listen(3000); ``` ## examples/otel-and-store.ts ```typescript /** * BareJS Example: OpenTelemetry OTLP Traces + Prometheus Metrics + Unified BareStore * Run: bun run examples/otel-and-store.ts */ import { BareJS, rateLimit, idempotency } from '../src/index'; import { cache } from '../src/utils/cache'; import { otel } from '../src/utils/otel'; import { metrics } from '../src/utils/metrics'; import { memoryStore, toRateLimitStore, toCacheStore, toIdempotencyStore } from '../src/utils/store'; const store = memoryStore(); // Swap for sqliteStore(db), upstashStore(...), or kvStore(env.KV) const otelMw = otel({ url: process.env.OTLP_URL || 'http://localhost:4318/v1/traces', serviceName: 'barejs-demo', flushIntervalMs: 5000 }); const app = new BareJS() .use(otelMw) .use(metrics({ path: '/metrics', prefix: 'demo_' })) .use(rateLimit({ max: 100, windowMs: 60_000, store: toRateLimitStore(store) })) .get('/catalog', cache({ cache: toCacheStore(store, 60_000), cacheControl: 'public, max-age=60' }), () => ({ items: ['barejs-core', 'barejs-edge', 'barejs-workflow'] })) .post('/orders', idempotency({ store: toIdempotencyStore(store) }), () => ({ status: 'accepted' })) .onStop(() => otelMw.stop()); app.listen(3000); ``` ## examples/realtime-ws-chat.ts ```typescript /** * Real-Time Parameterized WebSocket Chat + XSS-Safe HTML UI (Bun) * Run: bun run examples/realtime-ws-chat.ts */ import { BareJS, Type } from 'barejs'; import { html } from 'barejs/html'; const app = new BareJS() .get('/rooms/:room', (ctx) => { const room = ctx.params.room; return html` Room: ${room}

BareJS Chat — #${room}


    
    
    
  
`.toResponse();
  })
  .ws('/ws/:room', {
    body: Type.Object({ text: Type.String({ minLength: 1, maxLength: 500 }) }),
    open(ws) {
      ws.subscribe(`room:${ws.data.params.room}`);
    },
    message(ws, data) {
      const payload = JSON.stringify({ room: ws.data.params.room, text: data.text, at: Date.now() });
      ws.publish(`room:${ws.data.params.room}`, payload);
      ws.send(payload);
    }
  });

app.listen(3000);
console.log('Chat room live at http://localhost:3000/rooms/general');
```

## examples/rest-api.ts

```typescript
import { BareJS, Type, bareAuth, createToken, securityHeaders, type Context } from '../src/index';

const SECRET = process.env.JWT_SECRET || 'barejs-example-secret-key';

const app = new BareJS()
  .useLog({ format: 'json' })
  .use(securityHeaders());

const users = [
  { id: 1, email: 'alice@example.com', role: 'admin', password_hash: '$argon2id$...' },
  { id: 2, email: 'bob@example.com', role: 'user', password_hash: '$argon2id$...' }
];

app.get('/health', () => ({ ok: true }));

app.post('/auth/login', {
  body: Type.Object({
    email: Type.String({ format: 'email' })
  })
}, async (ctx: Context) => {
  const user = users.find((u) => u.email === ctx.body.email);
  if (!user) return ctx.status(401).json({ error: 'Invalid credentials' });
  const token = await createToken({ sub: String(user.id), role: user.role }, SECRET, { expiresIn: '1h' });
  return ctx.json({ token });
});

app.get('/users', {
  response: Type.Array(Type.Object({
    id: Type.Number(),
    email: Type.String(),
    role: Type.String()
  }))
}, bareAuth({ secret: SECRET }), () => users);

app.docs({ title: 'BareJS Example API', version: '0.2.1' });

if (import.meta.main) {
  app.listen(Number(process.env.PORT || 3000));
}

export default app;
```

## examples/sqlite-rest-api.ts

```typescript
/**
 * Production SQLite REST API Example (Bun)
 * Run: bun run examples/sqlite-rest-api.ts
 */
import { Database } from 'bun:sqlite';
import { BareJS, Type, securityHeaders, cors, tracing } from 'barejs';
import { etag } from 'barejs/etag';

const db = new Database(':memory:');
db.run(`
  CREATE TABLE items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    internal_cost REAL NOT NULL DEFAULT 0
  )
`);

const ItemSchema = Type.Object({
  id: Type.Integer(),
  name: Type.String(),
  price: Type.Number()
});

const app = new BareJS()
  .use(securityHeaders(), cors(), tracing(), etag())
  .get('/items', {
    response: Type.Array(ItemSchema)
  }, () => db.query('SELECT * FROM items').all() as any[])
  .post('/items', {
    body: Type.Object({
      name: Type.String({ minLength: 1 }),
      price: Type.Number({ minimum: 0 })
    }),
    response: {
      201: ItemSchema
    }
  }, (ctx) => {
    const info = db
      .query('INSERT INTO items (name, price, internal_cost) VALUES (?, ?, ?) RETURNING *')
      .get(ctx.body.name, ctx.body.price, ctx.body.price * 0.4) as any;
    // `internal_cost` is automatically stripped by the declared response schema
    return ctx.status(201).json(info);
  })
  .docs('/docs', { title: 'BareJS SQLite API', version: '1.0.0' });

app.listen(3000);
console.log('SQLite REST API running at http://localhost:3000/docs');
```

## examples/typed-sse-rpc.ts

```typescript
/**
 * BareJS Example: End-to-End Compile-Time Typed SSE Streaming + Rich Type Transformer
 * Run: bun run examples/typed-sse-rpc.ts
 */
import { BareJS, bareTreaty, bareTransformer } from '../src/index';

const app = new BareJS()
  .get('/ticker', (ctx) => {
    ctx.onAbort(() => console.log('Client disconnected from /ticker'));
    return ctx.sse<{ tick: number; at: Date }>((async function* () {
      for (let tick = 1; tick <= 3; tick++) {
        yield { data: bareTransformer.serialize({ tick, at: new Date() }) };
        await new Promise((r) => setTimeout(r, 50));
      }
    })());
  });

// Execute in-memory with full compile-time type safety (zero network sockets!)
const client = bareTreaty(app, { transformer: bareTransformer });
const res = await client.ticker.get();
if (res.ok) {
  for await (const chunk of res.data) {
    console.log(`Tick #${chunk.tick} at ${chunk.at.toISOString()}`);
  }
}
```