import type { Context, MiddlewareHandler, Env, ValidationTargets } from 'hono' import { validator } from 'hono/validator' import type { BaseSchema, Input, Output, SafeParseResult } from 'valibot' import { safeParse } from 'valibot' type Hook = ( result: SafeParseResult, c: Context ) => Response | Promise | void | Promise export const vValidator = < T extends BaseSchema, Target extends keyof ValidationTargets, E extends Env, P extends string, V extends { in: { [K in Target]: Input } out: { [K in Target]: Output } } = { in: { [K in Target]: Input } out: { [K in Target]: Output } } >( target: Target, schema: T, hook?: Hook ): MiddlewareHandler => validator(target, (value, c) => { const result = safeParse(schema, value) if (hook) { const hookResult = hook(result, c) if (hookResult instanceof Response || hookResult instanceof Promise) { return hookResult } } if (!result.success) { return c.json(result, 400) } const data = result.output as Output return data })