fix(readme): update README: rework features, add OpenAPI/Swagger, compression, request validation, examples, and runtime stats

This commit is contained in:
2025-12-20 06:59:55 +00:00
parent 697b7e92d7
commit d645311208
3 changed files with 468 additions and 91 deletions

View File

@@ -1,5 +1,14 @@
# Changelog # Changelog
## 2025-12-20 - 2.0.1 - fix(readme)
update README: rework features, add OpenAPI/Swagger, compression, request validation, examples, and runtime stats
- Reworked Features section into a markdown table and added items for OpenAPI/Swagger, Request Validation, and Auto Compression.
- Updated Quick Start example (removed Guard import) and added a Table of Contents.
- Expanded examples with a manual route handling snippet and guidance to bypass decorator routing.
- Added runtime example fields: instance.hostname and new stats() usage (uptime, requestsTotal, requestsActive).
- Minor legal/formatting updates: fixed LICENSE link casing/path and clarified trademark wording.
## 2025-12-20 - 2.0.0 - BREAKING CHANGE(request) ## 2025-12-20 - 2.0.0 - BREAKING CHANGE(request)
introduce lazy request body parsing via ctx.json()/text()/arrayBuffer()/formData and remove IRequestContext.body introduce lazy request body parsing via ctx.json()/text()/arrayBuffer()/formData and remove IRequestContext.body

548
readme.md
View File

