Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518// 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<typeof ValidationErrorDetailSchema>
/** * 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<typeof ProblemDetailsSchema>
/** * 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<typeof ProblemDetailsWithErrorsSchema>
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<typeof PaginationSchema>
/** * 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<typeof DataMetadataSchema>
/** * 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<typeof LinkMapSchema>
// ============================================================================// 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<typeof StandardHeadersSchema>
/** 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<typeof JsonHeadersSchema>
/** 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<typeof JsonHeadersWithLinksSchema>
/** 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<typeof ProblemHeadersSchema>
// ============================================================================// 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<typeof EnvelopeSchema> * // => { 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<typeof SuccessEnvelopeMetaSchema>
/** * Generic success envelope type built from the schema-backed meta contract. */export type SuccessEnvelope<T = unknown, M extends DataMetadata = DataMetadata> = { data: T meta: M & SuccessEnvelopeMeta}
export function makeSuccessEnvelopeSchema< TData extends z.ZodType, TMeta extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>>( 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<TData extends z.ZodType>( 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<typeof PaginationMetadataSchema>
/** * Generic pagination envelope type (for helpers like paginate()). */export type PaginationEnvelope<T = unknown> = SuccessEnvelope<T, PaginationMetadata>
/** * Create contentless result tuple schema * For responses with no body (204, 101, 205, 304) * * @example * const ResultSchema = makeContentlessResultSchema(204) * type Result = z.output<typeof ResultSchema> * // => 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<typeof ContentlessResultSchema>
// ============================================================================// 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<typeof ResultSchema> * // => readonly [{ data: User, meta: { timestamp: string } }, 200, JsonHeaders] */export function makeSuccessResultSchema< TData extends z.ZodType>( dataSchema: TData, metaSchema?: z.ZodObject<z.ZodRawShape>) { return z.tuple([ makeSuccessEnvelopeSchema(dataSchema, metaSchema), ContentfulStatusCodeSchema, JsonHeadersSchema ])}
/** * Generic success result tuple type * For actual validation, use makeSuccessResultSchema() */export type GenericSuccessResult<E extends SuccessEnvelope = SuccessEnvelope, H extends JsonHeaders = JsonHeaders> = readonly [ E, ContentfulStatusCode, H]
/** * Success Result */export type SuccessResult<T = unknown, M extends DataMetadata = DataMetadata> = GenericSuccessResult<SuccessEnvelope<T, M>>
/** * 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<typeof ResultSchema> * // => readonly [{ data: User[], meta: { timestamp: string, pagination: Pagination } }, 200, JsonHeadersWithLinks] */export function makePaginationResultSchema<TData extends z.ZodType>( dataSchema: TData) { return z.tuple([ makePaginationEnvelopeSchema(dataSchema), ContentfulStatusCodeSchema, JsonHeadersWithLinksSchema ])}
/** * Generic pagination result tuple type * For actual validation, use makePaginationResultSchema() */export type PaginationResult<T = unknown> = GenericSuccessResult<PaginationEnvelope<T>, JsonHeadersWithLinks>
/** * Create error result tuple schema * For RFC 7807 error responses * * @example * const ResultSchema = ErrorResultSchema * type Result = z.output<typeof ResultSchema> * // => 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<typeof ErrorResultSchema>
/** * Create validation errors result tuple schema * For 422 responses with multiple field errors * * @example * const ResultSchema = makeErrorsResultSchema() * type Result = z.output<typeof ResultSchema> * // => 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<typeof ErrorsResultSchema>
// ============================================================================// 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<TData extends z.ZodType>( dataSchema: TData) { return z.union([ makeSuccessResultSchema(dataSchema), makePaginationResultSchema(dataSchema), ContentlessResultSchema ])}
/** * Schema returned by `makeSuccessResponseSchema()` for a specific data schema. */export type SuccessResponseSchema<TData extends z.ZodType> = ReturnType< typeof makeSuccessResponseSchema<TData>>
/** * Success response tuple inferred from a specific data schema. */export type SuccessResponseFromSchema<TData extends z.ZodType> = ReturnType< SuccessResponseSchema<TData>['parse']>
/** * Union of success response types */export type SuccessResponse<T = unknown> = | SuccessResult<T> | PaginationResult<T> | 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<typeof ErrorResponseSchema>
/** * 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<TData extends z.ZodType>( dataSchema: TData) { return z.union([ makeSuccessResponseSchema(dataSchema), ErrorResponseSchema, ])}
/** * Schema returned by `makeResponseResultSchema()` for a specific data schema. */export type ResponseResultSchema<TData extends z.ZodType> = ReturnType< typeof makeResponseResultSchema<TData>>
/** * Response tuple inferred from a specific data schema. */export type ResponseResultFromSchema<TData extends z.ZodType> = ReturnType< ResponseResultSchema<TData>['parse']>
/** * Union of all response tuple types */export type ResponseResult<T = unknown> = | SuccessResponse<T> | ErrorResponse