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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hono-contract/core

v0.2.3

Published

Typed Hono route contracts with Standard Schema validation, OpenAPI, and route source generation

Readme

@hono-contract/core

Define routes as typed objects, check their handlers against those contracts, and generate registrations from .route.ts files.

Install

bun add @hono-contract/core hono hono-openapi zod

Use TypeScript with modern module resolution. The source-generation CLI runs with Bun.

Define a contract

Create the owning router:

// src/routes/index.ts
import { createRouter } from "@hono-contract/core"

const router = createRouter()

export { router }

Keep each contract and handler in a .route.ts module:

// src/routes/create-user.route.ts
import type { Handler, Route } from "@hono-contract/core"
import { z } from "zod"
import type { router } from "."

const route = {
	operationId: "createUser",
	method: "post",
	path: "/users",
	validators: {
		json: z.object({ name: z.string(), age: z.coerce.number() }),
	},
	responses: {
		201: z.object({ name: z.string(), age: z.number() }).describe("Created user"),
	},
} as const satisfies Route<typeof router>

const handler: Handler<typeof router, typeof route> = (c, respond) => {
	const user = c.req.valid("json") // age is a number
	return respond(201, user)
}

export default { route, handler }

as const satisfies Route<typeof router> checks the contract without widening its path or response statuses. Import the owning router with import type to avoid a runtime dependency cycle.

Handler<typeof router, typeof route> infers the router environment and validated schema outputs, including transforms. respond checks the declared status, representation, and matching response body. A bare schema sends JSON; response schemas are not executed against outgoing values.

These contracts type server handlers; they do not build a Hono RPC client schema.

Response representations

Use a media map when a response sends text, XML, binary data, or another representation. The handler chooses a declared media type explicitly:

const responses = {
	200: {
		"application/json": z.object({ message: z.string() }).describe("Greeting"),
		"text/plain": z.string().describe("Plain text greeting"),
		"application/xml": z.string().describe("XML greeting"),
	},
	204: null,
} as const

// In a handler whose route uses these responses:
return respond(200, "text/plain", "Hello", { Vary: "Accept" })
// Or: return respond(204)

JSON and +json media types are serialized as JSON. Other media types send the declared encoded body directly. The schema's output type determines the accepted body, including strings, bytes, and readable streams. Your handler handles content negotiation and produces XML or other encoded formats.

null declares an empty body: call respond(status, headers?). Statuses 204, 205, and 304 require null. This differs from a bare z.null() schema, which sends JSON null.

ContentType builds the same media maps while preserving their literal keys:

import { ContentType } from "@hono-contract/core"

const vendorJson = ContentType.Custom("application/vnd.example+json")
const responses = {
	200: {
		...vendorJson(z.object({ message: z.string() })),
		...ContentType.Text("plain")(z.string()),
	},
} as const

// In the typed handler:
return respond(200, vendorJson.type, { message: "Hello" })

Builders accept arbitrary subtypes under Application, Text, Image, Audio, Video, Multipart, Font, Message, and Model. Custom accepts the complete media type.

For status-specific methods, createSafeResponder(respond) exposes the same contract as safe[200]("text/plain", "Hello") or safe[204](). Import it from @hono-contract/core and create it inside the handler.

Typed streams

Sequential media accept synchronous or asynchronous item iterables. Use itemSchema to type each item and schema to describe the encoded body:

const updateSchema = z.object({ sequence: z.number(), message: z.string() })
const responses = {
	200: ContentType.Application("jsonl")({
		schema: z.string().describe("Newline-delimited updates"),
		itemSchema: updateSchema,
	}),
} as const

async function* updates() {
	yield { sequence: 1, message: "Ready" }
}

// In the typed handler:
return respond(200, "application/jsonl", updates())

The responder frames items as SSE for text/event-stream, newline-delimited JSON for application/jsonl and application/x-ndjson, or JSON sequences for application/json-seq and application/geo+json-seq. SSE items contain a string data field and optional event, id, and retry fields. A bare schema on these media types also describes each item.

