Skip to content
Myr

Merge pull request #5154 from honojs/next

Before adoption: this commit came in with the history the project adopted, so no landing records it.

next

authored by Yusuke Wada · committed by Yusuke Wada · parents 734755a, 8f07028 · Browse files · 41 files+2061 added−348 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

41 files+2061 added−348 removed

  • tests:+1369 added−44 removed
  • other:+692 added−304 removed

41 files+2061 added−348 removed

modified:benchmarks/fetch/bench.mts+41 added-12 removed
modified:src/client/types.test.ts+1 added
115 unmodified lines
116 expectTypeOf(client['all-route']).toHaveProperty('$put')117 expectTypeOf(client['all-route']).toHaveProperty('$delete')118 expectTypeOf(client['all-route']).toHaveProperty('$options')119 expectTypeOf(client['all-route']).toHaveProperty('$patch')120 expectTypeOf(client['all-route']).toHaveProperty('$query')121 })122123 it('should have correct return type for expanded methods', async () => {124 // The response type should match the original handler's return type
22 unmodified lines
modified:src/client/types.ts+1 added-1 removed
10 unmodified lines
11type MethodNameAll = `$${typeof METHOD_NAME_ALL_LOWERCASE}`1213/**14 * Type representing all standard HTTP methods prefixed with '$'15 * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch'15 * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch' | '$query'16 */17type StandardMethods = `$${(typeof METHODS)[number]}`1819/**
374 unmodified lines
modified:src/jsx/dom/intrinsic-element/components.ts+3 added-3 removed
20 unmodified lines
21}2223// this function is exported for testing and should not be used by the user24export const composeRef = <T>(25 ref: RefObject<T> | Function | undefined,25 ref: RefObject<T | null> | Function | undefined,26 cb: (e: T) => void | (() => void)27): ((e: T) => () => void) => {28 return useMemo(29 () => (e: T) => {
289 unmodified lines
319export const form: FC<320 PropsWithChildren<{321 action?: Function | string322 method?: 'get' | 'post'323 ref?: RefObject<HTMLFormElement> | ((e: HTMLFormElement | null) => void | (() => void))323 ref?: RefObject<HTMLFormElement | null> | ((e: HTMLFormElement | null) => void | (() => void))324 }>325> = (props) => {326 const { action, ...restProps } = props327 if (typeof action !== 'function') {
63 unmodified lines
391 formAction,392 ...props393 }: {394 formAction?: Function | string395 ref?: RefObject<HTMLInputElement> | ((e: HTMLInputElement) => void | (() => void))395 ref?: RefObject<HTMLInputElement | null> | ((e: HTMLInputElement) => void | (() => void))396 }397) => {398 if (typeof formAction === 'function') {399 const onClick = useCallback<(ev: MouseEvent) => void>((ev: MouseEvent) => {
39 unmodified lines
modified:src/jsx/dom/index.test.tsx+53 added-4 removed
372 unmodified lines
373 expect(root.innerHTML).toBe('<div>2</div><div>1</div><button>+</button>')374 expect(Child).toBeCalledTimes(3)375 })376377 it('returning an array', async () => {378 const App = () => {379 const [count, setCount] = useState(0)380 return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]381 }382 render(<App />, root)383 expect(root.innerHTML).toBe('<div>0</div><button>+</button>')384 root.querySelector('button')?.click()385 await Promise.resolve()386 expect(root.innerHTML).toBe('<div>1</div><button>+</button>')387 })388389 it('typed as FC returning an array', async () => {390 const App: FC = () => {391 const [count, setCount] = useState(0)392 return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]393 }394 render(<App />, root)395 expect(root.innerHTML).toBe('<div>0</div><button>+</button>')396 root.querySelector('button')?.click()397 await Promise.resolve()398 expect(root.innerHTML).toBe('<div>1</div><button>+</button>')399 })400401 it('multiple children', async () => {402 const Child = ({ name }: { name: string }) => {403 const [count, setCount] = useState(0)404 return (
1523 unmodified lines
1928 })1929 })19301931 describe('useRef', async () => {1932 it('types: non-null initial value returns RefObject<T>', () => {1933 const ref = useRef(new Map<string, number>())1934 // .current is non-nullable; this line would not type-check without the overload1935 ref.current.set('a', 1)1936 expect(ref.current.get('a')).toBe(1)1937 })19381939 it('types: null initial value returns RefObject<T | null>', () => {1940 const ref = useRef<HTMLDivElement>(null)1941 expect(ref.current).toBeNull()1942 })19431944 it('types: undefined initial value returns RefObject<T | undefined>', () => {1945 const ref = useRef<number>(undefined)1946 expect(ref.current).toBeUndefined()1947 ref.current = 11948 expect(ref.current).toBe(1)1949 })19501951 it('simple', async () => {1909 const Input = ({ label, ref }: { label: string; ref: RefObject<HTMLInputElement> }) => {1952 const Input = ({1953 label,1954 ref,1955 }: {1956 label: string1957 ref: RefObject<HTMLInputElement | null>1958 }) => {1959 return (1960 <div>1961 <label>{label}</label>1962 <input ref={ref} />
100 unmodified lines
2063 expect(root.innerHTML).toBe('<div>2</div>')2064 })20652066 it('cleanup', async () => {2018 const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2067 const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2068 useEffect(() => {2069 return () => {2070 parent.current?.setAttribute('data-cleanup', 'true')2071 }
91 unmodified lines
2163 expect(root.innerHTML).toBe('<div>2</div>')2164 })21652166 it('cleanup', async () => {2118 const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2167 const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2168 useLayoutEffect(() => {2169 return () => {2170 parent.current?.setAttribute('data-cleanup', 'true')2171 }
105 unmodified lines
2277 expect(root.innerHTML).toBe('<div>useInsertionEffect,useLayoutEffect</div>')2278 })22792280 it('cleanup', async () => {2232 const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2281 const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2282 useInsertionEffect(() => {2283 return () => {2284 parent.current?.setAttribute('data-cleanup', 'true')2285 }
663 unmodified lines
modified:src/jsx/dom/render.ts+1 added-1 removed
282 unmodified lines
283 ...node.props,284 }285 : node.props286 try {287 return [func.call(null, props)]287 return [func.call(null, props) as Child]288 } finally {289 buildDataStack.pop()290 }291}
534 unmodified lines
modified:src/jsx/hooks/index.ts+11 added-7 removed
313 unmodified lines
314 }315 return callback316}317318export type RefObject<T> = { current: T | null }319export const useRef = <T>(initialValue: T | null): RefObject<T> => {318export type RefObject<T> = { current: T }319320export function useRef<T>(initialValue: T): RefObject<T>321export function useRef<T>(initialValue: T | null): RefObject<T | null>322export function useRef<T>(initialValue: T | undefined): RefObject<T | undefined>323export function useRef<T>(initialValue?: T | null): RefObject<T | null | undefined> {324 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]325 if (!buildData) {322 return { current: initialValue }326 return { current: initialValue } as RefObject<T | null | undefined>327 }328 const [, node] = buildData329330 const refArray = (node[DOM_STASH][1][STASH_REF] ||= [])
40 unmodified lines
371372// Define to avoid errors. This hook currently does nothing.373export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}374371export const createRef = <T>(): RefObject<T> => {375export const createRef = <T>(): RefObject<T | null> => {376 return { current: null }377}378379export const forwardRef = <T, P = {}>(376 Component: (props: P, ref?: RefObject<T>) => JSX.Element377): ((props: P & { ref?: RefObject<T> }) => JSX.Element) => {380 Component: (props: P, ref?: RefObject<T | null>) => JSX.Element381): ((props: P & { ref?: RefObject<T | null> }) => JSX.Element) => {382 return (props) => {383 const { ref, ...rest } = props384 return Component(rest as P, ref)385 }386}387388export const useImperativeHandle = <T>(385 ref: RefObject<T>,389 ref: RefObject<T | null>,390 createHandle: () => T,391 deps: readonly unknown[]392): void => {393 useEffect(() => {
44 unmodified lines
modified:src/jsx/intrinsic-element/components.test.tsx+18 added
1/** @jsxImportSource ../ */2import { useActionState } from '../'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'45describe('intrinsic element', () => {6 describe('document metadata', () => {7 describe('title element', () => {
10 unmodified lines
18 expect(template.toString()).toBe(19 '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'20 )21 })2223 it('should hoist a title from an async component array', async () => {24 const Metadata = async () => [<title>Hello</title>]25 const template = (26 <html>27 <head></head>28 <body>29 <Metadata />30 <h1>World</h1>31 </body>32 </html>33 )34 const rendered = await template.toString()35 expect(await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})).toBe(36 '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'37 )38 })39 })4041 describe('link element', () => {42 it('should be hoisted link tag', async () => {
562 unmodified lines
modified:src/jsx/base.ts+41 added-18 removed
23 unmodified lines
24} from './utils'2526// eslint-disable-next-line @typescript-eslint/no-explicit-any27export type Props = Record<string, any>28type FunctionComponentResult =29 | HtmlEscapedString30 | Child[]31 | Promise<HtmlEscapedString | Child[]>32 | null33export type FC<P = Props> = {29 (props: P): HtmlEscapedString | Promise<HtmlEscapedString> | null34 (props: P): FunctionComponentResult35 defaultProps?: Partial<P> | undefined36 displayName?: string | undefined37}38export type DOMAttributes = HonoJSX.HTMLAttributes3940// eslint-disable-next-line @typescript-eslint/no-namespace41export namespace JSX {42 export type Element = HtmlEscapedString | Promise<HtmlEscapedString>43 export type ElementType = string | ((props: never) => FunctionComponentResult)44 export interface ElementChildrenAttribute {45 children: Child46 }47 export interface IntrinsicElements extends IntrinsicElementsDefined {
62 unmodified lines
110 'reversed',111 'selected',112]113114type SuspendedContext = <T>(callback: () => T) => T115116const resolveFunctionComponentResult = (117 result: Promise<string | JSXNode | Child[]>,118 suspendedContext?: SuspendedContext119): Promise<string> =>120 result.then((resolved) => {121 if (!Array.isArray(resolved) && !(resolved instanceof JSXNode)) {122 return resolved123 }124 const children = Array.isArray(resolved) ? resolved : [resolved]125 const render = () => {126 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks127 childrenToStringToBuffer(children, buffer)128 return buffer.length === 1129 ? raw(buffer[0], buffer.callbacks)130 : stringBufferToString(buffer, buffer.callbacks)131 }132 return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)133 })134135const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {136 for (let i = 0, len = children.length; i < len; i++) {137 const child = children[i]138 if (typeof child === 'string') {
1 unmodified line
140 } else if (typeof child === 'boolean' || child === null || child === undefined) {141 continue142 } else if (child instanceof JSXNode) {143 child.toStringToBuffer(buffer)117 } else if (118 typeof child === 'number' ||119 (child as unknown as { isEscaped: boolean }).isEscaped120 ) {144 } else if (typeof child === 'number') {145 ;(buffer[0] as string) += child146 } else if ((child as unknown as HtmlEscaped).isEscaped) {147 ;(buffer[0] as string) += child148 const callbacks = (child as unknown as HtmlEscapedString).callbacks149 if (callbacks) {150 buffer.callbacks ||= []151 buffer.callbacks.push(...callbacks)152 }153 } else if (child instanceof Promise) {154 buffer.unshift('', child)155 } else {156 // `child` type is `Child[]`, so stringify recursively
16 unmodified lines
173 props: Props174 key?: string175 children: Child[]176 isEscaped: true = true as const146 suspendedContext?: <T>(callback: () => T) => T177 constructor(tag: string | Function, props: Props, children: Child[]) {178 if (typeof tag !== 'function' && !isValidTagName(tag)) {179 throw new Error(`Invalid JSX tag name: ${tag}`)180 }
21 unmodified lines
202 ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()203 : buffer[0]204 : stringBufferToString(buffer, buffer.callbacks)205 }176 return this.suspendedContext ? this.suspendedContext(render) : runWithRenderContext(render)206 return runWithRenderContext(render)207 }208209 toStringToBuffer(buffer: StringBufferWithCallbacks): void {210 const tag = this.tag as string
85 unmodified lines
296 // boolean or null or undefined297 return298 } else if (res instanceof Promise) {299 if (globalContexts.length === 0) {270 buffer.unshift('', res)300 buffer.unshift('', resolveFunctionComponentResult(res))301 } else {302 // save the current context state for resuming the suspended subtree273 const suspendedContext = captureRenderContext()274 buffer.unshift(275 '',276 res.then((childRes) => {277 if (childRes instanceof JSXNode) {278 childRes.suspendedContext = suspendedContext279 }280 return childRes281 })282 )303 buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))304 }305 } else if (res instanceof JSXNode) {306 res.toStringToBuffer(buffer)307 } else if (Array.isArray(res)) {308 childrenToStringToBuffer(res, buffer)309 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {310 buffer[0] += res311 if (res.callbacks) {312 buffer.callbacks ||= []
147 unmodified lines
modified:src/jsx/index.test.tsx+95 added-1 removed
1/** @jsxImportSource ./ */2/* eslint-disable @typescript-eslint/no-explicit-any */3import { html } from '../helper/html'3import { html, raw } from '../helper/html'4import { Hono } from '../hono'5import { DOM_MEMO } from './constants'6import { captureRenderContext } from './context'7import { Suspense, renderToReadableStream } from './streaming'
163 unmodified lines
171 )172 expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')173 })174175 it('Component returning an array', () => {176 const Item = ({ x }: { x: number }) => <span>{x}</span>177 const Items = () => [0, 1].map((x) => <Item key={x} x={x} />)178 const template = <Items />179 expect(template.toString()).toBe('<span>0</span><span>1</span>')180 })181182 it('Component returning a nested array', () => {183 const Items = () => [['a', 'b'], [<span>c</span>], null]184 const template = <Items />185 expect(template.toString()).toBe('ab<span>c</span>')186 })187188 it('Component returning an array preserves escaped string callbacks', () => {189 const Items = () => [190 raw('a', [191 ({ buffer }) => {192 if (buffer) {193 buffer[0] += 'b'194 }195 },196 ]),197 ]198 expect((<Items />).toString()).toBe('ab')199 })200201 it('Component returning an array escapes strings', async () => {202 const SyncItems = () => ['<script>alert(1)</script>']203 const AsyncItems = async () => ['<script>alert(1)</script>']204 const expected = '&lt;script&gt;alert(1)&lt;/script&gt;'205206 expect((<SyncItems />).toString()).toBe(expected)207 expect((await (<AsyncItems />).toString()).toString()).toBe(expected)208 })209210 it('Component returning an array including async components', async () => {211 const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>212 const Items = () => [0, 1].map((x) => <AsyncItem key={x} x={x} />)213 const template = <Items />214 expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')215 })216217 it('Component typed as FC returning an array', () => {218 const Item: FC<{ x: number }> = ({ x }) => <span>{x}</span>219 const Items: FC = () => [0, 1].map((x) => <Item key={x} x={x} />)220 const template = <Items />221 expect(template.toString()).toBe('<span>0</span><span>1</span>')222 })223224 it('Async component returning an array', async () => {225 const AsyncItems = async () => [<span>a</span>, <span>b</span>]226 const template = <AsyncItems />227 expect((await template.toString()).toString()).toBe('<span>a</span><span>b</span>')228 })229230 it('Async component returning an array of async components', async () => {231 const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>232 const AsyncItems = async () => [<AsyncItem key={0} x={0} />, <AsyncItem key={1} x={1} />]233 const template = <AsyncItems />234 expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')235 })236237 it('Empty elements are rended without closing tag', () => {238 const template = <input />239 expect(template.toString()).toBe('<input/>')240 })
1072 unmodified lines
1313 )1314 expect((await template.toString()).toString()).toBe('<span>dark</span>')1315 })13161317 it('returning an array', async () => {1318 const ArrayConsumer = async () => {1319 await new Promise((resolve) => setTimeout(resolve, 10))1320 return [<span>{useContext(ThemeContext)}</span>, <span>x</span>]1321 }1322 const template = (1323 <ThemeContext.Provider value='dark'>1324 <ArrayConsumer />1325 </ThemeContext.Provider>1326 )1327 expect((await template.toString()).toString()).toBe('<span>dark</span><span>x</span>')1328 })13291330 it('isolates a shared async result between providers', async () => {1331 const sharedResult = Promise.resolve(<Consumer />)1332 const SharedConsumer = () => sharedResult1333 const [dark, black] = await Promise.all([1334 (1335 <ThemeContext.Provider value='dark'>1336 <SharedConsumer />1337 </ThemeContext.Provider>1338 ).toString(),1339 (1340 <ThemeContext.Provider value='black'>1341 <SharedConsumer />1342 </ThemeContext.Provider>1343 ).toString(),1344 ])1345 expect(dark.toString()).toBe('<span>dark</span>')1346 expect(black.toString()).toBe('<span>black</span>')1347 })13481349 it('nested', async () => {1350 const template = (1351 <ThemeContext.Provider value='dark'>1352 <ParentAsyncConsumer />
334 unmodified lines
modified:src/jsx/streaming.test.tsx+40 added
28 unmodified lines
29 afterEach(() => {30 suspenseCounter++31 })3233 it('Suspense / async component returning an array', async () => {34 const Content = async () => {35 await new Promise((resolve) => setTimeout(resolve, 10))36 return [<h1>Hello</h1>, <h2>World</h2>]37 }3839 const stream = renderToReadableStream(40 <Suspense fallback={<p>Loading...</p>}>41 <Content />42 </Suspense>43 )4445 const chunks = []46 const textDecoder = new TextDecoder()47 for await (const chunk of stream as any) {48 chunks.push(textDecoder.decode(chunk))49 }5051 expect(chunks[0]).toBe(52 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`53 )54 expect(chunks[1]).toContain(55 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><h2>World</h2></template>`56 )57 })5859 it('preserves callbacks in a streamed async component array', async () => {60 const phases: number[] = []61 const Content = async () => [62 raw('Hello', [({ phase }) => void phases.push(phase)]),63 <span>World</span>,64 ]6566 const html = await drainStream(renderToReadableStream(<Content />))6768 expect(html).toBe('Hello<span>World</span>')69 expect(phases).toEqual([HtmlEscapedCallbackPhase.BeforeStream, HtmlEscapedCallbackPhase.Stream])70 suspenseCounter--71 })7273 it('Suspense / renderToReadableStream', async () => {74 let contentEvaluatedCount = 075 const Content = () => {76 contentEvaluatedCount++
1081 unmodified lines
modified:src/middleware/cache/index.test.ts+394 added-1 removed
99 unmodified lines
100101 it('Should use dynamically generated cache key', async () => {102 await app.request('http://localhost/dynamic-cache-key/')103 const cache = await caches.open('my-app-v1')104 const response = await cache.match(dynamicCacheKey)104 const response = await cache.match(105 'http://localhost/.hono/cache?__hono_cache_key=dynamic-cache-key&__hono_cache_method=GET'106 )107 expect(response).not.toBeNull()108 })109110 it('Should retrieve cached response with dynamic cache name and key', async () => {
295 unmodified lines
406 })407 const res = await app.request('/')408 expect(res.status).toBe(200)409 expect(spy).toHaveBeenCalledOnce()410 expect(spy).toHaveBeenCalledWith(411 'Cache Middleware is not enabled because caches is not defined.'412 )413 vi.unstubAllGlobals()414 })415416 it('Should suppress default log when onCacheNotAvailable is false', async () => {
328 unmodified lines
745 expect(caches.open).not.toHaveBeenCalled()746 expect(putSpy).not.toHaveBeenCalled()747 })748749 it('Should cache QUERY responses without consuming the handler request body', async () => {750 const { mockCache } = stubStoreBackedCache()751 const app = new Hono()752 let queryCount = 0753 app.use('*', cache({ cacheName: 'query-test', wait: true, cacheControl: 'max-age=10' }))754 app.on('QUERY', '/resource', async (c) => {755 queryCount++756 c.header('X-Count', `${queryCount}`)757 return c.text(await c.req.raw.text())758 })759760 const request = () =>761 app.request('/resource', {762 method: 'QUERY',763 headers: { 'Content-Type': 'application/json' },764 body: '{"query":"hono"}',765 })766767 await request()768 const res = await request()769770 expect(await res.text()).toBe('{"query":"hono"}')771 expect(res.headers.get('X-Count')).toBe('1')772 expect(res.headers.get('Cache-Control')).toBe('max-age=10')773 expect(mockCache.put).toHaveBeenCalledOnce()774 })775776 it('Should bypass QUERY caching when the measured body exceeds the configured limit', async () => {777 const { mockCache } = stubStoreBackedCache()778 const app = new Hono()779 let queryCount = 0780 app.use('*', cache({ cacheName: 'query-body-limit-test', wait: true, maxQueryBodySize: 4 }))781 app.on('QUERY', '/resource', async (c) => {782 queryCount++783 c.header('X-Count', `${queryCount}`)784 return c.text(await c.req.text())785 })786787 const request = () => {788 const body = new ReadableStream({789 start(controller) {790 controller.enqueue(new TextEncoder().encode('ab'))791 controller.enqueue(new TextEncoder().encode('cde'))792 controller.close()793 },794 })795 return app.request('/resource', {796 method: 'QUERY',797 headers: {798 'Content-Length': '1',799 'Content-Type': 'text/plain',800 },801 body,802 duplex: 'half',803 } as RequestInit & { duplex: 'half' })804 }805806 await request()807 const res = await request()808809 expect(await res.text()).toBe('abcde')810 expect(res.headers.get('X-Count')).toBe('2')811 expect(caches.open).not.toHaveBeenCalled()812 expect(mockCache.put).not.toHaveBeenCalled()813 })814815 it('Should cache QUERY requests at the configured body size limit', async () => {816 const { mockCache } = stubStoreBackedCache()817 const app = new Hono()818 let queryCount = 0819 app.use(820 '*',821 cache({ cacheName: 'query-body-limit-boundary-test', wait: true, maxQueryBodySize: 4 })822 )823 app.on('QUERY', '/resource', async (c) => {824 queryCount++825 c.header('X-Count', `${queryCount}`)826 return c.text(await c.req.text())827 })828829 const request = () =>830 app.request('/resource', {831 method: 'QUERY',832 headers: { 'Content-Type': 'text/plain' },833 body: 'abcd',834 })835836 await request()837 const res = await request()838839 expect(await res.text()).toBe('abcd')840 expect(res.headers.get('X-Count')).toBe('1')841 expect(mockCache.put).toHaveBeenCalledOnce()842 })843844 it('Should keep QUERY request content and Content-Type in separate cache variants', async () => {845 const { mockCache } = stubStoreBackedCache()846 const app = new Hono()847 let queryCount = 0848 app.use(849 '*',850 cache({ cacheName: 'query-variant-test', wait: true, keyGenerator: () => 'query-key' })851 )852 app.on('QUERY', '/resource', async (c) => {853 queryCount++854 c.header('X-Count', `${queryCount}`)855 return c.text(`${c.req.header('Content-Type')}:${await c.req.text()}`)856 })857858 const request = (body: string, contentType: string) =>859 app.request('/resource', {860 method: 'QUERY',861 headers: { 'Content-Type': contentType },862 body,863 })864865 await request('one', 'text/plain')866 const same = await request('one', 'text/plain')867 await request('two', 'text/plain')868 const differentContent = await request('two', 'text/plain')869 await request('one', 'application/json')870 const differentContentType = await request('one', 'application/json')871872 expect(same.headers.get('X-Count')).toBe('1')873 expect(differentContent.headers.get('X-Count')).toBe('2')874 expect(differentContentType.headers.get('X-Count')).toBe('3')875 expect(mockCache.put).toHaveBeenCalledTimes(3)876 })877878 it('Should keep GET and QUERY responses in separate cache entries', async () => {879 const { mockCache } = stubStoreBackedCache()880 const app = new Hono()881 app.use('*', cache({ cacheName: 'method-test', wait: true }))882 app.get('/resource', (c) => c.text('get response'))883 app.on('QUERY', '/resource', (c) => c.text('query response'))884885 await app.request('/resource')886 await app.request('/resource', {887 method: 'QUERY',888 headers: { 'Content-Type': 'application/json' },889 body: '{}',890 })891 const getRes = await app.request('/resource')892 const queryRes = await app.request('/resource', {893 method: 'QUERY',894 headers: { 'Content-Type': 'application/json' },895 body: '{}',896 })897898 expect(await getRes.text()).toBe('get response')899 expect(await queryRes.text()).toBe('query response')900 expect(mockCache.put).toHaveBeenCalledTimes(2)901 })902903 it('Should not let a GET URL alias an internally generated QUERY cache key', async () => {904 const { mockCache } = stubStoreBackedCache()905 const app = new Hono()906 app.use('*', cache({ cacheName: 'method-collision-test', wait: true }))907 app.get('/resource', (c) => c.text('get response'))908 app.get('*', (c) => c.text('get response'))909 app.on('QUERY', '/resource', (c) => c.text('query response'))910911 await app.request('/resource', {912 method: 'QUERY',913 headers: { 'Content-Type': 'application/json' },914 body: '{}',915 })916917 const queryKey = mockCache.put.mock.calls[0][0] as string918 const getRes = await app.request(queryKey)919 const queryRes = await app.request('/resource', {920 method: 'QUERY',921 headers: { 'Content-Type': 'application/json' },922 body: '{}',923 })924925 expect(await getRes.text()).toBe('get response')926 expect(await queryRes.text()).toBe('query response')927 expect(mockCache.put).toHaveBeenCalledTimes(2)928 })929930 it('Should not resolve a custom cache key as a request URL', async () => {931 const { mockCache } = stubStoreBackedCache()932 const app = new Hono()933 app.use(934 '/resource',935 cache({936 cacheName: 'custom-key-collision-test',937 wait: true,938 keyGenerator: () => 'query-key',939 })940 )941 app.use('/query-key', cache({ cacheName: 'custom-key-collision-test', wait: true }))942 app.get('/resource', (c) => c.text('custom key response'))943 app.get('/query-key', (c) => c.text('request URL response'))944945 expect(await (await app.request('/resource')).text()).toBe('custom key response')946 expect(await (await app.request('/query-key')).text()).toBe('request URL response')947 expect(mockCache.put).toHaveBeenCalledTimes(2)948 })949950 it('Should keep QUERY digest and vary values with a fragmented custom cache key', async () => {951 const { mockCache } = stubStoreBackedCache()952 const app = new Hono()953 let queryCount = 0954 app.use(955 '*',956 cache({957 cacheName: 'query-fragment-test',958 wait: true,959 vary: 'X-Variant',960 keyGenerator: (c) => `${c.req.url}#custom-fragment`,961 })962 )963 app.on('QUERY', '/resource', async (c) => {964 queryCount++965 return c.text(`${await c.req.text()}:${c.req.header('X-Variant')}`)966 })967968 const request = (body: string, variant: string) =>969 app.request('/resource', {970 method: 'QUERY',971 headers: { 'Content-Type': 'text/plain', 'X-Variant': variant },972 body,973 })974975 expect(await (await request('one', 'a')).text()).toBe('one:a')976 expect(await (await request('two', 'a')).text()).toBe('two:a')977 expect(await (await request('one', 'b')).text()).toBe('one:b')978 expect(await (await request('one', 'a')).text()).toBe('one:a')979 expect(queryCount).toBe(3)980 expect(mockCache.put).toHaveBeenCalledTimes(3)981 })982983 it('Should bypass QUERY caching when Web Crypto is not available', async () => {984 const originalCrypto = globalThis.crypto985 vi.stubGlobal('crypto', undefined)986987 try {988 const { mockCache } = stubStoreBackedCache()989 const app = new Hono()990 let queryCount = 0991 let getCount = 0992 const onCacheNotAvailable = vi.fn()993 app.use(994 '*',995 cache({996 cacheName: 'query-no-crypto-test',997 wait: true,998 onCacheNotAvailable,999 })1000 )1001 app.get('/resource', (c) => {1002 getCount++1003 c.header('X-Count', `${getCount}`)1004 return c.text('get response')1005 })1006 app.on('QUERY', '/resource', (c) => {1007 queryCount++1008 c.header('X-Count', `${queryCount}`)1009 return c.text('query response')1010 })10111012 expect(onCacheNotAvailable).toHaveBeenCalledOnce()1013 expect(onCacheNotAvailable).toHaveBeenCalledWith(1014 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'1015 )10161017 const request = () =>1018 app.request('/resource', {1019 method: 'QUERY',1020 headers: { 'Content-Type': 'application/json' },1021 body: '{}',1022 })10231024 await request()1025 const res = await request()10261027 expect(res.headers.get('X-Count')).toBe('2')1028 expect(caches.open).not.toHaveBeenCalled()1029 expect(onCacheNotAvailable).toHaveBeenCalledOnce()10301031 await app.request('/resource')1032 const getRes = await app.request('/resource')10331034 expect(getRes.headers.get('X-Count')).toBe('1')1035 expect(mockCache.put).toHaveBeenCalledOnce()1036 } finally {1037 vi.stubGlobal('crypto', originalCrypto)1038 }1039 })10401041 it('Should bypass QUERY caching when the request content cannot be read', async () => {1042 const app = new Hono()1043 let queryCount = 01044 app.use('*', async (c, next) => {1045 await c.req.raw.text()1046 await next()1047 })1048 app.use('*', cache({ cacheName: 'query-consumed-body-test', wait: true }))1049 app.on('QUERY', '/resource', (c) => {1050 queryCount++1051 c.header('X-Count', `${queryCount}`)1052 return c.text('query response')1053 })10541055 const request = () =>1056 app.request('/resource', {1057 method: 'QUERY',1058 headers: { 'Content-Type': 'application/json' },1059 body: '{}',1060 })10611062 await request()1063 const res = await request()10641065 expect(res.headers.get('X-Count')).toBe('2')1066 expect(caches.open).not.toHaveBeenCalled()1067 })10681069 it('Should bypass QUERY caching after the body was read directly as FormData', async () => {1070 const { mockCache } = stubStoreBackedCache()1071 const app = new Hono()1072 let queryCount = 01073 app.use('*', async (c, next) => {1074 expect((await c.req.formData()).get('query')).toBe('hono')1075 await next()1076 })1077 app.use('*', cache({ cacheName: 'query-cached-form-data-test', wait: true }))1078 app.on('QUERY', '/resource', (c) => {1079 queryCount++1080 c.header('X-Count', `${queryCount}`)1081 return c.text('query response')1082 })10831084 const body = [1085 '--hono-boundary',1086 'Content-Disposition: form-data; name="query"',1087 '',1088 'hono',1089 '--hono-boundary--',1090 '',1091 ].join('\r\n')1092 const request = () =>1093 app.request('/resource', {1094 method: 'QUERY',1095 headers: { 'Content-Type': 'multipart/form-data; boundary=hono-boundary' },1096 body,1097 })10981099 await request()1100 const res = await request()11011102 expect(res.headers.get('X-Count')).toBe('2')1103 expect(caches.open).not.toHaveBeenCalled()1104 expect(mockCache.put).not.toHaveBeenCalled()1105 })11061107 it('Should cache QUERY after the body was read through HonoRequest', async () => {1108 const { mockCache } = stubStoreBackedCache()1109 const app = new Hono()1110 let queryCount = 01111 app.use('*', async (c, next) => {1112 expect(await c.req.text()).toBe('{}')1113 await next()1114 })1115 app.use('*', cache({ cacheName: 'query-cached-body-test', wait: true }))1116 app.on('QUERY', '/resource', async (c) => {1117 queryCount++1118 c.header('X-Count', `${queryCount}`)1119 return c.text(await c.req.text())1120 })11211122 const request = () =>1123 app.request('/resource', {1124 method: 'QUERY',1125 headers: { 'Content-Type': 'application/json' },1126 body: '{}',1127 })11281129 await request()1130 const res = await request()11311132 expect(await res.text()).toBe('{}')1133 expect(res.headers.get('X-Count')).toBe('1')1134 expect(mockCache.put).toHaveBeenCalledOnce()1135 })11361137 it('Should not use or store cache for POST requests', async () => {1138 const app = new Hono()1139 let postCount = 01140 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))
21 unmodified lines
modified:src/middleware/cache/index.ts+153 added-13 removed
2 unmodified lines
3 * Cache Middleware for Hono.4 */56import type { Context } from '../../context'7import { cloneRawRequest } from '../../request'8import type { MiddlewareHandler } from '../../types'9import { sha256 } from '../../utils/crypto'10import type { StatusCode } from '../../utils/http-status'1112/**13 * status codes that can be cached by default.14 */15const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]1617const defaultMaxQueryBodySize = 64 * 10241819const cacheKeyPath = '/.hono/cache'20const cacheKeyParameter = '__hono_cache_key'21const cacheMethodKeyParameter = '__hono_cache_method'22const queryDigestKeyParameter = '__hono_query_digest'23const cacheVaryKeyParameter = '__hono_cache_vary'2425type CacheKeyRequest =26 | { method: 'GET' }27 | {28 method: 'QUERY'29 digest: string30 }3132const queryRepresentationMetadataHeaders = [33 'content-type',34 'content-encoding',35 'content-language',36 'content-location',37] as const3839const shouldSkipCacheControl = (cacheControl: string | null): boolean =>40 !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)4142const parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => {
4 unmodified lines
47 .map((directive) => directive.trim().toLowerCase())48 .filter(Boolean)49}5051const createCacheKey = (52 key: string,53 requestUrl: string,54 request: CacheKeyRequest,55 varyHeaders: [string, string][]56): string => {57 const url = new URL(cacheKeyPath, requestUrl)58 url.searchParams.append(cacheKeyParameter, key.split('#', 1)[0])59 url.searchParams.append(cacheMethodKeyParameter, request.method)6061 if (request.method === 'QUERY') {62 url.searchParams.append(queryDigestKeyParameter, request.digest)63 }6465 for (const header of varyHeaders) {66 url.searchParams.append(cacheVaryKeyParameter, JSON.stringify(header))67 }6869 return url.href70}7172const shouldSkipCache = (73 res: Response,74 optionsVaryDirectives: Set<string> | undefined,75 responseVary: string[]
2 unmodified lines
78 (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) ||79 shouldSkipCacheControl(res.headers.get('Cache-Control')) ||80 res.headers.has('Set-Cookie')8182const reportCacheNotAvailable = (83 onCacheNotAvailable: ((reason: string) => void) | false | undefined,84 reason: string85): void => {86 if (onCacheNotAvailable === false) {87 // suppress log88 } else if (onCacheNotAvailable) {89 onCacheNotAvailable(reason)90 } else {91 console.log(reason)92 }93}9495const createQueryDigest = async (96 c: Context,97 maxQueryBodySize: number98): Promise<string | undefined> => {99 if (!globalThis.crypto?.subtle) {100 return undefined101 }102103 if (c.req.raw.bodyUsed && Object.keys(c.req.bodyCache)[0] === 'formData') {104 // FormData cannot be reserialized with a stable multipart boundary after105 // the original request body has been consumed.106 return undefined107 }108109 try {110 // RFC 10008 Section 2.7 requires QUERY cache keys to incorporate the111 // request content and its related representation metadata.112 const requestHeaders = c.req.raw.headers113 const metadata = new TextEncoder().encode(114 JSON.stringify(115 queryRepresentationMetadataHeaders.map((header) => [header, requestHeaders.get(header)])116 )117 )118 const body = (await cloneRawRequest(c.req)).body119 const chunks: Uint8Array[] = []120 let bodySize = 0121122 if (body) {123 const reader = body.getReader()124 for (;;) {125 const { done, value } = await reader.read()126 if (done) {127 break128 }129 bodySize += value.byteLength130 if (bodySize > maxQueryBodySize) {131 // Do not await cancellation because a cloned stream's cancellation132 // can wait for the original request stream to finish.133 void reader.cancel().catch(() => {})134 return undefined135 }136 chunks.push(value)137 }138 }139140 const data = new Uint8Array(metadata.byteLength + bodySize)141 data.set(metadata)142 let offset = metadata.byteLength143 for (const chunk of chunks) {144 data.set(chunk, offset)145 offset += chunk.byteLength146 }147148 return (await sha256(data)) ?? undefined149 } catch {150 // A QUERY response cannot be cached safely if its content cannot be read.151 return undefined152 }153}154155/**156 * Cache Middleware for Hono.157 *158 * @see {@link https://hono.dev/docs/middleware/builtin/cache}
2 unmodified lines
161 * @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers.162 * @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment.163 * @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header.164 * @param {string | string[]} [options.vary] - Adds the configured request headers to the cache key variants and sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates.47 * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters.165 * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters. QUERY keys additionally include a digest of the request content and its representation metadata.166 * @param {number} [options.maxQueryBodySize=65536] - The maximum QUERY request body size in bytes that can be cached. Larger QUERY requests bypass the cache.167 * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached.49 * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked when `globalThis.caches` is not available. By default, a message is logged to the console. Set to `false` to suppress the log, or provide a custom function.168 * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked with the reason when `globalThis.caches` is not available or QUERY caching cannot use Web Crypto. By default, the reason is logged to the console. Set to `false` to suppress the log, or provide a custom function.169 * @returns {MiddlewareHandler} The middleware handler function.170 * @throws {Error} If the `vary` option includes "*".171 *172 * @example173 * ```ts55 * app.get(174 * app.use(175 * '*',176 * cache({177 * cacheName: 'my-app',178 * cacheControl: 'max-age=3600',
6 unmodified lines
185 wait?: boolean186 cacheControl?: string187 vary?: string | string[]188 keyGenerator?: (c: Context) => Promise<string> | string189 maxQueryBodySize?: number190 cacheableStatusCodes?: StatusCode[]71 onCacheNotAvailable?: (() => void) | false191 onCacheNotAvailable?: ((reason: string) => void) | false192}): MiddlewareHandler => {193 if (!globalThis.caches) {74 if (options.onCacheNotAvailable === false) {75 // suppress log76 } else if (options.onCacheNotAvailable) {77 options.onCacheNotAvailable()78 } else {79 console.log('Cache Middleware is not enabled because caches is not defined.')80 }194 reportCacheNotAvailable(195 options.onCacheNotAvailable,196 'Cache Middleware is not enabled because caches is not defined.'197 )198 return async (_c, next) => await next()199 }200201 if (!globalThis.crypto?.subtle) {202 reportCacheNotAvailable(203 options.onCacheNotAvailable,204 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'205 )206 }207208 if (options.wait === undefined) {209 options.wait = false210 }211
12 unmodified lines
224225 const cacheableStatusCodes = new Set<number>(226 options.cacheableStatusCodes ?? defaultCacheableStatusCodes227 )228 const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySize229230 const addHeader = (c: Context, responseVary: string[]) => {231 if (cacheControlDirectives) {232 const existingDirectives =
30 unmodified lines
263 }264 }265266 return async function cache(c, next) {142 if (c.req.method !== 'GET' || c.req.raw.headers.has('Authorization')) {267 if (268 (c.req.method !== 'GET' && c.req.method !== 'QUERY') ||269 c.req.raw.headers.has('Authorization')270 ) {271 await next()272 return273 }274275 let cacheKeyRequest: CacheKeyRequest = { method: 'GET' }276 if (c.req.method === 'QUERY') {277 const digest = await createQueryDigest(c, maxQueryBodySize)278 if (digest === undefined) {279 await next()280 return281 }282 cacheKeyRequest = { method: 'QUERY', digest }283 }284285 let key = c.req.url286 if (options.keyGenerator) {287 key = await options.keyGenerator(c)288 }289 const varyHeaders: [string, string][] = []290 if (varyDirectives) {291 for (const directive of varyDirectives) {292 const value = c.req.raw.headers.get(directive) ?? ''154 key += `::${directive}=${encodeURIComponent(value)}`293 varyHeaders.push([directive, value])294 }295 }296 key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders)297298 const cacheName =299 typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName300 const cache = await caches.open(cacheName)
24 unmodified lines
modified:src/middleware/compress/index.test.ts+87 added
257 unmodified lines
258 expect(res.headers.get('ETag')).toBeNull()259 })260 })261262 describe('Vary Header', () => {263 const app = new Hono()264 app.use('*', compress())265 app.get('/no-vary', (c) => {266 c.header('Content-Type', 'text/plain')267 c.header('Content-Length', '1024')268 return c.text('a'.repeat(1024))269 })270 app.get('/existing-vary', (c) => {271 c.header('Content-Type', 'text/plain')272 c.header('Content-Length', '1024')273 c.header('Vary', 'Cookie')274 return c.text('a'.repeat(1024))275 })276 app.get('/already-accept-encoding', (c) => {277 c.header('Content-Type', 'text/plain')278 c.header('Content-Length', '1024')279 c.header('Vary', 'Accept-Encoding')280 return c.text('a'.repeat(1024))281 })282 app.get('/wildcard-vary', (c) => {283 c.header('Content-Type', 'text/plain')284 c.header('Content-Length', '1024')285 c.header('Vary', '*')286 return c.text('a'.repeat(1024))287 })288 app.get('/not-compressible', (c) => {289 c.header('Content-Type', 'image/png')290 c.header('Content-Length', '1024')291 return c.body('a'.repeat(1024))292 })293294 it('should set Vary: Accept-Encoding when compressing', async () => {295 const res = await app.request('/no-vary', {296 headers: { 'Accept-Encoding': 'gzip' },297 })298 expect(res.headers.get('Content-Encoding')).toBe('gzip')299 expect(res.headers.get('Vary')).toBe('Accept-Encoding')300 })301302 it('should append Accept-Encoding to an existing Vary header', async () => {303 const res = await app.request('/existing-vary', {304 headers: { 'Accept-Encoding': 'gzip' },305 })306 expect(res.headers.get('Content-Encoding')).toBe('gzip')307 expect(res.headers.get('Vary')).toBe('Cookie, Accept-Encoding')308 })309310 it('should not duplicate Accept-Encoding when Vary already lists it', async () => {311 const res = await app.request('/already-accept-encoding', {312 headers: { 'Accept-Encoding': 'gzip' },313 })314 expect(res.headers.get('Content-Encoding')).toBe('gzip')315 expect(res.headers.get('Vary')).toBe('Accept-Encoding')316 })317318 it('should leave Vary: * unchanged', async () => {319 const res = await app.request('/wildcard-vary', {320 headers: { 'Accept-Encoding': 'gzip' },321 })322 expect(res.headers.get('Content-Encoding')).toBe('gzip')323 expect(res.headers.get('Vary')).toBe('*')324 })325326 it('should set Vary on an identity response when Accept-Encoding is absent', async () => {327 const res = await app.request('/no-vary')328 expect(res.headers.get('Content-Encoding')).toBeNull()329 expect(res.headers.get('Vary')).toBe('Accept-Encoding')330 })331332 it('should set Vary on an identity response when no offered encoding is accepted', async () => {333 const res = await app.request('/no-vary', {334 headers: { 'Accept-Encoding': 'br' },335 })336 expect(res.headers.get('Content-Encoding')).toBeNull()337 expect(res.headers.get('Vary')).toBe('Accept-Encoding')338 })339340 it('should not add a Vary header when the response is not eligible for compression', async () => {341 const res = await app.request('/not-compressible', {342 headers: { 'Accept-Encoding': 'gzip' },343 })344 expect(res.headers.get('Content-Encoding')).toBeNull()345 expect(res.headers.get('Vary')).toBeNull()346 })347 })348349 describe('contentTypeFilter', () => {350 describe('RegExp', () => {351 const app = new Hono()352 app.use('*', compress({ contentTypeFilter: /^application\/json/, threshold: 0 }))
183 unmodified lines
modified:src/middleware/compress/index.ts+14 added
41 unmodified lines
42 }43 return best?.encoding44}4546const varyAcceptEncodingRegExp = /(?:^|,)\s*accept-encoding\s*(?:,|$)/i4748/**49 * Compress Middleware for Hono.50 *51 * @see {@link https://hono.dev/docs/middleware/builtin/compress}
50 unmodified lines
102 ) {103 return104 }105106 // From here on the representation is selected from the request's Accept-Encoding,107 // so caches must key on that header. This is done before the negotiation result is108 // known, because an identity response served for a missing or unsupported109 // Accept-Encoding is just as much a negotiated representation: RFC 9110 lists110 // Accept-Encoding "or lack thereof" as a determining factor. Without this, a shared111 // cache could reuse the identity response for a client that does accept gzip.112 // https://www.rfc-editor.org/rfc/rfc9110#field.vary113 const current = ctx.res.headers.get('Vary')114 if (current !== '*' && !(current && varyAcceptEncodingRegExp.test(current))) {115 ctx.header('Vary', current ? `${current}, Accept-Encoding` : 'Accept-Encoding')116 }117118 const accepted = ctx.req.header('Accept-Encoding')119 const encoding = selectEncoding(accepted, candidates)120 if (!encoding || !ctx.res.body) {121 return
22 unmodified lines
modified:src/middleware/cors/index.test.ts+16 added-3 removed
143 unmodified lines
144 expect(res.headers.get('Vary')).toBeNull()145 })146147 it('Preflight default', async () => {148 const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' })149 req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type')148 const req = new Request('https://localhost/api/abc', {149 method: 'OPTIONS',150 headers: {151 'Access-Control-Request-Method': 'QUERY',152 'Access-Control-Request-Headers': 'X-PINGOTHER, Content-Type',153 },154 })155 const res = await app.request(req)156157 expect(res.status).toBe(204)158 expect(res.statusText).toBe('No Content')154 expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')[0]).toBe('GET')159 expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')).toEqual([160 'GET',161 'HEAD',162 'PUT',163 'POST',164 'DELETE',165 'PATCH',166 'QUERY',167 ])168 expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([169 'X-PINGOTHER',170 'Content-Type',171 ])
322 unmodified lines
modified:src/middleware/cors/index.ts+2 added-2 removed
26 unmodified lines
27 * @see {@link https://hono.dev/docs/middleware/builtin/cors}28 *29 * @param {CORSOptions} [options] - The options for the CORS middleware.30 * @param {string | string[] | ((origin: string, c: Context) => Promise<string | undefined | null> | string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.31 * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.31 * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']] - The value of "Access-Control-Allow-Methods" CORS header.32 * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.33 * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.34 * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.35 * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header.
26 unmodified lines
62 */63export const cors = (options?: CORSOptions): MiddlewareHandler => {64 const opts = {65 origin: '*',66 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],66 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'],67 allowHeaders: [],68 exposeHeaders: [],69 ...options,70 } satisfies CORSOptions
87 unmodified lines
modified:src/middleware/etag/index.test.ts+47 added
224 unmodified lines
225 })226 expect(res.status).toBe(304)227 })228229 it('Should handle conditional QUERY requests', async () => {230 const app = new Hono()231 app.use('/etag/*', etag())232 app.on('QUERY', '/etag/query', (c) => c.text('Hono is great'))233234 // unconditional QUERY235 let res = await app.request('http://localhost/etag/query', {236 method: 'QUERY',237 body: 'select *',238 })239 expect(res.status).toBe(200)240 expect(res.headers.get('ETag')).not.toBeFalsy()241 const etagHeaderValue = res.headers.get('ETag') || ''242243 // conditional QUERY with the wrong ETag:244 res = await app.request('http://localhost/etag/query', {245 method: 'QUERY',246 body: 'select *',247 headers: {248 'If-None-Match': '"not the right etag"',249 },250 })251 expect(res.status).toBe(200)252253 // conditional QUERY with matching ETag:254 res = await app.request('http://localhost/etag/query', {255 method: 'QUERY',256 body: 'select *',257 headers: {258 'If-None-Match': etagHeaderValue,259 },260 })261 expect(res.status).toBe(304)262 expect(res.headers.get('ETag')).toBe(etagHeaderValue)263 expect(await res.text()).toBe('')264265 // conditional QUERY with `*` wildcard:266 res = await app.request('http://localhost/etag/query', {267 method: 'QUERY',268 body: 'select *',269 headers: {270 'If-None-Match': '*',271 },272 })273 expect(res.status).toBe(304)274 })275276 it('Should not return 304 for `If-None-Match: *` on unsafe methods or error responses', async () => {277 const app = new Hono()278 app.use('/etag/*', etag())279 app.put('/etag/put', (c) => c.text('created', 201))
118 unmodified lines
modified:src/middleware/etag/index.ts+1 added-1 removed
104 unmodified lines
105 }106107 const matched =108 ifNoneMatch === '*'109 ? (c.req.method === 'GET' || c.req.method === 'HEAD') && res.ok109 ? (c.req.method === 'GET' || c.req.method === 'HEAD' || c.req.method === 'QUERY') && res.ok110 : etagMatches(etag, ifNoneMatch)111112 if (matched) {113 c.res = new Response(null, {
16 unmodified lines
modified:src/middleware/jsx-renderer/index.test.tsx+16 added
53 unmodified lines
54 '<!DOCTYPE html><div class="nested"><h1>http://localhost/nested</h1></div>'55 )56 })5758 it('accepts an array result', async () => {59 const app = new Hono()60 app.use(jsxRenderer(({ children }) => [<header>Header</header>, <main>{children}</main>]))61 app.get('/', (c) => c.render(<h1>Hello</h1>, { title: 'Hello' }))6263 const res = await app.request('/')64 expect(await res.text()).toBe(65 '<!DOCTYPE html><header>Header</header><main><h1>Hello</h1></main>'66 )67 })6869 it('does not accept a null result', () => {70 // @ts-expect-error A JSX renderer component must produce renderable content.71 jsxRenderer(() => null)72 })7374 it('Should get the context object as a 2nd arg', async () => {75 const app = new Hono()76 app.use(77 jsxRenderer(
453 unmodified lines
modified:src/middleware/jsx-renderer/index.ts+4 added-6 removed
8 unmodified lines
9import { Fragment, createContext, jsx, useContext } from '../../jsx'10import type { FC, Context as JSXContext, JSXNode, PropsWithChildren } from '../../jsx'11import { renderToReadableStream } from '../../jsx/streaming'12import type { Env, Input, MiddlewareHandler } from '../../types'13import type { HtmlEscapedString } from '../../utils/html'1314export const RequestContext: JSXContext<Context<any, any, {}> | null> =15 createContext<Context | null>(null)16
1 unmodified line
18 docType?: boolean | string19 stream?: boolean | Record<string, string>20}2123type Component = (24 props: PropsForRenderer & { Layout: FC },25 c: Context26) => HtmlEscapedString | Promise<HtmlEscapedString>22type ComponentResult = Exclude<ReturnType<FC>, null>2324type Component = (props: PropsForRenderer & { Layout: FC }, c: Context) => ComponentResult2526type ComponentWithChildren = (27 props: PropsWithChildren<PropsForRenderer & { Layout: FC }>,28 c: Context31) => HtmlEscapedString | Promise<HtmlEscapedString>29) => ComponentResult3031const createRenderer =32 (33 c: Context,
130 unmodified lines
modified:src/middleware/jwk/index.test.ts+55 added
1075 unmodified lines
10761077 // Note: Test for "no whitelist" was removed because alg is now required.1078 // This is a breaking change that enforces explicit algorithm specification for security.1079 })1080 describe('WWW-Authenticate realm', () => {1081 it('Should default to the request URL', async () => {1082 const app = new Hono()1083 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'] }))1084 app.get('/auth/*', (c) => c.text('ok'))10851086 const res = await app.request('http://localhost/auth/page?a=1')10871088 expect(res.status).toBe(401)1089 expect(res.headers.get('WWW-Authenticate')).toBe(1090 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'1091 )1092 })10931094 it('Should use the configured realm', async () => {1095 const app = new Hono()1096 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1097 app.get('/auth/*', (c) => c.text('ok'))10981099 const res = await app.request('http://localhost/auth/page?a=1')11001101 expect(res.status).toBe(401)1102 expect(res.headers.get('WWW-Authenticate')).toBe(1103 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'1104 )1105 })11061107 it('Should use the configured realm for an invalid token', async () => {1108 const app = new Hono()1109 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1110 app.get('/auth/*', (c) => c.text('ok'))11111112 const req = new Request('http://localhost/auth/page')1113 req.headers.set('Authorization', 'Bearer invalid-token')1114 const res = await app.request(req)11151116 expect(res.status).toBe(401)1117 expect(res.headers.get('WWW-Authenticate')).toBe(1118 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'1119 )1120 })11211122 it('Should escape double quotes in the realm', async () => {1123 const app = new Hono()1124 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my "quoted" api' }))1125 app.get('/auth/*', (c) => c.text('ok'))11261127 const res = await app.request('http://localhost/auth/page')11281129 expect(res.status).toBe(401)1130 expect(res.headers.get('WWW-Authenticate')).toBe(1131 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'1132 )1133 })1134 })1135})
modified:src/middleware/jwk/jwk.ts+14 added-1 removed
23 unmodified lines
24 * @param {string | ((ctx: Context) => Promise<string> | string)} [options.jwks_uri] - If set to a URI string or a function that returns a URI string, attempt to fetch JWKs from it. The response must be a JSON object containing a `keys` array, which will be merged with the `keys` option.25 * @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication.26 * @param {string} [options.cookie] - If set, the middleware attempts to retrieve the token from a cookie with these options (optionally signed) only if no token is found in the header.27 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.28 * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.29 * @param {AsymmetricAlgorithm[]} options.alg - An array of allowed asymmetric algorithms for JWT verification. Only tokens signed with these algorithms will be accepted.30 * @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI.31 * @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification.32 * @returns {MiddlewareHandler} The middleware handler function.
25 unmodified lines
58 headerName?: string5960 alg: AsymmetricAlgorithm[]6162 realm?: string6364 verification?: VerifyOptions65 },66 init?: RequestInit67): MiddlewareHandler => {
21 unmodified lines
89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93 realm: options.realm,94 }),95 })96 } else {97 token = parts[1]
31 unmodified lines
129 res: unauthorizedResponse({130 ctx,131 error: 'invalid_request',132 errDescription,133 realm: options.realm,134 }),135 })136 }137
22 unmodified lines
160 ctx,161 error: 'invalid_token',162 statusText: 'Unauthorized',163 errDescription: 'token verification failure',164 realm: options.realm,165 }),166 cause,167 })168 }
8 unmodified lines
177 ctx: Context178 error: string179 errDescription: string180 statusText?: string181 realm?: string182}) {183 // `realm` and `error_description` end up inside a quoted-string, so any `"`184 // they contain has to be escaped or the header is cut short. Same handling as185 // the bearer-auth middleware.186 const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')187 const errDescription = opts.errDescription.replace(/"/g, '\\"')188189 return new Response('Unauthorized', {190 status: 401,191 statusText: opts.statusText,192 headers: {180 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,193 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,194 },195 })196}
modified:src/middleware/jwt/index.test.ts+55 added
742 unmodified lines
743 return c.json(payload)744 })745 })746 })747 describe('WWW-Authenticate realm', () => {748 it('Should default to the request URL', async () => {749 const app = new Hono()750 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))751 app.get('/auth/*', (c) => c.text('ok'))752753 const res = await app.request('http://localhost/auth/page?a=1')754755 expect(res.status).toBe(401)756 expect(res.headers.get('WWW-Authenticate')).toBe(757 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'758 )759 })760761 it('Should use the configured realm', async () => {762 const app = new Hono()763 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))764 app.get('/auth/*', (c) => c.text('ok'))765766 const res = await app.request('http://localhost/auth/page?a=1')767768 expect(res.status).toBe(401)769 expect(res.headers.get('WWW-Authenticate')).toBe(770 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'771 )772 })773774 it('Should use the configured realm for an invalid token', async () => {775 const app = new Hono()776 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))777 app.get('/auth/*', (c) => c.text('ok'))778779 const req = new Request('http://localhost/auth/page')780 req.headers.set('Authorization', 'Bearer invalid-token')781 const res = await app.request(req)782783 expect(res.status).toBe(401)784 expect(res.headers.get('WWW-Authenticate')).toBe(785 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'786 )787 })788789 it('Should escape double quotes in the realm', async () => {790 const app = new Hono()791 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my "quoted" api' }))792 app.get('/auth/*', (c) => c.text('ok'))793794 const res = await app.request('http://localhost/auth/page')795796 expect(res.status).toBe(401)797 expect(res.headers.get('WWW-Authenticate')).toBe(798 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'799 )800 })801 })802})
modified:src/middleware/jwt/jwt.ts+13 added-1 removed
27 unmodified lines
28 * @param {SignatureKey} options.secret - A value of your secret key.29 * @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.30 * @param {SignatureAlgorithm} options.alg - An algorithm type that is used for verifying (required). Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.31 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.32 * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.33 * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.34 * @returns {MiddlewareHandler} The middleware handler function.35 *36 * @example
20 unmodified lines
57 | string58 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }59 alg: SignatureAlgorithm60 headerName?: string61 realm?: string62 verification?: VerifyOptions63}): MiddlewareHandler => {64 const verifyOpts = options.verification || {}65
23 unmodified lines
89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93 realm: options.realm,94 }),95 })96 } else {97 token = parts[1]
28 unmodified lines
126 res: unauthorizedResponse({127 ctx,128 error: 'invalid_request',129 errDescription,130 realm: options.realm,131 }),132 })133 }134
14 unmodified lines
149 ctx,150 error: 'invalid_token',151 statusText: 'Unauthorized',152 errDescription: 'token verification failure',153 realm: options.realm,154 }),155 cause,156 })157 }
8 unmodified lines
166 ctx: Context167 error: string168 errDescription: string169 statusText?: string170 realm?: string171}) {172 // `realm` and `error_description` end up inside a quoted-string, so any `"`173 // they contain has to be escaped or the header is cut short. Same handling as174 // the bearer-auth middleware.175 const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')176 const errDescription = opts.errDescription.replace(/"/g, '\\"')177178 return new Response('Unauthorized', {179 status: 401,180 statusText: opts.statusText,181 headers: {170 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,182 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,183 },184 })185}186
4 unmodified lines
added:src/middleware/method-not-allowed/index.test.ts+292 added
1import { Hono } from '../../hono'2import { methodNotAllowed } from '.'34describe('Method Not Allowed Middleware', () => {5 it('infers the environment from the app', () => {6 const app = new Hono<{ Variables: { requestId: string } }>()7 const middleware = methodNotAllowed({8 app,9 onMethodNotAllowed: (c) => c.text(c.var.requestId, 405),10 })1112 expect(middleware).toBeTypeOf('function')13 })1415 it('returns 405 with every allowed method for an existing path', async () => {16 const app = new Hono()17 app.use(methodNotAllowed({ app }))18 app.get('/resource', (c) => c.text('GET'))19 app.post('/resource', (c) => c.text('POST'))20 app.delete('/resource', (c) => c.text('DELETE'))2122 const res = await app.request('/resource', { method: 'PUT' })2324 expect(res.status).toBe(405)25 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')26 expect(await res.text()).toBe('Method Not Allowed')2728 const resUsingCachedRouter = await app.request('/resource', { method: 'OPTIONS' })29 expect(resUsingCachedRouter.status).toBe(405)30 expect(resUsingCachedRouter.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')31 })3233 it('does not affect an allowed method', async () => {34 const app = new Hono()35 app.use(methodNotAllowed({ app }))36 app.get('/resource', (c) => c.text('GET'))3738 const res = await app.request('/resource')3940 expect(res.status).toBe(200)41 expect(res.headers.has('Allow')).toBe(false)42 expect(await res.text()).toBe('GET')43 })4445 it('returns 404 when the path does not exist', async () => {46 const app = new Hono()47 app.use(methodNotAllowed({ app }))48 app.get('/resource', (c) => c.text('GET'))4950 const res = await app.request('/missing', { method: 'POST' })5152 expect(res.status).toBe(404)53 expect(res.headers.has('Allow')).toBe(false)54 })5556 it('matches parameterized and overlapping routes without duplicate methods', async () => {57 const app = new Hono()58 app.use(methodNotAllowed({ app }))59 app.get('/users/:id', (_c, next) => next())60 app.get('/users/me', (c) => c.text('me'))61 app.patch('/users/:id', (c) => c.text(c.req.param('id')))6263 const res = await app.request('/users/me', { method: 'POST' })6465 expect(res.status).toBe(405)66 expect(res.headers.get('Allow')).toBe('GET, HEAD, PATCH')67 })6869 it('preserves an intentional 404 from a handler registered for the request method', async () => {70 const app = new Hono()71 app.use(methodNotAllowed({ app }))72 app.get('/users/:id', (c) => c.notFound())73 app.post('/users/:id', (c) => c.text('Created'))7475 const res = await app.request('/users/123')7677 expect(res.status).toBe(404)78 expect(res.headers.has('Allow')).toBe(false)79 })8081 it('preserves an intentional 404 for HEAD when a GET route is registered', async () => {82 const app = new Hono()83 app.use(methodNotAllowed({ app }))84 app.get('/users/:id', (c) => c.notFound())85 app.post('/users/:id', (c) => c.text('Created'))8687 const res = await app.request('/users/123', { method: 'HEAD' })8889 expect(res.status).toBe(404)90 expect(res.headers.has('Allow')).toBe(false)91 })9293 it('preserves a 404 returned by the error handler', async () => {94 const app = new Hono()95 app.onError((_error, c) => c.text('Handled error', 404))96 app.use(methodNotAllowed({ app }))97 app.use('/resource', () => {98 throw new Error('boom')99 })100 app.get('/resource', (c) => c.text('GET'))101102 const res = await app.request('/resource', { method: 'POST' })103104 expect(res.status).toBe(404)105 expect(res.headers.has('Allow')).toBe(false)106 expect(await res.text()).toBe('Handled error')107 })108109 it('returns 405 for HEAD when the path does not support GET', async () => {110 const app = new Hono()111 app.use(methodNotAllowed({ app }))112 app.post('/resource', (c) => c.text('POST'))113114 const res = await app.request('/resource', { method: 'HEAD' })115116 expect(res.status).toBe(405)117 expect(res.headers.get('Allow')).toBe('POST')118 expect(await res.text()).toBe('')119 })120121 it('does not advertise explicit HEAD routes that Hono cannot dispatch', async () => {122 const app = new Hono()123 app.use(methodNotAllowed({ app }))124 app.on('HEAD', '/resource', (c) => c.text('HEAD'))125126 const headRes = await app.request('/resource', { method: 'HEAD' })127 expect(headRes.status).toBe(404)128 expect(headRes.headers.has('Allow')).toBe(false)129130 const putRes = await app.request('/resource', { method: 'PUT' })131 expect(putRes.status).toBe(404)132 expect(putRes.headers.has('Allow')).toBe(false)133 })134135 it('supports custom methods', async () => {136 const app = new Hono()137 app.use(methodNotAllowed({ app }))138 app.on('PURGE', '/cache', (c) => c.text('Purged'))139140 const res = await app.request('/cache', { method: 'POST' })141142 expect(res.status).toBe(405)143 expect(res.headers.get('Allow')).toBe('PURGE')144 })145146 it('compares request methods case-sensitively', async () => {147 const app = new Hono()148 app.use(methodNotAllowed({ app }))149 app.patch('/item', (c) => c.text('PATCH'))150151 const request = new Request('http://localhost/item', { method: 'PATCH' })152 Object.defineProperty(request, 'method', { value: 'patch' })153 const res = await app.request(request)154155 expect(res.status).toBe(405)156 expect(res.headers.get('Allow')).toBe('PATCH')157 })158159 it('works with routes mounted using app.route()', async () => {160 const api = new Hono()161 api.get('/resource', (c) => c.text('GET'))162 api.post('/resource', (c) => c.text('POST'))163164 const app = new Hono()165 app.use(methodNotAllowed({ app }))166 app.route('/api', api)167168 const res = await app.request('/api/resource', { method: 'DELETE' })169170 expect(res.status).toBe(405)171 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')172 })173174 it('works when installed in an app mounted using app.route()', async () => {175 const api = new Hono().basePath('/v1')176 api.use(methodNotAllowed({ app: api }))177 api.get('/resource', (c) => c.text('GET'))178 api.post('/resource', (c) => c.text('POST'))179180 const app = new Hono()181 app.route('/api', api)182183 const res = await app.request('/api/v1/resource', { method: 'DELETE' })184185 expect(res.status).toBe(405)186 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')187 })188189 it('ignores ALL routes when collecting allowed methods', async () => {190 const app = new Hono()191 app.use(methodNotAllowed({ app }))192 app.all('/resource', (_c, next) => next())193194 const res = await app.request('/resource', { method: 'POST' })195196 expect(res.status).toBe(404)197 expect(res.headers.has('Allow')).toBe(false)198 })199200 it('does not invoke the error handler for a 405 response', async () => {201 const app = new Hono()202 const onError = vi.fn(() => new Response('error', { status: 500 }))203 app.onError(onError)204 app.use(methodNotAllowed({ app }))205 app.get('/resource', (c) => c.text('GET'))206207 const res = await app.request('/resource', { method: 'POST' })208209 expect(res.status).toBe(405)210 expect(onError).not.toHaveBeenCalled()211 })212213 it('preserves downstream headers and lets outer middleware observe the final status', async () => {214 const app = new Hono()215 let observedStatus: number | undefined216217 app.use(async (c, next) => {218 await next()219 observedStatus = c.res.status220 })221 app.use(methodNotAllowed({ app }))222 app.use(async (c, next) => {223 await next()224 c.header('X-Downstream', 'true')225 })226 app.get('/resource', (c) => c.text('GET'))227228 const res = await app.request('/resource', { method: 'POST' })229230 expect(res.status).toBe(405)231 expect(res.headers.get('X-Downstream')).toBe('true')232 expect(observedStatus).toBe(405)233 })234235 it('replaces stale representation headers from the not-found response', async () => {236 const app = new Hono()237 app.use(methodNotAllowed({ app }))238 app.get('/resource', (c) => c.text('GET'))239 app.post('/resource', (c) => c.text('POST'))240 app.notFound((c) =>241 c.text('Missing', 404, {242 Allow: 'BOGUS',243 'Content-Length': '7',244 })245 )246247 const res = await app.request('/resource', { method: 'PUT' })248249 expect(res.status).toBe(405)250 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')251 expect(res.headers.has('Content-Length')).toBe(false)252 expect(await res.text()).toBe('Method Not Allowed')253 })254255 it('supports a custom method-not-allowed response', async () => {256 const app = new Hono()257 app.use(258 methodNotAllowed({259 app,260 onMethodNotAllowed: (c, allowedMethods) =>261 c.json({ error: 'Method Not Allowed', allowedMethods }, 405, {262 Allow: allowedMethods.join(', '),263 }),264 })265 )266 app.get('/resource', (c) => c.text('GET'))267 app.post('/resource', (c) => c.text('POST'))268269 const res = await app.request('/resource', { method: 'PUT' })270271 expect(res.status).toBe(405)272 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')273 expect(res.headers.get('Content-Type')).toMatch(/^application\/json/)274 expect(await res.json()).toEqual({275 error: 'Method Not Allowed',276 allowedMethods: ['GET', 'HEAD', 'POST'],277 })278 })279280 it('leaves a non-404 custom not-found response unchanged', async () => {281 const app = new Hono()282 app.use(methodNotAllowed({ app }))283 app.get('/resource', (c) => c.text('GET'))284 app.notFound((c) => c.text('Missing', 410))285286 const res = await app.request('/resource', { method: 'POST' })287288 expect(res.status).toBe(410)289 expect(res.headers.has('Allow')).toBe(false)290 expect(await res.text()).toBe('Missing')291 })292})
added:src/middleware/method-not-allowed/index.ts+141 added
1/**2 * @module3 * Method Not Allowed Middleware for Hono.4 */56import type { Context } from '../../context'7import { basePath, matchedRoutes } from '../../helper/route'8import type { Hono } from '../../hono'9import { METHOD_NAME_ALL } from '../../router'10import { TrieRouter } from '../../router/trie-router'11import type { Env, MiddlewareHandler } from '../../types'1213type MethodNotAllowedHandler<E extends Env> = (14 c: Context<E>,15 allowedMethods: string[]16) => Response | Promise<Response>1718type MethodNotAllowedOptions<E extends Env> = {19 // eslint-disable-next-line @typescript-eslint/no-explicit-any20 app: Hono<E, any, any>21 onMethodNotAllowed?: MethodNotAllowedHandler<E>22}2324/**25 * Method Not Allowed Middleware for Hono.26 *27 * Returns a `405 Method Not Allowed` response with an `Allow` header when the request path28 * matches a registered route but the request method is not supported.29 *30 * @param {MethodNotAllowedOptions} options - The options for the middleware.31 * @param {Hono} options.app - The Hono instance used by the application.32 * @param {MethodNotAllowedHandler} [options.onMethodNotAllowed] - Generates the response, including its `Allow` header.33 * @returns {MiddlewareHandler} The middleware handler function.34 *35 * @example36 * ```ts37 * const app = new Hono()38 *39 * app.use(methodNotAllowed({ app }))40 *41 * app.get('/hello', (c) => c.text('Hello!'))42 * app.post('/hello', (c) => c.text('Posted!'))43 *44 * // PUT /hello -> 405 Method Not Allowed45 * // Allow: GET, HEAD, POST46 * ```47 *48 * @example49 * ```ts50 * app.use(51 * methodNotAllowed({52 * app,53 * onMethodNotAllowed: (c, methods) =>54 * c.json({ error: 'Method Not Allowed' }, 405, { Allow: methods.join(', ') }),55 * })56 * )57 * ```58 */59export const methodNotAllowed = <E extends Env = Env>(60 options: MethodNotAllowedOptions<E>61): MiddlewareHandler<E> => {62 let methodRouter: TrieRouter<string[]> | undefined6364 return async function methodNotAllowed(c, next) {65 const routeIndex = c.req.routeIndex66 await next()6768 if (c.res.status !== 404) {69 return70 }7172 if (c.error) {73 return74 }7576 if (!methodRouter) {77 const methodsByPath = new Map<string, Set<string>>()7879 for (const route of options.app.routes) {80 // Hono does not distinguish middleware registered with `app.use()` from handlers81 // registered with `app.all()`, so `ALL` routes cannot contribute to the Allow header.82 if (route.method === METHOD_NAME_ALL || route.method === 'HEAD') {83 continue84 }8586 const methods = methodsByPath.get(route.path) ?? new Set<string>()87 methods.add(route.method)8889 // Hono dispatches HEAD requests to GET routes.90 if (route.method === 'GET') {91 methods.add('HEAD')92 }9394 methodsByPath.set(route.path, methods)95 }9697 methodRouter = new TrieRouter()98 for (const [path, methods] of methodsByPath) {99 methodRouter.add(METHOD_NAME_ALL, path, [...methods])100 }101 }102103 let requestPath = c.req.path104 const routes = matchedRoutes(c)105 const currentRoute = routes[routeIndex]106 const sourceRoute = options.app.routes.find((route) => route.handler === methodNotAllowed)107 if (currentRoute && sourceRoute) {108 const currentBasePathParts = basePath(c, routeIndex).split('/').filter(Boolean)109 const sourceBasePathLength = sourceRoute.basePath.split('/').filter(Boolean).length110 const mountBasePathParts = currentBasePathParts.slice(111 0,112 currentBasePathParts.length - sourceBasePathLength113 )114 if (mountBasePathParts.length > 0) {115 const mountBasePath = `/${mountBasePathParts.join('/')}`116 requestPath = c.req.path.slice(mountBasePath.length) || '/'117 }118 }119120 const allowedMethods = new Set<string>()121 for (const [methods] of methodRouter.match(METHOD_NAME_ALL, requestPath)[0]) {122 for (const method of methods) {123 allowedMethods.add(method)124 }125 }126127 if (allowedMethods.size === 0 || allowedMethods.has(c.req.method)) {128 return129 }130131 // Prevent stale headers from being carried over from the 404 response.132 c.res.headers.delete('Allow')133 c.res.headers.delete('Content-Length')134135 const methods = [...allowedMethods]136 const allow = methods.join(', ')137 c.res = options.onMethodNotAllowed138 ? await options.onMethodNotAllowed(c, methods)139 : c.text('Method Not Allowed', 405, { Allow: allow })140 }141}
modified:src/router/reg-exp-router/node.ts+86 added-80 removed
23 unmodified lines
24 if (b.length === 1) {25 return 126 }2728 // wildcard28 // wildcard: the only wildcard (.*) precedes the tail wildcard29 if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {30 return 130 return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 131 } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {32 return -133 }34
7 unmodified lines
42 return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length43}4445export class Node {46 // handler index of a dynamic path, or -1 for a static path terminal47 #index?: number48 #varIndex?: number49 #children: Record<string, Node> = Object.create(null)50
1 unmodified line
52 tokens: readonly string[],53 index: number,54 paramMap: ParamAssocArray,55 context: Context,55 pathErrorCheckOnly: boolean56 isStatic: boolean57 ): void {57 if (tokens.length === 0) {58 if (this.#index !== undefined) {59 throw PATH_ERROR60 }61 if (pathErrorCheckOnly) {62 return63 }58 // eslint-disable-next-line @typescript-eslint/no-this-alias59 let node: Node = this60 for (let i = 0, len = tokens.length; i < len; i++) {61 const token = tokens[i]62 const pattern =63 token.length === 164 ? token === '*'65 ? i === len - 166 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths67 : ['', '', LABEL_REG_EXP_STR]68 : null69 : token === '/*'70 ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$71 : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)7265 this.#index = index66 return67 }6869 const [token, ...restTokens] = tokens70 const pattern =71 token === '*'72 ? restTokens.length === 073 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths74 : ['', '', LABEL_REG_EXP_STR]75 : token === '/*'76 ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$77 : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)7879 let node80 if (pattern) {81 const name = pattern[1]82 let regexpStr = pattern[2] || LABEL_REG_EXP_STR83 if (name && pattern[2]) {84 if (regexpStr === '.*') {85 throw PATH_ERROR73 let nextNode: Node74 if (pattern) {75 const name = pattern[1]76 let regexpStr = pattern[2] || LABEL_REG_EXP_STR77 if (name && pattern[2]) {78 if (regexpStr === '.*') {79 throw PATH_ERROR80 }81 regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b)82 if (/\((?!\?:)/.test(regexpStr)) {83 // prefix(?:a|b) is allowed, but prefix(a|b) is not84 throw PATH_ERROR85 }86 if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {87 // a single-char pattern like :x{.} is ambiguous with a literal character88 throw PATH_ERROR89 }90 }87 regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b)88 if (/\((?!\?:)/.test(regexpStr)) {89 // prefix(?:a|b) is allowed, but prefix(a|b) is not90 throw PATH_ERROR91 }92 }9194 node = this.#children[regexpStr]95 if (!node) {96 if (97 Object.keys(this.#children).some(98 (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR99 )100 ) {101 throw PATH_ERROR92 nextNode = node.#children[regexpStr]93 if (!nextNode) {94 if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {95 for (const k in node.#children) {96 if (97 // a single-char pattern coexists with single-char literals as a literal does98 (regexpStr.length > 1 || k.length > 1) &&99 k !== ONLY_WILDCARD_REG_EXP_STR &&100 k !== TAIL_WILDCARD_REG_EXP_STR101 ) {102 throw PATH_ERROR103 }104 }105 }106 nextNode = node.#children[regexpStr] = new Node()107 }103 if (pathErrorCheckOnly) {104 return105 }106 node = this.#children[regexpStr] = new Node()108 if (name !== '') {108 node.#varIndex = context.varIndex++109 nextNode.#varIndex ??= context.varIndex++110 paramMap.push([name, nextNode.#varIndex])111 }110 }111 if (!pathErrorCheckOnly && name !== '') {112 paramMap.push([name, node.#varIndex as number])113 }114 } else {115 node = this.#children[token]116 if (!node) {117 if (118 Object.keys(this.#children).some(119 (k) =>120 k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR121 )122 ) {123 throw PATH_ERROR112 } else {113 nextNode = node.#children[token]114 if (!nextNode) {115 for (const k in node.#children) {116 if (117 k.length > 1 &&118 k !== ONLY_WILDCARD_REG_EXP_STR &&119 k !== TAIL_WILDCARD_REG_EXP_STR120 ) {121 throw PATH_ERROR122 }123 }124 nextNode = node.#children[token] = new Node()125 }125 if (pathErrorCheckOnly) {126 return127 }128 node = this.#children[token] = new Node()126 }127128 node = nextNode129 }130132 node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)131 if (node.#index !== undefined) {132 throw PATH_ERROR133 }134 node.#index = isStatic ? -1 : index135 }136137 buildRegExpStr(): string {138 const childKeys = Object.keys(this.#children).sort(compareKey)139138 const strList = childKeys.map((k) => {139 const c = this.#children[k]140 return (141 (typeof c.#varIndex === 'number'142 ? `(${k})@${c.#varIndex}`143 : regExpMetaChars.has(k)144 ? `\\${k}`145 : k) + c.buildRegExpStr()146 )147 })140 const strList = childKeys141 .map((k) => {142 const c = this.#children[k]143 const childStr = c.buildRegExpStr()144 // an empty childStr means a static-only branch, which is handled by staticMap145 return childStr === ''146 ? ''147 : (typeof c.#varIndex === 'number'148 ? `(${k})@${c.#varIndex}`149 : regExpMetaChars.has(k)150 ? `\\${k}`151 : k) + childStr152 })153 .filter(Boolean)154149 if (typeof this.#index === 'number') {155 if (typeof this.#index === 'number' && this.#index !== -1) {156 strList.unshift(`#${this.#index}`)157 }158159 if (strList.length === 0) {
9 unmodified lines
modified:src/router/reg-exp-router/router.test.ts+159 added-35 removed
1import type { ParamStash } from '../../router'1import type { ParamIndexMap, ParamStash } from '../../router'2import { UnsupportedPathError } from '../../router'3import { runTest } from '../common.case.test'4import { RegExpRouter } from './router'5
32 unmodified lines
38 })3940 describe('UnsupportedPathError', () => {41 describe('Ambiguous', () => {42 const router = new RegExpRouter<string>()4344 router.add('GET', '/:user/entries', 'get user entries')45 router.add('GET', '/entry/:name', 'get entry')46 router.add('POST', '/entry', 'create entry')4748 it('GET /entry/entries', () => {42 it('GET /entry/:name', () => {43 const router = new RegExpRouter<string>()44 router.add('GET', '/:user/entries', 'get user entries')45 expect(() => {50 router.match('GET', '/entry/entries')46 router.add('GET', '/entry/:name', 'get entry')47 }).toThrowError(UnsupportedPathError)48 })49 })5051 describe('Multiple handlers with different label', () => {56 const router = new RegExpRouter<string>()5758 router.add('GET', '/:type/:id', ':type')59 router.add('GET', '/:class/:id', ':class')60 router.add('GET', '/:model/:id', ':model')6162 it('GET /entry/123', () => {52 it('GET /:class/:id', () => {53 const router = new RegExpRouter<string>()54 router.add('GET', '/:type/:id', ':type')55 expect(() => {64 router.match('GET', '/entry/123')56 router.add('GET', '/:class/:id', ':class')57 }).toThrowError(UnsupportedPathError)58 })59 })6061 it('parent', () => {62 const router = new RegExpRouter<string>()63 router.add('GET', '/:id/:action', 'foo')72 router.add('GET', '/posts/:id', 'bar')64 expect(() => {74 router.match('GET', '/')65 router.add('GET', '/posts/:id', 'bar')66 }).toThrowError(UnsupportedPathError)67 })6869 it('child', () => {70 const router = new RegExpRouter<string>()71 router.add('GET', '/posts/:id', 'foo')81 router.add('GET', '/:id/:action', 'bar')8272 expect(() => {84 router.match('GET', '/')73 router.add('GET', '/:id/:action', 'bar')74 }).toThrowError(UnsupportedPathError)75 })7677 describe('static and dynamic', () => {78 it('static first', () => {79 const router = new RegExpRouter<string>()80 router.add('GET', '/reg-exp/router', 'foo')92 router.add('GET', '/reg-exp/:id', 'bar')9381 expect(() => {95 router.match('GET', '/')82 router.add('GET', '/reg-exp/:id', 'bar')83 }).toThrowError(UnsupportedPathError)84 })8586 it('long label', () => {87 const router = new RegExpRouter<string>()88 router.add('GET', '/reg-exp/router', 'foo')102 router.add('GET', '/reg-exp/:service', 'bar')10389 expect(() => {105 router.match('GET', '/')90 router.add('GET', '/reg-exp/:service', 'bar')91 }).toThrowError(UnsupportedPathError)92 })9394 it('dynamic first', () => {95 const router = new RegExpRouter<string>()96 router.add('GET', '/reg-exp/:id', 'bar')112 router.add('GET', '/reg-exp/router', 'foo')11397 expect(() => {115 router.match('GET', '/')98 router.add('GET', '/reg-exp/router', 'foo')99 }).toThrowError(UnsupportedPathError)100 })101 })102103 it('different regular expression', () => {104 const router = new RegExpRouter<string>()105 router.add('GET', '/:id/:action{create|update}', 'foo')123 router.add('GET', '/:id/:action{delete}', 'bar')106 expect(() => {125 router.match('GET', '/')107 router.add('GET', '/:id/:action{delete}', 'bar')108 }).toThrowError(UnsupportedPathError)109 })110111 it('ALL route added after a specific-method route', () => {112 const router = new RegExpRouter<string>()113 router.add('GET', '/foo/:a', 'foo')114 expect(() => {115 router.add('ALL', '/foo/:b', 'bar')116 }).toThrowError(UnsupportedPathError)117 })118119 it('specific-method route added after an ALL route', () => {120 const router = new RegExpRouter<string>()121 router.add('ALL', '/reg-exp/router', 'foo')122123 expect(() => {124 router.add('GET', '/reg-exp/:id', 'bar')125 }).toThrowError(UnsupportedPathError)126 })127128 it('different methods do not conflict', () => {129 const router = new RegExpRouter<string>()130 router.add('GET', '/reg-exp/router', 'foo')131 router.add('POST', '/reg-exp/:id', 'bar')132133 expect(router.match('GET', '/reg-exp/router')[0][0][0]).toBe('foo')134 expect(router.match('POST', '/reg-exp/router')[0][0][0]).toBe('bar')135 })136137 describe('Capture Group', () => {138 describe('Complex capturing group', () => {139 it('GET request', () => {140 const router = new RegExpRouter<string>()133 router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')141 expect(() => {135 router.match('GET', '/foo/bar')142 router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')143 }).toThrowError(UnsupportedPathError)144 })145 })146 })147 })148149 describe('Wildcard after label', () => {150 it('Should be able to add a tail wildcard after a label', () => {151 const router = new RegExpRouter<string>()152 router.add('GET', '/api/:x', 'label')153 router.add('GET', '/api/*', 'wildcard')154155 const [res] = router.match('GET', '/api/foo')156 expect(res.length).toBe(2)157 expect(res[0][0]).toBe('label')158 expect(res[1][0]).toBe('wildcard')159 })160161 it('Should prioritize the only wildcard over the tail wildcard regardless of the order', () => {162 for (const paths of [163 ['/a*', '/a/*'],164 ['/a/*', '/a*'],165 ]) {166 const router = new RegExpRouter<string>()167 for (const path of paths) {168 router.add('GET', path, path)169 }170 const [res] = router.match('GET', '/a')171 expect(res[0][0]).toBe('/a*')172 }173 })174 })175176 describe('Single character regexp pattern', () => {177 it('Should capture a param even if a static path created the node first', () => {178 const router = new RegExpRouter<string>()179 router.add('GET', '/a/c', 'static')180 router.add('GET', '/:x{a}/b', 'pattern')181182 const [res, stash] = router.match('GET', '/a/b')183 expect(res.length).toBe(1)184 expect(res[0][0]).toBe('pattern')185 expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['x']]).toBe('a')186 })187188 it('Should throw an error when a pattern terminal conflicts with a static terminal', () => {189 for (const paths of [190 ['/a', '/:x{a}'],191 ['/:x{a}', '/a'],192 ]) {193 const router = new RegExpRouter<string>()194 router.add('GET', paths[0], paths[0])195 expect(() => {196 router.add('GET', paths[1], paths[1])197 }).toThrowError(UnsupportedPathError)198 }199 })200201 it('Should coexist with static paths regardless of the order', () => {202 for (const paths of [203 ['/foo/bar', '/:y{b}'],204 ['/:y{b}', '/foo/bar'],205 ]) {206 const router = new RegExpRouter<string>()207 for (const path of paths) {208 router.add('GET', path, path)209 }210 expect(router.match('GET', '/foo/bar')[0][0][0]).toBe('/foo/bar')211 expect(router.match('GET', '/b')[0][0][0]).toBe('/:y{b}')212 }213 })214215 it('Should coexist with dynamic paths regardless of the order', () => {216 for (const paths of [217 ['/foo/:p', '/:x{a}'],218 ['/:x{a}', '/foo/:p'],219 ]) {220 const router = new RegExpRouter<string>()221 for (const path of paths) {222 router.add('GET', path, path)223 }224 expect(router.match('GET', '/a')[0][0][0]).toBe('/:x{a}')225 expect(router.match('GET', '/foo/v')[0][0][0]).toBe('/foo/:p')226 }227 })228229 it('Should throw an error for a single meta character pattern', () => {230 const router = new RegExpRouter<string>()231 expect(() => {232 router.add('GET', '/:x{.}', 'meta')233 }).toThrowError(UnsupportedPathError)234 })235 })236237 describe('Capture a param of a label node created by a middle wildcard', () => {238 it('Should capture the param', () => {239 const router = new RegExpRouter<string>()240 router.add('GET', '/w/*/x', 'wildcard')241 router.add('GET', '/w/:id/y', 'label')242243 const [res, stash] = router.match('GET', '/w/123/y')244 expect(res.length).toBe(1)245 expect(res[0][0]).toBe('label')246 expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['id']]).toBe('123')247 })248 })249250 describe('Static path including a colon in the middle', () => {251 it('Should be treated as a static path', () => {252 for (const paths of [253 ['/v1/name:activate', '/v1/name2'],254 ['/v1/name2', '/v1/name:activate'],255 ]) {256 const router = new RegExpRouter<string>()257 for (const path of paths) {258 router.add('GET', path, path)259 }260 expect(router.match('GET', '/v1/name:activate')[0][0][0]).toBe('/v1/name:activate')261 expect(router.match('GET', '/v1/name2')[0][0][0]).toBe('/v1/name2')262 }263 })264 })265})
modified:src/router/reg-exp-router/router.ts+71 added-112 removed
6 unmodified lines
7import { checkOptionalParameter } from '../../utils/url'8import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9import { match, emptyParam } from './matcher'10import { PATH_ERROR } from './node'11import type { ParamAssocArray } from './node'11import { Trie } from './trie'1213type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]1416// eslint-disable-next-line @typescript-eslint/no-explicit-any17const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]1815let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)16function buildWildcardRegExp(path: string): RegExp {17 return (wildcardRegExpCache[path] ??= new RegExp(18 path === '*'
7 unmodified lines
26function clearWildcardRegExpCache() {27 wildcardRegExpCache = Object.create(null)28}2934function buildMatcherFromPreprocessedRoutes<T>(35 routes: [string, HandlerWithMetadata<T>[]][]36): Matcher<T> {37 const trie = new Trie()38 const handlerData: HandlerData<T>[] = []39 if (routes.length === 0) {40 return nullMatcher41 }4243 const routesWithStaticPathFlag = routes44 .map(45 (route) => [!/\*|\/:/.test(route[0]), ...route] as [boolean, string, HandlerWithMetadata<T>[]]46 )47 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>48 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length49 )5051 const staticMap: StaticMap<T> = Object.create(null)52 for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {53 const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]54 if (pathErrorCheckOnly) {55 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]56 } else {57 j++58 }5960 let paramAssoc: ParamAssocArray61 try {62 paramAssoc = trie.insert(path, j, pathErrorCheckOnly)63 } catch (e) {64 throw e === PATH_ERROR ? new UnsupportedPathError(path) : e65 }6667 if (pathErrorCheckOnly) {68 continue69 }7071 handlerData[j] = handlers.map(([h, paramCount]) => {72 const paramIndexMap: ParamIndexMap = Object.create(null)73 paramCount -= 174 for (; paramCount >= 0; paramCount--) {75 const [key, value] = paramAssoc[paramCount]76 paramIndexMap[key] = value77 }78 return [h, paramIndexMap]79 })80 }8182 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()83 for (let i = 0, len = handlerData.length; i < len; i++) {84 for (let j = 0, len = handlerData[i].length; j < len; j++) {85 const map = handlerData[i][j]?.[1]86 if (!map) {87 continue88 }89 const keys = Object.keys(map)90 for (let k = 0, len = keys.length; k < len; k++) {91 map[keys[k]] = paramReplacementMap[map[keys[k]]]92 }93 }94 }9596 const handlerMap: HandlerData<T>[] = []97 // using `in` because indexReplacementMap is a sparse array98 for (const i in indexReplacementMap) {99 handlerMap[i] = handlerData[indexReplacementMap[i]]100 }101102 return [regexp, handlerMap, staticMap] as Matcher<T>103}10430function findMiddleware<T>(31 middleware: Record<string, T[]> | undefined,32 path: string33): T[] | undefined {
13 unmodified lines
47export class RegExpRouter<T> implements Router<T> {48 name: string = 'RegExpRouter'49 #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>50 #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>51 #tries?: Record<string, Trie>5253 constructor() {54 this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }55 this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }56 this.#tries = { [METHOD_NAME_ALL]: new Trie() }57 }5859 #insertPath(method: string, path: string) {60 try {61 this.#tries![method].insert(path, !/\*|\/:/.test(path))62 } catch (e) {63 throw e === PATH_ERROR ? new UnsupportedPathError(path) : e64 }65 }6667 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69 const routes = this.#routes70
1 unmodified line
72 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)73 }7475 if (!middleware[method]) {76 this.#tries![method] = new Trie()77 ;[middleware, routes].forEach((handlerMap) => {78 handlerMap[method] = Object.create(null)79 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81 this.#insertPath(method, p)82 })83 })84 }85
4 unmodified lines
90 const paramCount = (path.match(/\/:/g) || []).length9192 if (/\*$/.test(path)) {93 const re = buildWildcardRegExp(path)157 if (method === METHOD_NAME_ALL) {158 Object.keys(middleware).forEach((m) => {159 middleware[m][path] ||=94 Object.keys(middleware).forEach((m) => {95 if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {96 this.#insertPath(m, path)97 middleware[m][path] =98 findMiddleware(middleware[m], path) ||99 findMiddleware(middleware[METHOD_NAME_ALL], path) ||100 []163 })164 } else {165 middleware[method][path] ||=166 findMiddleware(middleware[method], path) ||167 findMiddleware(middleware[METHOD_NAME_ALL], path) ||168 []169 }101 }102 })103 Object.keys(middleware).forEach((m) => {104 if (method === METHOD_NAME_ALL || method === m) {105 Object.keys(middleware[m]).forEach((p) => {106 re.test(p) && middleware[m][p].push([handler, paramCount])
17 unmodified lines
124 const path = paths[i]125126 Object.keys(routes).forEach((m) => {127 if (method === METHOD_NAME_ALL || method === m) {128 if (!routes[m][path]) {129 this.#insertPath(m, path)195 routes[m][path] ||= [196 ...(findMiddleware(middleware[m], path) ||197 findMiddleware(middleware[METHOD_NAME_ALL], path) ||198 []),199 ]130 routes[m][path] = [131 ...(findMiddleware(middleware[m], path) ||132 findMiddleware(middleware[METHOD_NAME_ALL], path) ||133 []),134 ]135 }136 routes[m][path].push([handler, paramCount - len + i + 1])137 }138 })139 }
10 unmodified lines
150 matchers[method] ||= this.#buildMatcher(method)151 })152153 // Release cache218 this.#middleware = this.#routes = undefined154 this.#middleware = this.#routes = this.#tries = undefined155 clearWildcardRegExpCache()156157 return matchers158 }159224 #buildMatcher(method: string): Matcher<T> | null {225 const routes: [string, HandlerWithMetadata<T>[]][] = []160 #buildMatcher(method: string): Matcher<T> {161 const middleware = this.#middleware![method]162 const routes = this.#routes![method]163227 let hasOwnRoute = method === METHOD_NAME_ALL164 const trie = this.#tries![method]165 const staticMap: StaticMap<T> = Object.create(null)166 const handlerData: HandlerData<T>[] = []167229 ;[this.#middleware!, this.#routes!].forEach((r) => {230 const ownRoute = r[method]231 ? Object.keys(r[method]).map((path) => [path, r[method][path]])232 : []233 if (ownRoute.length !== 0) {234 hasOwnRoute ||= true235 routes.push(...(ownRoute as [string, HandlerWithMetadata<T>[]][]))236 } else if (method !== METHOD_NAME_ALL) {237 routes.push(238 ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [239 string,240 HandlerWithMetadata<T>[],241 ][])242 )168 ;[middleware, routes].forEach((r) => {169 for (const path in r) {170 const handlers = r[path]171 const pathData = trie.paths[path]172 if (!pathData) {173 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]174 continue175 }176 const paramAssoc = pathData[1]177 handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {178 const paramIndexMap: ParamIndexMap = Object.create(null)179 paramCount -= 1180 for (; paramCount >= 0; paramCount--) {181 const [key, value] = paramAssoc[paramCount]182 paramIndexMap[key] = value183 }184 return [h, paramIndexMap]185 })186 }187 })188246 if (!hasOwnRoute) {247 return null248 } else {249 return buildMatcherFromPreprocessedRoutes(routes)189 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()190 for (let i = 0, len = handlerData.length; i < len; i++) {191 for (let j = 0, len = handlerData[i].length; j < len; j++) {192 const map = handlerData[i][j]?.[1]193 if (!map) {194 continue195 }196 const keys = Object.keys(map)197 for (let k = 0, len = keys.length; k < len; k++) {198 map[keys[k]] = paramReplacementMap[map[keys[k]]]199 }200 }201 }202203 const handlerMap: HandlerData<T>[] = []204 // using `in` because indexReplacementMap is a sparse array205 for (const i in indexReplacementMap) {206 handlerMap[i] = handlerData[indexReplacementMap[i]]207 }208209 return [regexp, handlerMap, staticMap] as Matcher<T>210 }211}
modified:src/router/reg-exp-router/trie.ts+15 added-6 removed
4 unmodified lines
56export class Trie {7 #context: Context = { varIndex: 0 }8 #root: Node = new Node()9 #index: number = 010 // dynamic path -> [handler index, param assoc]; static paths are not registered11 paths: Record<string, [number, ParamAssocArray]> = Object.create(null)1210 insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {13 insert(path: string, isStatic: boolean): void {14 if (isStatic) {15 // a static path has no pattern; every character is a literal token16 this.#root.insert(path.split(''), 0, [], this.#context, true)17 return18 }1920 const paramAssoc: ParamAssocArray = []2122 const groups: [string, string][] = [] // [mark, original string]23 let markedPath = path24 for (let i = 0; ; ) {25 let replaced = false16 path = path.replace(/\{[^}]+\}/g, (m) => {26 markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {27 const mark = `@\\${i}`28 groups[i] = [mark, m]29 i++30 replaced = true
8 unmodified lines
39 * - pattern (:label, :label{0-9]+}, ...)40 * - /* wildcard41 * - character42 */33 const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []43 const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []44 for (let i = groups.length - 1; i >= 0; i--) {45 const [mark] = groups[i]46 for (let j = tokens.length - 1; j >= 0; j--) {47 if (tokens[j].indexOf(mark) !== -1) {
2 unmodified lines
50 }51 }52 }5344 this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)4546 return paramAssoc54 this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false)55 this.paths[path] = [this.#index++, paramAssoc]56 }5758 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {59 let regexp = this.#root.buildRegExpStr()
24 unmodified lines
modified:src/utils/cookie.ts+2 added-3 removed
1 unmodified line
2 * @module3 * Cookie utility.4 */56import { decodeURIComponent_, tryDecode } from './url'6import { tryDecodeURIComponent } from './url'78export type Cookie = Record<string, string>9export type SignedCookie = Record<string, string | false>10
121 unmodified lines
132 if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {133 cookieValue = cookieValue.slice(1, -1)134 }135 if (validCookieValueRegEx.test(cookieValue)) {136 parsedCookie[cookieName] =137 cookieValue.indexOf('%') !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue136 parsedCookie[cookieName] = tryDecodeURIComponent(cookieValue)137 if (name) {138 // Fast-path: return only the demanded-key immediately. Other keys are not needed.139 break140 }
140 unmodified lines
modified:src/utils/headers.ts+23 added-1 removed
15 unmodified lines
16 | 'Accept-Features'17 | 'Accept-Language'18 | 'Accept-Patch'19 | 'Accept-Post'20 | 'Accept-Query'21 | 'Accept-Ranges'22 | 'Accept-Signature'23 | 'Access-Control'24 | 'Access-Control-Allow-Credentials'
3 unmodified lines
28 | 'Access-Control-Expose-Headers'29 | 'Access-Control-Max-Age'30 | 'Access-Control-Request-Headers'31 | 'Access-Control-Request-Method'32 | 'Activate-Storage-Access'33 | 'Age'34 | 'Allow'35 | 'ALPN'36 | 'Alt-Svc'
10 unmodified lines
47 | 'C-Opt'48 | 'C-PEP'49 | 'C-PEP-Info'50 | 'Cache-Control'51 | 'Cache-Group-Invalidation'52 | 'Cache-Groups'53 | 'Cache-Status'54 | 'Cal-Managed-ID'55 | 'CalDAV-Timezones'56 | 'Capsule-Protocol'
46 unmodified lines
103 | 'Deprecation'104 | 'Depth'105 | 'Derived-From'106 | 'Destination'107 | 'Detached-JWS'108 | 'Differential-ID'109 | 'Dictionary-ID'110 | 'Digest'111 | 'DPoP'
19 unmodified lines
131 | 'If-Schedule-Tag-Match'132 | 'If-Unmodified-Since'133 | 'IM'134 | 'Include-Referred-Token-Binding-ID'135 | 'Incremental'136 | 'Isolation'137 | 'Keep-Alive'138 | 'Label'139 | 'Last-Event-ID'
65 unmodified lines
205 | 'Retry-After'206 | 'Safe'207 | 'Schedule-Reply'208 | 'Schedule-Tag'209 | 'Sec-Fetch-Dest'210 | 'Sec-Fetch-Mode'211 | 'Sec-Fetch-Site'212 | 'Sec-Fetch-Storage-Access'213 | 'Sec-Fetch-User'214 | 'Sec-GPC'215 | 'Sec-Purpose'216 | 'Sec-Token-Binding'217 | 'Sec-WebSocket-Accept'
5 unmodified lines
223 | 'Server'224 | 'Server-Timing'225 | 'Set-Cookie'226 | 'Set-Cookie2'227 | 'Set-Txn'228 | 'SetProfile'229 | 'Signature'230 | 'Signature-Input'231 | 'SLUG'
12 unmodified lines
244 | 'Tracestate'245 | 'Trailer'246 | 'Transfer-Encoding'247 | 'TTL'248 | 'Unencoded-Digest'249 | 'Upgrade'250 | 'Urgency'251 | 'URI'252 | 'Use-As-Dictionary'
3 unmodified lines
256 | 'Via'257 | 'Want-Content-Digest'258 | 'Want-Digest'259 | 'Want-Repr-Digest'260 | 'Want-Unencoded-Digest'261 | 'Warning'262 | 'WWW-Authenticate'263 | 'X-Content-Type-Options'264 | 'X-Frame-Options'265266export type ResponseHeader =267 | 'Accept-Query'268 | 'Access-Control-Allow-Credentials'269 | 'Access-Control-Allow-Headers'270 | 'Access-Control-Allow-Methods'271 | 'Access-Control-Allow-Origin'272 | 'Access-Control-Expose-Headers'273 | 'Access-Control-Max-Age'274 | 'Activate-Storage-Access'275 | 'Age'276 | 'Allow'277 | 'Cache-Control'278 | 'Cache-Group-Invalidation'279 | 'Cache-Groups'280 | 'Clear-Site-Data'281 | 'Content-Disposition'282 | 'Content-Encoding'283 | 'Content-Language'
9 unmodified lines
293 | 'Cross-Origin-Resource-Policy'294 | 'Date'295 | 'ETag'296 | 'Expires'297 | 'Incremental'298 | 'Last-Modified'299 | 'Location'300 | 'Permissions-Policy'301 | 'Pragma'
20 unmodified lines
322 | 'Server'323 | 'Server-Timing'324 | 'Service-Worker-Navigation-Preload'325 | 'Set-Cookie'326 | 'Set-Txn'327 | 'Strict-Transport-Security'328 | 'Timing-Allow-Origin'329 | 'Trailer'330 | 'Transfer-Encoding'331 | 'Unencoded-Digest'332 | 'Upgrade'333 | 'Vary'313 | 'WWW-Authenticate'334 | 'Want-Unencoded-Digest'335 | 'Warning'336 | 'WWW-Authenticate'337 | 'X-Content-Type-Options'338 | 'X-DNS-Prefetch-Control'339 | 'X-Frame-Options'340 | 'X-Permitted-Cross-Domain-Policies'
15 unmodified lines
modified:src/utils/url.ts+6 added-6 removed
203 unmodified lines
204205 return results.filter((v, i, a) => a.indexOf(v) === i)206}207208export const tryDecodeURIComponent = (str: string): string =>209 str.indexOf('%') !== -1 ? tryDecode(str, decodeURIComponent_) : str210211// Optimized209const _decodeURI = (value: string) => {210 if (!/[%+]/.test(value)) {211 return value212 }212const _decodeURI = (value: string): string => {213 if (value.indexOf('+') !== -1) {214 value = value.replace(/\+/g, ' ')215 }216 return value.indexOf('%') !== -1 ? tryDecode(value, decodeURIComponent_) : value216 return tryDecodeURIComponent(value)217}218219const _getQueryParam = (220 url: string,
1 unmodified line
222 multiple?: boolean223): string | undefined | Record<string, string> | string[] | Record<string, string[]> => {224 let encoded225226 if (!multiple && key && !/[%+]/.test(key)) {226 if (!multiple && key && key.indexOf('%') === -1 && key.indexOf('+') === -1) {227 // optimized for unencoded key228229 let keyIndex = url.indexOf('?', 8)230 if (keyIndex === -1) {
89 unmodified lines
modified:src/context.ts+28 added-15 removed
604 unmodified lines
605 data: Data | null,606 arg?: StatusCode | ResponseOrInit,607 headers?: HeaderRecord608 ): Response {609 const responseHeaders = this.#res610 ? new Headers(this.#res.headers)611 : (this.#preparedHeaders ?? new Headers())609 let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders610613 if (typeof arg === 'object' && 'headers' in arg) {614 const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers)615 for (const [key, value] of argHeaders) {616 if (key.toLowerCase() === 'set-cookie') {611 if (typeof arg === 'object' && arg.headers) {612 responseHeaders ??= new Headers()613 for (const [key, value] of new Headers(arg.headers)) {614 if (key === 'set-cookie') {615 responseHeaders.append(key, value)616 } else {617 responseHeaders.set(key, value)618 }619 }620 }621622 if (headers) {625 for (const [k, v] of Object.entries(headers)) {626 if (typeof v === 'string') {627 responseHeaders.set(k, v)628 } else {629 responseHeaders.delete(k)630 for (const v2 of v) {631 responseHeaders.append(k, v2)623 if (!responseHeaders) {624 let count = 0625 for (const k in headers) {626 if (++count > 1 || typeof headers[k as keyof HeaderRecord] !== 'string') {627 responseHeaders = new Headers()628 break629 }630 }631 }632 if (responseHeaders) {633 for (const k in headers) {634 const v = headers[k as keyof HeaderRecord]635 if (typeof v === 'string') {636 responseHeaders.set(k, v)637 } else {638 responseHeaders.delete(k)639 for (const v2 of v) {640 responseHeaders.append(k, v2)641 }642 }643 }644 }645 }646647 const status = typeof arg === 'number' ? arg : (arg?.status ?? this.#status)638 return createResponseInstance(data, { status, headers: responseHeaders })648 return createResponseInstance(data, {649 status,650 headers: responseHeaders ?? (headers as Record<string, string> | undefined),651 })652 }653654 newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))655
138 unmodified lines
modified:src/hono-base.ts+4 added-3 removed
105 unmodified lines
106 put!: HandlerInterface<E, 'put', S, BasePath, CurrentPath>107 delete!: HandlerInterface<E, 'delete', S, BasePath, CurrentPath>108 options!: HandlerInterface<E, 'options', S, BasePath, CurrentPath>109 patch!: HandlerInterface<E, 'patch', S, BasePath, CurrentPath>110 query!: HandlerInterface<E, 'query', S, BasePath, CurrentPath>111 all!: HandlerInterface<E, 'all', S, BasePath, CurrentPath>112 on: OnHandlerInterface<E, S, BasePath>113 use: MiddlewareHandlerInterface<E, S, BasePath>114
356 unmodified lines
471 *472 * @see {@link https://hono.dev/docs/api/hono#fetch}473 *474 * @param {Request} request - request Object of request474 * @param {Env} Env - env Object475 * @param {ExecutionContext} - context of execution475 * @param {Env} env - env Object476 * @param {ExecutionContext} executionCtx - context of execution477 * @returns {Response | Promise<Response>} response of request478 *479 */480 fetch: (481 request: Request,481 Env?: E['Bindings'] | {},482 env?: E['Bindings'] | {},483 executionCtx?: ExecutionContext484 ) => Response | Promise<Response> = (request, ...rest) => {485 return this.#dispatch(request, rest[1], rest[0], request.method)486 }
60 unmodified lines
modified:src/hono.test.ts+41 added
2077 unmodified lines
2078 expect(res.status).toBe(404)2079 })2080})20812082describe('Using QUERY with `app.query` and `app.on`', () => {2083 it('Should handle QUERY method with app.query()', async () => {2084 const app = new Hono()20852086 app.query('/query', (c) => c.text('Accepted', 202))20872088 const req = new Request('http://localhost/query', {2089 method: 'QUERY',2090 })2091 const res = await app.request(req)2092 expect(res.status).toBe(202)2093 expect(await res.text()).toBe('Accepted')2094 })20952096 it('Should handle QUERY method with RegExpRouter', async () => {2097 const app = new Hono({ router: new RegExpRouter() })20982099 app.on('QUERY', '/query', (c) => c.text('Accepted', 202))21002101 const req = new Request('http://localhost/query', {2102 method: 'QUERY',2103 })2104 const res = await app.request(req)2105 expect(res.status).toBe(202)2106 expect(await res.text()).toBe('Accepted')2107 })21082109 it('Should handle QUERY method with TrieRouter', async () => {2110 const app = new Hono({ router: new TrieRouter() })21112112 app.on('QUERY', '/query', (c) => c.text('Accepted', 202))21132114 const req = new Request('http://localhost/query', {2115 method: 'QUERY',2116 })2117 const res = await app.request(req)2118 expect(res.status).toBe(202)2119 expect(await res.text()).toBe('Accepted')2120 })2121})21222123describe('Multiple paths with one handler', () => {2124 const app = new Hono()21252126 const paths = ['/hello', '/ja/hello', '/en/hello']
1674 unmodified lines
modified:src/request.ts+7 added-11 removed
13 unmodified lines
14import { parseBody } from './utils/body'15import type { BodyData, ParseBodyOptions } from './utils/body'16import type { CustomHeader, RequestHeader } from './utils/headers'17import type { Simplify, UnionToIntersection } from './utils/types'18import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'18import { getQueryParam, getQueryParams, tryDecodeURIComponent } from './utils/url'1920type Body = {21 json: any22 text: string
7 unmodified lines
30type RequiredRequestInit = Required<Omit<RequestInit, OptionalRequestInitProperties>> & {31 [Key in OptionalRequestInitProperties]?: RequestInit[Key]32}3334const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)3534export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {35 /**36 * `.raw` can get the raw Request object.37 *
9 unmodified lines
47 * ```48 */49 raw: Request5053 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData51 #validatedData: { [K in keyof ValidationTargets]?: {} } | undefined // Short name of validatedData52 #matchResult: Result<[unknown, RouterRoute]>53 routeIndex: number = 054 /**55 * `.path` can get the pathname of the request.
17 unmodified lines
73 ) {74 this.raw = request75 this.path = path76 this.#matchResult = matchResult79 this.#validatedData = {}77 }7879 /**80 * `.req.param()` gets the path parameters.
21 unmodified lines
102103 #getDecodedParam(key: string): string | undefined {104 const paramKey = this.#matchResult[0][this.routeIndex][1][key]105 const param = this.#getParamValue(paramKey)109 return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param106 return param && tryDecodeURIComponent(param)107 }108109 #getAllDecodedParams(): Record<string, string> {110 const decoded: Record<string, string> = {}
1 unmodified line
112 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])113 for (const key of keys) {114 const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])115 if (value !== undefined) {119 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value116 decoded[key] = tryDecodeURIComponent(value)117 }118 }119120 return decoded
100 unmodified lines
221 if (cachedBody) {222 return cachedBody223 }224228 const anyCachedKey = Object.keys(bodyCache)[0]229 if (anyCachedKey) {225 for (const anyCachedKey in bodyCache) {226 return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {227 if (anyCachedKey === 'json') {228 body = JSON.stringify(body)229 }
102 unmodified lines
332 * @param target - The target of the validation.333 * @param data - The validated data to add.334 */335 addValidatedData(target: keyof ValidationTargets, data: {}) {340 this.#validatedData[target] = data336 ;(this.#validatedData ??= {})[target] = data337 }338339 /**340 * Gets validated data from the request.
4 unmodified lines
345 * @see https://hono.dev/docs/api/request#valid346 */347 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>348 valid(target: keyof ValidationTargets) {353 return this.#validatedData[target] as unknown349 return this.#validatedData?.[target] as unknown350 }351352 /**353 * `.url()` can get the request url strings.
156 unmodified lines
modified:src/router.ts+1 added-1 removed
12 unmodified lines
13export const METHOD_NAME_ALL_LOWERCASE = 'all' as const14/**15 * Array of supported HTTP methods.16 */17export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const17export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch', 'query'] as const18/**19 * Error message indicating that a route cannot be added because the matcher is already built.20 */21export const MESSAGE_MATCHER_IS_ALREADY_BUILT =
82 unmodified lines
modified:jsr.json+1 added
43 unmodified lines
44 "./jwk": "./src/middleware/jwk/jwk.ts",45 "./timeout": "./src/middleware/timeout/index.ts",46 "./timing": "./src/middleware/timing/timing.ts",47 "./logger": "./src/middleware/logger/index.ts",48 "./method-not-allowed": "./src/middleware/method-not-allowed/index.ts",49 "./method-override": "./src/middleware/method-override/index.ts",50 "./powered-by": "./src/middleware/powered-by/index.ts",51 "./pretty-json": "./src/middleware/pretty-json/index.ts",52 "./request-id": "./src/middleware/request-id/request-id.ts",
60 unmodified lines
modified:package.json+8 added
229 unmodified lines
230 "types": "./dist/types/middleware/logger/index.d.ts",231 "import": "./dist/middleware/logger/index.js",232 "require": "./dist/cjs/middleware/logger/index.js"233 },234 "./method-not-allowed": {235 "types": "./dist/types/middleware/method-not-allowed/index.d.ts",236 "import": "./dist/middleware/method-not-allowed/index.js",237 "require": "./dist/cjs/middleware/method-not-allowed/index.js"238 },239 "./method-override": {240 "types": "./dist/types/middleware/method-override/index.d.ts",241 "import": "./dist/middleware/method-override/index.js",242 "require": "./dist/cjs/middleware/method-override/index.js"
289 unmodified lines
532 ],533 "logger": [534 "./dist/types/middleware/logger"535 ],536 "method-not-allowed": [537 "./dist/types/middleware/method-not-allowed"538 ],539 "method-override": [540 "./dist/types/middleware/method-override"541 ],542 "powered-by": [
164 unmodified lines