@contract-kit/core
v1.0.0
Published
Core contract definitions and builders for contract-kit
Downloads
730
Maintainers
Readme
@contract-kit/core
Core contract definitions and builders for Contract Kit
This package provides the foundation for defining type-safe API contracts that can be used across your entire stack. Contracts describe HTTP endpoints with full TypeScript support.
Installation
npm install @contract-kit/core
# Use with your preferred Standard Schema library
npm install zod
# or
npm install valibot
# or
npm install arktypeTypeScript requirements
This package requires TypeScript 5.0 or higher for proper type inference.
Key concepts
Contract
A contract is the single source of truth for an API endpoint. It describes:
- HTTP method and path (with path parameters)
- Path parameters, query parameters, request headers, and request body schemas
- Response schemas (per status code, including error responses)
- Metadata for auth, rate limiting, idempotency, etc.
Contract group
A contract group allows you to share configuration across related endpoints, such as a common namespace, authentication requirements, and shared response schemas.
Usage
Defining contracts
import { z } from "zod";
import { createContractGroup } from "@contract-kit/core";
// Create a contract group for related endpoints
const todos = createContractGroup()
.namespace("todos")
.prefix("/api/todos")
.meta({ auth: "required" })
.headers(z.object({
authorization: z.string().startsWith("Bearer "),
}));
// Define schemas
const TodoSchema = z.object({
id: z.string(),
title: z.string(),
completed: z.boolean(),
});
const CreateTodoRequest = z.object({
title: z.string().min(1),
completed: z.boolean().optional(),
});
// Define contracts
export const getTodo = todos
.get("/:id")
.pathParams(z.object({ id: z.string() }))
.responses({ 200: TodoSchema })
.errors({
TodoNotFound: {
code: "TODO_NOT_FOUND",
status: 404,
message: "Todo not found",
details: z.object({ id: z.string() }),
},
});
export const createTodo = todos
.post("/")
.body(CreateTodoRequest)
.responses({ 201: TodoSchema });
export const listTodos = todos
.get("/")
.query(z.object({
completed: z.boolean().optional(),
limit: z.coerce.number().optional(),
}))
.responses({ 200: z.array(TodoSchema) });Clients infer required path argument keys from literal path templates. Use .pathParams(...) when you want runtime validation or coercion, and for routes included in OpenAPI generation.
Use .headers(...) for request headers that are part of the endpoint contract. Declare header keys in lowercase; server and client runtime matching is case-insensitive.
Request bodies are supported for POST, PUT, and PATCH contracts only.
If you do not pass name, Contract Kit generates one from the HTTP method and full path:
createContract({ method: "GET", path: "/users/:id" }).name;
// "getUsersById"
createContract({ method: "POST", path: "/api/todos" }).name;
// "createTodos"Auto-generated names ignore a leading /api segment, include path parameters as By..., and are used as defaults in places like React Query keys and OpenAPI operationIds. Pass name explicitly when you need a custom stable identifier.
Path prefixes
Use .prefix(...) on a contract group to compose shared URL path segments without repeating them on every route:
const api = createContractGroup().prefix("/api/v1");
const todos = api
.namespace("todos")
.prefix("/todos");
export const listTodos = todos.get("/");
// GET /api/v1/todos
export const getTodo = todos.get("/:id");
// GET /api/v1/todos/:idPrefixes compose immutably and normalize boundary slashes. namespace() still controls contract names; prefix() only controls URL paths.
Contract metadata
Use metadata to drive cross-cutting concerns like authentication, rate limiting, and idempotency:
const sendMessage = messages
.post("/api/messages")
.body(SendMessageRequest)
.responses({ 201: SendMessageResponse })
.meta({
auth: "required",
idempotency: {
enabled: true,
header: "Idempotency-Key",
windowSeconds: 300,
},
rateLimit: {
max: 60,
windowSec: 60,
scope: "user",
},
});OpenAPI metadata
Add OpenAPI-specific metadata for documentation using the .openapi() method:
export const getTodo = todos
.get("/api/todos/:id")
.pathParams(z.object({ id: z.string() }))
.responses({ 200: TodoSchema })
.openapi({
summary: "Get a todo by ID",
description: "Retrieves a single todo item by its unique identifier",
tags: ["todos"],
deprecated: false,
operationId: "getTodoById",
externalDocs: {
url: "https://docs.example.com/todos",
description: "Todo documentation",
},
security: [{ bearerAuth: [] }],
});Schema introspection
Contracts expose their schemas for runtime introspection:
getTodo.schema.pathParams; // Path parameter schema
getTodo.schema.query; // Query parameter schema
getTodo.schema.body; // Request body schema
getTodo.schema.responses; // Response schemas by status code
getTodo.path; // "/api/todos/:id"
getTodo.pathTemplate; // "/api/todos/:id" (alias)
getTodo.method; // "GET"
getTodo.metadata; // { auth: "required", ... }API reference
createContractGroup()
Creates a new contract group for defining related endpoints.
const group = createContractGroup()
.namespace("myNamespace") // Optional namespace prefix
.prefix("/api/v1") // Optional URL path prefix
.meta({ auth: "required" }) // Shared metadata
.headers(AuthHeaders) // Shared request headers
.errors({ // Shared catalog errors
TenantSuspended: errors.TenantSuspended,
});Any non-empty response map is treated as a response contract. Include
successful statuses such as 200 or 201 alongside custom error statuses; use
responses: {} only when you want to skip response validation. Prefer
.errors(...) for expected business failures that should use Contract Kit's
standard error envelope.
Contract builder methods
| Method | Description |
|--------|-------------|
| .get(path) | Define a GET endpoint |
| .post(path) | Define a POST endpoint |
| .put(path) | Define a PUT endpoint |
| .patch(path) | Define a PATCH endpoint |
| .delete(path) | Define a DELETE endpoint |
| .pathParams(schema) | Define path parameter schema |
| .query(schema) | Define query parameter schema |
| .headers(schema) | Define request header schema |
| .body(schema) | Define request body schema |
| .responses({ ... }) | Define or merge response schemas by status code |
| .errors({ ... }) | Declare route-owned catalog errors using Contract Kit's standard error envelope |
| .meta(metadata) | Add custom metadata |
| .openapi(options) | Add OpenAPI metadata (summary, tags, etc.) |
Standard Schema support
This package works with any Standard Schema compatible library:
- Zod - Most popular, excellent TypeScript inference
- Valibot - Lightweight alternative to Zod
- ArkType - High-performance runtime validation
OpenAPI generation currently requires Zod schemas, even though core contracts can use any Standard Schema-compatible library.
Related packages
@contract-kit/client- HTTP client@contract-kit/next- Next.js server adapter@contract-kit/react-query- TanStack Query integration@contract-kit/react-hook-form- React Hook Form integration@contract-kit/nuqs- URL query state integration with nuqs@contract-kit/server- Server runtime for contract-backed HTTP routes@contract-kit/openapi- OpenAPI 3.1 generation
License
MIT
