Merge pull request #1489 from honojs/next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parents d6478aa, 6c37462 · Browse files · 28 files·+601 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+601 added−51 removed
- tests:+255 added−13 removed
- other:+346 added−38 removed
Provenance
- Commit
3eb52bc- Tree
85d8fa0- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
d6478aa- Parent 2
6c37462
28 files changed+601 added−51 removed
modified:benchmarks/routers/src/bench.mts+2 added
3 unmodified lines4567891011126 unmodified lines19202122232425262759 unmodified lines3 unmodified linesimport { regExpRouter, trieRouter } from './hono.mts'import { koaRouter } from './koa-router.mts'import { koaTreeRouter } from './koa-tree-router.mts'import { medleyRouter } from './medley-router.mts'import { memoiristRouter } from './memoirist.mts'import { radix3Router } from './radix3.mts'import type { Route, RouterInterface } from './tool.mts'import { trekRouter } from './trek-router.mts'
6 unmodified lines trekRouter, expressRouter, koaRouter, radix3Router, memoiristRouter,]
medleyRouter.match({ method: 'GET', path: '/user' })
59 unmodified linesmodified:benchmarks/routers/src/hono.mts+1 added-1 removed
1123456713 unmodified linesimport type { Router } from '../../../src/router.ts'import { RegExpRouter } from '../../../src/router/reg-exp-router/index.ts'import { TrieRouter } from '../../../src/router/trie-router/index.ts'import type { Router } from '../../../src/router.ts'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const createHonoRouter = (name: string, router: Router<unknown>): RouterInterface => {13 unmodified linesadded:benchmarks/routers/src/memoirist.mts+17 added
1234567891011121314151617import { Memoirist } from 'memoirist'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const name = 'Memoirist'const router = new Memoirist()
for (const route of routes) { router.add(route.method, route.path, handler)}
export const memoiristRouter: RouterInterface = { name, match: (route) => { router.find(route.method, route.path) },}modified:benchmarks/routers/package.json+1 added
13 unmodified lines1415161718192021222313 unmodified lines "express": "^4.18.2", "find-my-way": "^7.4.0", "koa-router": "^12.0.0", "koa-tree-router": "^0.12.1", "memoirist": "^0.1.4", "mitata": "^0.1.6", "radix3": "^1.0.1", "trek-router": "^1.2.0" }}modified:deno_dist/client/client.ts+14 added-1 removed
1 import type { Hono } from '../hono.ts'2 import type { ValidationTargets } from '../types.ts'3+import { serialize } from '../utils/cookie.ts'4 import type { UnionToIntersection } from '../utils/types.ts'5 import type { Callback, Client, ClientRequestOptions } from './types.ts'6 import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils.ts'7 78 unmodified lines86 87 let methodUpperCase = this.method.toUpperCase()88 let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')89 89- const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}90+ const headerValues: Record<string, string> = {91+ ...(args?.header ?? {}),92+ ...(opt?.headers ? opt.headers : {}),93+ }94+95+ if (args?.cookie) {96+ const cookies: string[] = []97+ for (const [key, value] of Object.entries(args.cookie)) {98+ cookies.push(serialize(key, value, { path: '/' }))99+ }100+ headerValues['Cookie'] = cookies.join(',')101+ }102+103 if (this.cType) headerValues['Content-Type'] = this.cType104 105 const headers = new Headers(headerValues ?? undefined)106 let url = this.url49 unmodified linesmodified:deno_dist/client/types.ts+26 added-11 removed
2 unmodified lines3 import type { RemoveBlankRecord } from '../utils/types.ts'4 5 type HonoRequest = typeof Hono.prototype['request']6 7+export type ClientRequestOptions<T = unknown> = keyof T extends never7-export type ClientRequestOptions = {8- headers?: Record<string, string>9- fetch?: typeof fetch | HonoRequest10-}8+ ? {9+ headers?: Record<string, string>10+ fetch?: typeof fetch | HonoRequest11+ }12+ : {13+ headers: T14+ fetch?: typeof fetch | HonoRequest15+ }16 17 type ClientRequest<S extends Schema> = {18 [M in keyof S]: S[M] extends { input: infer R; output: infer O }19 ? RemoveBlankRecord<R> extends never20 ? (args?: {}, options?: ClientRequestOptions) => Promise<ClientResponse<O>>16- : (17- // Client does not support `header` and `cookie`18- args: Omit<R, 'header' | 'cookie'>,19- options?: ClientRequestOptions20- ) => Promise<ClientResponse<O>>21+ : (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>22 : never23 } & {24 $url: () => URL25 }27 unmodified lines53 ) => Promise<ClientResponse<InferResponseType<T>>>54 55 export type InferResponseType<T> = T extends (56 // eslint-disable-next-line @typescript-eslint/no-explicit-any56- args: any | undefined57+ args: any | undefined,58+ // eslint-disable-next-line @typescript-eslint/no-explicit-any59+ options: any | undefined60 ) => Promise<ClientResponse<infer O>>61 ? O62 : never63 61-export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>64+export type InferRequestType<T> = T extends (65+ args: infer R,66+ // eslint-disable-next-line @typescript-eslint/no-explicit-any67+ options: any | undefined68+) => Promise<ClientResponse<unknown>>69 ? NonNullable<R>70 : never71 72+export type InferRequestOptionsType<T> = T extends (73+ // eslint-disable-next-line @typescript-eslint/no-explicit-any74+ args: any,75+ options: infer R76+) => Promise<ClientResponse<unknown>>77+ ? NonNullable<R>78+ : never79+80 type PathToChain<81 Path extends string,82 E extends Schema,83 Original extends string = ''30 unmodified linesadded:deno_dist/helper/testing/index.ts+18 added
123456789101112131415161718import { hc } from '../../client/index.ts'import type { Hono } from '../../hono.ts'
// eslint-disable-next-line @typescript-eslint/no-explicit-anytype ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const testClient = <T extends Hono<any, any, any>>( app: T, Env?: ExtractEnv<T>['Bindings'] | {}, executionCtx?: ExecutionContext) => { const customFetch = (input: RequestInfo | URL, init?: RequestInit) => { return app.request(input, init, Env, executionCtx) }
return hc<typeof app>('', { fetch: customFetch })}modified:deno_dist/middleware/jwt/index.ts+4 added
75 unmodified lines76 77 await next()78 }79 }80+81+export const verify = Jwt.verify82+export const decode = Jwt.decode83+export const sign = Jwt.signmodified:deno_dist/utils/body.ts+12 added-2 removed
1 import type { HonoRequest } from '../request.ts'2 3-export type BodyData = Record<string, string | File>3+export type BodyData = Record<string, string | string[] | File>4 5 export const parseBody = async <T extends BodyData = BodyData>(6 request: HonoRequest | Request7 ): Promise<T> => {8 unmodified lines16 const formData = await request.formData()17 if (formData) {18 const form: BodyData = {}19 formData.forEach((value, key) => {20+ if (key.slice(-2) === '[]') {21+ if (!form[key]) {22+ form[key] = [value.toString()]23+ } else {24+ if (Array.isArray(form[key])) {25+ ;(form[key] as string[]).push(value.toString())26+ }27+ }28+ } else {20- form[key] = value29+ form[key] = value30+ }31 })32 body = form33 }34 }2 unmodified linesmodified:deno_dist/utils/cookie.ts+8 added-3 removed
9 unmodified lines10 path?: string11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14+ partitioned?: boolean15 }16 17 const algorithm = { name: 'HMAC', hash: 'SHA-256' }18 85 unmodified lines104 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`105 }106 107 if (opt.domain) {107- cookie += '; Domain=' + opt.domain108+ cookie += `; Domain=${opt.domain}`109 }110 111 if (opt.path) {111- cookie += '; Path=' + opt.path112+ cookie += `; Path=${opt.path}`113 }114 115 if (opt.expires) {115- cookie += '; Expires=' + opt.expires.toUTCString()116+ cookie += `; Expires=${opt.expires.toUTCString()}`117 }118 119 if (opt.httpOnly) {120 cookie += '; HttpOnly'6 unmodified lines127 if (opt.sameSite) {128 cookie += `; SameSite=${opt.sameSite}`129 }130 131+ if (opt.partitioned) {132+ cookie += '; Partitioned'133+ }134+135 return cookie136 }137 138 export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {15 unmodified linesadded:deno_dist/utils/stream.ts+46 added
1+export class StreamingApi {2+ private writer: WritableStreamDefaultWriter<Uint8Array>3+ private encoder: TextEncoder4+ private writable: WritableStream5+6+ constructor(writable: WritableStream) {7+ this.writable = writable8+ this.writer = writable.getWriter()9+ this.encoder = new TextEncoder()10+ }11+12+ async write(input: Uint8Array | string) {13+ try {14+ if (typeof input === 'string') {15+ input = this.encoder.encode(input)16+ }17+ await this.writer.write(input)18+ } catch (e) {19+ // Do nothing. If you want to handle errors, create a stream by yourself.20+ }21+ return this22+ }23+24+ async writeln(input: string) {25+ await this.write(input + '\n')26+ return this27+ }28+29+ sleep(ms: number) {30+ return new Promise((res) => setTimeout(res, ms))31+ }32+33+ async close() {34+ try {35+ await this.writer.close()36+ } catch (e) {37+ // Do nothing. If you want to handle errors, create a stream by yourself.38+ }39+ }40+41+ async pipe(body: ReadableStream) {42+ this.writer.releaseLock()43+ await body.pipeTo(this.writable, { preventClose: true })44+ this.writer = this.writable.getWriter()45+ }46+}modified:deno_dist/context.ts+30 added-1 removed
2 unmodified lines3 import type { Env, NotFoundHandler, Input, TypedResponse } from './types.ts'4 import type { CookieOptions } from './utils/cookie.ts'5 import { serialize } from './utils/cookie.ts'6 import type { StatusCode } from './utils/http-status.ts'7+import { StreamingApi } from './utils/stream.ts'8 import type { JSONValue, InterfaceToType } from './utils/types.ts'9 10 type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'11 type HeaderRecord = Record<string, string | string[]>73 unmodified lines85 executionCtx?: FetchEventLike | ExecutionContext | undefined86 notFoundHandler?: NotFoundHandler<E>87 }88 89+const TEXT_PLAIN = 'text/plain; charset=UTF-8'90+91 export class Context<92 // eslint-disable-next-line @typescript-eslint/no-explicit-any93 E extends Env = any,94 // eslint-disable-next-line @typescript-eslint/no-explicit-any217 unmodified lines312 }313 // If Content-Type is not set, we don't have to set `text/plain`.314 // Fewer the header values, it will be faster.315 if (this._pH['content-type']) {313- this._pH['content-type'] = 'text/plain; charset=UTF-8'316+ this._pH['content-type'] = TEXT_PLAIN317 }318 return typeof arg === 'number'319 ? this.newResponse(text, arg, headers)320 : this.newResponse(text, arg)52 unmodified lines373 this._h.set('Location', location)374 return this.newResponse(null, status)375 }376 377+ streamText = (378+ cb: (stream: StreamingApi) => Promise<void>,379+ arg?: StatusCode | ResponseInit,380+ headers?: HeaderRecord381+ ): Response => {382+ headers ??= {}383+ this.header('content-type', TEXT_PLAIN)384+ this.header('x-content-type-options', 'nosniff')385+ this.header('transfer-encoding', 'chunked')386+ return this.stream(cb, arg, headers)387+ }388+389+ stream = (390+ cb: (stream: StreamingApi) => Promise<void>,391+ arg?: StatusCode | ResponseInit,392+ headers?: HeaderRecord393+ ): Response => {394+ const { readable, writable } = new TransformStream()395+ const stream = new StreamingApi(writable)396+ cb(stream).finally(() => stream.close())397+398+ return typeof arg === 'number'399+ ? this.newResponse(readable, arg, headers)400+ : this.newResponse(readable, arg)401+ }402+403 /** @deprecated404 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.405 *406 * @example66 unmodified linesmodified:src/client/client.test.ts+102 added-9 removed
5 unmodified lines6 import { setupServer } from 'msw/node'7 import _fetch, { Request as NodeFetchRequest } from 'node-fetch'8 import { vi } from 'vitest'9 import { Hono } from '../hono'10+import { parse, serialize } from '../utils/cookie'11 import type { Equal, Expect } from '../utils/types'12 import { validator } from '../validator'13 import { hc } from './client'13-import type { InferRequestType, InferResponseType } from './types'14+import type { InferRequestOptionsType, InferRequestType, InferResponseType } from './types'15 16 // @ts-ignore17 global.fetch = _fetch18 // @ts-ignore6 unmodified lines25 26 const route = app27 .post(28 '/posts',28- // Client does not support `cookie`29 validator('cookie', () => {30 return {} as {31 debug: string32 }33 }),34- // Client does not support `header`34 validator('header', () => {35 return {} as {37- 'x-request-id': string36+ 'x-message': string37 }38 }),39 validator('json', () => {40 return {} as {54 unmodified lines95 it('Should get 200 response', async () => {96 const res = await client.posts.$post(97 {98 json: payload,100- },101- {102- headers: {99+ header: {100 'x-message': 'foobar',101 },105- }102+ cookie: {103+ debug: 'true',104+ },105+ },106+ {}107 )108 109 expect(res.ok).toBe(true)110 const data = await res.json()10 unmodified lines121 expect(res.status).toBe(404)122 })123 })124 124-describe('Basic - query, queries, form, and path params', () => {125+describe('Basic - query, queries, form, path params, header and cookie', () => {126 const app = new Hono()127 128 const route = app129 .get(32 unmodified lines162 const data = c.req.valid('form')163 return c.jsonT(data)164 }165 )166+ .get(167+ '/header',168+ validator('header', () => {169+ return {170+ 'x-message-id': 'Hello',171+ }172+ }),173+ (c) => {174+ const data = c.req.valid('header')175+ return c.jsonT(data)176+ }177+ )178+ .get(179+ '/cookie',180+ validator('cookie', () => {181+ return {182+ hello: 'world',183+ }184+ }),185+ (c) => {186+ const data = c.req.valid('cookie')187+ return c.jsonT(data)188+ }189+ )190 191 const server = setupServer(192 rest.get('http://localhost/api/search', (req, res, ctx) => {193 const url = new URL(req.url)23 unmodified lines217 const buffer = await req.arrayBuffer()218 // @ts-ignore219 const string = String.fromCharCode.apply('', new Uint8Array(buffer))220 return res(ctx.status(200), ctx.text(string))221+ }),222+ rest.get('http://localhost/api/header', async (req, res, ctx) => {223+ const message = await req.headers.get('x-message-id')224+ return res(ctx.status(200), ctx.json({ 'x-message-id': message }))225+ }),226+227+ rest.get('http://localhost/api/cookie', async (req, res, ctx) => {228+ const obj = parse(req.headers.get('cookie') || '')229+ const value = obj['hello']230+ return res(ctx.status(200), ctx.json({ hello: value }))231 })232 )233 234 beforeAll(() => server.listen())47 unmodified lines282 283 expect(res.status).toBe(200)284 expect(await res.text()).toMatch('Good Night')285 })286+287+ it('Should get 200 response - header', async () => {288+ const header = {289+ 'x-message-id': 'Hello',290+ }291+ const res = await client.header.$get({292+ header,293+ })294+295+ expect(res.status).toBe(200)296+ expect(await res.json()).toEqual(header)297+ })298+299+ it('Should get 200 response - cookie', async () => {300+ const cookie = {301+ hello: 'world',302+ }303+ const res = await client.cookie.$get({304+ cookie,305+ })306+307+ expect(res.status).toBe(200)308+ expect(await res.json()).toEqual(cookie)309+ })310 })311 312 describe('Infer the response/request type', () => {313 const app = new Hono()4 unmodified lines318 name: 'dummy',319 age: 'dummy',320 }321 }),322+ validator('header', () => {323+ return {324+ 'x-request-id': 'dummy',325+ }326+ }),327+ validator('cookie', () => {328+ return {329+ name: 'dummy',330+ }331+ }),332 (c) =>333 c.jsonT({334 id: 123,335 title: 'Morning!',25 unmodified lines361 }362 type verify = Expect<Equal<Expected, Actual['query']>>363 })364 365+ it('Should infer request header type the type correctly', () => {366+ const client = hc<AppType>('/')367+ const req = client.index.$get368+ type c = typeof req369+370+ type Actual = InferRequestType<c>371+ type Expected = {372+ 'x-request-id': string373+ }374+ type verify = Expect<Equal<Expected, Actual['header']>>375+ })376+377+ it('Should infer request cookie type the type correctly', () => {378+ const client = hc<AppType>('/')379+ const req = client.index.$get380+ type c = typeof req381+382+ type Actual = InferRequestType<c>383+ type Expected = {384+ name: string385+ }386+ type verify = Expect<Equal<Expected, Actual['cookie']>>387+ })388+389 describe('Without input', () => {390 const route = app.get('/', (c) => c.jsonT({ ok: true }))391 type AppType = typeof route392 183 unmodified linesmodified:src/client/client.ts+14 added-1 removed
1 import type { Hono } from '../hono'2 import type { ValidationTargets } from '../types'3+import { serialize } from '../utils/cookie'4 import type { UnionToIntersection } from '../utils/types'5 import type { Callback, Client, ClientRequestOptions } from './types'6 import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'7 78 unmodified lines86 87 let methodUpperCase = this.method.toUpperCase()88 let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')89 89- const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}90+ const headerValues: Record<string, string> = {91+ ...(args?.header ?? {}),92+ ...(opt?.headers ? opt.headers : {}),93+ }94+95+ if (args?.cookie) {96+ const cookies: string[] = []97+ for (const [key, value] of Object.entries(args.cookie)) {98+ cookies.push(serialize(key, value, { path: '/' }))99+ }100+ headerValues['Cookie'] = cookies.join(',')101+ }102+103 if (this.cType) headerValues['Content-Type'] = this.cType104 105 const headers = new Headers(headerValues ?? undefined)106 let url = this.url49 unmodified linesmodified:src/client/types.ts+26 added-11 removed
2 unmodified lines3 import type { RemoveBlankRecord } from '../utils/types'4 5 type HonoRequest = typeof Hono.prototype['request']6 7+export type ClientRequestOptions<T = unknown> = keyof T extends never7-export type ClientRequestOptions = {8- headers?: Record<string, string>9- fetch?: typeof fetch | HonoRequest10-}8+ ? {9+ headers?: Record<string, string>10+ fetch?: typeof fetch | HonoRequest11+ }12+ : {13+ headers: T14+ fetch?: typeof fetch | HonoRequest15+ }16 17 type ClientRequest<S extends Schema> = {18 [M in keyof S]: S[M] extends { input: infer R; output: infer O }19 ? RemoveBlankRecord<R> extends never20 ? (args?: {}, options?: ClientRequestOptions) => Promise<ClientResponse<O>>16- : (17- // Client does not support `header` and `cookie`18- args: Omit<R, 'header' | 'cookie'>,19- options?: ClientRequestOptions20- ) => Promise<ClientResponse<O>>21+ : (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>22 : never23 } & {24 $url: () => URL25 }27 unmodified lines53 ) => Promise<ClientResponse<InferResponseType<T>>>54 55 export type InferResponseType<T> = T extends (56 // eslint-disable-next-line @typescript-eslint/no-explicit-any56- args: any | undefined57+ args: any | undefined,58+ // eslint-disable-next-line @typescript-eslint/no-explicit-any59+ options: any | undefined60 ) => Promise<ClientResponse<infer O>>61 ? O62 : never63 61-export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>64+export type InferRequestType<T> = T extends (65+ args: infer R,66+ // eslint-disable-next-line @typescript-eslint/no-explicit-any67+ options: any | undefined68+) => Promise<ClientResponse<unknown>>69 ? NonNullable<R>70 : never71 72+export type InferRequestOptionsType<T> = T extends (73+ // eslint-disable-next-line @typescript-eslint/no-explicit-any74+ args: any,75+ options: infer R76+) => Promise<ClientResponse<unknown>>77+ ? NonNullable<R>78+ : never79+80 type PathToChain<81 Path extends string,82 E extends Schema,83 Original extends string = ''30 unmodified linesmodified:src/helper/cookie/index.test.ts+1 added-1 removed
242 unmodified lines243 deleteCookie(c, 'delicious_cookie2')244 return c.text('Give cookie')245 })246 247- it('Delete multile cookies', async () => {247+ it('Delete multiple cookies', async () => {248 const res2 = await app.request('http://localhost/delete-cookie-multiple')249 expect(res2.status).toBe(200)250 const header2 = res2.headers.get('Set-Cookie')251 expect(header2).toBe('delicious_cookie=; Max-Age=0, delicious_cookie2=; Max-Age=0')19 unmodified linesadded:src/helper/testing/index.test.ts+19 added
1+import { Hono } from '../../hono'2+import { testClient } from '.'3+4+describe('hono testClinet', () => {5+ it('should return the correct search result', async () => {6+ const app = new Hono().get('/search', (c) => c.jsonT({ hello: 'world' }))7+ const res = await testClient(app).search.$get()8+ expect(await res.json()).toEqual({ hello: 'world' })9+ })10+11+ it('should return the correct environment variables value', async () => {12+ type Bindings = { hello: string }13+ const app = new Hono<{ Bindings: Bindings }>().get('/search', (c) => {14+ return c.jsonT({ hello: c.env.hello })15+ })16+ const res = await testClient(app, { hello: 'world' }).search.$get()17+ expect(await res.json()).toEqual({ hello: 'world' })18+ })19+})added:src/helper/testing/index.ts+18 added
1+import { hc } from '../../client'2+import type { Hono } from '../../hono'3+4+// eslint-disable-next-line @typescript-eslint/no-explicit-any5+type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never6+7+// eslint-disable-next-line @typescript-eslint/no-explicit-any8+export const testClient = <T extends Hono<any, any, any>>(9+ app: T,10+ Env?: ExtractEnv<T>['Bindings'] | {},11+ executionCtx?: ExecutionContext12+) => {13+ const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {14+ return app.request(input, init, Env, executionCtx)15+ }16+17+ return hc<typeof app>('', { fetch: customFetch })18+}modified:src/middleware/jwt/index.ts+4 added
75 unmodified lines76 77 await next()78 }79 }80+81+export const verify = Jwt.verify82+export const decode = Jwt.decode83+export const sign = Jwt.signmodified:src/utils/body.test.ts+3 added-1 removed
2 unmodified lines3 describe('Parse Body Util', () => {4 it('should parse `multipart/form-data`', async () => {5 const data = new FormData()6 data.append('message', 'hello')7+ data.append('multi[]', 'foo')8+ data.append('multi[]', 'bar')9 const req = new Request('https://localhost/form', {10 method: 'POST',11 body: data,12 // `Content-Type` header must not be set.13 })12- expect(await parseBody(req)).toEqual({ message: 'hello' })14+ expect(await parseBody(req)).toEqual({ message: 'hello', 'multi[]': ['foo', 'bar'] })15 })16 17 it('should parse `x-www-form-urlencoded`', async () => {18 const searchParams = new URLSearchParams()21 unmodified linesmodified:src/utils/body.ts+12 added-2 removed
1 import type { HonoRequest } from '../request'2 3-export type BodyData = Record<string, string | File>3+export type BodyData = Record<string, string | string[] | File>4 5 export const parseBody = async <T extends BodyData = BodyData>(6 request: HonoRequest | Request7 ): Promise<T> => {8 unmodified lines16 const formData = await request.formData()17 if (formData) {18 const form: BodyData = {}19 formData.forEach((value, key) => {20+ if (key.slice(-2) === '[]') {21+ if (!form[key]) {22+ form[key] = [value.toString()]23+ } else {24+ if (Array.isArray(form[key])) {25+ ;(form[key] as string[]).push(value.toString())26+ }27+ }28+ } else {20- form[key] = value29+ form[key] = value30+ }31 })32 body = form33 }34 }2 unmodified linesmodified:src/utils/cookie.test.ts+4 added-2 removed
160 unmodified lines161 httpOnly: true,162 maxAge: 1000,163 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),164 sameSite: 'Strict',165+ partitioned: true,166 })167 expect(serialized).toBe(167- 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'168+ 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'169 )170 })171 172 it('Should serialize a signed cookie', async () => {13 unmodified lines186 httpOnly: true,187 maxAge: 1000,188 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),189 sameSite: 'Strict',190+ partitioned: true,191 })192 expect(serialized).toBe(191- 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'193+ 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'194 )195 })196 197 it('Should serialize cookie with maxAge is 0', () => {13 unmodified linesmodified:src/utils/cookie.ts+8 added-3 removed
9 unmodified lines10 path?: string11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14+ partitioned?: boolean15 }16 17 const algorithm = { name: 'HMAC', hash: 'SHA-256' }18 85 unmodified lines104 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`105 }106 107 if (opt.domain) {107- cookie += '; Domain=' + opt.domain108+ cookie += `; Domain=${opt.domain}`109 }110 111 if (opt.path) {111- cookie += '; Path=' + opt.path112+ cookie += `; Path=${opt.path}`113 }114 115 if (opt.expires) {115- cookie += '; Expires=' + opt.expires.toUTCString()116+ cookie += `; Expires=${opt.expires.toUTCString()}`117 }118 119 if (opt.httpOnly) {120 cookie += '; HttpOnly'6 unmodified lines127 if (opt.sameSite) {128 cookie += `; SameSite=${opt.sameSite}`129 }130 131+ if (opt.partitioned) {132+ cookie += '; Partitioned'133+ }134+135 return cookie136 }137 138 export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {15 unmodified linesadded:src/utils/stream.test.ts+85 added
1+import { StreamingApi } from './stream'2+3+describe('StreamingApi', () => {4+ it('write(string)', async () => {5+ const { readable, writable } = new TransformStream()6+ const api = new StreamingApi(writable)7+ const reader = readable.getReader()8+ api.write('foo')9+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))10+ api.write('bar')11+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))12+ })13+14+ it('write(Uint8Array)', async () => {15+ const { readable, writable } = new TransformStream()16+ const api = new StreamingApi(writable)17+ const reader = readable.getReader()18+ api.write(new Uint8Array([1, 2, 3]))19+ expect((await reader.read()).value).toEqual(new Uint8Array([1, 2, 3]))20+ api.write(new Uint8Array([4, 5, 6]))21+ expect((await reader.read()).value).toEqual(new Uint8Array([4, 5, 6]))22+ })23+24+ it('writeln(string)', async () => {25+ const { readable, writable } = new TransformStream()26+ const api = new StreamingApi(writable)27+ const reader = readable.getReader()28+ api.writeln('foo')29+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo\n'))30+ api.writeln('bar')31+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar\n'))32+ })33+34+ it('pipe()', async () => {35+ const { readable: senderReadable, writable: senderWritable } = new TransformStream()36+37+ // send data to readable in other scope38+ ;(async () => {39+ const writer = senderWritable.getWriter()40+ await writer.write(new TextEncoder().encode('foo'))41+ await writer.write(new TextEncoder().encode('bar'))42+ // await writer.close()43+ })()44+45+ const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()46+47+ const api = new StreamingApi(receiverWritable)48+49+ // pipe readable to api in other scope50+ ;(async () => {51+ await api.pipe(senderReadable)52+ })()53+54+ // read data from api55+ const reader = receiverReadable.getReader()56+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))57+ expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))58+ })59+60+ it('close()', async () => {61+ const { readable, writable } = new TransformStream()62+ const api = new StreamingApi(writable)63+ const reader = readable.getReader()64+ await api.close()65+ expect((await reader.read()).done).toBe(true)66+ })67+68+ it('should not throw an error in write()', async () => {69+ const { writable } = new TransformStream()70+ const api = new StreamingApi(writable)71+ await api.close()72+ const write = () => api.write('foo')73+ expect(write).not.toThrow()74+ })75+76+ it('should not throw an error in close()', async () => {77+ const { writable } = new TransformStream()78+ const api = new StreamingApi(writable)79+ const close = async () => {80+ await api.close()81+ await api.close()82+ }83+ expect(close).not.toThrow()84+ })85+})added:src/utils/stream.ts+46 added
1+export class StreamingApi {2+ private writer: WritableStreamDefaultWriter<Uint8Array>3+ private encoder: TextEncoder4+ private writable: WritableStream5+6+ constructor(writable: WritableStream) {7+ this.writable = writable8+ this.writer = writable.getWriter()9+ this.encoder = new TextEncoder()10+ }11+12+ async write(input: Uint8Array | string) {13+ try {14+ if (typeof input === 'string') {15+ input = this.encoder.encode(input)16+ }17+ await this.writer.write(input)18+ } catch (e) {19+ // Do nothing. If you want to handle errors, create a stream by yourself.20+ }21+ return this22+ }23+24+ async writeln(input: string) {25+ await this.write(input + '\n')26+ return this27+ }28+29+ sleep(ms: number) {30+ return new Promise((res) => setTimeout(res, ms))31+ }32+33+ async close() {34+ try {35+ await this.writer.close()36+ } catch (e) {37+ // Do nothing. If you want to handle errors, create a stream by yourself.38+ }39+ }40+41+ async pipe(body: ReadableStream) {42+ this.writer.releaseLock()43+ await body.pipeTo(this.writable, { preventClose: true })44+ this.writer = this.writable.getWriter()45+ }46+}modified:src/context.test.ts+41 added
259 unmodified lines260 const res = c.html('<h1>foo</h1>', originalResponse)261 expect(res.headers.get('content-type')).toMatch(/^text\/html/)262 expect(await res.text()).toBe('<h1>foo</h1>')263 })264+265+ it('c.streamText()', async () => {266+ const res = c.streamText(async (stream) => {267+ for (let i = 0; i < 3; i++) {268+ await stream.write(`${i}`)269+ await stream.sleep(1)270+ }271+ })272+273+ expect(res.status).toBe(200)274+ expect(res.headers.get('content-type')).toMatch(/^text\/plain/)275+ expect(res.headers.get('x-content-type-options')).toBe('nosniff')276+ expect(res.headers.get('transfer-encoding')).toBe('chunked')277+278+ if (!res.body) {279+ throw new Error('Body is null')280+ }281+ const reader = res.body.getReader()282+ const decoder = new TextDecoder()283+ for (let i = 0; i < 3; i++) {284+ const { value } = await reader.read()285+ expect(decoder.decode(value)).toEqual(`${i}`)286+ }287+ })288+289+ it('c.stream()', async () => {290+ const res = c.stream(async (stream) => {291+ for (let i = 0; i < 3; i++) {292+ await stream.write(new Uint8Array([i]))293+ await stream.sleep(1)294+ }295+ })296+ if (!res.body) {297+ throw new Error('Body is null')298+ }299+ const reader = res.body.getReader()300+ for (let i = 0; i < 3; i++) {301+ const { value } = await reader.read()302+ expect(value).toEqual(new Uint8Array([i]))303+ }304+ })305 })306 307 declare module './context' {308 interface ContextRenderer {28 unmodified linesmodified:src/context.ts+30 added-1 removed
2 unmodified lines3 import type { Env, NotFoundHandler, Input, TypedResponse } from './types'4 import type { CookieOptions } from './utils/cookie'5 import { serialize } from './utils/cookie'6 import type { StatusCode } from './utils/http-status'7+import { StreamingApi } from './utils/stream'8 import type { JSONValue, InterfaceToType } from './utils/types'9 10 type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'11 type HeaderRecord = Record<string, string | string[]>73 unmodified lines85 executionCtx?: FetchEventLike | ExecutionContext | undefined86 notFoundHandler?: NotFoundHandler<E>87 }88 89+const TEXT_PLAIN = 'text/plain; charset=UTF-8'90+91 export class Context<92 // eslint-disable-next-line @typescript-eslint/no-explicit-any93 E extends Env = any,94 // eslint-disable-next-line @typescript-eslint/no-explicit-any217 unmodified lines312 }313 // If Content-Type is not set, we don't have to set `text/plain`.314 // Fewer the header values, it will be faster.315 if (this._pH['content-type']) {313- this._pH['content-type'] = 'text/plain; charset=UTF-8'316+ this._pH['content-type'] = TEXT_PLAIN317 }318 return typeof arg === 'number'319 ? this.newResponse(text, arg, headers)320 : this.newResponse(text, arg)52 unmodified lines373 this._h.set('Location', location)374 return this.newResponse(null, status)375 }376 377+ streamText = (378+ cb: (stream: StreamingApi) => Promise<void>,379+ arg?: StatusCode | ResponseInit,380+ headers?: HeaderRecord381+ ): Response => {382+ headers ??= {}383+ this.header('content-type', TEXT_PLAIN)384+ this.header('x-content-type-options', 'nosniff')385+ this.header('transfer-encoding', 'chunked')386+ return this.stream(cb, arg, headers)387+ }388+389+ stream = (390+ cb: (stream: StreamingApi) => Promise<void>,391+ arg?: StatusCode | ResponseInit,392+ headers?: HeaderRecord393+ ): Response => {394+ const { readable, writable } = new TransformStream()395+ const stream = new StreamingApi(writable)396+ cb(stream).finally(() => stream.close())397+398+ return typeof arg === 'number'399+ ? this.newResponse(readable, arg, headers)400+ : this.newResponse(readable, arg)401+ }402+403 /** @deprecated404 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.405 *406 * @example66 unmodified linesmodified:package.json+9 added-1 removed
1 {2 "name": "hono",3- "version": "3.6.3",3+ "version": "3.7.0-rc.1",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",224 unmodified lines232 "./lambda-edge": {233 "types": "./dist/types/adapter/lambda-edge/index.d.ts",234 "import": "./dist/adapter/lambda-edge/index.js",235 "require": "./dist/cjs/adapter/lambda-edge/index.js"236+ },237+ "./testing": {238+ "types": "./dist/types/helper/testing/index.d.ts",239+ "import": "./dist/helper/testing/index.js",240+ "require": "./dist/cjs/helper/testing/index.js"241 }242 },243 "typesVersions": {244 "*": {112 unmodified lines357 "./dist/types/adapter/vercel"358 ],359 "lambda-edge": [360 "./dist/types/adapter/lambda-edge"361+ ],362+ "testing": [363+ "./dist/types/helper/testing"364 ]365 }366 },367 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",75 unmodified lines