2023-10-20 18:13:10 +02:00
2023-03-29 14:54:07 +02:00
2024-05-13 23:24:08 +02:00
2023-03-29 14:54:07 +02:00
2023-03-29 14:54:07 +02:00
2025-12-04 22:20:55 +00:00

@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/. 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/ 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

# Using pnpm (recommended)
pnpm add @api.global/typedserver

# Using npm
npm install @api.global/typedserver

🚀 Quick Start

Basic Static File Server

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

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

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<IGetUser>(
  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

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<IChatMessage>(
  new typedrequest.TypedHandler('sendMessage', async (data) => {
    return { messageId: crypto.randomUUID(), timestamp: Date.now() };
  })
);

🛠️ Server Tools

Custom Route Handlers

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

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)

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

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

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the 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.

Description
No description provided
Readme 3.4 MiB
Languages
TypeScript 100%