// utils/response/schemas.ts /** * Response types and schemas following RFC 7807 (Problem Details) and success envelopes * * Architecture: * - Everything is a Zod schema first * - Types are derived from schemas via z.input and z.output * - Factory functions create generic schemas (like in fields.ts, filtering.ts) * - Follows same pattern as query processing utilities * - Aligns with Hono's ContentfulStatusCode and ContentlessStatusCode types */ import type { ContentfulStatusCode } from 'hono/utils/http-status' import { ContentfulStatusCodeSchema, ContentlessStatusCodeSchema } from './status-codes.ts' import { z } from 'zod' /** * Validation error detail schema. */ export const ValidationErrorDetailSchema = z.object({ field: z.string(), message: z.string(), }) /** * One field-level validation failure inferred from the schema. */ export type ValidationErrorDetail = z.output /** * Canonical JSON content type for successful API envelopes. */ export const JSON_CONTENT_TYPE = 'application/json' as const /** * Canonical JSON content type for RFC 7807 problem responses. */ export const PROBLEM_JSON_CONTENT_TYPE = 'application/problem+json' as const /** * RFC 7807 problem-details base schema. */ export const ProblemDetailsSchema = z.object({ type: z.string().describe('A URI reference that identifies the problem type.'), title: z.string().describe('A short, human-readable summary of the problem type.'), status: ContentfulStatusCodeSchema.describe('The HTTP status code generated by the origin server for this occurrence of the problem.'), detail: z.string().describe('A human-readable request specific explanation to this occurrence of the problem.'), instance: z.string().describe('A URI reference that identifies the specific occurrence of the problem.'), timestamp: z.coerce.date().describe('The time at which the problem occurred.'), docs: z.url().optional().describe('A URL pointing to documentation about this problem type.'), }).catchall(z.unknown()) /** * RFC 7807 problem-details payload inferred from the schema. */ export type ProblemDetails = z.output /** * RFC 7807 problem-details schema with validation errors. */ export const ProblemDetailsWithErrorsSchema = ProblemDetailsSchema.extend({ errors: z.array(ValidationErrorDetailSchema) }) /** * Problem-details payload with field-level validation failures inferred from * the schema. */ export type ProblemDetailsWithErrors = z.output export const PaginationSchema = z.object({ hasMore: z.boolean(), limit: z.number().int().positive(), count: z.number().int().min(0), // Cursor-based navigation nextCursor: z.string().optional(), prevCursor: z.string().optional(), // Offset-based navigation offset: z.number().int().min(0).optional(), nextOffset: z.number().int().min(0).optional(), prevOffset: z.number().int().min(0).optional(), // Totals total: z.number().int().min(0).optional(), approxTotal: z.number().int().min(0).optional(), // Cursor expiration expiresAt: z.coerce.date().optional() }) /** * Pagination metadata inferred from the schema. */ export type Pagination = z.output /** * Base metadata schema - accepts arbitrary additional fields. */ export const DataMetadataSchema = z.object().catchall(z.unknown()) /** * Arbitrary metadata object inferred from the schema. */ export type DataMetadata = z.output /** * LinkMap * * Normalized representation of RFC 8288-style links for a single response. * * - Keys are **link relation types** (`rel`): "self", "next", "prev", "first", "last", etc. * - Values are URI references (often relative paths like `/articles?page=2`). * - `self` is **required** and must be non-empty. * - Standard pagination rels (`first`, `last`, `next`, `prev`) are optional. * - Any additional rel (e.g. "describedby", "up", custom rels) is allowed via catchall. * * @example * const links = LinkMapSchema.parse({ * self: "/articles?offset=40&limit=20", * first: "/articles?offset=0&limit=20", * prev: "/articles?offset=20&limit=20", * next: "/articles?offset=60&limit=20", * last: "/articles?offset=120&limit=20", * }) * * @example * const links = LinkMapSchema.parse({ * self: "/articles?offset=0&limit=20", * describedby: "https://api.example.com/schemas/articles", * profile: "https://api.example.com/profiles/pagination", * }) */ export const LinkMapSchema = z.object({ self: z.string().min(1, 'self link must be a non-empty URI reference'), first: z.string().min(1).optional(), last: z.string().min(1).optional(), next: z.string().min(1).optional(), prev: z.string().min(1).optional(), }).catchall(z.string().min(1)) /** * RFC 8288-style link map inferred from the schema. */ export type LinkMap = z.output // ============================================================================ // HEADER SCHEMAS // ============================================================================ /** Standard headers schema. */ export const StandardHeadersSchema = z.object().catchall(z.string()); /** * Basic string header map inferred from the schema. */ export type StandardHeaders = z.output /** JSON response headers schema. */ export const JsonHeadersSchema = StandardHeadersSchema.extend({ 'Content-Type': z.union([z.literal(JSON_CONTENT_TYPE), z.string()]) }) /** * Standard JSON response headers inferred from the schema. */ export type JsonHeaders = z.output /** Pagination response headers schema. */ export const JsonHeadersWithLinksSchema = JsonHeadersSchema.extend({ 'Link': z.string(), 'X-Total-Count': z.string().optional(), 'X-Per-Page': z.string().optional(), 'X-Page': z.string().optional(), 'X-Total-Pages': z.string().optional(), 'Preference-Applied': z.string().optional(), 'Range-Unit': z.string().optional(), 'Content-Range': z.string().optional() }) /** * Pagination response headers inferred from the schema. */ export type JsonHeadersWithLinks = z.output /** Problem-response headers schema. */ export const ProblemHeadersSchema = StandardHeadersSchema.extend({ 'Content-Type': z.literal(PROBLEM_JSON_CONTENT_TYPE) }) /** * RFC 7807 problem-response headers inferred from the schema. */ export type ProblemHeaders = z.output // ============================================================================ // ENVELOPE SCHEMA FACTORIES (for generic data types) // ============================================================================ /** * Create success envelope schema * * Structure: { data: T, meta: { timestamp: string, ...custom } } * * @example * const UserSchema = z.object({ id: z.string(), name: z.string() }) * const EnvelopeSchema = makeSuccessEnvelopeSchema(UserSchema) * type Envelope = z.output * // => { data: User, meta: { timestamp: string } } */ export const SuccessEnvelopeMetaSchema = z.object({ timestamp: z.iso.datetime(), }) /** * Success-envelope metadata inferred from the schema. */ export type SuccessEnvelopeMeta = z.output /** * Generic success envelope type built from the schema-backed meta contract. */ export type SuccessEnvelope = { data: T meta: M & SuccessEnvelopeMeta } export function makeSuccessEnvelopeSchema< TData extends z.ZodType, TMeta extends z.ZodObject = z.ZodObject >( dataSchema: TData, metaSchema?: TMeta ){ const meta = metaSchema ? z.intersection(SuccessEnvelopeMetaSchema, metaSchema) : SuccessEnvelopeMetaSchema return z.object({ data: dataSchema, meta: meta }) } /** * Generic pagination envelope type (for helpers like paginate()). */ export function makePaginationEnvelopeSchema( dataSchema: TData ) { return makeSuccessEnvelopeSchema(dataSchema, PaginationMetadataSchema) } /** * Pagination-specific metadata schema used by generic response helpers. * * `paginate()` always emits a normalized `links` object with at least a * `self` relation, so this schema keeps `links` required. That makes the Zod * validator, exported TypeScript type, and helper behavior all describe the * same contract. */ export const PaginationMetadataSchema = DataMetadataSchema.extend({ pagination: PaginationSchema, links: LinkMapSchema, }) /** * Pagination-specific response metadata inferred from the schema. */ export type PaginationMetadata = z.output /** * Generic pagination envelope type (for helpers like paginate()). */ export type PaginationEnvelope = SuccessEnvelope /** * Create contentless result tuple schema * For responses with no body (204, 101, 205, 304) * * @example * const ResultSchema = makeContentlessResultSchema(204) * type Result = z.output * // => readonly [undefined, 204, JsonHeaders] */ export const ContentlessResultSchema = z.tuple([ z.undefined(), ContentlessStatusCodeSchema, JsonHeadersSchema ]) /** * Generic contentless result tuple type * For actual validation, use makeContentlessResultSchema() */ export type ContentlessResult = z.output // ============================================================================ // RESULT TUPLE SCHEMA FACTORIES // ============================================================================ /** * Create success result tuple schema * For responses with data (200, 201, etc.) * * @example * const UserSchema = z.object({ id: z.string() }) * const ResultSchema = makeSuccessResultSchema(UserSchema, 200) * type Result = z.output * // => readonly [{ data: User, meta: { timestamp: string } }, 200, JsonHeaders] */ export function makeSuccessResultSchema< TData extends z.ZodType >( dataSchema: TData, metaSchema?: z.ZodObject ) { return z.tuple([ makeSuccessEnvelopeSchema(dataSchema, metaSchema), ContentfulStatusCodeSchema, JsonHeadersSchema ]) } /** * Generic success result tuple type * For actual validation, use makeSuccessResultSchema() */ export type GenericSuccessResult = readonly [ E, ContentfulStatusCode, H ] /** * Success Result */ export type SuccessResult = GenericSuccessResult> /** * Create pagination result tuple schema * Always returns 200 with pagination metadata * * @example * const UserSchema = z.object({ id: z.string() }) * const ResultSchema = makePaginationResultSchema(z.array(UserSchema)) * type Result = z.output * // => readonly [{ data: User[], meta: { timestamp: string, pagination: Pagination } }, 200, JsonHeadersWithLinks] */ export function makePaginationResultSchema( dataSchema: TData ) { return z.tuple([ makePaginationEnvelopeSchema(dataSchema), ContentfulStatusCodeSchema, JsonHeadersWithLinksSchema ]) } /** * Generic pagination result tuple type * For actual validation, use makePaginationResultSchema() */ export type PaginationResult = GenericSuccessResult, JsonHeadersWithLinks> /** * Create error result tuple schema * For RFC 7807 error responses * * @example * const ResultSchema = ErrorResultSchema * type Result = z.output * // => readonly [ProblemDetails, 404, ProblemHeaders] */ export const ErrorResultSchema = z.tuple([ ProblemDetailsSchema, ContentfulStatusCodeSchema, ProblemHeadersSchema ]) /** * Generic error result tuple type * For actual validation, use makeErrorResultSchema() */ export type ErrorResult = z.output /** * Create validation errors result tuple schema * For 422 responses with multiple field errors * * @example * const ResultSchema = makeErrorsResultSchema() * type Result = z.output * // => readonly [ProblemDetailsWithErrors, 422, ProblemHeaders] */ export const ErrorsResultSchema = z.tuple([ ProblemDetailsWithErrorsSchema, ContentfulStatusCodeSchema, ProblemHeadersSchema ]) /** * Generic errors result tuple type (with validation errors array) * For actual validation, use makeErrorsResultSchema() */ export type ErrorsResult = z.output // ============================================================================ // RESPONSE UNION SCHEMAS (for comprehensive validation) // ============================================================================ /** * Create success response union schema * Includes contentless (204), success, and pagination results * * @example * const UserSchema = z.object({ id: z.string() }) * const ResponseSchema = makeSuccessResponseSchema(UserSchema) * * // Can validate any of: * // - [{ data: User, meta }, 200, JsonHeaders] * // - [{ data: User[], meta: { pagination } }, 200, JsonHeadersWithLinks] * // - [undefined, 204, JsonHeaders] */ export function makeSuccessResponseSchema( dataSchema: TData ) { return z.union([ makeSuccessResultSchema(dataSchema), makePaginationResultSchema(dataSchema), ContentlessResultSchema ]) } /** * Schema returned by `makeSuccessResponseSchema()` for a specific data schema. */ export type SuccessResponseSchema = ReturnType< typeof makeSuccessResponseSchema > /** * Success response tuple inferred from a specific data schema. */ export type SuccessResponseFromSchema = ReturnType< SuccessResponseSchema['parse'] > /** * Union of success response types */ export type SuccessResponse = | SuccessResult | PaginationResult | ContentlessResult /** * Create error response union schema * Includes common error status codes * * @example * const ResponseSchema = ErrorResponseSchema * * // Can validate any of: * // - [ProblemDetails, 400, ProblemHeaders] * // - [ProblemDetails, 404, ProblemHeaders] * // - [ProblemDetailsWithErrors, 422, ProblemHeaders] * // - [ProblemDetails, 500, ProblemHeaders] */ export const ErrorResponseSchema = z.union([ ErrorResultSchema, ErrorsResultSchema ]) /** * Union of error response types inferred from `ErrorResponseSchema`. */ export type ErrorResponse = z.output /** * Create complete response union schema * Includes all success and error variants * * @example * const UserSchema = z.object({ id: z.string() }) * const ResponseSchema = makeResponseResultSchema(UserSchema) * * // Can validate any response tuple from your API */ export function makeResponseResultSchema( dataSchema: TData ) { return z.union([ makeSuccessResponseSchema(dataSchema), ErrorResponseSchema, ]) } /** * Schema returned by `makeResponseResultSchema()` for a specific data schema. */ export type ResponseResultSchema = ReturnType< typeof makeResponseResultSchema > /** * Response tuple inferred from a specific data schema. */ export type ResponseResultFromSchema = ReturnType< ResponseResultSchema['parse'] > /** * Union of all response tuple types */ export type ResponseResult = | SuccessResponse | ErrorResponse