From a94ddbd04929181a49ad238850147f12187af7ab Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Fri, 4 Dec 2026 00:27:49 +0900 Subject: [PATCH 1/2] fix(void): type c.req.valid() after Hono validator middleware In `defineHandler(middleware..., handler)`, a Hono validator such as `zValidator()` or `validator()` ran, but its types did not reach the handler: `c.req.valid()` accepted no target, and a validator that returns a typed response was rejected. - Infer each middleware as a whole and pass what the validators return to the handler's `c`. `CloudContext` takes an optional Hono input type. - `defineMiddleware()` keeps the types of a validator it wraps. - A middleware typed with `CloudContext<{ out: ... }>` reads the validated data after the validator. - A middleware factory called in place, such as a rate limiter with a key function, still gets CloudEnv for its callbacks. Co-Authored-By: Claude Fable 5.2 --- docs/integrations/hono.md | 2 + packages/void/src/runtime/handler/index.ts | 311 ++++++++++++++---- .../integration/route-url-builder.test.ts | 15 + .../define-handler-middleware.typecheck.ts | 280 ++++++++++++++++ .../void/test/unit/define-handler.test.ts | 55 ++++ 5 files changed, 593 insertions(+), 70 deletions(-) create mode 100644 packages/void/test/unit/define-handler-middleware.typecheck.ts diff --git a/docs/integrations/hono.md b/docs/integrations/hono.md index 6f79b29224..6750b82562 100644 --- a/docs/integrations/hono.md +++ b/docs/integrations/hono.md @@ -107,6 +107,8 @@ import { defineMiddleware } from 'void'; export default defineMiddleware(uaBlocker({ blocklist: aiBots })); ``` +Validator middleware, such as `validator()` from `hono/validator` or `zValidator()` from `@hono/zod-validator`, types `c.req.valid()` in the route handler. The [typed fetch client](../guide/typed-fetch.md) does not read these validators. To check request bodies at the call site as well, validate with [`defineHandler.withValidator()`](../guide/server-routing.md#validation). + Workers do not allow timers, random values, or I/O at the top level of a file. A package that uses them when you create its middleware, such as `hono-rate-limiter` with its default store, works in dev but fails in preview and production. To rate-limit requests, keep the count in [Durable State](../guide/durable-state.md) or, on direct Cloudflare deployments, use a [Workers Rate Limiting binding](../guide/type-safety.md#custom-binding-types). ## Utilities diff --git a/packages/void/src/runtime/handler/index.ts b/packages/void/src/runtime/handler/index.ts index 70e9eeb7bf..c0bfc0ea21 100644 --- a/packages/void/src/runtime/handler/index.ts +++ b/packages/void/src/runtime/handler/index.ts @@ -1,4 +1,13 @@ -import type { Context, Env, MiddlewareHandler, Next, TypedResponse } from 'hono'; +import type { + Context, + Env, + HonoRequest, + Input, + MiddlewareHandler, + Next, + TypedResponse, +} from 'hono'; +import type { BlankInput } from 'hono/types'; import type { RedirectStatusCode } from 'hono/utils/http-status'; import type { RewriteDestination, RouteDestination, RouteUrl, RouteUrlInput } from 'void/routes'; import type { HeadConfig } from '../../pages/head.ts'; @@ -105,12 +114,21 @@ declare module 'hono' { } } +// Exists only in types. See CloudContext. +declare const validatedInput: unique symbol; + /** * Hono {@link Context} pre-typed with {@link CloudEnv}. * * This is the type of the `c` parameter in route handlers and middleware * created with {@link defineHandler} and {@link defineMiddleware}. * `redirect` accepts a {@link RouteUrlInput}. + * + * `I` is Hono's input type, as in `Context`. After a validator + * middleware such as `validator()` from `hono/validator`, the handler's `c` + * is a `CloudContext<{ out: { json: ... } }>`, which types `c.req.valid()`. + * A middleware after the validator reads the same data when its `c` has that + * type. */ // `c` must still be assignable to Hono's `Context`, as in `getCookie(c)` and // `etag()`. An interface with its own members is compared member by member, @@ -125,7 +143,16 @@ declare module 'hono' { // `(location: string | URL)` signature callable. // Keep method variance on both overloads so an unchecked Hono context is // assignable back to CloudContext, including in raw Hono middleware. -export interface CloudContext extends Context { +// TypeScript relates the `c.req` of two contexts when either validated input +// is assignable to the other, so a context without a validated target would +// pass for one that has it. `[validatedInput]` compares the validated input +// one way. It is optional, so a Hono `Context` is still assignable. As a mapped +// type, it makes TypeScript compare two CloudContexts with different `I` +// member by member, so only `out` counts: an input with `in` as well, as Hono +// writes it, still matches. +// oxlint-disable-next-line typescript/no-explicit-any -- The path type of `Context`. +export interface CloudContext extends Context { + readonly [validatedInput]?: { [K in keyof I['out']]: I['out'][K] }; redirect( this: never, location: string | URL, @@ -143,10 +170,65 @@ export interface CloudContext extends Context { type HandlerFn = (c: CloudContext) => unknown | Promise; // `R` is the loader's data, so `defineHandler(async (c) => ...)` works. -type LoaderFn = (c: CloudContext) => R | Response | Promise; -// For loaders that LoaderFn cannot infer, such as `cond ? loadA() : loadB()`. -type LoaderOutput = Exclude>, Response>; -type MiddlewareFn = (c: CloudContext, next: Next) => ReturnType>; +type LoaderFn = (c: C) => R | Response | Promise; +type LoaderHandler = TypedHandler, Response>>; +// Middleware that defineHandler() runs before the handler. Its context is the +// plain CloudContext, which keeps `c.redirect()` typed in inline middleware and +// accepts every Hono validator. A validator may return a `TypedResponse`, as +// from `c.text()`. +// As a method, it has its `c` compared in both directions. A middleware typed +// with `CloudContext<{ out: ... }>`, to read what a validator before it +// stored, is accepted: as a function type, the one-way check of CloudContext +// would reject it. +type RouteMiddleware = { + bivariant(c: CloudContext, next: Next): Promise; +}['bivariant']; +// What validators add for `c.req.valid()`, by target, such as +// `{ json: { name: string } }`: the `out` of Hono's input type. +type HonoValidated = NonNullable; +// What a middleware validates, read from the `c.req` of its context: `c.req` +// is the only member of Hono's `Context` that uses the input type. A +// conditional middleware is a union and gives one result per branch. A context +// without an input type, or with `any`, validates nothing. +// A middleware typed with CloudContext only reads validated data. Counting what +// it reads as validated would replace the validator's data with the fields the +// middleware names, and would let a handler read a target that no validator +// checked. +type MiddlewareValidated = M extends (c: infer C, next: Next) => unknown + ? typeof validatedInput extends keyof C + ? HonoValidated + : // oxlint-disable-next-line typescript/no-explicit-any -- Any route path. + C extends { req: HonoRequest } + ? 0 extends 1 & V + ? HonoValidated + : V + : HonoValidated + : HonoValidated; +// Hono keeps one result per target, so a later validator replaces what an +// earlier one stored for the same target. +type Overwrite = A extends unknown + ? B extends unknown + ? { [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never } + : never + : never; +type ChainValidated< + Middleware extends ReadonlyArray, + V = HonoValidated, +> = Middleware extends readonly [infer M, ...infer Rest] + ? ChainValidated>> + : V; +// The handler's context after middleware. +type HandlerContext> = ValidatedContext< + ChainValidated +>; +// `keyof` of a union keeps the targets that every branch validates, each with +// the data of all branches. Without a target, it is the plain CloudContext. +type ValidatedContext = [keyof V] extends [never] + ? CloudContext + : CloudContext<{ out: { [K in keyof V & string]: V extends unknown ? V[K] : never } }>; +// `true` for each branch that validates a target, so a conditional validator +// counts as one. +type ValidatesTarget = V extends unknown ? ([keyof V] extends [never] ? false : true) : never; type BasicAuthOptionValue = string | (() => string); export interface BasicAuthOptions { @@ -228,78 +310,137 @@ export type TypedHandler = * Single argument: identity wrapper. * Multiple arguments: middleware chain + final handler, composed at runtime. */ -export function defineHandler( - handler: LoaderFn, -): TypedHandler, Response>>; +export function defineHandler(handler: LoaderFn): LoaderHandler; +// This overload matches no call, because no handler is `undefined`. It is here +// for a middleware factory called in place, such as `createMiddleware()` or a +// rate limiter with a key function. The overloads below infer each middleware +// as a type parameter, which gives the factory no expected type, so its +// callbacks would lose CloudEnv. Here TypeScript resolves the factory call +// against RouteMiddleware first, and reuses the result in the later overloads. +// Keep this overload before the generic ones: after one of them has deferred a +// factory call, TypeScript defers it here as well. +// The last element is not `never`: `never` fits every constraint, so a wrapper +// around the handler, such as `(handler: T) => T`, would +// infer it for `T` from the type it is expected to return. +export function defineHandler(...args: [...Array, undefined]): never; // Middleware keeps a typed leaf's validators and output (e.g. withValidator). +// Keep this overload before the ones below, which would take the leaf for a +// loader and lose its output type. export function defineHandler( - ...args: [MiddlewareFn, ...Array, TypedHandler] + ...args: [RouteMiddleware, ...Array, TypedHandler] ): TypedHandler; -export function defineHandler( - firstMiddleware: MiddlewareFn, - handler: LoaderFn, -): TypedHandler, Response>>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - handler: F, -): TypedHandler>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - handler: LoaderFn, -): TypedHandler, Response>>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, +// The middleware type parameters come after `R` and have defaults, so +// `defineHandler(middleware, handler)` names only the loader data. Each +// middleware is inferred as a whole, so a conditional one keeps its branches. +// The `F` overloads take loaders that LoaderFn cannot infer, such as +// `cond ? loadA() : loadB()`. +export function defineHandler( + firstMiddleware: M1, + handler: LoaderFn>, +): LoaderHandler; +export function defineHandler< + F extends (c: HandlerContext<[M1]>) => unknown, + M1 extends RouteMiddleware = RouteMiddleware, +>(firstMiddleware: M1, handler: F): LoaderHandler>; +export function defineHandler< + R, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + handler: LoaderFn>, +): LoaderHandler; +export function defineHandler< + F extends (c: HandlerContext<[M1, M2]>) => unknown, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, +>(firstMiddleware: M1, secondMiddleware: M2, handler: F): LoaderHandler>; +export function defineHandler< + R, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, + handler: LoaderFn>, +): LoaderHandler; +export function defineHandler< + F extends (c: HandlerContext<[M1, M2, M3]>) => unknown, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, handler: F, -): TypedHandler>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, - handler: LoaderFn, -): TypedHandler, Response>>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, +): LoaderHandler>; +export function defineHandler< + R, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, + M4 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, + fourthMiddleware: M4, + handler: LoaderFn>, +): LoaderHandler; +export function defineHandler< + F extends (c: HandlerContext<[M1, M2, M3, M4]>) => unknown, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, + M4 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, + fourthMiddleware: M4, handler: F, -): TypedHandler>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, - fourthMiddleware: MiddlewareFn, - handler: LoaderFn, -): TypedHandler, Response>>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, - fourthMiddleware: MiddlewareFn, +): LoaderHandler>; +export function defineHandler< + R, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, + M4 extends RouteMiddleware = RouteMiddleware, + M5 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, + fourthMiddleware: M4, + fifthMiddleware: M5, + handler: LoaderFn>, +): LoaderHandler; +export function defineHandler< + F extends (c: HandlerContext<[M1, M2, M3, M4, M5]>) => unknown, + M1 extends RouteMiddleware = RouteMiddleware, + M2 extends RouteMiddleware = RouteMiddleware, + M3 extends RouteMiddleware = RouteMiddleware, + M4 extends RouteMiddleware = RouteMiddleware, + M5 extends RouteMiddleware = RouteMiddleware, +>( + firstMiddleware: M1, + secondMiddleware: M2, + thirdMiddleware: M3, + fourthMiddleware: M4, + fifthMiddleware: M5, handler: F, -): TypedHandler>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, - fourthMiddleware: MiddlewareFn, - fifthMiddleware: MiddlewareFn, - handler: LoaderFn, -): TypedHandler, Response>>; -export function defineHandler( - firstMiddleware: MiddlewareFn, - secondMiddleware: MiddlewareFn, - thirdMiddleware: MiddlewareFn, - fourthMiddleware: MiddlewareFn, - fifthMiddleware: MiddlewareFn, - handler: F, -): TypedHandler>; -export function defineHandler(...args: Array): TypedHandler { +): LoaderHandler>; +export function defineHandler( + ...args: Array +): TypedHandler { if (args.length === 1) { return args[0] as TypedHandler; } - const middlewares = args.slice(0, -1) as Array; + const middlewares = args.slice(0, -1) as Array; const handler = args.at(-1) as HandlerFn; // Pages read the recorded composition to render inside the same chain. const composed = setHandlerComposition( @@ -351,11 +492,41 @@ export namespace defineHandler { } } +// What a middleware factory called in place is expected to return, as in +// `defineMiddleware(rateLimiter({ keyGenerator: (c) => ... }))`. No middleware +// returns a promise with `unmatchable`, so the overload that takes this type +// matches no middleware. +// The mark is on the returned promise and not on the function. A wrapper such +// as `(middleware: T) => T` infers `T` from the type it +// is expected to return, and TypeScript compares an inline middleware with that +// `T` before it types the parameters: only a plain function type passes. +type ExpectedMiddleware = ( + c: CloudContext, + next: Next, +) => ReturnType & { readonly unmatchable: never }; + /** * Identity function that provides type inference for middleware. * At runtime it simply returns the function passed to it. */ -export function defineMiddleware(handler: MiddlewareFn): MiddlewareHandler { +// As in defineHandler(), TypeScript resolves a factory call against this +// overload first and reuses the result in the next one. The type parameter of +// that overload gives the factory no expected type, so its callbacks would lose +// CloudEnv. An argument that does match, such as one of type `any`, gets the +// type that other middleware get. +export function defineMiddleware(handler: ExpectedMiddleware): MiddlewareHandler; +// A Hono validator keeps what it validates, so defineHandler() still reads it, +// including what it replaces for a target an earlier validator checked. Other +// middleware are typed as `MiddlewareHandler`. The return type names +// `M` only inside MiddlewareValidated, so the type a call is expected to have, +// as in `app.use(defineMiddleware(...))`, does not infer `M`: inline +// middleware would get Hono's context instead of CloudContext. +export function defineMiddleware( + handler: M, +): true extends ValidatesTarget> + ? MiddlewareHandler }> + : MiddlewareHandler; +export function defineMiddleware(handler: RouteMiddleware): RouteMiddleware { return handler; } diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 4eed9faefe..a415696e80 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -27,6 +27,7 @@ afterEach(() => { const typedCheck = `import type { Context } from 'hono'; import { getCookie } from 'hono/cookie'; import { etag } from 'hono/etag'; +import { validator } from 'hono/validator'; import { routeUrl, type Href, type RouteUrl } from 'void/routes'; import { defineConfig } from 'void/config'; import type { VoidRouter } from 'void/pages-client'; @@ -136,6 +137,20 @@ defineMiddleware(async (c) => { const honoContext: Context = context; void [honoContext, getCookie(context, 'session')]; defineHandler(etag(), (c) => c.redirect('/about')); +// Inline middleware and a handler after a validator keep checked redirects. +defineHandler( + async (c, next) => { + // @ts-expect-error unknown routes are rejected + if (!getCookie(c, 'session')) return c.redirect('/unknown'); + await next(); + }, + validator('json', (value: unknown) => ({ name: String(value) })), + (c) => { + void c.req.valid('json').name; + // @ts-expect-error unknown routes are rejected + return c.redirect('/unknown'); + }, +); defineMiddleware(async (c, next) => { if (!getCookie(c, 'session')) return c.redirect('/about'); await next(); diff --git a/packages/void/test/unit/define-handler-middleware.typecheck.ts b/packages/void/test/unit/define-handler-middleware.typecheck.ts new file mode 100644 index 0000000000..1ff124cb11 --- /dev/null +++ b/packages/void/test/unit/define-handler-middleware.typecheck.ts @@ -0,0 +1,280 @@ +import { Hono } from 'hono'; +import type { MiddlewareHandler, Next } from 'hono'; +import { createMiddleware } from 'hono/factory'; +import { validator } from 'hono/validator'; +import { describe, expectTypeOf, it } from 'vite-plus/test'; +import type { RouteUrlInput } from 'void/routes'; +import { z } from 'zod'; +import { basicAuth, defineHandler, defineMiddleware } from '../../src/runtime/handler/index.ts'; +import type { CloudContext, CloudEnv } from '../../src/runtime/handler/index.ts'; + +declare const enabled: boolean; +declare function wrap unknown>(wrapped: T): T; + +const body = z.object({ name: z.string() }); +const json = validator('json', (value, c) => { + const result = body.safeParse(value); + if (!result.success) { + return c.json({ issues: result.error.issues }, 400); + } + return result.data; +}); +const jsonId = validator('json', (value: unknown) => ({ id: Number(value) })); +const query = validator('query', (value) => ({ page: Number(value.page) })); +const sort = validator('query', () => ({ sort: 'asc' as const })); +const passThrough = defineMiddleware(async (_c, next) => { + await next(); +}); + +describe('defineHandler with Hono validator middleware', () => { + it('types c.req.valid() for each validated target', () => { + const handler = defineHandler(passThrough, json, query, (c) => { + expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string }>(); + expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ page: number }>(); + // @ts-expect-error form was not validated + c.req.valid('form'); + // @ts-expect-error name is a string + const count: number = c.req.valid('json').name; + void count; + return { name: c.req.valid('json').name }; + }); + + expectTypeOf(handler.__output).toEqualTypeOf<{ name: string }>(); + }); + + it('accepts a validator that returns a typed response', () => { + const handler = defineHandler( + validator('json', (value: unknown, c) => { + if ( + typeof value !== 'object' || + value === null || + !('name' in value) || + typeof value.name !== 'string' + ) { + return c.text('name is required', 400); + } + return { name: value.name }; + }), + (c) => c.req.valid('json'), + ); + + expectTypeOf(handler.__output).toEqualTypeOf<{ name: string }>(); + }); + + it('reads a validator in the last middleware position and after inline middleware', () => { + const last = defineHandler(passThrough, passThrough, passThrough, passThrough, json, (c) => + c.req.valid('json'), + ); + const afterInline = defineHandler( + async (_c, next) => { + await next(); + }, + json, + (c) => c.req.valid('json'), + ); + + expectTypeOf(last.__output).toEqualTypeOf<{ name: string }>(); + expectTypeOf(afterInline.__output).toEqualTypeOf<{ name: string }>(); + }); + + it('keeps the data of the last validator for a target', () => { + defineHandler(query, sort, (c) => { + expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ sort: 'asc' }>(); + // @ts-expect-error the second validator replaced page + void c.req.valid('query').page; + return null; + }); + defineHandler(json, query, sort, (c) => { + expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string }>(); + return null; + }); + }); + + it('exposes only the targets that every branch of a conditional middleware validates', () => { + defineHandler(enabled ? json : passThrough, (c) => { + // @ts-expect-error json is not validated when the validator is off + return c.req.valid('json'); + }); + defineHandler(enabled ? json : query, (c) => { + // @ts-expect-error each branch validates another target + c.req.valid('json'); + return c.text('OK'); + }); + defineHandler(enabled ? json : jsonId, (c) => { + expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string } | { id: number }>(); + return null; + }); + defineHandler(query, enabled ? sort : passThrough, (c) => { + expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ page: number } | { sort: 'asc' }>(); + return null; + }); + }); + + it('keeps CloudContext without a validator, including in inline middleware', () => { + defineHandler( + async (c, next) => { + expectTypeOf(c).toEqualTypeOf(); + expectTypeOf[0]>().toEqualTypeOf(); + await next(); + }, + basicAuth({ username: 'admin', password: 'secret' }), + (c) => { + expectTypeOf(c).toEqualTypeOf(); + return null; + }, + ); + defineHandler(json, (c) => { + expectTypeOf[0]>().toEqualTypeOf(); + return null; + }); + }); + + it('accepts a handler typed with the validated input only after that validator', () => { + const create = (c: CloudContext<{ out: { json: { name: string } } }>) => ({ + created: c.req.valid('json').name, + }); + + expectTypeOf(defineHandler(json, create).__output).toEqualTypeOf<{ created: string }>(); + expectTypeOf(defineHandler(passThrough, json, query, create).__output).toEqualTypeOf<{ + created: string; + }>(); + // @ts-expect-error json is not validated + defineHandler(passThrough, create); + // @ts-expect-error json is not validated when the validator is off + defineHandler(enabled ? json : passThrough, create); + // @ts-expect-error the json data has no name + defineHandler(jsonId, create); + // A handler typed with the plain CloudContext fits after any middleware. + defineHandler(json, (c: CloudContext) => c.req.path); + }); + + it('compares only the validated output of two contexts', () => { + type Body = { name: string }; + const honoStyle = (c: CloudContext<{ in: { json: Body }; out: { json: Body } }>) => + c.req.valid('json').name; + defineHandler(json, honoStyle); + + const validated = {} as CloudContext<{ out: { json: Body } }>; + const plain: CloudContext = validated; + // @ts-expect-error a plain context has no validated json + const required: CloudContext<{ out: { json: Body } }> = plain; + void required; + }); + + it('lets a middleware typed with the validated input read it after the validator', () => { + type Item = { name: string; price: number }; + const item = validator('json', (value: unknown): Item => ({ name: String(value), price: 3 })); + // A guard names only the fields it reads. + const guard = async (c: CloudContext<{ out: { json: { name: string } } }>, next: Next) => { + expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string }>(); + await next(); + }; + + // The guard adds nothing, so the handler keeps what the validator returned. + defineHandler(item, guard, (c) => { + expectTypeOf(c.req.valid('json')).toEqualTypeOf(); + return null; + }); + defineHandler(passThrough, guard, (c) => { + // @ts-expect-error the guard reads json and does not validate it + return c.req.valid('json'); + }); + expectTypeOf(defineMiddleware(guard)).toEqualTypeOf>(); + }); + + it('keeps what a validator wrapped in defineMiddleware() validates', () => { + const wrappedSort = defineMiddleware(sort); + defineHandler(query, wrappedSort, (c) => { + expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ sort: 'asc' }>(); + // @ts-expect-error the wrapped validator replaced page + void c.req.valid('query').page; + return null; + }); + expectTypeOf( + defineHandler(wrappedSort, (c) => c.req.valid('query').sort).__output, + ).toEqualTypeOf<'asc'>(); + defineHandler(query, defineMiddleware(enabled ? sort : passThrough), (c) => { + expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ page: number } | { sort: 'asc' }>(); + return null; + }); + + const typedResponse = defineMiddleware( + validator('json', (value: unknown, c) => + typeof value === 'string' ? { value } : c.text('a string is required', 400), + ), + ); + expectTypeOf( + defineHandler(typedResponse, (c) => c.req.valid('json').value).__output, + ).toEqualTypeOf(); + }); + + it('types other middleware from defineMiddleware() with CloudContext', () => { + expectTypeOf(passThrough).toEqualTypeOf>(); + new Hono().use( + defineMiddleware(async (c, next) => { + expectTypeOf(c).toEqualTypeOf(); + await next(); + }), + ); + }); + + it('gives a middleware factory called in place CloudEnv for its callback', () => { + defineHandler( + createMiddleware(async (c, next) => { + expectTypeOf(c.env).toEqualTypeOf(); + await next(); + }), + passThrough, + createMiddleware(async (c, next) => { + expectTypeOf(c.env).toEqualTypeOf(); + await next(); + }), + (c) => c.req.path, + ); + defineMiddleware( + createMiddleware(async (c, next) => { + expectTypeOf(c.env).toEqualTypeOf(); + await next(); + }), + ); + }); + + it('keeps the context of a handler inside a generic wrapper', () => { + const handler = defineHandler( + passThrough, + wrap((c) => { + expectTypeOf(c).toEqualTypeOf(); + return { path: c.req.path }; + }), + ); + + expectTypeOf(handler.__output).toEqualTypeOf<{ path: string }>(); + }); + + it('keeps the context of a middleware inside a generic wrapper', () => { + const middleware = defineMiddleware( + wrap(async (c, next) => { + expectTypeOf(c).toEqualTypeOf(); + await next(); + }), + ); + + expectTypeOf(middleware).toEqualTypeOf>(); + }); + + it('keeps the validator types with an annotated return type', () => { + type Created = { name: string }; + const handler = defineHandler(json, (c): Created => c.req.valid('json')); + + expectTypeOf(handler.__output).toEqualTypeOf(); + }); + + it('keeps a typed withValidator leaf after a validator', () => { + const leaf = defineHandler.withValidator({ query: z.object({ q: z.string() }) })( + (_c, { query }) => ({ q: query.q }), + ); + + expectTypeOf(defineHandler(passThrough, json, leaf)).toEqualTypeOf(leaf); + expectTypeOf(defineHandler(enabled ? json : passThrough, leaf)).toEqualTypeOf(leaf); + }); +}); diff --git a/packages/void/test/unit/define-handler.test.ts b/packages/void/test/unit/define-handler.test.ts index 276e03d364..04fdfaaa42 100644 --- a/packages/void/test/unit/define-handler.test.ts +++ b/packages/void/test/unit/define-handler.test.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import type { MiddlewareHandler } from 'hono'; +import { validator } from 'hono/validator'; import { describe, expect, it, vi } from 'vite-plus/test'; import { objectToFormData } from '../../src/pages/navigation-engine.ts'; import { defineHandler, defineMiddleware } from '../../src/runtime/handler/index.ts'; @@ -167,6 +168,60 @@ describe('defineHandler', () => { expect(await res.json()).toEqual({ ok: true }); }); + it('passes data from a Hono validator to the route handler', async () => { + const handler = defineHandler( + validator('json', (value: unknown, c) => { + if ( + typeof value !== 'object' || + value === null || + !('name' in value) || + typeof value.name !== 'string' + ) { + return c.text('name is required', 400); + } + return { name: value.name }; + }), + (c) => ({ greeting: `Hello ${c.req.valid('json').name}` }), + ); + const app = new Hono(); + app.post( + '/test', + createHttpRouteHandler(async () => ({ POST: handler }), 'POST'), + ); + const post = (body: unknown) => + app.request( + req({ + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }), + ); + + const valid = await post({ name: 'Ada' }); + expect(valid.status).toBe(200); + expect(await valid.json()).toEqual({ greeting: 'Hello Ada' }); + + const invalid = await post({ name: 1 }); + expect(invalid.status).toBe(400); + expect(await invalid.text()).toBe('name is required'); + }); + + it('keeps the data of the last validator for a target', async () => { + const handler = defineHandler( + validator('query', () => ({ page: 1 })), + defineMiddleware(validator('query', () => ({ sort: 'asc' }))), + (c) => c.req.valid('query'), + ); + const app = new Hono(); + app.get( + '/test', + createHttpRouteHandler(async () => ({ GET: handler }), 'GET'), + ); + + const res = await app.request(req()); + expect(await res.json()).toEqual({ sort: 'asc' }); + }); + it('middleware error propagates', async () => { const failing = defineMiddleware(async () => { throw new Error('middleware boom'); From 2f987d86f101b3493a3d1b8b242b3bfd2b6d742d Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Fri, 4 Dec 2026 01:24:16 +0900 Subject: [PATCH 2/2] fix(void): simplify validator middleware types in defineHandler The overload that matched no call gave a call in the handler position no expected type: in `defineHandler(auth, traced((c) => ...))`, `c` was `any` or `unknown` instead of CloudContext. - Take each middleware as `M | MiddlewareFn`. A middleware factory called in place keeps CloudEnv for its callbacks without the two overloads that matched no call, and a wrapper around the handler keeps CloudContext. - Add up what the middleware validate, as Hono does. This replaces the rule that the last validator wins for a target, and the separate handling of a middleware that only reads validated data. - Reject a middleware that needs more than CloudContext again. - Keep the names and return types of main where they need no change. - Describe the type argument of `CloudContext` in the API reference. Co-Authored-By: Claude Fable 5.2 --- docs/reference/api/types.md | 2 + packages/void/src/runtime/handler/index.ts | 296 +++++++----------- .../define-handler-middleware.typecheck.ts | 132 ++++---- .../void/test/unit/define-handler.test.ts | 16 - 4 files changed, 175 insertions(+), 271 deletions(-) diff --git a/docs/reference/api/types.md b/docs/reference/api/types.md index e027f85011..d22ec3aea0 100644 --- a/docs/reference/api/types.md +++ b/docs/reference/api/types.md @@ -13,6 +13,8 @@ Hono `Context` pre-typed with [`CloudEnv`](#cloudenv). This is the type of the ` import type { CloudContext } from 'void'; ``` +After [validator middleware](../../integrations/hono.md#third-party-middleware), the handler's `c` is a `CloudContext<{ out: { json: ... } }>`. The type argument is Hono's input type, which types `c.req.valid()`. + ## `CloudEnv` {#cloudenv} Hono environment type for Void workers. Extends Hono's `Env` with Cloudflare bindings and context variables. diff --git a/packages/void/src/runtime/handler/index.ts b/packages/void/src/runtime/handler/index.ts index c0bfc0ea21..4ce85146e4 100644 --- a/packages/void/src/runtime/handler/index.ts +++ b/packages/void/src/runtime/handler/index.ts @@ -114,9 +114,6 @@ declare module 'hono' { } } -// Exists only in types. See CloudContext. -declare const validatedInput: unique symbol; - /** * Hono {@link Context} pre-typed with {@link CloudEnv}. * @@ -127,8 +124,6 @@ declare const validatedInput: unique symbol; * `I` is Hono's input type, as in `Context`. After a validator * middleware such as `validator()` from `hono/validator`, the handler's `c` * is a `CloudContext<{ out: { json: ... } }>`, which types `c.req.valid()`. - * A middleware after the validator reads the same data when its `c` has that - * type. */ // `c` must still be assignable to Hono's `Context`, as in `getCookie(c)` and // `etag()`. An interface with its own members is compared member by member, @@ -143,16 +138,8 @@ declare const validatedInput: unique symbol; // `(location: string | URL)` signature callable. // Keep method variance on both overloads so an unchecked Hono context is // assignable back to CloudContext, including in raw Hono middleware. -// TypeScript relates the `c.req` of two contexts when either validated input -// is assignable to the other, so a context without a validated target would -// pass for one that has it. `[validatedInput]` compares the validated input -// one way. It is optional, so a Hono `Context` is still assignable. As a mapped -// type, it makes TypeScript compare two CloudContexts with different `I` -// member by member, so only `out` counts: an input with `in` as well, as Hono -// writes it, still matches. // oxlint-disable-next-line typescript/no-explicit-any -- The path type of `Context`. export interface CloudContext extends Context { - readonly [validatedInput]?: { [K in keyof I['out']]: I['out'][K] }; redirect( this: never, location: string | URL, @@ -170,65 +157,38 @@ export interface CloudContext extends Context unknown | Promise; // `R` is the loader's data, so `defineHandler(async (c) => ...)` works. +// `C` is the handler's context after middleware. type LoaderFn = (c: C) => R | Response | Promise; -type LoaderHandler = TypedHandler, Response>>; -// Middleware that defineHandler() runs before the handler. Its context is the -// plain CloudContext, which keeps `c.redirect()` typed in inline middleware and -// accepts every Hono validator. A validator may return a `TypedResponse`, as -// from `c.text()`. -// As a method, it has its `c` compared in both directions. A middleware typed -// with `CloudContext<{ out: ... }>`, to read what a validator before it -// stored, is accepted: as a function type, the one-way check of CloudContext -// would reject it. -type RouteMiddleware = { - bivariant(c: CloudContext, next: Next): Promise; -}['bivariant']; -// What validators add for `c.req.valid()`, by target, such as +// For loaders that LoaderFn cannot infer, such as `cond ? loadA() : loadB()`. +type LoaderOutput unknown> = Exclude>, Response>; +// A validator may return a `TypedResponse`, as from `c.text()`. +type MiddlewareFn = (c: CloudContext, next: Next) => Promise; +// What validators store for `c.req.valid()`, by target, such as // `{ json: { name: string } }`: the `out` of Hono's input type. type HonoValidated = NonNullable; -// What a middleware validates, read from the `c.req` of its context: `c.req` -// is the only member of Hono's `Context` that uses the input type. A +// What a middleware validates, read from the `c.req` of its context. A // conditional middleware is a union and gives one result per branch. A context // without an input type, or with `any`, validates nothing. -// A middleware typed with CloudContext only reads validated data. Counting what -// it reads as validated would replace the validator's data with the fields the -// middleware names, and would let a handler read a target that no validator -// checked. type MiddlewareValidated = M extends (c: infer C, next: Next) => unknown - ? typeof validatedInput extends keyof C - ? HonoValidated - : // oxlint-disable-next-line typescript/no-explicit-any -- Any route path. - C extends { req: HonoRequest } - ? 0 extends 1 & V - ? HonoValidated - : V - : HonoValidated + ? // oxlint-disable-next-line typescript/no-explicit-any -- Any route path. + C extends { req: HonoRequest } + ? 0 extends 1 & V + ? HonoValidated + : V + : HonoValidated : HonoValidated; -// Hono keeps one result per target, so a later validator replaces what an -// earlier one stored for the same target. -type Overwrite = A extends unknown - ? B extends unknown - ? { [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never } - : never - : never; -type ChainValidated< +// The handler's context after middleware. What the middleware validate adds +// up, as in Hono's `app.post(path, ...middleware, handler)`. `keyof` of a union +// keeps the targets that every branch of a conditional middleware validates. +// Without a target, it is the plain CloudContext. +type HandlerContext< Middleware extends ReadonlyArray, V = HonoValidated, > = Middleware extends readonly [infer M, ...infer Rest] - ? ChainValidated>> - : V; -// The handler's context after middleware. -type HandlerContext> = ValidatedContext< - ChainValidated ->; -// `keyof` of a union keeps the targets that every branch validates, each with -// the data of all branches. Without a target, it is the plain CloudContext. -type ValidatedContext = [keyof V] extends [never] - ? CloudContext - : CloudContext<{ out: { [K in keyof V & string]: V extends unknown ? V[K] : never } }>; -// `true` for each branch that validates a target, so a conditional validator -// counts as one. -type ValidatesTarget = V extends unknown ? ([keyof V] extends [never] ? false : true) : never; + ? HandlerContext> + : [keyof V] extends [never] + ? CloudContext + : CloudContext<{ out: { [K in keyof V & string]: V[K] } }>; type BasicAuthOptionValue = string | (() => string); export interface BasicAuthOptions { @@ -310,137 +270,131 @@ export type TypedHandler = * Single argument: identity wrapper. * Multiple arguments: middleware chain + final handler, composed at runtime. */ -export function defineHandler(handler: LoaderFn): LoaderHandler; -// This overload matches no call, because no handler is `undefined`. It is here -// for a middleware factory called in place, such as `createMiddleware()` or a -// rate limiter with a key function. The overloads below infer each middleware -// as a type parameter, which gives the factory no expected type, so its -// callbacks would lose CloudEnv. Here TypeScript resolves the factory call -// against RouteMiddleware first, and reuses the result in the later overloads. -// Keep this overload before the generic ones: after one of them has deferred a -// factory call, TypeScript defers it here as well. -// The last element is not `never`: `never` fits every constraint, so a wrapper -// around the handler, such as `(handler: T) => T`, would -// infer it for `T` from the type it is expected to return. -export function defineHandler(...args: [...Array, undefined]): never; +export function defineHandler( + handler: LoaderFn, +): TypedHandler, Response>>; // Middleware keeps a typed leaf's validators and output (e.g. withValidator). // Keep this overload before the ones below, which would take the leaf for a // loader and lose its output type. export function defineHandler( - ...args: [RouteMiddleware, ...Array, TypedHandler] + ...args: [MiddlewareFn, ...Array, TypedHandler] ): TypedHandler; // The middleware type parameters come after `R` and have defaults, so // `defineHandler(middleware, handler)` names only the loader data. Each // middleware is inferred as a whole, so a conditional one keeps its branches. -// The `F` overloads take loaders that LoaderFn cannot infer, such as -// `cond ? loadA() : loadB()`. -export function defineHandler( - firstMiddleware: M1, +// A middleware parameter is `M | MiddlewareFn` and not `M`: a type parameter +// alone gives a middleware factory called in place, such as `createMiddleware()` +// or a rate limiter with a key function, no expected type, so its callbacks +// would lose CloudEnv. +export function defineHandler( + firstMiddleware: M1 | MiddlewareFn, handler: LoaderFn>, -): LoaderHandler; +): TypedHandler, Response>>; export function defineHandler< F extends (c: HandlerContext<[M1]>) => unknown, - M1 extends RouteMiddleware = RouteMiddleware, ->(firstMiddleware: M1, handler: F): LoaderHandler>; + M1 extends MiddlewareFn = MiddlewareFn, +>(firstMiddleware: M1 | MiddlewareFn, handler: F): TypedHandler>; export function defineHandler< R, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, handler: LoaderFn>, -): LoaderHandler; +): TypedHandler, Response>>; export function defineHandler< F extends (c: HandlerContext<[M1, M2]>) => unknown, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, ->(firstMiddleware: M1, secondMiddleware: M2, handler: F): LoaderHandler>; + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, +>( + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + handler: F, +): TypedHandler>; export function defineHandler< R, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, handler: LoaderFn>, -): LoaderHandler; +): TypedHandler, Response>>; export function defineHandler< F extends (c: HandlerContext<[M1, M2, M3]>) => unknown, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, handler: F, -): LoaderHandler>; +): TypedHandler>; export function defineHandler< R, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, - M4 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, + M4 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, - fourthMiddleware: M4, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, + fourthMiddleware: M4 | MiddlewareFn, handler: LoaderFn>, -): LoaderHandler; +): TypedHandler, Response>>; export function defineHandler< F extends (c: HandlerContext<[M1, M2, M3, M4]>) => unknown, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, - M4 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, + M4 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, - fourthMiddleware: M4, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, + fourthMiddleware: M4 | MiddlewareFn, handler: F, -): LoaderHandler>; +): TypedHandler>; export function defineHandler< R, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, - M4 extends RouteMiddleware = RouteMiddleware, - M5 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, + M4 extends MiddlewareFn = MiddlewareFn, + M5 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, - fourthMiddleware: M4, - fifthMiddleware: M5, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, + fourthMiddleware: M4 | MiddlewareFn, + fifthMiddleware: M5 | MiddlewareFn, handler: LoaderFn>, -): LoaderHandler; +): TypedHandler, Response>>; export function defineHandler< F extends (c: HandlerContext<[M1, M2, M3, M4, M5]>) => unknown, - M1 extends RouteMiddleware = RouteMiddleware, - M2 extends RouteMiddleware = RouteMiddleware, - M3 extends RouteMiddleware = RouteMiddleware, - M4 extends RouteMiddleware = RouteMiddleware, - M5 extends RouteMiddleware = RouteMiddleware, + M1 extends MiddlewareFn = MiddlewareFn, + M2 extends MiddlewareFn = MiddlewareFn, + M3 extends MiddlewareFn = MiddlewareFn, + M4 extends MiddlewareFn = MiddlewareFn, + M5 extends MiddlewareFn = MiddlewareFn, >( - firstMiddleware: M1, - secondMiddleware: M2, - thirdMiddleware: M3, - fourthMiddleware: M4, - fifthMiddleware: M5, + firstMiddleware: M1 | MiddlewareFn, + secondMiddleware: M2 | MiddlewareFn, + thirdMiddleware: M3 | MiddlewareFn, + fourthMiddleware: M4 | MiddlewareFn, + fifthMiddleware: M5 | MiddlewareFn, handler: F, -): LoaderHandler>; -export function defineHandler( - ...args: Array -): TypedHandler { +): TypedHandler>; +export function defineHandler(...args: Array): TypedHandler { if (args.length === 1) { return args[0] as TypedHandler; } - const middlewares = args.slice(0, -1) as Array; + const middlewares = args.slice(0, -1) as Array; const handler = args.at(-1) as HandlerFn; // Pages read the recorded composition to render inside the same chain. const composed = setHandlerComposition( @@ -492,41 +446,23 @@ export namespace defineHandler { } } -// What a middleware factory called in place is expected to return, as in -// `defineMiddleware(rateLimiter({ keyGenerator: (c) => ... }))`. No middleware -// returns a promise with `unmatchable`, so the overload that takes this type -// matches no middleware. -// The mark is on the returned promise and not on the function. A wrapper such -// as `(middleware: T) => T` infers `T` from the type it -// is expected to return, and TypeScript compares an inline middleware with that -// `T` before it types the parameters: only a plain function type passes. -type ExpectedMiddleware = ( - c: CloudContext, - next: Next, -) => ReturnType & { readonly unmatchable: never }; - /** * Identity function that provides type inference for middleware. * At runtime it simply returns the function passed to it. */ -// As in defineHandler(), TypeScript resolves a factory call against this -// overload first and reuses the result in the next one. The type parameter of -// that overload gives the factory no expected type, so its callbacks would lose -// CloudEnv. An argument that does match, such as one of type `any`, gets the -// type that other middleware get. -export function defineMiddleware(handler: ExpectedMiddleware): MiddlewareHandler; -// A Hono validator keeps what it validates, so defineHandler() still reads it, -// including what it replaces for a target an earlier validator checked. Other -// middleware are typed as `MiddlewareHandler`. The return type names -// `M` only inside MiddlewareValidated, so the type a call is expected to have, -// as in `app.use(defineMiddleware(...))`, does not infer `M`: inline -// middleware would get Hono's context instead of CloudContext. -export function defineMiddleware( - handler: M, -): true extends ValidatesTarget> - ? MiddlewareHandler }> - : MiddlewareHandler; -export function defineMiddleware(handler: RouteMiddleware): RouteMiddleware { +// A Hono validator keeps what it validates, so defineHandler() still types +// `c.req.valid()` after it. Other middleware are typed as +// `MiddlewareHandler`. The return type names `M` only inside +// MiddlewareValidated, so the type a call is expected to have, as in +// `app.use(defineMiddleware(...))`, does not infer `M`: inline middleware would +// get Hono's context instead of CloudContext. The parameter is +// `M | MiddlewareFn` for the same reason as in defineHandler(). +export function defineMiddleware( + handler: M | MiddlewareFn, +): [keyof MiddlewareValidated] extends [never] + ? MiddlewareHandler + : MiddlewareHandler }>; +export function defineMiddleware(handler: MiddlewareFn): MiddlewareFn { return handler; } diff --git a/packages/void/test/unit/define-handler-middleware.typecheck.ts b/packages/void/test/unit/define-handler-middleware.typecheck.ts index 1ff124cb11..6f220ebb26 100644 --- a/packages/void/test/unit/define-handler-middleware.typecheck.ts +++ b/packages/void/test/unit/define-handler-middleware.typecheck.ts @@ -10,6 +10,9 @@ import type { CloudContext, CloudEnv } from '../../src/runtime/handler/index.ts' declare const enabled: boolean; declare function wrap unknown>(wrapped: T): T; +declare function wrapParameter(wrapped: (c: C) => R): (c: C) => R; +// oxlint-disable-next-line typescript/no-explicit-any -- A common shape of function wrappers. +declare function wrapAny) => any>(wrapped: T): T; const body = z.object({ name: z.string() }); const json = validator('json', (value, c) => { @@ -21,7 +24,6 @@ const json = validator('json', (value, c) => { }); const jsonId = validator('json', (value: unknown) => ({ id: Number(value) })); const query = validator('query', (value) => ({ page: Number(value.page) })); -const sort = validator('query', () => ({ sort: 'asc' as const })); const passThrough = defineMiddleware(async (_c, next) => { await next(); }); @@ -77,15 +79,21 @@ describe('defineHandler with Hono validator middleware', () => { expectTypeOf(afterInline.__output).toEqualTypeOf<{ name: string }>(); }); - it('keeps the data of the last validator for a target', () => { - defineHandler(query, sort, (c) => { - expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ sort: 'asc' }>(); - // @ts-expect-error the second validator replaced page - void c.req.valid('query').page; - return null; - }); - defineHandler(json, query, sort, (c) => { - expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string }>(); + it('adds up what the middleware validate, as Hono does', () => { + type Item = { name: string; price: number }; + const item = validator('json', (value: unknown): Item => ({ name: String(value), price: 3 })); + // A guard that reads validated data names only the field it needs. + const guard = createMiddleware( + async (c, next) => { + if (c.req.valid('json').name === 'blocked') { + return c.text('Forbidden', 403); + } + await next(); + }, + ); + + defineHandler(item, guard, (c) => { + expectTypeOf(c.req.valid('json').price).toEqualTypeOf(); return null; }); }); @@ -104,10 +112,6 @@ describe('defineHandler with Hono validator middleware', () => { expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string } | { id: number }>(); return null; }); - defineHandler(query, enabled ? sort : passThrough, (c) => { - expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ page: number } | { sort: 'asc' }>(); - return null; - }); }); it('keeps CloudContext without a validator, including in inline middleware', () => { @@ -129,7 +133,18 @@ describe('defineHandler with Hono validator middleware', () => { }); }); - it('accepts a handler typed with the validated input only after that validator', () => { + it('reads no target from a middleware whose input type is any', () => { + // oxlint-disable-next-line typescript/no-explicit-any -- A loosely typed middleware. + const loose = passThrough as MiddlewareHandler; + + defineHandler(loose, (c) => { + // @ts-expect-error json was not validated + c.req.valid('json'); + return null; + }); + }); + + it('accepts a handler typed with the validated input', () => { const create = (c: CloudContext<{ out: { json: { name: string } } }>) => ({ created: c.req.valid('json').name, }); @@ -138,74 +153,21 @@ describe('defineHandler with Hono validator middleware', () => { expectTypeOf(defineHandler(passThrough, json, query, create).__output).toEqualTypeOf<{ created: string; }>(); - // @ts-expect-error json is not validated - defineHandler(passThrough, create); - // @ts-expect-error json is not validated when the validator is off - defineHandler(enabled ? json : passThrough, create); // @ts-expect-error the json data has no name defineHandler(jsonId, create); // A handler typed with the plain CloudContext fits after any middleware. defineHandler(json, (c: CloudContext) => c.req.path); }); - it('compares only the validated output of two contexts', () => { - type Body = { name: string }; - const honoStyle = (c: CloudContext<{ in: { json: Body }; out: { json: Body } }>) => - c.req.valid('json').name; - defineHandler(json, honoStyle); - - const validated = {} as CloudContext<{ out: { json: Body } }>; - const plain: CloudContext = validated; - // @ts-expect-error a plain context has no validated json - const required: CloudContext<{ out: { json: Body } }> = plain; - void required; - }); - - it('lets a middleware typed with the validated input read it after the validator', () => { - type Item = { name: string; price: number }; - const item = validator('json', (value: unknown): Item => ({ name: String(value), price: 3 })); - // A guard names only the fields it reads. - const guard = async (c: CloudContext<{ out: { json: { name: string } } }>, next: Next) => { - expectTypeOf(c.req.valid('json')).toEqualTypeOf<{ name: string }>(); - await next(); - }; - - // The guard adds nothing, so the handler keeps what the validator returned. - defineHandler(item, guard, (c) => { - expectTypeOf(c.req.valid('json')).toEqualTypeOf(); - return null; - }); - defineHandler(passThrough, guard, (c) => { - // @ts-expect-error the guard reads json and does not validate it - return c.req.valid('json'); - }); - expectTypeOf(defineMiddleware(guard)).toEqualTypeOf>(); - }); - it('keeps what a validator wrapped in defineMiddleware() validates', () => { - const wrappedSort = defineMiddleware(sort); - defineHandler(query, wrappedSort, (c) => { - expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ sort: 'asc' }>(); - // @ts-expect-error the wrapped validator replaced page - void c.req.valid('query').page; - return null; - }); - expectTypeOf( - defineHandler(wrappedSort, (c) => c.req.valid('query').sort).__output, - ).toEqualTypeOf<'asc'>(); - defineHandler(query, defineMiddleware(enabled ? sort : passThrough), (c) => { - expectTypeOf(c.req.valid('query')).toEqualTypeOf<{ page: number } | { sort: 'asc' }>(); - return null; - }); - - const typedResponse = defineMiddleware( - validator('json', (value: unknown, c) => - typeof value === 'string' ? { value } : c.text('a string is required', 400), - ), + const handler = defineHandler( + passThrough, + defineMiddleware(json), + defineMiddleware(query), + (c) => ({ name: c.req.valid('json').name, page: c.req.valid('query').page }), ); - expectTypeOf( - defineHandler(typedResponse, (c) => c.req.valid('json').value).__output, - ).toEqualTypeOf(); + + expectTypeOf(handler.__output).toEqualTypeOf<{ name: string; page: number }>(); }); it('types other middleware from defineMiddleware() with CloudContext', () => { @@ -251,6 +213,26 @@ describe('defineHandler with Hono validator middleware', () => { expectTypeOf(handler.__output).toEqualTypeOf<{ path: string }>(); }); + it('keeps the context of a handler inside a wrapper that does not name CloudContext', () => { + const byParameter = defineHandler( + passThrough, + wrapParameter((c) => { + expectTypeOf(c).toEqualTypeOf(); + return { path: c.req.path }; + }), + ); + const byFunction = defineHandler( + passThrough, + wrapAny((c) => { + expectTypeOf(c).toEqualTypeOf(); + return { path: c.req.path }; + }), + ); + + expectTypeOf(byParameter.__output).toEqualTypeOf<{ path: string }>(); + expectTypeOf(byFunction.__output).toEqualTypeOf<{ path: string }>(); + }); + it('keeps the context of a middleware inside a generic wrapper', () => { const middleware = defineMiddleware( wrap(async (c, next) => { diff --git a/packages/void/test/unit/define-handler.test.ts b/packages/void/test/unit/define-handler.test.ts index 04fdfaaa42..d3720adf8f 100644 --- a/packages/void/test/unit/define-handler.test.ts +++ b/packages/void/test/unit/define-handler.test.ts @@ -206,22 +206,6 @@ describe('defineHandler', () => { expect(await invalid.text()).toBe('name is required'); }); - it('keeps the data of the last validator for a target', async () => { - const handler = defineHandler( - validator('query', () => ({ page: 1 })), - defineMiddleware(validator('query', () => ({ sort: 'asc' }))), - (c) => c.req.valid('query'), - ); - const app = new Hono(); - app.get( - '/test', - createHttpRouteHandler(async () => ({ GET: handler }), 'GET'), - ); - - const res = await app.request(req()); - expect(await res.json()).toEqual({ sort: 'asc' }); - }); - it('middleware error propagates', async () => { const failing = defineMiddleware(async () => { throw new Error('middleware boom');