@@ -1,6 +1,6 @@
# @push.rocks/smartserve # @push.rocks/smartserve
A cross-platform HTTP server module for Node.js, Deno, and Bun with decorator-based routing, WebSocket support, static file serving, and WebDAV protocol. 🚀 A blazing-fast, cross-platform HTTP server for Node.js, Deno, and Bun with decorator-based routing, OpenAPI/Swagger integration, automatic compression, WebSocket support, static file serving, and WebDAV protocol. 🚀
## Issue Reporting and Security ## Issue Reporting and Security
@@ -16,21 +16,25 @@ pnpm add @push.rocks/smartserve
## Features ## Features
**Cross-Platform** - Works seamlessly on Node.js, Deno, and Bun | Feature | Description |
🎯 **Decorator-Based Routing** - Clean, expressive `@Route`, `@Get`, `@Post` decorators |---------|-------------|
🛡️ **Guards & Interceptors** - Built-in `@Guard`, `@Transform`, `@Intercept` for auth and transformation | ✨ **Cross-Platform** | Works seamlessly on Node.js, Deno, and Bun with zero config |
📁 **Static File Server** - Streaming, ETags, Range requests, directory listing | 🎯 **Decorator-Based Routing** | Clean, expressive `@Route`, `@Get`, `@Post` decorators |
🌐 **WebDAV Support** - Mount as network drive with full RFC 4918 compliance | 📖 **OpenAPI/Swagger** | Auto-generate OpenAPI 3.1 specs with built-in Swagger UI & ReDoc |
🔌 **WebSocket Ready** - Native WebSocket support across all runtimes | ✅ **Request Validation** | Validate requests against JSON Schema with automatic coercion |
**Zero Overhead** - Native Web Standards API (Request/Response) on Deno/Bun | 🗜️ **Auto Compression** | Brotli/gzip compression with smart content detection |
🔒 **HTTPS/TLS** - Built-in TLS support with certificate configuration | 🛡️ **Guards & Interceptors** | Built-in `@Guard`, `@Transform`, `@Intercept` for auth & transformation |
| 📁 **Static File Server** | Streaming, ETags, Range requests, directory listing, pre-compressed files |
| 🌐 **WebDAV Support** | Mount as network drive with full RFC 4918 compliance |
| 🔌 **WebSocket Ready** | Native WebSocket support with TypedRouter for type-safe RPC |
| ⚡ **Zero Overhead** | Native Web Standards API (Request/Response) on Deno/Bun |
| 🔒 **HTTPS/TLS** | Built-in TLS support with certificate configuration |
## Quick Start ## Quick Start
```typescript ```typescript
import { SmartServe, Route, Get, Post, Guard, type IRequestContext } from '@push.rocks/smartserve'; import { SmartServe, Route, Get, Post, type IRequestContext } from '@push.rocks/smartserve';
// Define a controller with decorators
@Route('/api') @Route('/api')
class UserController { class UserController {
@Get('/hello') @Get('/hello')
@@ -50,7 +54,6 @@ class UserController {
} }
} }
// Create and start server
const server = new SmartServe({ port: 3000 }); const server = new SmartServe({ port: 3000 });
server.register(UserController); server.register(UserController);
await server.start(); await server.start();
@@ -58,6 +61,28 @@ await server.start();
console.log('🚀 Server running at http://localhost:3000'); console.log('🚀 Server running at http://localhost:3000');
``` ```
## Table of Contents
- [Decorators](#decorators)
- [Route Decorators](#route-decorators)
- [Guards](#guards-authenticationauthorization)
- [Transforms](#transforms-response-modification)
- [Intercept](#intercept-full-control)
- [OpenAPI & Swagger](#openapi--swagger)
- [Documenting APIs](#documenting-apis)
- [Request Validation](#request-validation)
- [Swagger UI & ReDoc](#swagger-ui--redoc)
- [Compression](#compression)
- [Static File Server](#static-file-server)
- [WebDAV Support](#webdav-support)
- [WebSocket Support](#websocket-support)
- [HTTPS/TLS](#httpstls)
- [Error Handling](#error-handling)
- [Request Context](#request-context)
- [Custom Request Handler](#custom-request-handler)
---
## Decorators ## Decorators
### Route Decorators ### Route Decorators
@@ -68,9 +93,11 @@ import { Route, Get, Post, Put, Delete, Patch, All } from '@push.rocks/smartserv
@Route('/api/v1') // Base path for all routes in this controller @Route('/api/v1') // Base path for all routes in this controller
class ApiController { class ApiController {
@Get('/items') // GET /api/v1/items @Get('/items') // GET /api/v1/items
listItems() { ... } listItems() {
return [{ id: 1, name: 'Item 1' }];
}
@Get('/items/:id') // GET /api/v1/items/:id - path parameters @Get('/items/:id') // GET /api/v1/items/:id
getItem(ctx: IRequestContext) { getItem(ctx: IRequestContext) {
return { id: ctx.params.id }; return { id: ctx.params.id };
} }
@@ -82,13 +109,20 @@ class ApiController {
} }
@Put('/items/:id') // PUT /api/v1/items/:id @Put('/items/:id') // PUT /api/v1/items/:id
updateItem(ctx: IRequestContext) { ... } async updateItem(ctx: IRequestContext) {
const body = await ctx.json();
return { updated: ctx.params.id, ...body };
}
@Delete('/items/:id') // DELETE /api/v1/items/:id @Delete('/items/:id') // DELETE /api/v1/items/:id
deleteItem(ctx: IRequestContext) { ... } deleteItem(ctx: IRequestContext) {
return { deleted: ctx.params.id };
}
@All('/webhook') // Matches ALL HTTP methods @All('/webhook') // Matches ALL HTTP methods
handleWebhook(ctx: IRequestContext) { ... } handleWebhook(ctx: IRequestContext) {
return { method: ctx.method };
}
} }
``` ```
@@ -97,9 +131,9 @@ class ApiController {
Guards protect routes by returning `true` (allow) or `false` (reject with 403): Guards protect routes by returning `true` (allow) or `false` (reject with 403):
```typescript ```typescript
import { Route, Get, Guard, type IRequestContext } from '@push.rocks/smartserve'; import { Route, Get, Guard, hasBearerToken, type IRequestContext } from '@push.rocks/smartserve';
// Guard function // Custom guard function
const isAuthenticated = (ctx: IRequestContext) => { const isAuthenticated = (ctx: IRequestContext) => {
return ctx.headers.has('Authorization'); return ctx.headers.has('Authorization');
}; };
@@ -108,7 +142,6 @@ const isAdmin = (ctx: IRequestContext) => {
return ctx.headers.get('X-Role') === 'admin'; return ctx.headers.get('X-Role') === 'admin';
}; };
// Apply guard to entire controller
@Route('/admin') @Route('/admin')
@Guard(isAuthenticated) @Guard(isAuthenticated)
@Guard(isAdmin) // Multiple guards - all must pass @Guard(isAdmin) // Multiple guards - all must pass
@@ -125,6 +158,16 @@ class AdminController {
return { level: 'super-secret' }; return { level: 'super-secret' };
} }
} }
// Built-in utility guards
@Route('/protected')
@Guard(hasBearerToken()) // Requires Authorization: Bearer <token>
class ProtectedController {
@Get('/data')
getData() {
return { protected: true };
}
}
``` ```
### Transforms (Response Modification) ### Transforms (Response Modification)
@@ -132,29 +175,24 @@ class AdminController {
Transforms modify the response before sending: Transforms modify the response before sending:
```typescript ```typescript
import { Route, Get, Transform } from '@push.rocks/smartserve'; import { Route, Get, Transform, wrapSuccess, addTimestamp } from '@push.rocks/smartserve';
// Transform function
const wrapResponse = <T>(data: T) => ({
success: true,
data,
timestamp: Date.now(),
});
// Custom transform
const addVersion = <T extends object>(data: T) => ({ const addVersion = <T extends object>(data: T) => ({
...data, ...data,
apiVersion: '2.0', apiVersion: '2.0',
}); });
@Route('/api') @Route('/api')
@Transform(wrapResponse) // Applied to all routes in controller @Transform(wrapSuccess) // Built-in: wraps in { success: true, data: ... }
class ApiController { class ApiController {
@Get('/info') @Get('/info')
@Transform(addVersion) // Stacks with class transform @Transform(addTimestamp) // Built-in: adds timestamp field
@Transform(addVersion) // Transforms stack
getInfo() { getInfo() {
return { name: 'MyAPI' }; return { name: 'MyAPI' };
} }
// Response: { success: true, data: { name: 'MyAPI', apiVersion: '2.0' }, timestamp: ... } // Response: { success: true, data: { name: 'MyAPI', timestamp: '...', apiVersion: '2.0' } }
} }
``` ```
@@ -167,16 +205,26 @@ import { Route, Get, Intercept, type IRequestContext } from '@push.rocks/smartse
@Route('/api') @Route('/api')
@Intercept({ @Intercept({
// Runs before handler // Runs BEFORE handler
request: async (ctx) => { request: async (ctx) => {
console.log(`${ctx.method} ${ctx.path}`); console.log(`📥 ${ctx.method} ${ctx.path}`);
// Return Response to short-circuit // Return Response to short-circuit
// Return modified context to continue if (ctx.headers.get('X-Block') === 'true') {
// Return void to continue with original return new Response('Blocked', { status: 403 });
}
// Add data to state for handler access
ctx.state.requestTime = Date.now();
// Return void to continue with original context
}, },
// Runs after handler
// Runs AFTER handler
response: async (data, ctx) => { response: async (data, ctx) => {
return { ...data, processedAt: new Date().toISOString() }; const duration = Date.now() - (ctx.state.requestTime as number);
console.log(`📤 Response in ${duration}ms`);
return { ...data, processedIn: `${duration}ms` };
}, },
}) })
class LoggedController { class LoggedController {
@@ -187,9 +235,242 @@ class LoggedController {
} }
``` ```
---
## OpenAPI & Swagger
SmartServe includes first-class OpenAPI 3.1 support with automatic spec generation, Swagger UI, ReDoc, and request validation.
### Documenting APIs
```typescript
import {
SmartServe,
Route,
Get,
Post,
ApiOperation,
ApiParam,
ApiQuery,
ApiRequestBody,
ApiResponseBody,
ApiTag,
ApiSecurity,
type IRequestContext,
} from '@push.rocks/smartserve';
// Define JSON Schemas for validation
const UserSchema = {
type: 'object',
properties: {
id: { type: 'string', format: 'uuid' },
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
},
required: ['id', 'name', 'email'],
} as const;
const CreateUserSchema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
},
required: ['name', 'email'],
} as const;
@Route('/api/users')
@ApiTag('Users')
class UserController {
@Get('/')
@ApiOperation({
summary: 'List all users',
description: 'Returns a paginated list of users',
})
@ApiQuery('page', {
description: 'Page number',
schema: { type: 'integer', minimum: 1, default: 1 },
})
@ApiQuery('limit', {
description: 'Items per page',
schema: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
})
@ApiResponseBody(200, {
description: 'List of users',
schema: { type: 'array', items: UserSchema },
})
listUsers(ctx: IRequestContext) {
const page = ctx.query.page ?? '1';
const limit = ctx.query.limit ?? '20';
return { users: [], page: parseInt(page), limit: parseInt(limit) };
}
@Get('/:id')
@ApiOperation({ summary: 'Get user by ID' })
@ApiParam('id', {
description: 'User UUID',
schema: { type: 'string', format: 'uuid' },
})
@ApiResponseBody(200, { description: 'User found', schema: UserSchema })
@ApiResponseBody(404, { description: 'User not found' })
getUser(ctx: IRequestContext) {
return { id: ctx.params.id, name: 'John Doe', email: 'john@example.com' };
}
@Post('/')
@ApiOperation({ summary: 'Create a new user' })
@ApiRequestBody({
description: 'User data',
schema: CreateUserSchema,
})
@ApiResponseBody(201, { description: 'User created', schema: UserSchema })
@ApiResponseBody(400, { description: 'Validation error' })
@ApiSecurity('bearerAuth')
async createUser(ctx: IRequestContext<{ name: string; email: string }>) {
const body = await ctx.json();
return { id: 'new-uuid', name: body.name, email: body.email };
}
}
```
### Request Validation
When you define `@ApiRequestBody`, `@ApiParam`, or `@ApiQuery` with schemas, SmartServe **automatically validates** incoming requests:
```typescript
const server = new SmartServe({
port: 3000,
openapi: {
enabled: true,
info: {
title: 'My API',
version: '1.0.0',
description: 'A well-documented API',
},
validate: true, // 🔥 Enable automatic request validation
},
});
server.register(UserController);
await server.start();
// Invalid request → 400 Bad Request with details
// POST /api/users with { "name": "" }
// Response: { "error": "Validation failed", "source": "body", "details": [...] }
```
**Automatic Type Coercion**: Query and path parameters are automatically coerced to their schema types:
```typescript
@Get('/items')
@ApiQuery('page', { schema: { type: 'integer', default: 1 } })
@ApiQuery('active', { schema: { type: 'boolean' } })
listItems(ctx: IRequestContext) {
// ctx.query.page is coerced to number (1)
// ctx.query.active is coerced to boolean
return { page: ctx.query.page, active: ctx.query.active };
}
```
### Swagger UI & ReDoc
```typescript
const server = new SmartServe({
port: 3000,
openapi: {
enabled: true,
info: {
title: 'My Awesome API',
version: '2.0.0',
description: 'API documentation with interactive testing',
contact: {
name: 'API Support',
email: 'support@example.com',
},
},
servers: [
{ url: 'http://localhost:3000', description: 'Development' },
{ url: 'https://api.example.com', description: 'Production' },
],
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
// Customize paths
specPath: '/openapi.json', // Default: /openapi.json
swaggerPath: '/docs', // Default: /docs
redocPath: '/redoc', // Default: /redoc
},
});
await server.start();
// 📖 Swagger UI: http://localhost:3000/docs
// 📕 ReDoc: http://localhost:3000/redoc
// 📄 OpenAPI: http://localhost:3000/openapi.json
```
---
## Compression
SmartServe automatically compresses responses using Brotli or gzip based on client support:
```typescript
const server = new SmartServe({
port: 3000,
compression: {
enabled: true, // Default: true
threshold: 1024, // Min bytes to compress (default: 1KB)
level: 6, // Compression level 1-11 for br, 1-9 for gzip
preferBrotli: true, // Prefer Brotli over gzip
},
});
```
### Per-Route Compression Control
```typescript
import { Route, Get, Compress, NoCompress } from '@push.rocks/smartserve';
@Route('/api')
class ApiController {
@Get('/large-data')
@Compress({ level: 9 }) // Force high compression
getLargeData() {
return { data: '...massive payload...' };
}
@Get('/already-compressed')
@NoCompress() // Skip compression (e.g., for pre-compressed content)
getCompressed() {
return someCompressedBuffer;
}
}
```
### Pre-Compressed Static Files
Serve `.br` or `.gz` files automatically when available:
```typescript
const server = new SmartServe({
port: 3000,
static: {
root: './dist',
precompressed: true, // Serve main.js.br instead of main.js
},
});
```
---
## Static File Server ## Static File Server
Serve static files with streaming, ETags, and directory listing: Serve static files with streaming, ETags, Range requests, and directory listing:
```typescript ```typescript
const server = new SmartServe({ const server = new SmartServe({
@@ -197,29 +478,32 @@ const server = new SmartServe({
static: { static: {
root: './public', root: './public',
index: ['index.html', 'index.htm'], index: ['index.html', 'index.htm'],
dotFiles: 'deny', // 'allow' | 'deny' | 'ignore' dotFiles: 'deny', // 'allow' | 'deny' | 'ignore'
etag: true, // Generate ETags etag: true, // Generate ETags for caching
lastModified: true, // Add Last-Modified header lastModified: true, // Add Last-Modified header
cacheControl: 'max-age=3600', cacheControl: 'max-age=3600', // Or function: (path) => 'max-age=...'
extensions: ['.html'], // Try these extensions extensions: ['.html'], // Try these extensions for extensionless URLs
precompressed: true, // Serve .br/.gz files when available
directoryListing: { directoryListing: {
showHidden: false, showHidden: false,
sortBy: 'name', // 'name' | 'size' | 'modified' sortBy: 'name', // 'name' | 'size' | 'modified'
sortOrder: 'asc', sortOrder: 'asc',
}, },
}, },
}); });
``` ```
Or simply: Or use the shorthand:
```typescript ```typescript
const server = new SmartServe({ const server = new SmartServe({
port: 3000, port: 3000,
static: './public', // Shorthand - uses defaults static: './public', // Uses sensible defaults
}); });
``` ```
---
## WebDAV Support ## WebDAV Support
Mount the server as a network drive on macOS, Windows, or Linux: Mount the server as a network drive on macOS, Windows, or Linux:
@@ -230,75 +514,115 @@ const server = new SmartServe({
webdav: { webdav: {
root: '/path/to/files', root: '/path/to/files',
auth: (ctx) => { auth: (ctx) => {
// Optional Basic auth // Optional: Basic authentication
const auth = ctx.headers.get('Authorization'); const auth = ctx.headers.get('Authorization');
if (!auth) return false; if (!auth) return false;
const [, credentials] = auth.split(' '); const [, credentials] = auth.split(' ');
const [user, pass] = atob(credentials).split(':'); const [user, pass] = atob(credentials).split(':');
return user === 'admin' && pass === 'secret'; return user === 'admin' && pass === 'secret';
}, },
locking: true, // Enable RFC 4918 file locking locking: true, // Enable RFC 4918 exclusive write locks
}, },
}); });
await server.start(); await server.start();
// Mount: Connect to Server → http://localhost:8080 // 💾 Connect: Finder → Go → Connect to Server → http://localhost:8080
``` ```
**Supported WebDAV Methods:** **Supported WebDAV Methods:**
- `OPTIONS` - Capability discovery
- `PROPFIND` - Directory listing and file metadata | Method | Description |
- `MKCOL` - Create directory |--------|-------------|
- `COPY` / `MOVE` - Copy and move operations | `OPTIONS` | Capability discovery |
- `LOCK` / `UNLOCK` - Exclusive write locking | `PROPFIND` | Directory listing and file metadata |
- `GET` / `PUT` / `DELETE` - File operations | `MKCOL` | Create directory |
| `COPY` | Copy files/directories |
| `MOVE` | Move/rename files/directories |
| `LOCK` | Acquire exclusive write lock |
| `UNLOCK` | Release lock |
| `GET` / `PUT` / `DELETE` | File operations |
---
## WebSocket Support ## WebSocket Support
WebSocket connections are handled natively: WebSocket connections are handled natively across all runtimes:
```typescript ```typescript
const server = new SmartServe({ const server = new SmartServe({
port: 3000, port: 3000,
websocket: { websocket: {
onOpen: (peer) => { onOpen: (peer) => {
console.log(`Connected: ${peer.id}`); console.log(`🔗 Connected: ${peer.id}`);
peer.send('Welcome!'); peer.send('Welcome!');
peer.tags.add('authenticated'); // Tag for filtering
}, },
onMessage: (peer, message) => { onMessage: (peer, message) => {
console.log(`Received: ${message.text}`); console.log(`📨 ${message.text}`);
peer.send(`Echo: ${message.text}`); peer.send(`Echo: ${message.text}`);
}, },
onClose: (peer, code, reason) => { onClose: (peer, code, reason) => {
console.log(`Disconnected: ${peer.id}`); console.log(`👋 Disconnected: ${peer.id}`);
}, },
onError: (peer, error) => { onError: (peer, error) => {
console.error(`Error: ${error.message}`); console.error(`Error: ${error.message}`);
}, },
}, },
}); });
``` ```
### TypedRouter for Type-Safe RPC
Use `@api.global/typedrequest` for type-safe WebSocket communication:
```typescript
import { TypedRouter } from '@api.global/typedrequest';
const typedRouter = new TypedRouter();
typedRouter.addTypedHandler(MyTypedRequest, async (request) => {
return { result: 'processed' };
});
const server = new SmartServe({
port: 3000,
websocket: {
typedRouter, // Handles message routing automatically
onConnectionOpen: (peer) => {
peer.tags.add('subscriber');
},
},
});
// Broadcast to tagged connections
server.broadcast({ event: 'update' }, (peer) => peer.tags.has('subscriber'));
```
---
## HTTPS/TLS ## HTTPS/TLS
Enable HTTPS with certificate configuration: Enable HTTPS with certificate configuration:
```typescript ```typescript
import * as fs from 'fs';
const server = new SmartServe({ const server = new SmartServe({
port: 443, port: 443,
tls: { tls: {
cert: fs.readFileSync('./cert.pem'), cert: fs.readFileSync('./cert.pem'),
key: fs.readFileSync('./key.pem'), key: fs.readFileSync('./key.pem'),
// Optional ca: fs.readFileSync('./ca.pem'), // Optional: CA chain
ca: fs.readFileSync('./ca.pem'), minVersion: 'TLSv1.2', // Optional: minimum TLS version
minVersion: 'TLSv1.2', passphrase: 'optional-key-passphrase',
}, },
}); });
``` ```
---
## Error Handling ## Error Handling
Built-in HTTP error classes: Built-in HTTP error classes with factory methods:
```typescript ```typescript
import { HttpError, type IRequestContext } from '@push.rocks/smartserve'; import { HttpError, type IRequestContext } from '@push.rocks/smartserve';
@@ -326,50 +650,73 @@ HttpError.conflict(message, details); // 409
HttpError.internal(message, details); // 500 HttpError.internal(message, details); // 500
``` ```
Global error handling: ### Global Error Handler
```typescript ```typescript
const server = new SmartServe({ const server = new SmartServe({
port: 3000, port: 3000,
onError: (error, request) => { onError: (error, request) => {
console.error('Server error:', error); console.error('💥 Server error:', error);
return new Response(JSON.stringify({ error: 'Something went wrong' }), {
status: 500, // Return custom error response
headers: { 'Content-Type': 'application/json' }, return new Response(
}); JSON.stringify({ error: 'Something went wrong', requestId: crypto.randomUUID() }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}, },
}); });
``` ```
---
## Request Context ## Request Context
Every handler receives a typed request context: Every handler receives a typed request context:
```typescript ```typescript
interface IRequestContext<TBody = unknown> { interface IRequestContext<TBody = unknown> {
request: Request; // Original Web Standards Request (body never consumed by framework) request: Request; // Original Request (body never consumed by framework)
params: Record<string, string>; // URL path parameters params: Record<string, string>; // URL path parameters (/users/:id → { id: '123' })
query: Record<string, string>; // Query string parameters query: Record<string, string>; // Query string (?page=1 → { page: '1' })
headers: Headers; // Request headers headers: Headers; // Request headers
path: string; // Matched route path path: string; // Matched route path
method: THttpMethod; // HTTP method method: THttpMethod; // GET, POST, PUT, DELETE, etc.
url: URL; // Full URL object url: URL; // Full URL object
runtime: 'node' | 'deno' | 'bun'; // Current runtime runtime: 'node' | 'deno' | 'bun';
state: Record<string, unknown>; // Per-request state bag state: Record<string, unknown>; // Per-request state (share data between interceptors)
// Lazy body parsing methods (cached after first call) // 🔥 Lazy body parsing (cached after first call)
json(): Promise<TBody>; // Parse body as JSON (typed) json(): Promise<TBody>; // Parse as JSON (typed!)
text(): Promise<string>; // Parse body as text text(): Promise<string>; // Parse as text
arrayBuffer(): Promise<ArrayBuffer>; // Parse body as binary arrayBuffer(): Promise<ArrayBuffer>;
formData(): Promise<FormData>; // Parse body as form data formData(): Promise<FormData>;
} }
``` ```
Body parsing is lazy - the request body is only consumed when you call `json()`, `text()`, etc. This allows raw access to `ctx.request` for cases like signature verification. **Lazy Body Parsing**: The request body is only consumed when you call `json()`, `text()`, etc. This allows raw access to `ctx.request` for cases like webhook signature verification:
```typescript
@Post('/webhook')
async handleWebhook(ctx: IRequestContext) {
// Get raw body for signature verification
const rawBody = await ctx.request.text();
const signature = ctx.headers.get('X-Signature');
if (!verifyHmac(rawBody, signature)) {
throw HttpError.unauthorized('Invalid signature');
}
// Parse the body manually
const payload = JSON.parse(rawBody);
return { processed: true };
}
```
---
## Custom Request Handler ## Custom Request Handler
Bypass decorator routing entirely: Bypass decorator routing entirely for low-level control:
```typescript ```typescript
const server = new SmartServe({ port: 3000 }); const server = new SmartServe({ port: 3000 });
@@ -381,12 +728,22 @@ server.setHandler(async (request, connectionInfo) => {
return new Response('OK', { status: 200 }); return new Response('OK', { status: 200 });
} }
if (url.pathname.startsWith('/api')) {
// Handle API routes manually
const body = await request.json();
return new Response(JSON.stringify({ received: body }), {
headers: { 'Content-Type': 'application/json' },
});
}
return new Response('Not Found', { status: 404 }); return new Response('Not Found', { status: 404 });
}); });
await server.start(); await server.start();
``` ```
---
## Runtime Detection ## Runtime Detection
SmartServe automatically detects and optimizes for the current runtime: SmartServe automatically detects and optimizes for the current runtime:
@@ -394,26 +751,37 @@ SmartServe automatically detects and optimizes for the current runtime:
```typescript ```typescript
const instance = await server.start(); const instance = await server.start();
console.log(instance.runtime); // 'node' | 'deno' | 'bun' console.log(instance.runtime); // 'node' | 'deno' | 'bun'
console.log(instance.port); // 3000 console.log(instance.port); // 3000
console.log(instance.secure); // true if TLS enabled console.log(instance.hostname); // '0.0.0.0'
console.log(instance.secure); // true if TLS enabled
// Server statistics
const stats = instance.stats();
console.log(stats.uptime); // Seconds since start
console.log(stats.requestsTotal); // Total requests handled
console.log(stats.requestsActive); // Currently processing
``` ```
---
## License and Legal Information ## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks ### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartserve', name: '@push.rocks/smartserve',
version: '2.0.0', version: '2.0.1',
description: 'a cross platform server module for Node, Deno and Bun' description: 'a cross platform server module for Node, Deno and Bun'
} }