npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

capibara.ts

v1.0.4

Published

Simple HTTP framework

Readme


🦫 Capibara.ts – Lightweight HTTP Framework for Node.js

npm version license typescript

Minimalist web framework with middleware support, input validation, and native http handling — inspired by Express, built from scratch in TypeScript.


🚀 Features

  • Native HTTP server & lightweight router
  • 🔁 Middleware chaining via next()
  • 🔒 Input validation with capyScrub()
  • 🧾 Built-in body parser for JSON & URL-encoded
  • res.testStart() / res.testEnd() to track response duration
  • 📦 Request/Response wrappers for cleaner API
  • 🦺 Zero dependencies, fully native
  • 🧠 Written in TypeScript with full typings
  • 🧩 Supports modular routers like Router("/prefix")

📦 Installation

npm install capibara.ts

Or clone manually:

git clone https://github.com/your-username/capibara.ts.git
cd capibara.ts
npm install

🛠 Quick Start

import capi from "capibara.ts";

capi.get("/hello", (req, res) => {
  res.status(200).json({ message: "Hello from Capibara!" });
});

capi.start(3000, "🔥 Server running at http://localhost:3000");

🔧 Global Middleware

capi.use((req, res, next) => {
  console.log(`[${req.method}] ${req.url}`);
  next();
});

🧪 Input Validation with capyScrub()

import { capyScrub } from "capibara.ts";

capi.post(
  "/login",
  capyScrub({
    body: {
      username: "string",
      password: "string"
    }
  }),
  (req, res) => {
    const { username } = req.body;
    res.status(200).json({ welcome: username });
  }
);

⏱ Track Response Time

capi.get("/track", (req, res) => {
  res.testStart();

  setTimeout(() => {
    res.status(200).testEnd("Delayed response complete!");
  }, 150);
});

🧩 Grouping Routes with Router

import { Router } from "capibara.ts";

const userRouter = new Router("/user");

userRouter.get("/profile", (req, res) => {
  res.json({ user: "me" });
});

userRouter.post("/login", (req, res) => {
  res.json({ msg: "logged in" });
});

capi.use("/user", userRouter);

🧽 capyScrub Input Types

| Type | Validates... | | ----------- | ---------------------- | | "string" | Must be a string | | "number" | Must be a number | | "boolean" | Must be a boolean | | "email" | Must match email regex | | "object" | Must be a plain object | | "array" | Must be an array |


🧾 Request Wrapper (req)

| Property | Description | | ------------- | ----------------------------- | | req.body | Parsed JSON or form body | | req.query | Parsed query string | | req.ctx | Context object for middleware | | req.headers | Request headers | | req.method | HTTP method | | req.url | Raw URL |


📤 Response Wrapper (res)

| Method | Description | | ------------------- | ---------------------- | | res.status(code) | Set HTTP status code | | res.json(data) | Send JSON response | | res.text(str) | Send plain text | | res.testStart() | Start timing benchmark | | res.testEnd(data) | End timing and respond |


✅ Example: Full Route

import { capi, capyScrub } from "capibara.ts";

capi.post(
  "/register",
  capyScrub({
    body: {
      email: "email",
      username: "string"
    }
  }),
  (req, res) => {
    res.status(201).json({ success: true });
  }
);

⚠️ Route Format Rules

All routes must match this format:

^\/[a-z0-9\-\/]*$

This keeps route paths clean and safe from malformed input.


🧪 Local Dev & Testing

Start the server with:

# Development
npx ts-node index.ts

# Or build and run
npx tsc && node dist/index.js

🔐 Error Handling

To send custom error response:

capi.use((req, res, next) => {
  try {
    next();
  } catch (err) {
    res.status(500).json({ error: "Internal Server Error" });
  }
});

You can also wrap route handlers manually with try/catch if needed.


🧠 Typing Helpers

If you're getting type errors like:

'_req' implicitly has 'any' type

You can create a helper:

import type { Handler } from "capibara.ts";

export const defineHandler = (fn: Handler): Handler => fn;

Then use:

route.post("/login", defineHandler((_req, res) => {
  res.status(200).json({ msg: "login" });
}));

🌐 Enable CORS Middleware

Capibara.ts includes flexible CORS middleware support using capi.use(cors()). You can configure allowed origins, methods, headers, and credentials.

🔧 Setup Example

import { capi, cors } from "capibara.ts";

capi.use(cors({
  origin: ["http://localhost:5173", "https://myapp.com"],
  methods: "GET, POST, PUT, DELETE",
  headers: "Content-Type, Authorization",
  credentials: true
}));

🔒 This ensures your API only accepts requests from trusted origins and supports preflight handling automatically.


🔁 CORS Middleware Features

| Option | Description | | ------------- | ------------------------------------------------------ | | origin | List of allowed origins (e.g., ["*"], or specific) | | methods | Allowed HTTP methods (e.g., "GET, POST") | | headers | Allowed request headers | | credentials | Support cookies/auth headers (must not use * origin) | | silent | Suppress console logs for blocked origins |


🚫 Preflight Example

Capibara handles OPTIONS requests automatically with this middleware:

OPTIONS /user/login HTTP/1.1
Origin: http://localhost:5173
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization

Your server will respond with:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true


📄 License

MIT © Andrew Tangel

Capibara.ts was created to explore low-level HTTP handling with modern TypeScript. It's a minimalist yet powerful alternative to larger frameworks.



---