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 fileTake 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 back1import 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 back4import 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 back5import 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 back7import type { InferInput } from './utils'chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 8–17why, one step back89type 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 back18 P extends string = string,chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 19–21why, one step back19> = (20 value: InputType,21 c: Context<E, P>Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 22why, one step back22) => OutputType | TypedResponse | Promise<OutputType> | Promise<TypedResponse>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 23–27why, one step back2324const 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\-]+\=([^;]+))*$/27Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
lines 28–32why, one step back28export type ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R29 ? R extends Promise<infer PR>30 ? PR extends TypedResponse<infer T, infer S, infer F>31 ? TypedResponse<T, S, F>32 : PR extends Responsechore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 33–36why, one step back33 ? PR34 : PR extends undefined35 ? never // undefined → never36 : never // anything else → neverMerge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 37why, one step back37 : R extends TypedResponse<infer T, infer S, infer F>chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 38–43why, one step back38 ? TypedResponse<T, S, F>39 : R extends Response40 ? R41 : R extends undefined42 ? never // undefined → never43 : never // anything else → neverMerge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
lines 44–45why, one step back44 : never // Can't extract → never45chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 46–51why, one step back46export 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 back52 // Capture the actual validation function as a type53 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 back64 V extends {65 in: {66 [K in U]: K extends 'json'67 ? unknown extends InputTypeMerge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 68why, one step back68 ? ExtractValidatorOutput<VF>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
line 69why, one step back69 : InputTypefix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03
line 70why, one step back70 : InferInput<ExtractValidatorOutput<VF>, K, FormValue>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
line 71why, one step back71 }Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 72why, one step back72 out: { [K in U]: ExtractValidatorOutput<VF> }chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 73–76why, one step back73 } = {74 in: {75 [K in U]: K extends 'json'76 ? unknown extends InputTypeMerge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 77why, one step back77 ? ExtractValidatorOutput<VF>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
line 78why, one step back78 : InputTypefix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03
line 79why, one step back79 : InferInput<ExtractValidatorOutput<VF>, K, FormValue>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
line 80why, one step back80 }Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 81why, one step back81 out: { [K in U]: ExtractValidatorOutput<VF> }chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 82–83why, one step back82 },83 // eslint-disable-next-line @typescript-eslint/no-explicit-anychore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
line 84why, one step back84 E extends Env = any,chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 85–86why, one step back85>(86 target: U,Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
lines 87–88why, one step back87 validationFunc: VF88): MiddlewareHandler<E, P, V, ExtractValidationResponse<VF>> => {chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 89–128why, one step back89 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 }128fix(validator): prevent type diff bug in form data parsing (#4753)EdamAmexbefore adoption4bb70fa
line 129why, one step back129 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 back130 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 back135 } else if (Object.hasOwn(form, key)) {chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 136–164why, one step back136 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 back165 return res as ExtractValidationResponse<VF>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 166–169why, one step back166 }167168 c.req.addValidatedData(target, res as never)169Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 170why, one step back170 return (await next()) as ExtractValidationResponse<VF>chore(ci): upgrade bun version to 1.2.19 (#4323)Jonathan Hainesbefore adoption1e10493
lines 171–172why, one step back171 }172}Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
lines 173–181why, one step back173174// 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-anychore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 182–184why, one step back182 R extends Response | TypedResponse<any, any, any>183 ? never184 : RMerge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
line 185why, one step back185 : never