kitcn
Version:
kitcn - React Query integration and CLI tools for Convex
293 lines (292 loc) • 11.5 kB
TypeScript
import { o as Simplify } from "./types-DF2cg_w0.js";
import { g as UnsetMarker, t as AnyMiddleware } from "./types-CnTpHR1F.js";
import { GenericActionCtx, GenericDataModel, HttpRouter } from "convex/server";
import { z } from "zod";
import { Context, Hono } from "hono";
//#region src/crpc/transformer.d.ts
/**
* Generic transformer contract (mirrors tRPC shape).
*/
interface DataTransformer {
deserialize(object: any): any;
serialize(object: any): any;
}
/**
* Separate input/output transformers.
*/
interface CombinedDataTransformer {
input: DataTransformer;
output: DataTransformer;
}
/**
* Transformer config accepted by cRPC.
*/
type DataTransformerOptions = CombinedDataTransformer | DataTransformer;
/**
* Extensible tagged wire codec.
*/
interface WireCodec {
decode(value: unknown): unknown;
encode(value: unknown): unknown;
isType(value: unknown): boolean;
readonly tag: `$${string}`;
}
/**
* Date wire tag (Convex-style reserved key).
*/
declare const DATE_CODEC_TAG = "$date";
/**
* Built-in Date codec.
*/
declare const dateWireCodec: WireCodec;
/**
* Build a recursive tagged transformer from codecs.
*/
declare const createTaggedTransformer: (codecs: readonly WireCodec[]) => DataTransformer;
/**
* Default cRPC transformer (Date-enabled).
*/
declare const defaultCRPCTransformer: DataTransformer;
/**
* Normalize transformer config to split input/output shape.
* User transformers are additive and always composed with default Date handling.
*/
declare const getTransformer: (transformer?: DataTransformerOptions) => CombinedDataTransformer;
/**
* Encode request payloads (input direction).
*/
declare const encodeWire: (value: unknown, transformer?: DataTransformerOptions) => unknown;
/**
* Decode response payloads (output direction).
*/
declare const decodeWire: (value: unknown, transformer?: DataTransformerOptions) => unknown;
/**
* Exposed identity transformer for advanced composition.
*/
declare const identityTransformer: CombinedDataTransformer;
//#endregion
//#region src/server/http-types.d.ts
type ProcedureMeta = object;
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
interface HttpRouteDefinition<TMethod extends HttpMethod = HttpMethod> {
method: TMethod;
path: string;
pathParamNames: string[];
usePathPrefix: boolean;
}
/**
* Infer output type from schema, defaulting to void for UnsetMarker
*/
type InferHttpInput$1<T> = T extends UnsetMarker ? undefined : T extends z.ZodTypeAny ? z.output<T> : never;
/**
* Internal definition for HttpProcedureBuilder
* Stores schema types directly (like QueryProcedureBuilder)
*/
interface HttpProcedureBuilderDef<TCtx, TInput extends UnsetMarker | z.ZodTypeAny, TOutput extends UnsetMarker | z.ZodTypeAny, TParams extends UnsetMarker | z.ZodTypeAny, TQuery extends UnsetMarker | z.ZodTypeAny, TMeta extends ProcedureMeta, TMethod extends HttpMethod = HttpMethod, TForm extends UnsetMarker | z.ZodTypeAny = UnsetMarker> {
/** @internal Phantom types for type inference */
_types?: {
input: TInput;
output: TOutput;
params: TParams;
query: TQuery;
form: TForm;
};
formSchema?: z.ZodTypeAny;
functionConfig: {
base: HttpActionConstructor;
createContext: (ctx: GenericActionCtx<GenericDataModel>) => TCtx;
transformer: CombinedDataTransformer;
};
inputSchema?: z.ZodTypeAny;
meta: TMeta;
middlewares: AnyMiddleware[];
outputSchema?: z.ZodTypeAny;
paramsSchema?: z.ZodTypeAny;
procedureName?: string;
querySchema?: z.ZodTypeAny;
route?: HttpRouteDefinition<TMethod>;
}
type HttpActionConstructor = (handler: (ctx: GenericActionCtx<GenericDataModel>, request: Request) => Promise<Response>) => HttpActionHandler;
interface HttpActionHandler {
isHttp: true;
}
interface HttpProcedure<TInput extends UnsetMarker | z.ZodTypeAny = any, TOutput extends UnsetMarker | z.ZodTypeAny = any, TParams extends UnsetMarker | z.ZodTypeAny = any, TQuery extends UnsetMarker | z.ZodTypeAny = any, TMethod extends HttpMethod = HttpMethod, TForm extends UnsetMarker | z.ZodTypeAny = any> extends HttpActionHandler {
_crpcHttpRoute: HttpRouteDefinition<TMethod>;
/** @internal Expose def for client-side type inference */
_def: {
inputSchema?: TInput;
outputSchema?: TOutput;
paramsSchema?: TParams;
querySchema?: TQuery;
formSchema?: TForm;
};
}
/**
* Handler options with ctx namespace (consistent with cRPC queries/mutations).
* - ctx: context properties (userId, db, runQuery, etc.)
* - input: parsed JSON body
* - params: parsed path params
* - searchParams: parsed query params
* - form: parsed form data
* - c: Hono Context for Response helpers (c.json, c.text, c.redirect, c.header, c.req)
*/
type HttpHandlerOpts<TCtx, TInput extends UnsetMarker | z.ZodTypeAny, TParams extends UnsetMarker | z.ZodTypeAny, TSearchParams extends UnsetMarker | z.ZodTypeAny, TForm extends UnsetMarker | z.ZodTypeAny> = {
ctx: TCtx;
c: Context;
} & (TInput extends UnsetMarker ? object : {
input: z.output<TInput>;
}) & (TParams extends UnsetMarker ? object : {
params: z.output<TParams>;
}) & (TSearchParams extends UnsetMarker ? object : {
searchParams: z.output<TSearchParams>;
}) & (TForm extends UnsetMarker ? object : {
form: z.output<TForm>;
});
/**
* Hono handler with cRPC route metadata attached
*/
interface CRPCHonoHandler {
_crpcRoute: {
path: string;
method: HttpMethod;
};
(c: Context): Promise<Response>;
}
//#endregion
//#region src/server/http-router.d.ts
/**
* Recursive router record - can contain procedures or nested routers
*/
interface HttpRouterRecord {
[key: string]: HttpProcedure | HttpRouterRecord | CRPCHttpRouter<any>;
}
/**
* Router definition - stores both flat procedures and hierarchical record
*/
interface HttpRouterDef<TRecord extends HttpRouterRecord> {
/** Flat map with dot-notation keys (e.g., "todos.get") for lookup */
procedures: Record<string, HttpProcedure>;
/** Hierarchical structure for type inference */
record: TRecord;
router: true;
}
/**
* HTTP Router - like tRPC's BuiltRouter
*/
interface CRPCHttpRouter<TRecord extends HttpRouterRecord> {
_def: HttpRouterDef<TRecord>;
}
/**
* HTTP Router that wraps a Hono app for use with Convex.
* Internal class - use `createHttpRouter()` factory instead.
*/
declare class HttpRouterWithHono extends HttpRouter {
private _app;
private _handler;
constructor(app: Hono);
}
/**
* Create a router factory function (like tRPC's createRouterFactory)
*
* @example
* ```ts
* // In crpc.ts
* export const router = c.router;
*
* // In api/todos.ts
* export const todosRouter = router({
* get: publicRoute.get('/api/todos/:id')...,
* create: authRoute.post('/api/todos')...,
* });
*
* // In http.ts
* export const httpRouter = router({
* todos: todosRouter,
* health,
* });
* export type AppRouter = typeof httpRouter;
* ```
*/
declare function createHttpRouterFactory(): <TRecord extends HttpRouterRecord>(record: TRecord) => CRPCHttpRouter<TRecord>;
/**
* Create an HTTP router with cRPC routes registered.
*
* @example
* ```ts
* import { Hono } from 'hono';
* import { cors } from 'hono/cors';
* import { createHttpRouter } from 'kitcn/server';
*
* const app = new Hono();
* app.use('/api/*', cors({ origin: process.env.SITE_URL, credentials: true }));
*
* export default createHttpRouter(app, httpRouter);
* ```
*/
declare function createHttpRouter<TRecord extends HttpRouterRecord>(app: Hono, router: CRPCHttpRouter<TRecord>): HttpRouterWithHono;
/**
* Extract route map from procedures for client runtime
*
* @example
* ```ts
* export const httpRoutes = extractRouteMap(httpRouter._def.procedures);
* ```
*/
declare function extractRouteMap<T extends Record<string, HttpProcedure>>(procedures: T): { [K in keyof T]: {
path: string;
method: string;
} };
//#endregion
//#region src/crpc/http-types.d.ts
/** Route definition for client runtime */
type HttpRouteInfo = {
path: string;
method: string;
};
/** Route map type - from codegen */
type HttpRouteMap = Record<string, HttpRouteInfo>;
/** Infer schema type or return empty object if UnsetMarker */
type InferSchemaOrEmpty<T> = T extends UnsetMarker ? object : T extends z.ZodTypeAny ? z.infer<T> : object;
/**
* Infer merged input from HttpProcedure
* Combines params, query, and body input into a single object
*/
type InferHttpInput<T> = T extends HttpProcedure<infer TInput, infer _TOutput, infer TParams, infer TQuery> ? Simplify<InferSchemaOrEmpty<TParams> & InferSchemaOrEmpty<TQuery> & InferSchemaOrEmpty<TInput>> : object;
/**
* Infer output type from HttpProcedure
*/
type InferHttpOutput<T> = T extends HttpProcedure<infer _TInput, infer TOutput, infer _TParams, infer _TQuery> ? TOutput extends UnsetMarker ? unknown : TOutput extends z.ZodTypeAny ? z.infer<TOutput> : unknown : unknown;
/**
* Single procedure call signature
* Returns a function that takes merged input and returns output
*/
type HttpProcedureCall<T extends HttpProcedure> = keyof InferHttpInput<T> extends never ? () => Promise<InferHttpOutput<T>> : object extends InferHttpInput<T> ? (input?: InferHttpInput<T>) => Promise<InferHttpOutput<T>> : (input: InferHttpInput<T>) => Promise<InferHttpOutput<T>>;
/**
* HTTP Client type from router record
* Maps each procedure to its call signature, recursively for nested routers
*/
type HttpClient<T extends HttpRouterRecord> = { [K in keyof T]: T[K] extends HttpProcedure ? HttpProcedureCall<T[K]> : T[K] extends CRPCHttpRouter<infer R> ? HttpClient<R> : T[K] extends HttpRouterRecord ? HttpClient<T[K]> : never };
/**
* HTTP Client type from a CRPCHttpRouter
* Use this when your type is the router object (with _def)
*/
type HttpClientFromRouter<TRouter extends CRPCHttpRouter<any>> = HttpClient<TRouter['_def']['record']>;
/** Error codes that can be returned from HTTP endpoints */
type HttpErrorCode = 'BAD_REQUEST' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'METHOD_NOT_SUPPORTED' | 'CONFLICT' | 'UNPROCESSABLE_CONTENT' | 'TOO_MANY_REQUESTS' | 'INTERNAL_SERVER_ERROR' | 'UNKNOWN';
/** HTTP client error */
declare class HttpClientError extends Error {
readonly name = "HttpClientError";
readonly code: HttpErrorCode;
readonly status: number;
readonly procedureName: string;
constructor(opts: {
code: HttpErrorCode;
status: number;
procedureName: string;
message?: string;
});
}
/** Type guard for HttpClientError */
declare const isHttpClientError: (error: unknown) => error is HttpClientError;
//#endregion
export { DataTransformer as A, HttpProcedure as C, ProcedureMeta as D, InferHttpInput$1 as E, decodeWire as F, defaultCRPCTransformer as I, encodeWire as L, WireCodec as M, createTaggedTransformer as N, CombinedDataTransformer as O, dateWireCodec as P, getTransformer as R, HttpMethod as S, HttpRouteDefinition as T, extractRouteMap as _, HttpProcedureCall as a, HttpActionHandler as b, InferHttpInput as c, CRPCHttpRouter as d, HttpRouterDef as f, createHttpRouterFactory as g, createHttpRouter as h, HttpErrorCode as i, DataTransformerOptions as j, DATE_CODEC_TAG as k, InferHttpOutput as l, HttpRouterWithHono as m, HttpClientError as n, HttpRouteInfo as o, HttpRouterRecord as p, HttpClientFromRouter as r, HttpRouteMap as s, HttpClient as t, isHttpClientError as u, CRPCHonoHandler as v, HttpProcedureBuilderDef as w, HttpHandlerOpts as x, HttpActionConstructor as y, identityTransformer as z };