Core — Application, Router & Lifecycle

The Application class is the central orchestrator of Katal. It binds the router, onion middleware pipeline, IoC container, runtime adapters, and production subsystems (queues, cache, auth, observability).


1. Application Initialization

import { Application } from "katal";

const app = new Application({
    port: 3000,          // Listening port (default: 3000)
    host: "0.0.0.0",     // Binding host (default: "localhost")
    cors: true,          // Built-in CORS middleware
    bodyParser: true,    // Lazy streaming body parser
});

2. Multi-Runtime Portability

Katal v3 runs seamlessly across all modern JavaScript runtimes using native Web Standards (Request, Response, Headers, crypto.subtle):

  • Bun: High-throughput native Bun.serve adapter.
  • Node.js (18+): Built-in Node adapter with zero dependencies.
  • Cloudflare Workers / Vercel Edge / Deno: Export app.fetch directly!
// Export for Cloudflare Workers / Vercel Edge
export default {
    fetch(request: Request, env: unknown, ctx: unknown) {
        return app.fetch(request, env, ctx);
    },
};

3. Pure In-Memory Request Dispatch

For testing or microservice composition, dispatch requests directly without binding to a TCP port:

const response = await app.handle(new Request("http://localhost/api/health"));
console.log(response.status); // 200


4. Routing Engine & Fluent Chaining

Katal supports both traditional controller-based routing and Hono-style fluent route chaining directly on the Application instance:

// 1. Fluent Route Chaining with Automatic RPC Inference
export const app = new Application({ port: 3000 })
    .get("/api/health", (ctx) => ctx.json({ status: "ok" }))
    .post("/api/echo", async (ctx) => ctx.json({ received: ctx.body }));

// 2. Controller-Based Routing with Dual-Tier Radix Trie
const router = app.getRouter();

// Exact match (O(1))
router.get("/api/health", HealthController);

// Parameterized match
router.get("/users/:id", UserController);

// Wildcard match
router.get("/static/*path", AssetController);

// Route Groups with Prefix & Middleware
app.group("/api/v1", (r) => {
    r.get("/profile", ProfileController);
    r.post("/settings", SettingsController);
}, { middleware: ["auth"] });

5. Decomposed ServiceProvider Architecture

Application is purely an orchestrator. All major subsystems (Configuration, Routing, Queue, Cache, OpenAPI, Health, Events, Rate Limiting) are managed through standard ServiceProvider contracts:

import { Application, ServiceProvider } from "katal";

// Extend with custom service providers
class AuditServiceProvider extends ServiceProvider {
    register() {
        this.container.singleton("audit", () => new AuditLogger());
    }

    async boot() {
        // Run async setup after all providers are registered
    }

    async stop() {
        // Guaranteed LIFO graceful teardown
    }
}

app.register(new AuditServiceProvider(app));

6. Lifecycle Hooks & Graceful Teardown

// 1. Explicit boot phase (registers providers and plugins in Phase order)
await app.boot();

// 2. Access configuration
const appName = app.config.get("app.name", "Katal");

// 3. Start server
await app.listen(3000, "0.0.0.0");

// 4. Graceful shutdown
// Shuts down HTTP server, tears down providers in LIFO reverse order, closes plugins and active queue workers
await app.stop();