# @api.global/typedserver A powerful TypeScript-first web server framework featuring static file serving, live reload, compression, and seamless type-safe API integration. Part of the `@api.global` ecosystem, it provides a modern foundation for building full-stack TypeScript applications with first-class support for typed HTTP requests and WebSocket communication. ## Issue Reporting and Security For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly. ## ✨ Features - πŸ”’ **Type-Safe API Ecosystem** - Full TypeScript support with `@api.global/typedrequest` and `@api.global/typedsocket` - ⚑ **Live Reload** - Automatic browser refresh on file changes during development - πŸ—œοΈ **Compression** - Built-in support for gzip, deflate, and brotli compression - 🌐 **CORS Management** - Flexible cross-origin resource sharing configuration - πŸ”§ **Service Worker Integration** - Advanced caching and offline capabilities - ☁️ **Edge Worker Support** - Cloudflare Workers compatible edge computing - πŸ“‘ **WebSocket Support** - Real-time bidirectional communication via TypedSocket - πŸ—ΊοΈ **Sitemap & Feeds** - Automatic sitemap and RSS feed generation - πŸ€– **Robots.txt** - Built-in robots.txt handling ## πŸ“¦ Installation ```bash # Using pnpm (recommended) pnpm add @api.global/typedserver # Using npm npm install @api.global/typedserver ``` ## πŸš€ Quick Start ### Basic Static File Server ```typescript import { TypedServer } from '@api.global/typedserver'; const server = new TypedServer({ serveDir: './public', cors: true, watch: true, // Enable file watching injectReload: true, // Inject live reload script }); await server.start(); console.log('Server running on port 3000'); ``` ### Server with All Options ```typescript import { TypedServer } from '@api.global/typedserver'; const server = new TypedServer({ port: 8080, serveDir: './dist', cors: true, watch: true, injectReload: true, enableCompression: true, preferredCompressionMethod: 'brotli', forceSsl: false, sitemap: true, feed: true, robots: true, domain: 'example.com', appVersion: 'v1.0.0', manifest: { name: 'My App', short_name: 'myapp', start_url: '/', display: 'standalone', background_color: '#ffffff', theme_color: '#000000', }, }); await server.start(); ``` ## πŸ”Œ Type-Safe API Integration ### Adding TypedRequest Handlers ```typescript import { TypedServer, servertools } from '@api.global/typedserver'; import * as typedrequest from '@api.global/typedrequest'; // Define your typed request interface interface IGetUser { method: 'getUser'; request: { userId: string }; response: { name: string; email: string }; } const server = new TypedServer({ serveDir: './public', cors: true }); // Create a typed router const typedRouter = new typedrequest.TypedRouter(); // Add a typed handler typedRouter.addTypedHandler( new typedrequest.TypedHandler('getUser', async (data) => { // Your logic here return { name: 'John Doe', email: 'john@example.com' }; }) ); // Attach the router to the server server.server.addRoute('/api', new servertools.HandlerTypedRouter(typedRouter)); await server.start(); ``` ### WebSocket Communication with TypedSocket ```typescript import { TypedServer } from '@api.global/typedserver'; import * as typedrequest from '@api.global/typedrequest'; import * as typedsocket from '@api.global/typedsocket'; const server = new TypedServer({ serveDir: './public', cors: true }); const typedRouter = new typedrequest.TypedRouter(); await server.start(); // Create WebSocket server attached to the HTTP server const socketServer = await typedsocket.TypedSocket.createServer( typedRouter, server.server ); // Handle real-time events interface IChatMessage { method: 'sendMessage'; request: { text: string; room: string }; response: { messageId: string; timestamp: number }; } typedRouter.addTypedHandler( new typedrequest.TypedHandler('sendMessage', async (data) => { return { messageId: crypto.randomUUID(), timestamp: Date.now() }; }) ); ``` ## πŸ› οΈ Server Tools ### Custom Route Handlers ```typescript import { servertools } from '@api.global/typedserver'; const server = new servertools.Server({ cors: true, domain: 'example.com', }); // Add a custom route with handler server.addRoute('/api/hello', new servertools.Handler('GET', async (req, res) => { res.json({ message: 'Hello, World!' }); })); // Serve static files from a directory server.addRoute('/{*splat}', new servertools.HandlerStatic('./public', { serveIndexHtmlDefault: true, enableCompression: true, })); await server.start(3000); ``` ### Proxy Handler ```typescript import { servertools } from '@api.global/typedserver'; const server = new servertools.Server({ cors: true }); // Proxy requests to another server server.addRoute('/proxy/{*splat}', new servertools.HandlerProxy({ target: 'https://api.example.com', })); await server.start(3000); ``` ## ☁️ Edge Worker (Cloudflare Workers) ```typescript import { EdgeWorker, DomainRouter } from '@api.global/typedserver/edgeworker'; const router = new DomainRouter(); router.addDomainInstruction({ domainPattern: '*.example.com', originUrl: 'https://origin.example.com', cacheConfig: { maxAge: 3600 }, }); const worker = new EdgeWorker(router); // In your Cloudflare Worker entry point export default { fetch: (request: Request, env: any, ctx: any) => worker.handleRequest(request, env, ctx), }; ``` ## πŸ”§ Service Worker Client ```typescript import { ServiceWorkerClient } from '@api.global/typedserver/web_serviceworker_client'; const swClient = new ServiceWorkerClient(); // Register and manage service worker await swClient.register('/serviceworker.bundle.js'); // Listen for updates swClient.onUpdate(() => { console.log('New version available!'); }); ``` ## πŸ“‹ Configuration Reference ### IServerOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `serveDir` | `string` | - | Directory to serve static files from | | `port` | `number \| string` | `3000` | Port to listen on | | `cors` | `boolean` | `true` | Enable CORS headers | | `watch` | `boolean` | `false` | Watch files for changes | | `injectReload` | `boolean` | `false` | Inject live reload script into HTML | | `enableCompression` | `boolean` | `false` | Enable response compression | | `preferredCompressionMethod` | `'gzip' \| 'deflate' \| 'brotli'` | - | Preferred compression algorithm | | `forceSsl` | `boolean` | `false` | Redirect HTTP to HTTPS | | `sitemap` | `boolean` | `false` | Generate sitemap at `/sitemap` | | `feed` | `boolean` | `false` | Generate RSS feed at `/feed` | | `robots` | `boolean` | `false` | Serve robots.txt | | `domain` | `string` | - | Domain name for sitemap/feeds | | `appVersion` | `string` | - | Application version string | | `manifest` | `object` | - | Web App Manifest configuration | | `publicKey` | `string` | - | SSL certificate | | `privateKey` | `string` | - | SSL private key | ## πŸ—οΈ Architecture ``` @api.global/typedserver β”œβ”€β”€ /backend - Main server exports (TypedServer, servertools) β”œβ”€β”€ /edgeworker - Cloudflare Workers edge computing β”œβ”€β”€ /web_inject - Live reload script injection β”œβ”€β”€ /web_serviceworker - Service Worker implementation └── /web_serviceworker_client - Service Worker client utilities ``` ## License and Legal Information 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. ### 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 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 Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany 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.