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

@md-oss/api-types

v0.10.0

Published

Type-safe API contracts, client factory, and handler helpers built on Zod

Readme

@md-oss/api-types

Type-safe API contracts and helpers for building clients and route handlers around shared @md-oss/common errors and Zod-validated inputs/outputs.

Features

  • Route registries with Zod schemas for params, query, body, and optional response validation
  • Typed API client factory (createApiClient) that strips unsafe headers and returns full HTTP response metadata (statusCode, headers, raw Response, etc.)
  • Generic controller/route handler builders (createGenericController, createGenericRouteHandler) with pluggable auth/context/permission strategies
  • Response helpers (sendTypedResponse) and request parsers (parseRequestParameters) that serialize/validate against your route contract
  • Utilities for prefixing routes, parsing/stripping proxy headers, and fine-grained debug namespaces (md-oss:api-types:*)

Installation

pnpm add @md-oss/api-types

Define a typed route registry

import { z } from 'zod';
import type { RouteRegistry } from '@md-oss/api-types';

const routes = {
	'/users/:id': {
		params: z.object({ id: z.string() }),
		endpoints: {
			GET: {
				response: { id: '123', email: '[email protected]' },
				permissions: null,
			},
		},
	},
	'/posts': {
		endpoints: {
			POST: {
				body: z.object({ title: z.string(), body: z.string() }),
				response: { id: 'post-id' },
				permissions: { role: 'editor' },
			},
		},
	},
} satisfies RouteRegistry;

Create a typed client

import { createApiClient } from '@md-oss/api-types';

const client = createApiClient(routes, {
	baseUrl: 'https://api.example.com',
});

const result = await client.request('/users/:id', {
	method: 'GET',
	params: { id: '123' },
});

if (!result.ok) {
	// HTTP error response with metadata
}

const user = result.data;

Opt-in response validation with Zod

When an endpoint declares response as a Zod schema, response typing and runtime validation are both enabled automatically.

You can also declare responses as a status-code map of schemas.

response and responses are mutually exclusive. Use exactly one.

import { z } from 'zod';
import type { RouteRegistry } from '@md-oss/api-types';

const routes = {
	'/users/:id': {
		params: z.object({ id: z.string() }),
		endpoints: {
			GET: {
				response: z.object({ id: z.string(), email: z.email() }),
				permissions: null,
			},
		},
	},
} satisfies RouteRegistry;
  • Server: sendTypedResponse validates the outgoing body when a response schema is present.
  • Client: createApiClient(...).request(...) validates successful responses when a response schema is present.
  • Non-Zod response values continue to work as before (type-only behavior, no runtime validation).

Status-code response schemas (responses)

const routes = {
	'/users/:id': {
		params: z.object({ id: z.string() }),
		endpoints: {
			GET: {
				responses: {
					200: z.object({ id: z.string(), email: z.email() }),
					304: z.null(),
					default: apiErrorResponseSchema // <- Used if status code not included in mapping
				},
				permissions: null,
			},
		},
	},
} satisfies RouteRegistry;
  • responses[statusCode] is used for runtime validation when present.
  • If responses is used and a status code has no schema, no runtime response validation is applied for that status.

Build controllers with typed context

import {
	createGenericController,
	sendTypedResponse,
	type ContextProvider,
} from '@md-oss/api-types';

const authStrategy = {
	async resolveAuthentication(req, res, endpoint) {
		// return { session: { userId: 'u1' } } or { session: null }
		return { session: null };
	},
};

const contextStrategy = {
	async buildContext(session, endpoint, parsed, injected, req, res, requestId) {
		return {
			...parsed,
			session,
			endpoint,
			ctx: { requestId },
			cps: async () => true,
		} satisfies ContextProvider<typeof routes, any, '/users/:id', 'GET', null>;
	},
};

const getUser = createGenericController(
	routes,
	'/users/:id',
	'GET',
	{ authStrategy, contextStrategy }
)((context, respond) => {
	respond({
		path: '/users/:id',
		method: 'GET',
		data: { id: context.params.id, email: '[email protected]' },
	});
});

// use getUser as an Express/Next/fastify style handler

createGenericRouteHandler powers .withContext(...) so you can inject pre-built context when wiring routes.

Validate requests and respond consistently

  • parseRequestParameters validates params/query/body against Zod schemas and builds a typed context payload.
  • sendTypedResponse returns exactly the data you pass in.
  • Signed access errors can be converted to HTTPError via parseSignedAccessError.

Model envelope-style APIs with schemas

For APIs that use envelope response bodies, define a re-usable zod schema:

import { z } from 'zod/v4';
import { extendDefaultHttpResponseEnvelope } from '@md-oss/common/http/schemas';

const apiResponseEnvelope = <D extends z.ZodTypeAny>(data: D) =>
	extendDefaultHttpResponseEnvelope(data, {
		rid: z.uuid(),
	});

const routes = {
	'/': {
		endpoints: {
			GET: {
				permissions: { requireAuthentication: false },
				responses: {
					200: apiResponseEnvelope(apiInfoResponseDataSchema),
					default: httpErrorResponseSchema,
				},
			},
		},
	},
	'/health': {
		endpoints: {
			GET: {
				permissions: { requireAuthentication: false },
				responses: {
					200: apiResponseEnvelope(healthResponseDataSchema),
					default: httpErrorResponseSchema,
				},
			},
		},
	},
} satisfies RouteRegistry;

This keeps the core transport behavior simple while still supporting arbitrary envelope shapes (including fields like rid) through your own schemas.

sendTypedResponse utilities

You can wrap sendTypedResponse to set defaults and/or extend behavior:

import {
	createGenericController,
	extendSendTypedResponse,
	withSendTypedResponseDefaults,
} from '@md-oss/api-types';

const sendWithDefaults = withSendTypedResponseDefaults(
	{
		headers: {
			'x-api-version': '2026-05-05',
		},
	},
);

const sendWithDefaultsAndAudit = extendSendTypedResponse(
	({ options, res, next }) => {
		res.setHeader('x-request-id', options.path);
		next(res, options);
	},
	sendWithDefaults
);

// Respond directly anywhere
sendWithDefaultsAndAudit(res, {
	path: TPath;
	method: TMethod;
	data: API[TPath]['endpoints'][TMethod]['response'];
	status?: number;
	headers?: Record<string, string>;
	responseSchemas?: ResponseSchemas;
});

// Or use in a route-handler
const getUserController = createGenericController(
	routes,
	'/users/:id',
	'GET',
	{ authStrategy, contextStrategy, permissionStrategy, sendWithDefaultsAndAudit }
)((context, respond) => {
	respond({
		data: { id: context.params.id, email: '[email protected]' },
	});
});

Debugging

Enable scoped debugging with DEBUG=md-oss:api-types* to trace parameter parsing, performance timings, and controller responses. Namespaces include md-oss:api-types:route, :performance, and :errors.

Exports

Key exports from the package entrypoint:

  • Client: createApiClient, parseHeaders, stripProxyAndWebsocketHeaders, ApiClient
  • Server: createGenericController, createGenericRouteHandler, sendTypedResponse, parseRequestParameters
  • Types: RouteRegistry, EndpointDefinition, InferApi, RouteHandler, ControllerFunction, RequestOptions, ExtractResolvedContext, PrefixRoutes, RouteKeys, MethodKeys

See the source in src/ for strategy interfaces (auth, context, permission tracking) and additional helpers.