Skip to content
Myr

validator.ts

This file

Path

src/validator/validator.ts

185 lines · 6.0 KiB · TypeScript

Last changed by

fix(validator): prevent type diff bug in form data parsing (#4753)EdamAmexbefore adoption4bb70fa

History of this file

Take it

The walk stopped after 200 commits: lines older than 1e10493 point at it.

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 1–3why, one step back
1import type { Context } from '../context'
2import { getCookie } from '../helper/cookie'3import { HTTPException } from '../http-exception'

fix(validator): fix incomplete types and wrong tests (#4521)EdamAmexbefore adoptiona5f3958

line 4why, one step back
4import type { Env, MiddlewareHandler, TypedResponse, ValidationTargets, FormValue } from '../types'

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 5–6why, one step back
5import type { BodyData } from '../utils/body'
6import { bufferToFormData } from '../utils/buffer'

fix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03

line 7why, one step back
7import type { InferInput } from './utils'

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 8–17why, one step back
8
9type ValidationTargetKeysWithBody = 'form' | 'json'10type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.11 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>12 : keyof ValidationTargets1314export type ValidationFunction<15 InputType,16 OutputType,17 E extends Env = {},

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

line 18why, one step back
18 P extends string = string,

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 19–21why, one step back
19> = (
20 value: InputType,21 c: Context<E, P>

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 22why, one step back
22) => OutputType | TypedResponse | Promise<OutputType> | Promise<TypedResponse>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 23–27why, one step back
23
24const jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/25const multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/26const urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/27

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

lines 28–32why, one step back
28export type ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R
29 ? R extends Promise<infer PR>30 ? PR extends TypedResponse<infer T, infer S, infer F>31 ? TypedResponse<T, S, F>32 : PR extends Response

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

lines 33–36why, one step back
33 ? PR
34 : PR extends undefined35 ? never // undefined → never36 : never // anything else → never

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 37why, one step back
37 : R extends TypedResponse<infer T, infer S, infer F>

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

lines 38–43why, one step back
38 ? TypedResponse<T, S, F>
39 : R extends Response40 ? R41 : R extends undefined42 ? never // undefined → never43 : never // anything else → never

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

lines 44–45why, one step back
44 : never // Can't extract → never
45

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 46–51why, one step back
46export const validator = <
47 InputType,48 P extends string,49 M extends string,50 U extends ValidationTargetByMethod<M>,51 P2 extends string = P,

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

lines 52–63why, one step back
52 // Capture the actual validation function as a type
53 VF extends (54 value: unknown extends InputType ? ValidationTargets[U] : InputType,55 // eslint-disable-next-line @typescript-eslint/no-explicit-any56 c: Context<any, P2>57 // eslint-disable-next-line @typescript-eslint/no-explicit-any58 ) => any = (59 value: unknown extends InputType ? ValidationTargets[U] : InputType,60 // eslint-disable-next-line @typescript-eslint/no-explicit-any61 c: Context<any, P2>62 // eslint-disable-next-line @typescript-eslint/no-explicit-any63 ) => any,

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 64–67why, one step back
64 V extends {
65 in: {66 [K in U]: K extends 'json'67 ? unknown extends InputType

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 68why, one step back
68 ? ExtractValidatorOutput<VF>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

line 69why, one step back
69 : InputType

fix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03

line 70why, one step back
70 : InferInput<ExtractValidatorOutput<VF>, K, FormValue>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

line 71why, one step back
71 }

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 72why, one step back
72 out: { [K in U]: ExtractValidatorOutput<VF> }

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 73–76why, one step back
73 } = {
74 in: {75 [K in U]: K extends 'json'76 ? unknown extends InputType

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 77why, one step back
77 ? ExtractValidatorOutput<VF>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

line 78why, one step back
78 : InputType

fix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03

line 79why, one step back
79 : InferInput<ExtractValidatorOutput<VF>, K, FormValue>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

line 80why, one step back
80 }

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 81why, one step back
81 out: { [K in U]: ExtractValidatorOutput<VF> }

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 82–83why, one step back
82 },
83 // eslint-disable-next-line @typescript-eslint/no-explicit-any

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

line 84why, one step back
84 E extends Env = any,

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 85–86why, one step back
85>(
86 target: U,

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

lines 87–88why, one step back
87 validationFunc: VF
88): MiddlewareHandler<E, P, V, ExtractValidationResponse<VF>> => {

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 89–128why, one step back
89 return async (c, next) => {
90 let value = {}91 const contentType = c.req.header('Content-Type')9293 switch (target) {94 case 'json':95 if (!contentType || !jsonRegex.test(contentType)) {96 break97 }98 try {99 value = await c.req.json()100 } catch {101 const message = 'Malformed JSON in request body'102 throw new HTTPException(400, { message })103 }104 break105 case 'form': {106 if (107 !contentType ||108 !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))109 ) {110 break111 }112113 let formData: FormData114115 if (c.req.bodyCache.formData) {116 formData = await c.req.bodyCache.formData117 } else {118 try {119 const arrayBuffer = await c.req.arrayBuffer()120 formData = await bufferToFormData(arrayBuffer, contentType)121 c.req.bodyCache.formData = formData122 } catch (e) {123 let message = 'Malformed FormData request.'124 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`125 throw new HTTPException(400, { message })126 }127 }128

fix(validator): prevent type diff bug in form data parsing (#4753)EdamAmexbefore adoption4bb70fa

line 129why, one step back
129 const form: BodyData<{ all: true }> = Object.create(null)

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 130–134why, one step back
130 formData.forEach((value, key) => {
131 if (key.endsWith('[]')) {132 ;((form[key] ??= []) as unknown[]).push(value)133 } else if (Array.isArray(form[key])) {134 ;(form[key] as unknown[]).push(value)

fix(validator): prevent type diff bug in form data parsing (#4753)EdamAmexbefore adoption4bb70fa

line 135why, one step back
135 } else if (Object.hasOwn(form, key)) {

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 136–164why, one step back
136 form[key] = [form[key] as string | File, value]
137 } else {138 form[key] = value139 }140 })141 value = form142 break143 }144 case 'query':145 value = Object.fromEntries(146 Object.entries(c.req.queries()).map(([k, v]) => {147 return v.length === 1 ? [k, v[0]] : [k, v]148 })149 )150 break151 case 'param':152 value = c.req.param() as Record<string, string>153 break154 case 'header':155 value = c.req.header()156 break157 case 'cookie':158 value = getCookie(c)159 break160 }161162 const res = await validationFunc(value as never, c as never)163164 if (res instanceof Response) {

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 165why, one step back
165 return res as ExtractValidationResponse<VF>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 166–169why, one step back
166 }
167168 c.req.addValidatedData(target, res as never)169

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 170why, one step back
170 return (await next()) as ExtractValidationResponse<VF>

chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493

lines 171–172why, one step back
171 }
172}

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

lines 173–181why, one step back
173
174// eslint-disable-next-line @typescript-eslint/no-explicit-any175export type ExtractValidatorOutput<VF> = VF extends (value: any, c: any) => infer R176 ? R extends Promise<infer PR>177 ? // eslint-disable-next-line @typescript-eslint/no-explicit-any178 PR extends Response | TypedResponse<any, any, any>179 ? never180 : PR181 : // eslint-disable-next-line @typescript-eslint/no-explicit-any

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

lines 182–184why, one step back
182 R extends Response | TypedResponse<any, any, any>
183 ? never184 : R

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

line 185why, one step back
185 : never