An encoded ReadableStream<Uint8Array> passes through unchanged. Custom streaming formats and multipart/mixed require encoded streams; supply multipart framing and its boundary yourself. Cancelling the response closes an item iterator.

Descriptors require schema, itemSchema, or both. Upstream OpenAPI conversion includes schema; it does not currently emit itemSchema. See the complete SSE and JSONL contracts.

Generate registrations

bunx hono-contract-gen ./src/routes

The CLI updates the root index:

import { createRouter } from "@hono-contract/core"
import createUser from "./create-user.route"

const router = createRouter()

router.implement(createUser)

export { router }

This is the same registration as router.implement({ route, handler }). Contracts remain plain objects; no route-builder call is needed.

Add generation and freshness checks to your application:

{
	"scripts": {
		"routes:generate": "hono-contract-gen ./src/routes",
		"routes:check": "hono-contract-gen ./src/routes --check"
	}
}
  • --dry / -d prints proposed files without writing them.
  • --check writes nothing and exits with code 1 when registrations need updating.
  • --verbose / -v includes discovery and skipped-file diagnostics.
  • --help / -h shows usage.

The CLI scans .route.ts files recursively without executing them. It accepts default { route, handler } bundles or named route and handler exports. Files without a complete pair are skipped; syntax errors stop generation before files are written.

Missing indexes are created. Nested indexes use scope<typeof parentRouter>(), and parents mount their children. Existing router setup, middleware, and registrations are preserved; repeated runs do not duplicate them.

Updates are additive. After deleting or moving a route, remove its obsolete imports and registrations. Directory names do not add URL prefixes.

Scoped contracts and middleware

Pass your application's environment to createRouter<AppEnv>(). Route handlers then infer that environment through Handler<typeof router, typeof route>.

For a child with additional context, use scope<typeof parentRouter, ChildEnv>(). The child environment must include the parent's. The CLI generates inherited scopes automatically; customize a child index when it needs its own middleware or environment.

Typed middleware uses the same response contract:

import { middleware, type Responses } from "@hono-contract/core"
import { z } from "zod"
import type { AppEnv } from "./env"

const authResponses = {
	401: z.object({ error: z.literal("unauthorized") }).describe("Authentication required"),
} satisfies Responses

const authenticate = middleware<AppEnv, typeof authResponses>(authResponses, async (c, next, respond) => {
	if (!c.req.header("Authorization")) {
		return respond(401, { error: "unauthorized" })
	}
	await next()
})

Pass the response map to middleware so early responses use the same serialization as route handlers. Include ...authResponses in affected route contracts; middleware responses are not merged automatically. Install middleware before implementing or mounting its routes. The generator preserves this setup.

parent.mount(child) mounts the child's registered routes at their declared paths. Implement child routes before mounting them. An optional second onMount argument to createRouter or scope runs after mounting.

See the example's scoped router and typed authentication middleware for a complete setup.

Schema libraries and descriptions

Request and response schemas accept Standard Schema implementations, including Zod and Valibot. You can mix libraries in one contract. Validation and inferred types use the schemas directly; documentation conversion depends on hono-openapi's supported converters.

For Valibot documentation conversion:

bun add valibot @valibot/to-json-schema

Attach descriptions to the schemas themselves: .describe("Created user") with Zod, or v.pipe(schema, v.description("Created user")) with Valibot. The upstream converter preserves schema and field descriptions. The first described representation supplies the OpenAPI response description; each representation keeps its own schema description. Responses without a description use "No description".

Description extraction runs only when generating the OpenAPI document; ordinary API requests do not run it.

router.app exposes the underlying Hono app. Refer to Hono for routing and transport APIs, and hono-openapi for serving or exporting documentation. The example includes an OpenAPI export command.

See the usage example to run the complete workflow.

License

MIT