Skip to content
Myr

client.test.ts

This file

Path

src/client/client.test.ts

2,310 lines 路 65.6 KiB 路 TypeScript

Last changed by

fix(client): normalize root WebSocket URLs (#5291)Ersa Oktavian Ramadanbefore adoption499c35e

History of this file

Take it

1/* eslint-disable @typescript-eslint/no-unused-vars */23/* eslint-disable @typescript-eslint/ban-ts-comment */4import { HttpResponse, http } from 'msw'5import { setupServer } from 'msw/node'6import { expectTypeOf, vi } from 'vitest'7import { upgradeWebSocket } from '../adapter/deno/websocket'8import { Hono } from '../hono'9import { parse } from '../utils/cookie'10import type { Equal, Expect, JSONValue, SimplifyDeepArray } from '../utils/types'11import { validator } from '../validator'12import { hc } from './client'13import type {14  ClientResponse,15  InferRequestType,16  InferResponseType,17  ApplyGlobalResponse,18  PickResponseByStatusCode,19} from './types'2021class SafeBigInt {22  unsafe = BigInt(42)2324  toJSON() {25    return {26      value: '42n',27    }28  }29}3031describe('Basic - JSON', () => {32  const app = new Hono()3334  const route = app35    .post(36      '/posts',37      validator('cookie', () => {38        return {} as {39          debug: string40        }41      }),42      validator('header', () => {43        return {} as {44          'x-message': string45        }46      }),47      validator('json', () => {48        return {} as {49          id: number50          title: string51        }52      }),53      (c) => {54        return c.json({55          success: true,56          message: 'dummy',57          requestContentType: 'dummy',58          requestHono: 'dummy',59          requestMessage: 'dummy',60          requestBody: {61            id: 123,62            title: 'dummy',63          },64        })65      }66    )67    .get('/hello-not-found', (c) => c.notFound())68    .get('/null', (c) => c.json(null))69    .get('/empty', (c) => c.json({}))70    .get('/bigint', (c) => c.json({ value: BigInt(42) }))71    .get('/safe-bigint', (c) => c.json(new SafeBigInt()))7273  type AppType = typeof route7475  const server = setupServer(76    http.post('http://localhost/posts', async ({ request }) => {77      const requestContentType = request.headers.get('content-type')78      const requestHono = request.headers.get('x-hono')79      const requestMessage = request.headers.get('x-message')80      const requestBody = await request.json()81      const payload = {82        message: 'Hello!',83        success: true,84        requestContentType,85        requestHono,86        requestMessage,87        requestBody,88      }89      return HttpResponse.json(payload)90    }),91    http.get('http://localhost/hello-not-found', () => {92      return HttpResponse.text(null, {93        status: 404,94      })95    }),96    http.get('http://localhost/null', () => {97      return HttpResponse.json(null)98    }),99    http.get('http://localhost/empty', () => {100      return HttpResponse.json({})101    }),102    http.get('http://localhost/bigint', () => {103      return HttpResponse.json({ value: BigInt(42) })104    }),105    http.get('http://localhost/safe-bigint', () => {106      return HttpResponse.json(new SafeBigInt())107    }),108    http.get('http://localhost/api/string', () => {109      return HttpResponse.json('a-string')110    }),111    http.get('http://localhost/api/number', async () => {112      return HttpResponse.json(37)113    }),114    http.get('http://localhost/api/boolean', async () => {115      return HttpResponse.json(true)116    }),117    http.get('http://localhost/api/generic', async () => {118      return HttpResponse.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random())119    })120  )121122  beforeAll(() => server.listen())123  afterEach(() => server.resetHandlers())124  afterAll(() => server.close())125126  const payload = {127    id: 123,128    title: 'Hello! Hono!',129  }130131  const client = hc<AppType>('http://localhost', { headers: { 'x-hono': 'hono' } })132133  it('Should get 200 response', async () => {134    const res = await client.posts.$post(135      {136        json: payload,137        header: {138          'x-message': 'foobar',139        },140        cookie: {141          debug: 'true',142        },143      },144      {}145    )146147    expect(res.ok).toBe(true)148    const data = await res.json()149    expect(data.success).toBe(true)150    expect(data.message).toBe('Hello!')151    expect(data.requestContentType).toBe('application/json')152    expect(data.requestHono).toBe('hono')153    expect(data.requestMessage).toBe('foobar')154    expect(data.requestBody).toEqual(payload)155  })156157  it('Should get 404 response', async () => {158    const res = await client['hello-not-found'].$get()159    expect(res.status).toBe(404)160  })161162  it('Should get a `null` content', async () => {163    const client = hc<AppType>('http://localhost')164    const res = await client.null.$get()165    const data = await res.json()166    expectTypeOf(data).toMatchTypeOf<null>()167    expect(data).toBe(null)168  })169170  it('Should get a `{}` content', async () => {171    const client = hc<AppType>('http://localhost')172    const res = await client.empty.$get()173    const data = await res.json()174    expectTypeOf(data).toMatchTypeOf<{}>()175    expect(data).toStrictEqual({})176  })177178  it('Should get a `{}` content', async () => {179    const client = hc<AppType>('http://localhost')180    const res = await client['safe-bigint'].$get()181    const data = await res.json()182    expectTypeOf(data).toMatchTypeOf<{ value: string }>()183    expect(data).toStrictEqual({ value: '42n' })184  })185186  it('Should get an error response', async () => {187    const client = hc<AppType>('http://localhost')188    const res = await client.bigint.$get()189    const data = await res.json()190    expectTypeOf(data).toMatchTypeOf<never>()191    expect(res.status).toBe(500)192    expect(data).toMatchObject({193      message: 'Do not know how to serialize a BigInt',194      name: 'TypeError',195    })196  })197198  it('Should have correct types - primitives', async () => {199    const app = new Hono()200    const route = app201      .get('/api/string', (c) => c.json('a-string'))202      .get('/api/number', (c) => c.json(37))203      .get('/api/boolean', (c) => c.json(true))204      .get('/api/generic', (c) =>205        c.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random())206      )207    type AppType = typeof route208    const client = hc<AppType>('http://localhost')209    const stringFetch = await client.api.string.$get()210    const stringRes = await stringFetch.json()211    const numberFetch = await client.api.number.$get()212    const numberRes = await numberFetch.json()213    const booleanFetch = await client.api.boolean.$get()214    const booleanRes = await booleanFetch.json()215    const genericFetch = await client.api.generic.$get()216    const genericRes = await genericFetch.json()217    type stringVerify = Expect<Equal<'a-string', typeof stringRes>>218    expect(stringRes).toBe('a-string')219    type numberVerify = Expect<Equal<37, typeof numberRes>>220    expect(numberRes).toBe(37)221    type booleanVerify = Expect<Equal<true, typeof booleanRes>>222    expect(booleanRes).toBe(true)223    type genericVerify = Expect<Equal<number | boolean, typeof genericRes>>224    expect(typeof genericRes === 'number' || typeof genericRes === 'boolean').toBe(true)225226    // using .text() on json endpoint should return string227    type textTest = Expect<Equal<Promise<string>, ReturnType<typeof genericFetch.text>>>228  })229})230231describe('Basic - query, queries, form, path params, header and cookie', () => {232  const app = new Hono()233234  const route = app235    .get(236      '/search',237      validator('query', () => {238        return {} as { q: string; tag: string[]; filter: string }239      }),240      (c) => {241        return c.json({242          q: 'fake',243          tag: ['fake'],244          filter: 'fake',245        })246      }247    )248    .put(249      '/posts/:id',250      validator('form', () => {251        return {252          title: 'Hello',253        }254      }),255      (c) => {256        const data = c.req.valid('form')257        return c.json(data)258      }259    )260    .get(261      '/header',262      validator('header', () => {263        return {264          'x-message-id': 'Hello',265        }266      }),267      (c) => {268        const data = c.req.valid('header')269        return c.json(data)270      }271    )272    .get(273      '/cookie',274      validator('cookie', () => {275        return {276          hello: 'world',277          goodbye: 'moon',278        }279      }),280      (c) => {281        const data = c.req.valid('cookie')282        return c.json(data)283      }284    )285286  const server = setupServer(287    http.get('http://localhost/api/search', ({ request }) => {288      const url = new URL(request.url)289      const query = url.searchParams.get('q')290      const tag = url.searchParams.getAll('tag')291      const filter = url.searchParams.get('filter')292      return HttpResponse.json({293        q: query,294        tag,295        filter,296      })297    }),298    http.get('http://localhost/api/posts', ({ request }) => {299      const url = new URL(request.url)300      const tags = url.searchParams.getAll('tags')301      return HttpResponse.json({302        tags: tags,303      })304    }),305    http.put('http://localhost/api/posts/123', async ({ request }) => {306      const buffer = await request.arrayBuffer()307      // @ts-ignore308      const string = String.fromCharCode.apply('', new Uint8Array(buffer))309      return HttpResponse.text(string)310    }),311    http.get('http://localhost/api/header', async ({ request }) => {312      const message = await request.headers.get('x-message-id')313      return HttpResponse.json({ 'x-message-id': message })314    }),315    http.get('http://localhost/api/cookie', async ({ request }) => {316      return HttpResponse.json(parse(request.headers.get('cookie') || ''))317    })318  )319320  beforeAll(() => server.listen())321  afterEach(() => server.resetHandlers())322  afterAll(() => server.close())323324  type AppType = typeof route325326  const client = hc<AppType>('http://localhost/api')327328  it('Should get 200 response - query', async () => {329    const res = await client.search.$get({330      query: {331        q: 'foobar',332        tag: ['a', 'b'],333        // @ts-expect-error334        filter: undefined,335      },336    })337338    expect(res.status).toBe(200)339    expect(await res.json()).toEqual({340      q: 'foobar',341      tag: ['a', 'b'],342      filter: null,343    })344  })345346  it('Should get 200 response - form, params', async () => {347    const res = await client.posts[':id'].$put({348      form: {349        title: 'Good Night',350      },351      param: {352        id: '123',353      },354    })355356    expect(res.status).toBe(200)357    expect(await res.text()).toMatch('Good Night')358  })359360  it('Should get 200 response - header', async () => {361    const header = {362      'x-message-id': 'Hello',363    }364    const res = await client.header.$get({365      header,366    })367368    expect(res.status).toBe(200)369    expect(await res.json()).toEqual(header)370  })371372  it('Should get 200 response - cookie', async () => {373    const cookie = {374      hello: 'world',375      goodbye: 'moon',376    }377    const res = await client.cookie.$get({378      cookie,379    })380381    expect(res.status).toBe(200)382    expect(await res.json()).toEqual(cookie)383  })384})385386describe('Basic - $url()', () => {387  const api = new Hono().get('/', (c) => c.text('API')).get('/posts/:id', (c) => c.text('Post'))388  const content = new Hono().get(389    '/search',390    validator('query', () => {391      return { page: '1', limit: '10' }392    }),393    (c) => c.text('Search')394  )395  const app = new Hono()396    .get('/', (c) => c.text('Index'))397    .route('/api', api)398    .route('/content', content)399400  it('Should return a correct url via $url().href', async () => {401    const client = hc<typeof app>('http://fake')402    expect(client.index.$url().href).toBe('http://fake/')403    expect(404      client.index.$url({405        query: {406          page: '123',407          limit: '20',408        },409      }).href410    ).toBe('http://fake/?page=123&limit=20')411    expect(client.api.$url().href).toBe('http://fake/api')412    expect(413      client.api.posts[':id'].$url({414        param: {415          id: '123',416        },417      }).href418    ).toBe('http://fake/api/posts/123')419    expect(420      client.content.search.$url({421        query: {422          page: '123',423          limit: '20',424        },425      }).href426    ).toBe('http://fake/content/search?page=123&limit=20')427  })428429  it.each(['http://fake', 'http://fake/', 'http://fake//', 'http://fake/api'])(430    'Should return a correct path via $path() regardless of %s',431    async (baseURL) => {432      const client = hc<typeof app>(baseURL)433      expect(client.index.$path()).toBe('/')434      expect(435        client.index.$path({436          query: {437            page: '123',438            limit: '20',439          },440        })441      ).toBe('/?page=123&limit=20')442      expect(client.api.$path()).toBe('/api')443      expect(444        client.api.posts[':id'].$path({445          param: {446            id: '123',447          },448        })449      ).toBe('/api/posts/123')450      expect(451        client.content.search.$path({452          query: {453            page: '123',454            limit: '20',455          },456        })457      ).toBe('/content/search?page=123&limit=20')458    }459  )460})461462describe('Form - Multiple Values', () => {463  const server = setupServer(464    http.post('http://localhost/multiple-values', async ({ request }) => {465      const data = await request.formData()466      return HttpResponse.json(data.getAll('key'))467    })468  )469470  beforeAll(() => server.listen())471  afterEach(() => server.resetHandlers())472  afterAll(() => server.close())473474  const client = hc('http://localhost/')475476  it('Should get 200 response - query', async () => {477    // @ts-expect-error `client['multiple-values'].$post` is not typed478    const res = await client['multiple-values'].$post({479      form: {480        key: ['foo', 'bar'],481      },482    })483    expect(res.status).toBe(200)484    expect(await res.json()).toEqual(['foo', 'bar'])485  })486})487488describe('Form - Undefined Values', () => {489  const server = setupServer(490    http.post('http://localhost/form-undefined', async ({ request }) => {491      const data = await request.formData()492      return HttpResponse.json({493        keys: [...data.keys()],494        title: data.get('title'),495        optional: data.get('optional'),496      })497    })498  )499500  beforeAll(() => server.listen())501  afterEach(() => server.resetHandlers())502  afterAll(() => server.close())503504  const client = hc('http://localhost/')505506  it('Should skip undefined values in form data', async () => {507    // @ts-expect-error `client['form-undefined'].$post` is not typed508    const res = await client['form-undefined'].$post({509      form: {510        title: 'Hello',511        optional: undefined,512      },513    })514    expect(res.status).toBe(200)515    const json = await res.json()516    expect(json).toEqual({517      keys: ['title'],518      title: 'Hello',519      optional: null,520    })521  })522})523524describe('Form arrays containing undefined', () => {525  const app = new Hono().post(526    '/',527    validator('form', () => ({}) as { tag: (string | undefined)[] | undefined }),528    async (c) => {529      const body = await c.req.parseBody({ all: true })530      return c.json({ tag: body['tag'] })531    }532  )533  const client = hc<typeof app>('', { fetch: app.request })534535  it('Should not send the literal string "undefined" for an absent entry', async () => {536    const res = await client.index.$post({537      form: {538        tag: ['a', undefined, 'b'],539      },540    })541    expect(res.status).toBe(200)542    expect(await res.json()).toEqual({ tag: ['a', 'b'] })543  })544545  it('Should keep an empty string in an array', async () => {546    const res = await client.index.$post({547      form: {548        tag: ['a', '', 'b'],549      },550    })551    expect(res.status).toBe(200)552    expect(await res.json()).toEqual({ tag: ['a', '', 'b'] })553  })554})555556describe('Optional header and cookie values', () => {557  const app = new Hono().get(558    '/',559    validator('header', () => {560      return {} as {561        'x-required': string562        'x-optional'?: string563      }564    }),565    validator('cookie', () => {566      return {} as {567        required: string568        optional?: string569      }570    }),571    (c) =>572      c.json({573        requiredHeader: c.req.header('x-required'),574        optionalHeader: c.req.header('x-optional') ?? null,575        cookies: parse(c.req.header('cookie') ?? ''),576      })577  )578  const client = hc<typeof app>('', { fetch: app.request })579580  it('Should skip undefined header and cookie values', async () => {581    const res = await client.index.$get({582      header: {583        'x-required': 'header-value',584        'x-optional': undefined,585      },586      cookie: {587        required: 'cookie-value',588        optional: undefined,589      },590    })591592    expect(res.status).toBe(200)593    expect(await res.json()).toEqual({594      requiredHeader: 'header-value',595      optionalHeader: null,596      cookies: {597        required: 'cookie-value',598      },599    })600  })601602  it('Should not send a Cookie header if all cookie values are undefined', async () => {603    const app = new Hono().get(604      '/',605      validator('cookie', () => {606        return {} as {607          optional?: string608        }609      }),610      (c) => c.json({ cookieHeader: c.req.header('cookie') ?? null })611    )612    const client = hc<typeof app>('', { fetch: app.request })613614    const res = await client.index.$get({615      cookie: {616        optional: undefined,617      },618    })619620    expect(res.status).toBe(200)621    expect(await res.json()).toEqual({ cookieHeader: null })622  })623})624625describe('Infer the response/request type', () => {626  const app = new Hono()627  const route = app.get(628    '/',629    validator('query', () => {630      return {631        name: 'dummy',632        age: 'dummy',633      }634    }),635    validator('header', () => {636      return {637        'x-request-id': 'dummy',638      }639    }),640    validator('cookie', () => {641      return {642        name: 'dummy',643      }644    }),645    (c) =>646      c.json({647        id: 123,648        title: 'Morning!',649      })650  )651652  type AppType = typeof route653654  it('Should infer response type the type correctly', () => {655    const client = hc<AppType>('/')656    const req = client.index.$get657658    type Actual = InferResponseType<typeof req>659    type Expected = {660      id: number661      title: string662    }663    type verify = Expect<Equal<Expected, Actual>>664  })665666  it('Should infer request type the type correctly', () => {667    const client = hc<AppType>('/')668    const req = client.index.$get669670    type Actual = InferRequestType<typeof req>671    type Expected = {672      age: string | string[]673      name: string | string[]674    }675    type verify = Expect<Equal<Expected, Actual['query']>>676  })677678  it('Should infer request header type the type correctly', () => {679    const client = hc<AppType>('/')680    const req = client.index.$get681    type c = typeof req682683    type Actual = InferRequestType<c>684    type Expected = {685      'x-request-id': string686    }687    type verify = Expect<Equal<Expected, Actual['header']>>688  })689690  it('Should infer request cookie type the type correctly', () => {691    const client = hc<AppType>('/')692    const req = client.index.$get693    type c = typeof req694695    type Actual = InferRequestType<c>696    type Expected = {697      name: string698    }699    type verify = Expect<Equal<Expected, Actual['cookie']>>700  })701702  describe('Without input', () => {703    const route = app.get('/', (c) => c.json({ ok: true }))704    type AppType = typeof route705706    it('Should infer response type the type correctly', () => {707      const client = hc<AppType>('/')708      const req = client.index.$get709710      type Actual = InferResponseType<typeof req>711      type Expected = { ok: true }712      type verify = Expect<Equal<Expected, Actual>>713    })714715    it('Should infer request type the type correctly', () => {716      const client = hc<AppType>('/')717      const req = client.index.$get718719      type Actual = InferRequestType<typeof req>720      type Expected = {}721      type verify = Expect<Equal<Expected, Actual>>722    })723  })724})725726describe('Merge path with `app.route()`', () => {727  const server = setupServer(728    http.get('http://localhost/api/search', async () => {729      return HttpResponse.json({730        ok: true,731      })732    }),733    http.get('http://localhost/api/searchArray', async () => {734      return HttpResponse.json([735        {736          ok: true,737        },738      ])739    }),740    http.get('http://localhost/api/foo', async () => {741      return HttpResponse.json({742        ok: true,743      })744    }),745    http.post('http://localhost/api/bar', async () => {746      return HttpResponse.json({747        ok: true,748      })749    }),750    http.get('http://localhost/v1/book', async () => {751      return HttpResponse.json({752        ok: true,753      })754    })755  )756757  beforeAll(() => server.listen())758  afterEach(() => server.resetHandlers())759  afterAll(() => server.close())760761  type Env = {762    Bindings: {763      TOKEN: string764    }765  }766767  it('Should have correct types', async () => {768    const api = new Hono<Env>().get('/search', (c) => c.json({ ok: true }))769    const app = new Hono<Env>().route('/api', api)770    type AppType = typeof app771    const client = hc<AppType>('http://localhost')772    const res = await client.api.search.$get()773    const data = await res.json()774    type verify = Expect<Equal<true, typeof data.ok>>775    expect(data.ok).toBe(true)776  })777778  it('Should have correct types - basePath() then get()', async () => {779    const base = new Hono<Env>().basePath('/api')780    const app = base.get('/search', (c) => c.json({ ok: true }))781    type AppType = typeof app782    const client = hc<AppType>('http://localhost')783    const res = await client.api.search.$get()784    const data = await res.json()785    type verify = Expect<Equal<true, typeof data.ok>>786    expect(data.ok).toBe(true)787  })788789  it('Should have correct types - basePath(), route(), get()', async () => {790    const book = new Hono().get('/', (c) => c.json({ ok: true }))791    const app = new Hono().basePath('/v1').route('/book', book)792    type AppType = typeof app793    const client = hc<AppType>('http://localhost')794    const res = await client.v1.book.$get()795    const data = await res.json()796    type verify = Expect<Equal<true, typeof data.ok>>797    expect(data.ok).toBe(true)798  })799800  it('Should have correct types - with interface', async () => {801    interface Result {802      ok: boolean803      okUndefined?: boolean804    }805    const result: Result = { ok: true }806    const base = new Hono<Env>().basePath('/api')807    const app = base.get('/search', (c) => c.json(result))808    type AppType = typeof app809    const client = hc<AppType>('http://localhost')810    const res = await client.api.search.$get()811    const data = await res.json()812    type verify = Expect<Equal<Result, typeof data>>813    expect(data.ok).toBe(true)814815    // A few more types only tests816    interface DeepInterface {817      l2: {818        l3: Result819      }820    }821    interface ExtraDeepInterface {822      l4: DeepInterface823    }824    type verifyDeepInterface = Expect<825      Equal<SimplifyDeepArray<DeepInterface> extends JSONValue ? true : false, true>826    >827    type verifyExtraDeepInterface = Expect<828      Equal<SimplifyDeepArray<ExtraDeepInterface> extends JSONValue ? true : false, true>829    >830  })831832  it('Should have correct types - with array of interfaces', async () => {833    interface Result {834      ok: boolean835      okUndefined?: boolean836    }837    type Results = Result[]838839    const results: Results = [{ ok: true }]840    const base = new Hono<Env>().basePath('/api')841    const app = base.get('/searchArray', (c) => c.json(results))842    type AppType = typeof app843    const client = hc<AppType>('http://localhost')844    const res = await client.api.searchArray.$get()845    const data = await res.json()846    type verify = Expect<Equal<Results, typeof data>>847    expect(data[0].ok).toBe(true)848849    // A few more types only tests850    type verifyNestedArrayTyped = Expect<851      Equal<SimplifyDeepArray<[string, Results]> extends JSONValue ? true : false, true>852    >853    type verifyNestedArrayInterfaceArray = Expect<854      Equal<SimplifyDeepArray<[string, Result[]]> extends JSONValue ? true : false, true>855    >856    type verifyExtraNestedArrayTyped = Expect<857      Equal<SimplifyDeepArray<[string, Results[]]> extends JSONValue ? true : false, true>858    >859    type verifyExtraNestedArrayInterfaceArray = Expect<860      Equal<SimplifyDeepArray<[string, Result[][]]> extends JSONValue ? true : false, true>861    >862  })863864  it('Should allow a Date object and return it as a string', async () => {865    const app = new Hono()866    const route = app.get('/api/foo', (c) => c.json({ datetime: new Date() }))867    type AppType = typeof route868    const client = hc<AppType>('http://localhost')869    const res = await client.api.foo.$get()870    const { datetime } = await res.json()871    type verify = Expect<Equal<string, typeof datetime>>872  })873874  describe('Multiple endpoints', () => {875    const api = new Hono()876      .get('/foo', (c) => c.json({ foo: '' }))877      .post('/bar', (c) => c.json({ bar: 0 }))878    const app = new Hono().route('/api', api)879    type AppType = typeof app880    const client = hc<typeof app>('http://localhost')881882    it('Should return correct types - GET /api/foo', async () => {883      const res = await client.api.foo.$get()884      const data = await res.json()885      type verify = Expect<Equal<string, typeof data.foo>>886    })887888    it('Should return correct types - POST /api/bar', async () => {889      const res = await client.api.bar.$post()890      const data = await res.json()891      type verify = Expect<Equal<number, typeof data.bar>>892    })893    it('Should work with $url', async () => {894      const url = client.api.bar.$url()895      expect(url.href).toBe('http://localhost/api/bar')896    })897    it('Should work with $path', async () => {898      const path = client.api.bar.$path()899      expect(path).toBe('/api/bar')900    })901  })902903  describe('With a blank path', () => {904    const app = new Hono().basePath('/api/v1')905    const routes = app.route(906      '/me',907      new Hono().route(908        '',909        new Hono().get('', async (c) => {910          return c.json({ name: 'hono' })911        })912      )913    )914    const client = hc<typeof routes>('http://localhost')915916    it('Should infer paths correctly', async () => {917      // Should not a throw type error918      const url = client.api.v1.me.$url()919      expectTypeOf<URL>(url)920      expect(url.href).toBe('http://localhost/api/v1/me')921922      const path = client.api.v1.me.$path()923      expectTypeOf<'/api/v1/me'>(path)924      expect(path).toBe('/api/v1/me')925    })926  })927928  describe('With endpoint pathname', () => {929    const app = new Hono().basePath('/api/v1')930    const routes = app.route(931      '/me',932      new Hono().route(933        '',934        new Hono().get('', async (c) => {935          return c.json({ name: 'hono' })936        })937      )938    )939    const client = hc<typeof routes>('http://localhost/proxy')940941    it('Should infer paths correctly', async () => {942      // Should not a throw type error943      const url = client.api.v1.me.$url()944      expectTypeOf<URL>(url)945      expect(url.href).toBe('http://localhost/proxy/api/v1/me')946947      const path = client.api.v1.me.$path()948      expectTypeOf<'/api/v1/me'>(path)949      expect(path).toBe('/api/v1/me')950    })951  })952})953954describe('Use custom fetch method', () => {955  it('Should call the custom fetch method when provided', async () => {956    const fetchMock = vi.fn()957958    const api = new Hono().get('/search', (c) => c.json({ ok: true }))959    const app = new Hono().route('/api', api)960    type AppType = typeof app961    const client = hc<AppType>('http://localhost', { fetch: fetchMock })962    await client.api.search.$get()963    expect(fetchMock).toHaveBeenCalledTimes(1)964  })965966  it('Should return Response from custom fetch method', async () => {967    const fetchMock = vi.fn()968    const returnValue = new Response(null, { status: 200 })969    fetchMock.mockReturnValueOnce(returnValue)970971    const api = new Hono().get('/search', (c) => c.json({ ok: true }))972    const app = new Hono().route('/api', api)973    type AppType = typeof app974    const client = hc<AppType>('http://localhost', { fetch: fetchMock })975    const res = await client.api.search.$get()976    expect(res.ok).toBe(true)977    expect(res).toEqual(returnValue)978  })979})980981describe('Use custom fetch (app.request) method', () => {982  it('Should return Response from app request method', async () => {983    const app = new Hono().get('/search', (c) => c.json({ ok: true }))984    type AppType = typeof app985    const client = hc<AppType>('', { fetch: app.request })986    const res = await client.search.$get()987    expect(res.ok).toBe(true)988  })989990  it.each([false, 0, '', null])('Should send falsy JSON value: %j', async (json) => {991    const app = new Hono().post(992      '/json',993      validator('json', (value) => value as boolean | number | string | null),994      (c) => c.json(c.req.valid('json'))995    )996    const client = hc<typeof app>('', { fetch: app.request })997998    const res = await client.json.$post({ json })9991000    expect(res.status).toBe(200)1001    expect(await res.json()).toBe(json)1002  })1003})10041005describe('Optional parameters in JSON response', () => {1006  it('Should return the correct type', async () => {1007    const app = new Hono().get('/', (c) => {1008      return c.json({ message: 'foo' } as { message?: string })1009    })1010    type AppType = typeof app1011    const client = hc<AppType>('', { fetch: app.request })1012    const res = await client.index.$get()1013    const data = await res.json()1014    expectTypeOf(data).toEqualTypeOf<{1015      message?: string1016    }>()1017  })1018})10191020describe('ClientResponse<T>.json() returns a Union type correctly', () => {1021  const condition = () => true1022  const app = new Hono().get('/', async (c) => {1023    const ok = condition()1024    if (ok) {1025      return c.json({ data: 'foo' })1026    }1027    return c.json({ message: 'error' })1028  })10291030  const client = hc<typeof app>('', { fetch: app.request })1031  it('Should be a Union type', async () => {1032    const res = await client.index.$get()1033    const json = await res.json()1034    expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()1035  })1036})10371038describe('Response with different status codes', () => {1039  const condition = () => true1040  const app = new Hono().get('/', async (c) => {1041    const ok = condition()1042    if (ok) {1043      return c.json({ data: 'foo' }, 200)1044    }1045    if (!ok) {1046      return c.json({ message: 'error' }, 400)1047    }1048    return c.json(null)1049  })10501051  const client = hc<typeof app>('', { fetch: app.request })10521053  it('all', async () => {1054    const res = await client.index.$get()1055    const json = await res.json()1056    expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string } | null>()1057  })10581059  it('status 200', async () => {1060    const res = await client.index.$get()1061    if (res.status === 200) {1062      const json = await res.json()1063      expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()1064    }1065  })10661067  it('status 400', async () => {1068    const res = await client.index.$get()1069    if (res.status === 400) {1070      const json = await res.json()1071      expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()1072    }1073  })10741075  it('response is ok', async () => {1076    const res = await client.index.$get()1077    if (res.ok) {1078      const json = await res.json()1079      expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()1080    }1081  })10821083  it('response is not ok', async () => {1084    const res = await client.index.$get()1085    if (!res.ok) {1086      const json = await res.json()1087      expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()1088    }1089  })1090})10911092describe('Infer the response type with different status codes', () => {1093  const condition = () => true1094  const app = new Hono().get('/', async (c) => {1095    const ok = condition()1096    if (ok) {1097      return c.json({ data: 'foo' }, 200)1098    }1099    if (!ok) {1100      return c.json({ message: 'error' }, 400)1101    }1102    return c.json(null)1103  })11041105  const client = hc<typeof app>('', { fetch: app.request })11061107  it('Should infer response type correctly', () => {1108    const req = client.index.$get11091110    type Actual = InferResponseType<typeof req>1111    type Expected =1112      | {1113          data: string1114        }1115      | {1116          message: string1117        }1118      | null1119    type verify = Expect<Equal<Expected, Actual>>1120  })11211122  it('Should infer response type of status 200 correctly', () => {1123    const req = client.index.$get11241125    type Actual = InferResponseType<typeof req, 200>1126    type Expected = {1127      data: string1128    } | null1129    type verify = Expect<Equal<Expected, Actual>>1130  })1131})11321133describe('Infer the response types from middlewares', () => {1134  const app = new Hono()1135    .get(1136      '/',1137      validator('query', (input, c) => {1138        if (!input.page || typeof input.page !== 'string') {1139          return c.json({ error: 'Bad request' as const }, 400)1140        }11411142        return input as { page: string }1143      }),1144      async (c) => {1145        const query = c.req.valid('query')1146        return c.json({ data: 'foo', page: query.page }, 200)1147      }1148    )1149    .post(1150      '/posts',1151      async (c, next) => {1152        const auth = c.req.header('authorization')1153        if (!auth || !auth.startsWith('Bearer ')) {1154          return c.json({ error: 'Unauthorized' as const }, 401)1155        }1156        return next()1157      },1158      validator('json', (input, c) => {1159        if (!input.title) {1160          return c.json({ error: 'Bad request' as const }, 400)1161        }11621163        return input as { title: string }1164      }),1165      (c) => {1166        const data = c.req.valid('json')1167        return c.json(data, 200)1168      }1169    )11701171  type AppType = typeof app1172  const client = hc<AppType>('', { fetch: app.request })11731174  it('Should infer response type of status 200 correctly', () => {1175    const req = client.posts.$post11761177    type Actual = InferResponseType<typeof req, 200>1178    type Expected = {1179      title: string1180    }1181    type verify = Expect<Equal<Expected, Actual>>1182  })11831184  it('Should infer response type of status 400 correctly', () => {1185    const req = client.posts.$post11861187    type Actual = InferResponseType<typeof req, 400>1188    type Expected = {1189      error: 'Bad request'1190    }1191    type verify = Expect<Equal<Expected, Actual>>1192  })11931194  it('Should infer response type of status 401 correctly', () => {1195    const req = client.posts.$post11961197    type Actual = InferResponseType<typeof req, 401>1198    type Expected = {1199      error: 'Unauthorized'1200    }1201    type verify = Expect<Equal<Expected, Actual>>1202  })12031204  it('Should infer all possible response statuses', async () => {1205    const req = await client.posts.$post({1206      json: {1207        title: 'hello',1208      },1209    })12101211    type Actual = typeof req.status1212    type Expected = 200 | 400 | 4011213    type verify = Expect<Equal<Expected, Actual>>1214  })12151216  it('Should properly assign response to corresponding status', async () => {1217    const req = await client.posts.$post({1218      json: {1219        title: 'hello',1220      },1221    })12221223    if (req.status === 200) {1224      const data = await req.json()12251226      expectTypeOf(data).toEqualTypeOf<{ title: string }>()1227    } else if (req.status === 400) {1228      const data = await req.json()12291230      expectTypeOf(data).toEqualTypeOf<{ error: 'Bad request' }>()1231    } else if (req.status === 401) {1232      const data = await req.json()12331234      expectTypeOf(data).toEqualTypeOf<{ error: 'Unauthorized' }>()1235    }1236  })1237})12381239const pathname = <T extends URL | string>(value: T): string =>1240  value instanceof URL ? value.pathname : value12411242describe.each(['$path', '$url'] as const)('%s() with a param option', (cmd) => {1243  const app = new Hono()1244    .get('/posts/:id/comments', (c) => c.json({ ok: true }))1245    .get('/something/:firstId/:secondId/:version?', (c) => c.json({ ok: true }))1246    .get('/docs/:page', (c) => c.json({ ok: true }))1247    .get('/files/:dir/', (c) => c.json({ ok: true }))1248    .get('/:page', (c) => c.json({ ok: true }))1249    .get('/index/:v?', (c) => c.json({ ok: true }))1250  type AppType = typeof app1251  const client = hc<AppType>('http://localhost')12521253  it('Should return the correct url path - /posts/123/comments', async () => {1254    const value = client.posts[':id'].comments[cmd]({1255      param: {1256        id: '123',1257      },1258    })1259    expect(pathname(value)).toBe('/posts/123/comments')1260  })12611262  it('Should return the correct path - /posts/:id/comments', async () => {1263    const value = client.posts[':id'].comments[cmd]()1264    expect(pathname(value)).toBe('/posts/:id/comments')1265  })12661267  it('Should return the correct path - /something/123/456', async () => {1268    const value = client.something[':firstId'][':secondId'][':version?'][cmd]({1269      param: {1270        firstId: '123',1271        secondId: '456',1272        version: undefined,1273      },1274    })1275    expect(pathname(value)).toBe('/something/123/456')1276  })12771278  it('Should keep a param value of "index" - /docs/index', async () => {1279    const value = client.docs[':page'][cmd]({1280      param: {1281        page: 'index',1282      },1283    })1284    expect(pathname(value)).toBe('/docs/index')1285  })12861287  it('Should keep a root-level param value of "index" - /index', async () => {1288    const value = client[':page'][cmd]({1289      param: {1290        page: 'index',1291      },1292    })1293    expect(pathname(value)).toBe('/index')1294  })12951296  it('Should keep a literal index segment when an optional param is omitted - /index', async () => {1297    const value = client.index[':v?'][cmd]({1298      param: {1299        v: undefined,1300      },1301    })1302    expect(pathname(value)).toBe('/index')1303  })13041305  it('Should still drop the index alias of a route with a param - /files/123', async () => {1306    const value = client.files[':dir'].index[cmd]({1307      param: {1308        dir: '123',1309      },1310    })1311    expect(pathname(value)).toBe('/files/123')1312  })1313})13141315describe('$url() / $path() with a query option', () => {1316  const app = new Hono()1317    .get(1318      '/posts',1319      validator('query', () => {1320        return {} as { filter: 'test' }1321      }),1322      (c) => c.json({ ok: true })1323    )1324    .get('/docs/:page', (c) => c.json({ ok: true }))1325  type AppType = typeof app1326  const client = hc<AppType>('http://localhost')13271328  it('Should return the correct path - /posts?filter=test', async () => {1329    const url = client.posts.$url({1330      query: {1331        filter: 'test',1332      },1333    })1334    expect(url.search).toBe('?filter=test')13351336    const path = client.posts.$path({1337      query: {1338        filter: 'test',1339      },1340    })1341    expect(path).toBe('/posts?filter=test')1342  })13431344  it('Should return the correct path - /docs/index?filter=test', async () => {1345    const url = client.docs[':page'].$url({1346      param: {1347        page: 'index',1348      },1349      query: {1350        filter: 'test',1351      },1352    })1353    expect(url.href).toBe('http://localhost/docs/index?filter=test')13541355    const path = client.docs[':page'].$path({1356      param: {1357        page: 'index',1358      },1359      query: {1360        filter: 'test',1361      },1362    })1363    expect(path).toBe('/docs/index?filter=test')1364  })1365})13661367describe('Client can be awaited', () => {1368  it('Can be awaited without side effects', async () => {1369    const client = hc('http://localhost')13701371    const awaited = await client13721373    expect(awaited).toEqual(client)1374  })1375})13761377describe('Dynamic headers', () => {1378  const app = new Hono()13791380  const route = app.post('/posts', (c) => {1381    return c.json({1382      requestDynamic: 'dummy',1383      requestHono: 'dummy',1384    })1385  })13861387  type AppType = typeof route13881389  const server = setupServer(1390    http.post('http://localhost/posts', async ({ request }) => {1391      const requestDynamic = request.headers.get('x-dynamic')1392      const requestHono = request.headers.get('x-hono')1393      const payload = {1394        requestDynamic,1395        requestHono,1396      }1397      return HttpResponse.json(payload)1398    })1399  )14001401  beforeAll(() => server.listen())1402  afterEach(() => server.resetHandlers())1403  afterAll(() => server.close())14041405  let dynamic = ''14061407  const client = hc<AppType>('http://localhost', {1408    headers: () => ({ 'x-hono': 'hono', 'x-dynamic': dynamic }),1409  })14101411  it('Should have "x-dynamic": "one"', async () => {1412    dynamic = 'one'14131414    const res = await client.posts.$post()14151416    expect(res.ok).toBe(true)1417    const data = await res.json()1418    expect(data.requestDynamic).toEqual('one')1419  })14201421  it('Should have "x-dynamic": "two"', async () => {1422    dynamic = 'two'14231424    const res = await client.posts.$post()14251426    expect(res.ok).toBe(true)1427    const data = await res.json()1428    expect(data.requestDynamic).toEqual('two')1429  })14301431  it('Should merge function headers with per-request object headers', async () => {1432    const clientWithFn = hc<AppType>('http://localhost', {1433      headers: async () => ({ 'x-hono': 'hono' }),1434    })14351436    const res = await clientWithFn.posts.$post({}, { headers: { 'x-dynamic': 'request' } })14371438    expect(res.ok).toBe(true)1439    const data = await res.json()1440    expect(data.requestHono).toEqual('hono')1441    expect(data.requestDynamic).toEqual('request')1442  })14431444  it('Should merge function headers with per-request function headers', async () => {1445    const clientWithFn = hc<AppType>('http://localhost', {1446      headers: () => ({ 'x-hono': 'hono' }),1447    })14481449    const res = await clientWithFn.posts.$post(1450      {},1451      { headers: async () => ({ 'x-dynamic': 'request' }) }1452    )14531454    expect(res.ok).toBe(true)1455    const data = await res.json()1456    expect(data.requestHono).toEqual('hono')1457    expect(data.requestDynamic).toEqual('request')1458  })14591460  it('Should merge object headers with per-request function headers', async () => {1461    const clientWithObject = hc<AppType>('http://localhost', {1462      headers: { 'x-hono': 'hono' },1463    })14641465    const res = await clientWithObject.posts.$post(1466      {},1467      { headers: async () => ({ 'x-dynamic': 'request' }) }1468    )14691470    expect(res.ok).toBe(true)1471    const data = await res.json()1472    expect(data.requestHono).toEqual('hono')1473    expect(data.requestDynamic).toEqual('request')1474  })14751476  it('Should prioritize per-request headers when the keys conflict', async () => {1477    const clientWithFn = hc<AppType>('http://localhost', {1478      headers: async () => ({ 'x-hono': 'client' }),1479    })14801481    const res = await clientWithFn.posts.$post({}, { headers: { 'x-hono': 'request' } })14821483    expect(res.ok).toBe(true)1484    const data = await res.json()1485    expect(data.requestHono).toEqual('request')1486  })1487})14881489describe('RequestInit work as expected', () => {1490  const app = new Hono()14911492  const route = app1493    .get('/credentials', (c) => {1494      return c.text('' as RequestCredentials)1495    })1496    .get('/headers', (c) => {1497      return c.json({} as Record<string, string>)1498    })1499    .post('/headers', (c) => c.text('Not found', 404))15001501  type AppType = typeof route15021503  const server = setupServer(1504    http.get('http://localhost/credentials', ({ request }) => {1505      return HttpResponse.text(request.credentials)1506    }),1507    http.get('http://localhost/headers', ({ request }) => {1508      const allHeaders: Record<string, string> = {}1509      for (const [k, v] of request.headers.entries()) {1510        allHeaders[k] = v1511      }15121513      return HttpResponse.json(allHeaders)1514    }),1515    http.post('http://localhost/headers', () => {1516      return HttpResponse.text('Should not be here', {1517        status: 400,1518      })1519    })1520  )15211522  beforeAll(() => server.listen())1523  afterEach(() => server.resetHandlers())1524  afterAll(() => server.close())15251526  const client = hc<AppType>('http://localhost', {1527    headers: { 'x-hono': 'fire' },1528    init: {1529      credentials: 'include',1530    },1531  })15321533  it('Should overwrite method and fail', async () => {1534    const res = await client.headers.$get(undefined, { init: { method: 'POST' } })15351536    expect(res.ok).toBe(false)1537  })15381539  it('Should clear headers', async () => {1540    const res = await client.headers.$get(undefined, { init: { headers: undefined } })15411542    expect(res.ok).toBe(true)1543    const data = await res.json()1544    expect(data).toEqual({})1545  })15461547  it('Should overwrite headers', async () => {1548    const res = await client.headers.$get(undefined, {1549      init: { headers: new Headers({ 'x-hono': 'awesome' }) },1550    })15511552    expect(res.ok).toBe(true)1553    const data = await res.json()1554    expect(data).toEqual({ 'x-hono': 'awesome' })1555  })15561557  it('credentials is include', async () => {1558    const res = await client.credentials.$get()15591560    expect(res.ok).toBe(true)1561    const data = await res.text()1562    expect(data).toEqual('include')1563  })15641565  it('deepMerge should works and not unset credentials', async () => {1566    const res = await client.credentials.$get(undefined, { init: { headers: { hi: 'hello' } } })15671568    expect(res.ok).toBe(true)1569    const data = await res.text()1570    expect(data).toEqual('include')1571  })15721573  it('Should unset credentials', async () => {1574    const res = await client.credentials.$get(undefined, { init: { credentials: undefined } })15751576    expect(res.ok).toBe(true)1577    const data = await res.text()1578    expect(data).toEqual('same-origin')1579  })1580})15811582describe('WebSocket URL Protocol Translation', () => {1583  const app = new Hono()1584  const route = app.get(1585    '/',1586    upgradeWebSocket((c) => ({1587      onMessage(event, ws) {1588        console.log(`Message from client: ${event.data}`)1589        ws.send('Hello from server!')1590      },1591      onClose: () => {1592        console.log('Connection closed')1593      },1594    }))1595  )15961597  type AppType = typeof route15981599  const server = setupServer()1600  const webSocketMock = vi.fn()16011602  beforeAll(() => server.listen())1603  beforeEach(() => {1604    vi.stubGlobal('WebSocket', webSocketMock)1605  })1606  afterEach(() => {1607    vi.clearAllMocks()1608    server.resetHandlers()1609  })1610  afterAll(() => server.close())16111612  it('Translates HTTP to ws', async () => {1613    const client = hc<AppType>('http://localhost')1614    client.index.$ws()1615    expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/')1616  })16171618  it('Translates HTTPS to wss', async () => {1619    const client = hc<AppType>('https://localhost')1620    client.index.$ws()1621    expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/')1622  })16231624  it('Keeps ws unchanged', async () => {1625    const client = hc<AppType>('ws://localhost')1626    client.index.$ws()1627    expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/')1628  })16291630  it('Keeps wss unchanged', async () => {1631    const client = hc<AppType>('wss://localhost')1632    client.index.$ws()1633    expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/')1634  })16351636  it('Preserves an index path parameter value', async () => {1637    const dynamicRoute = new Hono().get(1638      '/:id',1639      upgradeWebSocket(() => ({}))1640    )1641    const client = hc<typeof dynamicRoute>('http://localhost')16421643    client[':id'].$ws({ param: { id: 'index' } })16441645    expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index')1646  })1647})16481649describe('WebSocket URL Protocol Translation with Query Parameters', () => {1650  const app = new Hono()1651  const route = app.get(1652    '/',1653    upgradeWebSocket((c) => ({1654      onMessage(event, ws) {1655        ws.send('Hello from server!')1656      },1657      onClose: () => {1658        console.log('Connection closed')1659      },1660    }))1661  )16621663  type AppType = typeof route16641665  const server = setupServer()1666  const webSocketMock = vi.fn()16671668  beforeAll(() => server.listen())1669  beforeEach(() => {1670    vi.stubGlobal('WebSocket', webSocketMock)1671  })1672  afterEach(() => {1673    vi.clearAllMocks()1674    server.resetHandlers()1675  })1676  afterAll(() => server.close())16771678  it('Translates HTTP to ws and includes query parameters', async () => {1679    const client = hc<AppType>('http://localhost')1680    client.index.$ws({1681      query: {1682        id: '123',1683        type: 'test',1684        tag: ['a', 'b'],1685      },1686    })1687    expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/?id=123&type=test&tag=a&tag=b')1688  })16891690  it('Translates HTTPS to wss and includes query parameters', async () => {1691    const client = hc<AppType>('https://localhost')1692    client.index.$ws({1693      query: {1694        id: '456',1695        type: 'secure',1696      },1697    })1698    expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/?id=456&type=secure')1699  })17001701  it('Keeps ws unchanged and includes query parameters', async () => {1702    const client = hc<AppType>('ws://localhost')1703    client.index.$ws({1704      query: {1705        id: '789',1706        type: 'plain',1707      },1708    })1709    expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/?id=789&type=plain')1710  })17111712  it('Keeps wss unchanged and includes query parameters', async () => {1713    const client = hc<AppType>('wss://localhost')1714    client.index.$ws({1715      query: {1716        id: '1011',1717        type: 'secure',1718      },1719    })1720    expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/?id=1011&type=secure')1721  })1722})17231724describe('Client can be console.log in react native', () => {1725  it('Returns a function name with function.name.toString', async () => {1726    const client = hc('http://localhost')1727    // @ts-ignore1728    expect(client.posts.name.toString()).toEqual('posts')1729  })17301731  it('Returns a function name with function.name.valueOf', async () => {1732    const client = hc('http://localhost')1733    // @ts-ignore1734    expect(client.posts.name.valueOf()).toEqual('posts')1735  })17361737  it('Returns a function with function.valueOf', async () => {1738    const client = hc('http://localhost')1739    expect(typeof client.posts.valueOf()).toEqual('function')1740  })17411742  it('Returns a function source with function.toString', async () => {1743    const client = hc('http://localhost')1744    expect(client.posts.toString()).toMatch('function proxyCallback')1745  })1746})17471748describe('Text response', () => {1749  const text = 'My name is Hono'1750  const obj = { ok: true }1751  const server = setupServer(1752    http.get('http://localhost/about/me', async () => {1753      return HttpResponse.text(text)1754    }),1755    http.get('http://localhost/api', async ({ request }) => {1756      return HttpResponse.json(obj)1757    })1758  )17591760  beforeAll(() => server.listen())1761  afterEach(() => server.resetHandlers())1762  afterAll(() => server.close())17631764  const app = new Hono().get('/about/me', (c) => c.text(text)).get('/api', (c) => c.json(obj))1765  const client = hc<typeof app>('http://localhost/')17661767  it('Should be never with res.json() - /about/me', async () => {1768    const res = await client.about.me.$get()1769    type Actual = ReturnType<typeof res.json>1770    type Expected = Promise<never>1771    type verify = Expect<Equal<Expected, Actual>>1772  })17731774  it('Should be "Hello, World!" with res.text() - /about/me', async () => {1775    const res = await client.about.me.$get()1776    const data = await res.text()1777    expectTypeOf(data).toEqualTypeOf<'My name is Hono'>()1778    expect(data).toBe(text)1779  })17801781  /**1782   * Also check the type of JSON response with res.text().1783   */1784  it('Should be string with res.text() - /api', async () => {1785    const res = await client.api.$get()1786    type Actual = ReturnType<typeof res.text>1787    type Expected = Promise<string>1788    type verify = Expect<Equal<Expected, Actual>>1789  })1790})17911792describe('Redirect response - only types', () => {1793  const server = setupServer(1794    http.get('http://localhost/', async () => {1795      return HttpResponse.redirect('/')1796    })1797  )17981799  beforeAll(() => server.listen())1800  afterEach(() => server.resetHandlers())1801  afterAll(() => server.close())18021803  const condition = () => true1804  const app = new Hono().get('/', async (c) => {1805    const ok = condition()1806    const temporary = condition()1807    if (ok) {1808      return c.json({ ok: true }, 200)1809    }1810    if (temporary) {1811      return c.redirect('/302')1812    }1813    return c.redirect('/301', 301)1814  })18151816  const client = hc<typeof app>('http://localhost/')1817  const req = client.index.$get18181819  it('Should infer request type the type correctly', () => {1820    type Actual = InferResponseType<typeof req>1821    type Expected =1822      | {1823          ok: true1824        }1825      | undefined1826    type verify = Expect<Equal<Expected, Actual>>1827  })18281829  it('Should infer response type correctly', async () => {1830    const res = await req()1831    if (res.ok) {1832      const data = await res.json()1833      expectTypeOf(data).toMatchTypeOf({ ok: true })1834    }1835    if (res.status === 301) {1836      type Expected = ClientResponse<undefined, 301, 'redirect'>1837      type verify = Expect<Equal<Expected, typeof res>>1838    }1839    if (res.status === 302) {1840      type Expected = ClientResponse<undefined, 302, 'redirect'>1841      type verify = Expect<Equal<Expected, typeof res>>1842    }1843  })1844})18451846describe('WebSocket Provider Integration', () => {1847  const app = new Hono()1848  const route = app.get(1849    '/',1850    upgradeWebSocket((c) => ({1851      onMessage(event, ws) {1852        ws.send('Hello from server!')1853      },1854      onClose() {1855        console.log('Connection closed')1856      },1857    }))1858  )18591860  type AppType = typeof route18611862  const server = setupServer()1863  beforeAll(() => server.listen())1864  afterEach(() => {1865    vi.clearAllMocks()1866    server.resetHandlers()1867  })1868  afterAll(() => server.close())18691870  it.each([1871    {1872      description: 'should initialize the WebSocket provider correctly',1873      url: 'http://localhost',1874      query: undefined,1875      expectedUrl: 'ws://localhost/',1876    },1877    {1878      description: 'should correctly add query parameters to the WebSocket URL',1879      url: 'http://localhost',1880      query: { id: '123', type: 'test', tag: ['a', 'b'] },1881      expectedUrl: 'ws://localhost/?id=123&type=test&tag=a&tag=b',1882    },1883  ])('$description', ({ url, expectedUrl, query }) => {1884    const webSocketMock = vi.fn()1885    const client = hc<AppType>(url, {1886      webSocket(url, options) {1887        return webSocketMock(url, options)1888      },1889    })1890    client.index.$ws({ query })1891    expect(webSocketMock).toHaveBeenCalledWith(expectedUrl, undefined)1892  })1893})18941895describe('Query arrays containing undefined', () => {1896  // A validator whose query field is an optional union gives the client an input1897  // type of `(string | undefined)[] | undefined`, so this compiles with no cast.1898  const app = new Hono().get(1899    '/search',1900    validator('query', () => ({}) as { tag: (string | undefined)[] | undefined }),1901    (c) => c.json({ ok: true })1902  )1903  type AppType = typeof app19041905  it('Should not send the literal string "undefined" for an absent entry', async () => {1906    let requestedUrl = ''1907    const client = hc<AppType>('http://localhost', {1908      fetch: (input: RequestInfo | URL) => {1909        requestedUrl = input.toString()1910        return Promise.resolve(new Response('{}'))1911      },1912    })19131914    await client.search.$get({ query: { tag: ['a', undefined, 'b'] } })19151916    expect(requestedUrl).toBe('http://localhost/search?tag=a&tag=b')1917  })1918})19191920describe('Empty serialized query', () => {1921  const app = new Hono().get(1922    '/search',1923    validator('query', () => ({}) as { q?: string }),1924    (c) => c.json({ ok: true })1925  )1926  const input = { query: { q: undefined } }19271928  it('Should omit the query delimiter when no query values are serialized', async () => {1929    let requestedUrl = ''1930    const client = hc<typeof app>('http://localhost', {1931      fetch: (input: RequestInfo | URL) => {1932        requestedUrl = input.toString()1933        return Promise.resolve(new Response('{}'))1934      },1935    })19361937    await client.search.$get(input)19381939    expect(requestedUrl).toBe('http://localhost/search')1940    expect(client.search.$url(input).href).toBe('http://localhost/search')1941    expect(client.search.$path(input)).toBe('/search')1942  })19431944  it('Should omit the query delimiter when a custom serializer returns no values', async () => {1945    let requestedUrl = ''1946    const client = hc<typeof app>('http://localhost', {1947      buildSearchParams: () => new URLSearchParams(),1948      fetch: (input: RequestInfo | URL) => {1949        requestedUrl = input.toString()1950        return Promise.resolve(new Response('{}'))1951      },1952    })1953    const customInput = { query: { q: 'ignored' } }19541955    await client.search.$get(customInput)19561957    expect(requestedUrl).toBe('http://localhost/search')1958    expect(client.search.$url(customInput).href).toBe('http://localhost/search')1959    expect(client.search.$path(customInput)).toBe('/search')1960  })19611962  it('Should preserve empty-string query values', async () => {1963    let requestedUrl = ''1964    const client = hc<typeof app>('http://localhost', {1965      fetch: (input: RequestInfo | URL) => {1966        requestedUrl = input.toString()1967        return Promise.resolve(new Response('{}'))1968      },1969    })1970    const emptyStringInput = { query: { q: '' } }19711972    await client.search.$get(emptyStringInput)19731974    expect(requestedUrl).toBe('http://localhost/search?q=')1975    expect(client.search.$url(emptyStringInput).href).toBe('http://localhost/search?q=')1976    expect(client.search.$path(emptyStringInput)).toBe('/search?q=')1977  })1978})19791980describe('Custom buildSearchParams', () => {1981  const app = new Hono()1982  const route = app.get(1983    '/search',1984    validator('query', () => {1985      return {} as { q: string; tags: string[] }1986    }),1987    (c) => {1988      return c.json({1989        message: 'success',1990        queryString: '',1991      })1992    }1993  )19941995  type AppType = typeof route19961997  const server = setupServer(1998    http.get('http://localhost/search', ({ request }) => {1999      const url = new URL(request.url)2000      return HttpResponse.json({

The first 2,000 of 2,310 lines.