types.ts
This file
Path
src/client/types.ts
393 lines · 12.2 KiB · TypeScript
Last changed by
feat(client): add `PickResponseByStatusCode` type (#4791)Yusuke Wadabefore adoptiond1722e3
History of this fileTake it
The walk stopped after 200 commits: lines older than 793ffda point at it.
chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 1–2why, one step back1import type { Hono } from '../hono'2import type { HonoBase } from '../hono-base'fix(client): exclude $all from ClientRequest type (#4611)Ryota Ikezawabefore adoption5d4e6aa
line 3why, one step back3import type { METHODS, METHOD_NAME_ALL_LOWERCASE } from '../router'fix(client): preserve route schema in ApplyGlobalResponse (#4777)Oguma Shunyabefore adoption0768232
line 4why, one step back4import type { Endpoint, ExtractSchema, KnownResponseFormat, ResponseFormat, Schema } from '../types'chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 5–7why, one step back5import type { StatusCode, SuccessStatusCode } from '../utils/http-status'6import type { HasRequiredKeys } from '../utils/types'7fix(client): exclude $all from ClientRequest type (#4611)Ryota Ikezawabefore adoption5d4e6aa
lines 8–27why, one step back8/**9 * Type representing the '$all' method name10 */11type MethodNameAll = `$${typeof METHOD_NAME_ALL_LOWERCASE}`1213/**14 * Type representing all standard HTTP methods prefixed with '$'15 * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch'16 */17type StandardMethods = `$${(typeof METHODS)[number]}`1819/**20 * Expands '$all' into all standard HTTP methods.21 * If the schema contains '$all', it creates a type where all standard HTTP methods22 * point to the same endpoint definition as '$all', while removing '$all' itself.23 */24type ExpandAllMethod<S> = MethodNameAll extends keyof S25 ? { [M in StandardMethods]: S[MethodNameAll] } & Omit<S, MethodNameAll>26 : S27chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 28–29why, one step back28type HonoRequest = (typeof Hono.prototype)['request']29Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 30–31why, one step back30export type BuildSearchParamsFn = (query: Record<string, string | string[]>) => URLSearchParams31chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 32–41why, one step back32export type ClientRequestOptions<T = unknown> = {33 fetch?: typeof fetch | HonoRequest34 webSocket?: (...args: ConstructorParameters<typeof WebSocket>) => WebSocket35 /**36 * Standard `RequestInit`, caution that this take highest priority37 * and could be used to overwrite things that Hono sets for you, like `body | method | headers`.38 *39 * If you want to add some headers, use in `headers` instead of `init`40 */41 init?: RequestInitMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 42–56why, one step back42 /**43 * Custom function to serialize query parameters into URLSearchParams.44 * By default, arrays are serialized as multiple parameters with the same key (e.g., `key=a&key=b`).45 * You can provide a custom function to change this behavior, for example to use bracket notation (e.g., `key[]=a&key[]=b`).46 *47 * @example48 * ```ts49 * const client = hc('http://localhost', {50 * buildSearchParams: (query) => {51 * return new URLSearchParams(qs.stringify(query))52 * }53 * })54 * ```55 */56 buildSearchParams?: BuildSearchParamsFnchore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 57–66why, one step back57} & (keyof T extends never58 ? {59 headers?:60 | Record<string, string>61 | (() => Record<string, string> | Promise<Record<string, string>>)62 }63 : {64 headers: T | (() => T | Promise<T>)65 })66Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 67why, one step back67export type ClientRequest<Prefix extends string, Path extends string, S extends Schema> = {fix(client): exclude $all from ClientRequest type (#4611)Ryota Ikezawabefore adoption5d4e6aa
line 68why, one step back68 [M in keyof ExpandAllMethod<S>]: ExpandAllMethod<S>[M] extends Endpoint & { input: infer R }chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 69–70why, one step back69 ? R extends object70 ? HasRequiredKeys<R> extends truefix(client): exclude $all from ClientRequest type (#4611)Ryota Ikezawabefore adoption5d4e6aa
lines 71–78why, one step back71 ? (72 args: R,73 options?: ClientRequestOptions74 ) => Promise<ClientResponseOfEndpoint<ExpandAllMethod<S>[M]>>75 : (76 args?: R,77 options?: ClientRequestOptions78 ) => Promise<ClientResponseOfEndpoint<ExpandAllMethod<S>[M]>>chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 79–81why, one step back79 : never80 : never81} & {Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 82–96why, one step back82 $url: <83 const Arg extends84 | (S[keyof S] extends { input: infer R }85 ? R extends { param: infer P }86 ? R extends { query: infer Q }87 ? { param: P; query: Q }88 : { param: P }89 : R extends { query: infer Q }90 ? { query: Q }91 : {}92 : {})93 | undefined = undefined,94 >(95 arg?: Arg96 ) => HonoURL<Prefix, Path, Arg>Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 97–111why, one step back97 $path: <98 const Arg extends99 | (S[keyof S] extends { input: infer R }100 ? R extends { param: infer P }101 ? R extends { query: infer Q }102 ? { param: P; query: Q }103 : { param: P }104 : R extends { query: infer Q }105 ? { query: Q }106 : {}107 : {})108 | undefined = undefined,109 >(110 arg?: Arg111 ) => BuildPath<Path, Arg>chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 112–130why, one step back112} & (S['$get'] extends { outputFormat: 'ws' }113 ? S['$get'] extends { input: infer I }114 ? {115 $ws: (args?: I) => WebSocket116 }117 : {}118 : {})119120type ClientResponseOfEndpoint<T extends Endpoint = Endpoint> = T extends {121 output: infer O122 outputFormat: infer F123 status: infer S124}125 ? ClientResponse<O, S extends number ? S : never, F extends ResponseFormat ? F : never>126 : never127128export interface ClientResponse<129 T,130 U extends number = StatusCode,chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
line 131why, one step back131 F extends ResponseFormat = ResponseFormat,fix(types): remove DOM type dependencies from ClientResponse and request method (#4768)YevheniiKotyrlobefore adoptioneb9c112
line 132why, one step back132> {chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 133–137why, one step back133 readonly body: ReadableStream | null134 readonly bodyUsed: boolean135 ok: U extends SuccessStatusCode136 ? true137 : U extends Exclude<StatusCode, SuccessStatusCode>chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 138–139why, one step back138 ? false139 : booleanfix(types): remove DOM type dependencies from ClientResponse and request method (#4768)YevheniiKotyrlobefore adoptioneb9c112
line 140why, one step back140 redirected: booleanchore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 141–142why, one step back141 status: U142 statusText: stringfix(types): remove DOM type dependencies from ClientResponse and request method (#4768)YevheniiKotyrlobefore adoptioneb9c112
line 143why, one step back143 type: 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 144–147why, one step back144 headers: Headers145 url: string146 redirect(url: string, status: number): Response147 clone(): Responsefix(types): remove DOM type dependencies from ClientResponse and request method (#4768)YevheniiKotyrlobefore adoptioneb9c112
line 148why, one step back148 bytes(): Promise<Uint8Array<ArrayBuffer>>chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 149–155why, one step back149 json(): F extends 'text' ? Promise<never> : F extends 'json' ? Promise<T> : Promise<unknown>150 text(): F extends 'text' ? (T extends string ? Promise<T> : Promise<never>) : Promise<string>151 blob(): Promise<Blob>152 formData(): Promise<FormData>153 arrayBuffer(): Promise<ArrayBuffer>154}155refactor(client): refactor `HonoURL` types (#4592)Yusuke Wadabefore adoption41ee1bb
lines 156–165why, one step back156type BuildSearch<Arg, Key extends 'query'> = Arg extends { [K in Key]: infer Query }157 ? IsEmptyObject<Query> extends true158 ? ''159 : `?${string}`160 : ''161162type BuildPathname<P extends string, Arg> = Arg extends { param: infer Param }163 ? `${ApplyParam<TrimStartSlash<P>, Param>}`164 : `/${TrimStartSlash<P>}`165Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 166–167why, one step back166type BuildPath<P extends string, Arg> = `${BuildPathname<P, Arg>}${BuildSearch<Arg, 'query'>}`167refactor(client): refactor `HonoURL` types (#4592)Yusuke Wadabefore adoption41ee1bb
lines 168–175why, one step back168type BuildTypedURL<169 Protocol extends string,170 Host extends string,171 Port extends string,172 P extends string,173 Arg,174> = TypedURL<`${Protocol}:`, Host, Port, BuildPathname<P, Arg>, BuildSearch<Arg, 'query'>>175Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 176–180why, one step back176type HonoURL<Prefix extends string, Path extends string, Arg> =177 IsLiteral<Prefix> extends true178 ? TrimEndSlash<Prefix> extends `${infer Protocol}://${infer Rest}`179 ? Rest extends `${infer Hostname}/${infer P}`180 ? ParseHostName<Hostname> extends [infer Host extends string, infer Port extends string]refactor(client): refactor `HonoURL` types (#4592)Yusuke Wadabefore adoption41ee1bb
line 181why, one step back181 ? BuildTypedURL<Protocol, Host, Port, P, Arg>Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 182–183why, one step back182 : never183 : ParseHostName<Rest> extends [infer Host extends string, infer Port extends string]refactor(client): refactor `HonoURL` types (#4592)Yusuke Wadabefore adoption41ee1bb
line 184why, one step back184 ? BuildTypedURL<Protocol, Host, Port, Path, Arg>Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 185–231why, one step back185 : never186 : URL187 : URL188type ParseHostName<T extends string> = T extends `${infer Host}:${infer Port}`189 ? [Host, Port]190 : [T, '']191type TrimStartSlash<T extends string> = T extends `/${infer R}` ? TrimStartSlash<R> : T192type TrimEndSlash<T extends string> = T extends `${infer R}/` ? TrimEndSlash<R> : T193type IsLiteral<T extends string> = [T] extends [never] ? false : string extends T ? false : true194type ApplyParam<195 Path extends string,196 P,197 Result extends string = '',198> = Path extends `${infer Head}/${infer Rest}`199 ? Head extends `:${infer Param}`200 ? P extends Record<Param, infer Value extends string>201 ? IsLiteral<Value> extends true202 ? ApplyParam<Rest, P, `${Result}/${Value & string}`>203 : ApplyParam<Rest, P, `${Result}/${Head}`>204 : ApplyParam<Rest, P, `${Result}/${Head}`>205 : ApplyParam<Rest, P, `${Result}/${Head}`>206 : Path extends `:${infer Param}`207 ? P extends Record<Param, infer Value extends string>208 ? IsLiteral<Value> extends true209 ? `${Result}/${Value & string}`210 : `${Result}/${Path}`211 : `${Result}/${Path}`212 : `${Result}/${Path}`213type IsEmptyObject<T> = keyof T extends never ? true : false214215export interface TypedURL<216 Protocol extends string,217 Hostname extends string,218 Port extends string,219 Pathname extends string,220 Search extends string,221> extends URL {222 protocol: Protocol223 hostname: Hostname224 port: Port225 host: Port extends '' ? Hostname : `${Hostname}:${Port}`226 origin: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}`227 pathname: Pathname228 search: Search229 href: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}${Pathname}${Search}`230}231chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 232–280why, one step back232export interface Response extends ClientResponse<unknown> {}233234export type Fetch<T> = (235 args?: InferRequestType<T>,236 opt?: ClientRequestOptions237) => Promise<ClientResponseOfEndpoint<InferEndpointType<T>>>238239type InferEndpointType<T> = T extends (240 args: infer R,241 // eslint-disable-next-line @typescript-eslint/no-explicit-any242 options: any | undefined243) => Promise<infer U>244 ? U extends ClientResponse<infer O, infer S, infer F>245 ? { input: NonNullable<R>; output: O; outputFormat: F; status: S } extends Endpoint246 ? { input: NonNullable<R>; output: O; outputFormat: F; status: S }247 : never248 : never249 : never250251export type InferResponseType<T, U extends StatusCode = StatusCode> = InferResponseTypeFromEndpoint<252 InferEndpointType<T>,253 U254>255256type InferResponseTypeFromEndpoint<T extends Endpoint, U extends StatusCode> = T extends {257 output: infer O258 status: infer S259}260 ? S extends U261 ? O262 : never263 : never264265export type InferRequestType<T> = T extends (266 args: infer R,267 // eslint-disable-next-line @typescript-eslint/no-explicit-any268 options: any | undefined269) => Promise<ClientResponse<unknown>>270 ? NonNullable<R>271 : never272273export type InferRequestOptionsType<T> = T extends (274 // eslint-disable-next-line @typescript-eslint/no-explicit-any275 args: any,276 options: infer R277) => Promise<ClientResponse<unknown>>278 ? NonNullable<R>279 : never280fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2
lines 281–285why, one step back281/**282 * Filter a ClientResponse type so it only includes responses of specific status codes.283 */284export type FilterClientResponseByStatusCode<285 T extends ClientResponse<any, any, any>,chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 286–291why, one step back286 U extends number = StatusCode,287> =288 T extends ClientResponse<infer RT, infer RC, infer RF>289 ? RC extends U290 ? ClientResponse<RT, RC, RF>291 : neverfix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2
lines 292–293why, one step back292 : never293chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
line 294why, one step back294type PathToChain<Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 295why, one step back295 Prefix extends string,chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 296–297why, one step back296 Path extends string,297 E extends Schema,chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
line 298why, one step back298 Original extends string = Path,chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
line 299why, one step back299> = Path extends `/${infer P}`Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 300why, one step back300 ? PathToChain<Prefix, P, E, Path>chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
line 301why, one step back301 : Path extends `${infer P}/${infer R}`Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 302why, one step back302 ? { [K in P]: PathToChain<Prefix, R, E, Original> }chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 303–304why, one step back303 : {304 [K in Path extends '' ? 'index' : Path]: ClientRequest<Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 305–306why, one step back305 Prefix,306 Original,chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 307–309why, one step back307 E extends Record<string, unknown> ? E[Original] : never308 >309 }chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
line 310why, one step back310Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 311why, one step back311export type Client<T, Prefix extends string> =chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
lines 312–314why, one step back312 T extends HonoBase<any, infer S, any>313 ? S extends Record<infer K, Schema>314 ? K extends stringMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 315why, one step back315 ? PathToChain<Prefix, K, S>chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd
line 316why, one step back316 : neverchore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 317–330why, one step back317 : never318 : never319320export type Callback = (opts: CallbackOptions) => unknown321322interface CallbackOptions {323 path: string[]324 // eslint-disable-next-line @typescript-eslint/no-explicit-any325 args: any[]326}327328export type ObjectType<T = unknown> = {329 [key: string]: T330}Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 331–358why, one step back331332type GlobalResponseDefinition = {333 [S in StatusCode]?: {334 [F in KnownResponseFormat]?: unknown335 }336}337338type ToEndpoints<Def extends GlobalResponseDefinition, R> = {339 [S in keyof Def & StatusCode]: {340 [F in keyof Def[S] & KnownResponseFormat]: Omit<R, 'output' | 'status' | 'outputFormat'> & {341 output: Def[S][F]342 status: S343 outputFormat: F344 }345 }[keyof Def[S] & KnownResponseFormat]346}[keyof Def & StatusCode]347348type ModRoute<R, Def extends GlobalResponseDefinition> = R extends Endpoint349 ? R | ToEndpoints<Def, R>350 : R351352type ModSchema<D, Def extends GlobalResponseDefinition> = {353 [K in keyof D]: {354 [M in keyof D[K]]: ModRoute<D[K][M], Def>355 }356}357358export type ApplyGlobalResponse<App, Def extends GlobalResponseDefinition> =fix(client): preserve route schema in ApplyGlobalResponse (#4777)Oguma Shunyabefore adoption0768232
lines 359–362why, one step back359 App extends HonoBase<infer E, infer _ extends Schema, infer B>360 ? ModSchema<ExtractSchema<App>, Def> extends infer S extends Schema361 ? Hono<E, S, B>362 : neverMerge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 363why, one step back363 : neverfeat(client): add `PickResponseByStatusCode` type (#4791)Yusuke Wadabefore adoptiond1722e3
lines 364–393why, one step back364365type PickRoute<R, U extends StatusCode> = R extends Endpoint366 ? R extends { status: U }367 ? R368 : never369 : R370371type PickSchema<D, U extends StatusCode> = {372 [K in keyof D]: {373 [M in keyof D[K]]: PickRoute<D[K][M], U>374 }375}376377/**378 * Keep only specific status code responses from all routes of an app.379 * Useful when error responses are handled centrally (e.g., via custom fetch)380 * and you want the client to only expose success response types.381 *382 * @example383 * ```ts384 * type AppSuccessOnly = PickResponseByStatusCode<typeof app, 200>385 * const client = hc<AppSuccessOnly>('http://localhost')386 * ```387 */388export type PickResponseByStatusCode<App, U extends StatusCode> =389 App extends HonoBase<infer E, infer _ extends Schema, infer B>390 ? PickSchema<ExtractSchema<App>, U> extends infer S extends Schema391 ? Hono<E, S, B>392 : never393 : never