Merge pull request #2454 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 GitHub · parents 98d4334, 545203f · Browse files · 55 files·+2616 added−782 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
55 files+2616 added−782 removed
- tests:+1255 added−423 removed
- other:+1361 added−359 removed
Provenance
- Commit
eb97ee2- Tree
a2a7ebc- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
98d4334- Parent 2
545203f
55 files changed+2616 added−782 removed
modified:deno_dist/helper/ssg/ssg.ts+26 added-14 removed
28 unmodified lines29 files: string[]30 error?: Error31 }32 33-const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34- const extension = determineExtension(mimeType)33+const generateFilePath = (34+ routePath: string,35+ outDir: string,36+ mimeType: string,37+ extensionMap?: Record<string, string>38+) => {39+ const extension = determineExtension(mimeType, extensionMap)40 41 if (routePath.endsWith(`.${extension}`)) {42 return joinPaths(outDir, routePath)43 }22 unmodified lines66 )67 }68 }69 65-const determineExtension = (mimeType: string): string => {66- switch (mimeType) {67- case 'text/html':68- return 'html'69- case 'text/xml':70- case 'application/xml':71- return 'xml'72- default: {73- return getExtension(mimeType) || 'html'74- }70+export const defaultExtensionMap: Record<string, string> = {71+ 'text/html': 'html',72+ 'text/xml': 'xml',73+ 'application/xml': 'xml',74+ 'application/yaml': 'yaml',75+}76+77+const determineExtension = (78+ mimeType: string,79+ userExtensionMap?: Record<string, string>80+): string => {81+ const extensionMap = userExtensionMap || defaultExtensionMap82+ if (mimeType in extensionMap) {83+ return extensionMap[mimeType]84 }85+ return getExtension(mimeType) || 'html'86 }87 88 export type BeforeRequestHook = (req: Request) => Request | false | Promise<Request | false>89 export type AfterResponseHook = (res: Response) => Response | false | Promise<Response | false>4 unmodified lines94 beforeRequestHook?: BeforeRequestHook95 afterResponseHook?: AfterResponseHook96 afterGenerateHook?: AfterGenerateHook97 concurrency?: number98+ extensionMap?: Record<string, string>99 }100 101 /**102 * @experimental111 unmodified lines214 const createdDirs: Set<string> = new Set()215 export const saveContentToFile = async (216 data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,217 fsModule: FileSystemModule,207- outDir: string218+ outDir: string,219+ extensionMap?: Record<string, string>220 ): Promise<string | undefined> => {221 const awaitedData = await data222 if (!awaitedData) {223 return224 }225 const { routePath, content, mimeType } = awaitedData214- const filePath = generateFilePath(routePath, outDir, mimeType)226+ const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap)227 const dirPath = dirname(filePath)228 229 if (!createdDirs.has(dirPath)) {230 await fsModule.mkdir(dirPath, { recursive: true })86 unmodified linesmodified:deno_dist/jsx/dom/index.ts+3 added
13 unmodified lines14151617181920212246 unmodified lines69707172737475767717 unmodified lines95969798991001011021038 unmodified lines13 unmodified lines useViewTransition, useMemo, useLayoutEffect, useReducer, useId, useDebugValue,} from '../hooks/index.ts'import { Suspense, ErrorBoundary } from './components.ts'import { createContext } from './context.ts'46 unmodified lines useViewTransition, useMemo, useLayoutEffect, useReducer, useId, useDebugValue, Suspense, ErrorBoundary, createContext,17 unmodified lines useViewTransition, useMemo, useLayoutEffect, useReducer, useId, useDebugValue, Suspense, ErrorBoundary, createContext,8 unmodified linesmodified:deno_dist/jsx/hooks/index.ts+3 added
347 unmodified lines348 }349 return memoArray[hookIndex][0] as T350 }351 352+let idCounter = 0353+export const useId = (): string => useMemo(() => `:r${(idCounter++).toString(32)}:`, [])354+355 // Define to avoid errors. This hook currently does nothing.356 // eslint-disable-next-line @typescript-eslint/no-unused-vars357 export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}modified:deno_dist/jsx/index.ts+3 added
13 unmodified lines14151617181920212211 unmodified lines34353637383940414218 unmodified lines61626364656667686911 unmodified lines13 unmodified lines useViewTransition, useMemo, useLayoutEffect, useReducer, useId, useDebugValue,} from './hooks/index.ts'import { Suspense } from './streaming.ts'
11 unmodified lines useEffect, useRef, useCallback, useReducer, useId, useDebugValue, use, startTransition, useTransition,18 unmodified lines useEffect, useRef, useCallback, useReducer, useId, useDebugValue, use, startTransition, useTransition,11 unmodified linesmodified:deno_dist/middleware/basic-auth/index.ts+39 added-10 removed
1+import type { Context } from '../../context.ts'2 import { HTTPException } from '../../http-exception.ts'3 import type { HonoRequest } from '../../request.ts'4 import type { MiddlewareHandler } from '../../types.ts'5 import { timingSafeEqual } from '../../utils/buffer.ts'20 unmodified lines26 27 return { username: userPass[1], password: userPass[2] }28 }29 30+type BasicAuthOptions =31+ | {32+ username: string33+ password: string34+ realm?: string35+ hashFunction?: Function36+ }37+ | {38+ verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean>39+ realm?: string40+ hashFunction?: Function41+ }42+43 export const basicAuth = (30- options: { username: string; password: string; realm?: string; hashFunction?: Function },44+ options: BasicAuthOptions,45 ...users: { username: string; password: string }[]46 ): MiddlewareHandler => {33- if (!options) {34- throw new Error('basic auth middleware requires options for "username and password"')47+ const usernamePasswordInOptions = 'username' in options && 'password' in options48+ const verifyUserInOptions = 'verifyUser' in options49+50+ if (!(usernamePasswordInOptions || verifyUserInOptions)) {51+ throw new Error(52+ 'basic auth middleware requires options for "username and password" or "verifyUser"'53+ )54 }55 56 if (!options.realm) {57 options.realm = 'Secure Area'58 }40- users.unshift({ username: options.username, password: options.password })59 60+ if (usernamePasswordInOptions) {61+ users.unshift({ username: options.username, password: options.password })62+ }63+64 return async function basicAuth(ctx, next) {65 const requestUser = auth(ctx.req)66 if (requestUser) {45- for (const user of users) {46- const [usernameEqual, passwordEqual] = await Promise.all([47- timingSafeEqual(user.username, requestUser.username, options.hashFunction),48- timingSafeEqual(user.password, requestUser.password, options.hashFunction),49- ])50- if (usernameEqual && passwordEqual) {67+ if (verifyUserInOptions) {68+ if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) {69 await next()70 return71 }72+ } else {73+ for (const user of users) {74+ const [usernameEqual, passwordEqual] = await Promise.all([75+ timingSafeEqual(user.username, requestUser.username, options.hashFunction),76+ timingSafeEqual(user.password, requestUser.password, options.hashFunction),77+ ])78+ if (usernameEqual && passwordEqual) {79+ await next()80+ return81+ }82+ }83 }84 }85 const res = new Response('Unauthorized', {86 status: 401,7 unmodified linesmodified:deno_dist/middleware/bearer-auth/index.ts+20 added-8 removed
1+import type { Context } from '../../context.ts'2 import { HTTPException } from '../../http-exception.ts'3 import type { MiddlewareHandler } from '../../types.ts'4 import { timingSafeEqual } from '../../utils/buffer.ts'5 6 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7 const PREFIX = 'Bearer'8 9+type BearerAuthOptions =8-export const bearerAuth = (options: {9- token: string | string[]10- realm?: string11- prefix?: string12- hashFunction?: Function13-}): MiddlewareHandler => {14- if (!options.token) {10+ | {11+ token: string | string[]12+ realm?: string13+ prefix?: string14+ hashFunction?: Function15+ }16+ | {17+ realm?: string18+ prefix?: string19+ verifyToken: (token: string, c: Context) => boolean | Promise<boolean>20+ hashFunction?: Function21+ }22+23+export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {24+ if (!('token' in options || 'verifyToken' in options)) {25 throw new Error('bearer auth middleware requires options for "token"')26 }27 if (!options.realm) {28 options.realm = ''29 unmodified lines58 })59 throw new HTTPException(400, { res })60 } else {61 let equal = false62+ if ('verifyToken' in options) {63+ equal = await options.verifyToken(match[1], c)52- if (typeof options.token === 'string') {64+ } else if (typeof options.token === 'string') {65 equal = await timingSafeEqual(options.token, match[1], options.hashFunction)66 } else if (Array.isArray(options.token) && options.token.length > 0) {67 for (const token of options.token) {68 if (await timingSafeEqual(token, match[1], options.hashFunction)) {20 unmodified linesmodified:deno_dist/middleware/cache/index.ts+36 added-3 removed
3 unmodified lines4 export const cache = (options: {5 cacheName: string6 wait?: boolean7 cacheControl?: string8+ vary?: string | string[]9 }): MiddlewareHandler => {10 if (!globalThis.caches) {11 console.log('Cache Middleware is not enabled because caches is not defined.')12 return async (_c, next) => await next()2 unmodified lines15 if (options.wait === undefined) {16 options.wait = false17 }18 18- const directives = options.cacheControl?.split(',').map((directive) => directive.toLowerCase())19+ const cacheControlDirectives = options.cacheControl20+ ?.split(',')21+ .map((directive) => directive.toLowerCase())22+ const varyDirectives = Array.isArray(options.vary)23+ ? options.vary24+ : options.vary?.split(',').map((directive) => directive.trim())25+ // RFC 7231 Section 7.1.4 specifies that "*" is not allowed in Vary header.26+ // See: https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.427+ if (options.vary?.includes('*')) {28+ throw new Error(29+ 'Middleware vary configuration cannot include "*", as it disallows effective caching.'30+ )31+ }32 33 const addHeader = (c: Context) => {21- if (directives) {34+ if (cacheControlDirectives) {35 const existingDirectives =36 c.res.headers37 .get('Cache-Control')38 ?.split(',')39 .map((d) => d.trim().split('=', 1)[0]) ?? []27- for (const directive of directives) {40+ for (const directive of cacheControlDirectives) {41 let [name, value] = directive.trim().split('=', 2)42 name = name.toLowerCase()43 if (!existingDirectives.includes(name)) {44 c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true })45 }46 }47 }48+49+ if (varyDirectives) {50+ const existingDirectives =51+ c.res.headers52+ .get('Vary')53+ ?.split(',')54+ .map((d) => d.trim()) ?? []55+56+ const vary = Array.from(57+ new Set(58+ [...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase())59+ )60+ ).sort()61+62+ if (vary.includes('*')) {63+ c.header('Vary', '*')64+ } else {65+ c.header('Vary', vary.join(', '))66+ }67+ }68 }69 70 return async function cache(c, next) {71 const key = c.req.url19 unmodified linesmodified:deno_dist/middleware/cors/index.ts+3 added-2 removed
1+import type { Context } from '../../context.ts'2 import type { MiddlewareHandler } from '../../types.ts'3 4 type CORSOptions = {4- origin: string | string[] | ((origin: string) => string | undefined | null)5+ origin: string | string[] | ((origin: string, c: Context) => string | undefined | null)6 allowMethods?: string[]7 allowHeaders?: string[]8 maxAge?: number9 credentials?: boolean26 unmodified lines36 function set(key: string, value: string) {37 c.res.headers.set(key, value)38 }39 39- const allowOrigin = findAllowOrigin(c.req.header('origin') || '')40+ const allowOrigin = findAllowOrigin(c.req.header('origin') || '', c)41 if (allowOrigin) {42 set('Access-Control-Allow-Origin', allowOrigin)43 }44 47 unmodified linesmodified:deno_dist/middleware/jwt/index.ts+14 added-8 removed
1 unmodified line2 import { getCookie } from '../../helper/cookie/index.ts'3 import { HTTPException } from '../../http-exception.ts'4 import type { MiddlewareHandler } from '../../types.ts'5 import { Jwt } from '../../utils/jwt/index.ts'6-import type { AlgorithmTypes } from '../../utils/jwt/types.ts'6 import '../../context.ts'7+import type { SignatureAlgorithm } from '../../utils/jwt/jwa.ts'8 9 declare module '../../context.ts' {10 interface ContextVariableMap {11 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 unmodified lines15 16 export const jwt = (options: {17 secret: string18 cookie?: string19- alg?: string19+ alg?: SignatureAlgorithm20 }): MiddlewareHandler => {21 if (!options) {22 throw new Error('JWT auth middleware requires options for "secret')23 }7 unmodified lines31 let token32 if (credentials) {33 const parts = credentials.split(/\s+/)34 if (parts.length !== 2) {35+ const errDescription = 'invalid credentials structure'36 throw new HTTPException(401, {37+ message: errDescription,38 res: unauthorizedResponse({39 ctx,40 error: 'invalid_request',39- errDescription: 'invalid credentials structure',41+ errDescription,42 }),43 })44 } else {45 token = parts[1]2 unmodified lines48 token = getCookie(ctx)[options.cookie]49 }50 51 if (!token) {52+ const errDescription = 'no authorization included in request'53 throw new HTTPException(401, {54+ message: errDescription,55 res: unauthorizedResponse({56 ctx,57 error: 'invalid_request',54- errDescription: 'no authorization included in request',58+ errDescription,59 }),60 })61 }62 63 let payload60- let msg = ''64+ let cause65 try {62- payload = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes)66+ payload = await Jwt.verify(token, options.secret, options.alg)67 } catch (e) {64- msg = `${e}`68+ cause = e69 }70 if (!payload) {71 throw new HTTPException(401, {72+ message: 'Unauthorized',73 res: unauthorizedResponse({74 ctx,75 error: 'invalid_token',71- statusText: msg,76+ statusText: 'Unauthorized',77 errDescription: 'token verification failure',78 }),79+ cause,80 })81 }82 83 ctx.set('jwtPayload', payload)23 unmodified linesadded:deno_dist/middleware/method-override/index.ts+134 added
1+import { URLSearchParams } from 'node:url'2+import type { Context } from '../../context.ts'3+import type { Hono } from '../../hono.ts'4+import type { MiddlewareHandler } from '../../types.ts'5+import { parseBody } from '../../utils/body.ts'6+7+type MethodOverrideOptions = {8+ // eslint-disable-next-line @typescript-eslint/no-explicit-any9+ app: Hono<any, any, any>10+} & (11+ | {12+ // Default is 'form' and the value is `_method`13+ form?: string14+ header?: never15+ query?: never16+ }17+ | {18+ form?: never19+ header: string20+ query?: never21+ }22+ | {23+ form?: never24+ header?: never25+ query: string26+ }27+)28+29+const DEFAULT_METHOD_FORM_NAME = '_method'30+31+/**32+ * Method Override Middleware33+ *34+ * @example35+ * // with form input method36+ * const app = new Hono()37+ * app.use('/books/*', methodOverride({ app })) // the default `form` value is `_method`38+ * app.use('/authors/*', methodOverride({ app, form: 'method' }))39+ *40+ * @example41+ * // with custom header42+ * app.use('/books/*', methodOverride({ app, header: 'X-HTTP-METHOD-OVERRIDE' }))43+ *44+ * @example45+ * // with query parameter46+ * app.use('/books/*', methodOverride({ app, query: '_method' }))47+ */48+export const methodOverride = (options: MethodOverrideOptions): MiddlewareHandler =>49+ async function methodOverride(c, next) {50+ if (c.req.method === 'GET') {51+ return await next()52+ }53+54+ const app = options.app55+ // Method override by form56+ if (!(options.header || options.query)) {57+ const contentType = c.req.header('content-type')58+ const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME59+ const clonedRequest = c.req.raw.clone()60+ const newRequest = clonedRequest.clone()61+ // Content-Type is `multipart/form-data`62+ if (contentType?.startsWith('multipart/form-data')) {63+ const form = await clonedRequest.formData()64+ const method = form.get(methodFormName)65+ if (method) {66+ const newForm = await newRequest.formData()67+ newForm.delete(methodFormName)68+ const newHeaders = new Headers(clonedRequest.headers)69+ newHeaders.delete('content-type')70+ newHeaders.delete('content-length')71+ const request = new Request(c.req.url, {72+ body: newForm,73+ headers: newHeaders,74+ method: method as string,75+ })76+ return app.fetch(request, c.env, getExecutionCtx(c))77+ }78+ }79+ // Content-Type is `application/x-www-form-urlencoded`80+ if (contentType === 'application/x-www-form-urlencoded') {81+ const params = await parseBody<Record<string, string>>(clonedRequest)82+ const method = params[methodFormName]83+ if (method) {84+ delete params[methodFormName]85+ const newParams = new URLSearchParams(params)86+ const request = new Request(newRequest, {87+ body: newParams,88+ method: method as string,89+ })90+ return app.fetch(request, c.env, getExecutionCtx(c))91+ }92+ }93+ }94+ // Method override by header95+ else if (options.header) {96+ const headerName = options.header97+ const method = c.req.header(headerName)98+ if (method) {99+ const newHeaders = new Headers(c.req.raw.headers)100+ newHeaders.delete(headerName)101+ const request = new Request(c.req.raw, {102+ headers: newHeaders,103+ method,104+ })105+ return app.fetch(request, c.env, getExecutionCtx(c))106+ }107+ }108+ // Method override by query109+ else if (options.query) {110+ const queryName = options.query111+ const method = c.req.query(queryName)112+ if (method) {113+ const url = new URL(c.req.url)114+ url.searchParams.delete(queryName)115+ const request = new Request(url.toString(), {116+ body: c.req.raw.body,117+ headers: c.req.raw.headers,118+ method,119+ })120+ return app.fetch(request, c.env, getExecutionCtx(c))121+ }122+ }123+ await next()124+ }125+126+const getExecutionCtx = (c: Context) => {127+ let executionCtx: ExecutionContext | undefined128+ try {129+ executionCtx = c.executionCtx130+ } catch {131+ // Do nothing132+ }133+ return executionCtx134+}added:deno_dist/middleware/trailing-slash/index.ts+46 added
1+import type { MiddlewareHandler } from '../../types.ts'2+3+/**4+ * Trim the trailing slash from the URL if it does have one. For example, `/path/to/page/` will be redirected to `/path/to/page`.5+ * @access public6+ * @example app.use(trimTrailingSlash())7+ */8+export const trimTrailingSlash = (): MiddlewareHandler => {9+ return async function trimTrailingSlash(c, next) {10+ await next()11+12+ if (13+ c.res.status === 404 &&14+ c.req.method === 'GET' &&15+ c.req.path !== '/' &&16+ c.req.path[c.req.path.length - 1] === '/'17+ ) {18+ const url = new URL(c.req.url)19+ url.pathname = url.pathname.substring(0, url.pathname.length - 1)20+21+ c.res = c.redirect(url.toString(), 301)22+ }23+ }24+}25+26+/**27+ * Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`.28+ * @access public29+ * @example app.use(appendTrailingSlash())30+ */31+export const appendTrailingSlash = (): MiddlewareHandler => {32+ return async function appendTrailingSlash(c, next) {33+ await next()34+35+ if (36+ c.res.status === 404 &&37+ c.req.method === 'GET' &&38+ c.req.path[c.req.path.length - 1] !== '/'39+ ) {40+ const url = new URL(c.req.url)41+ url.pathname += '/'42+43+ c.res = c.redirect(url.toString(), 301)44+ }45+ }46+}modified:deno_dist/utils/jwt/index.ts+2 added-1 removed
1-export * as Jwt from './jwt.ts'1+import { sign, verify, decode } from './jwt.ts'2+export const Jwt = { sign, verify, decode }added:deno_dist/utils/jwt/jwa.ts+20 added
1+// JSON Web Algorithms (JWA)2+// https://datatracker.ietf.org/doc/html/rfc75183+4+export enum AlgorithmTypes {5+ HS256 = 'HS256',6+ HS384 = 'HS384',7+ HS512 = 'HS512',8+ RS256 = 'RS256',9+ RS384 = 'RS384',10+ RS512 = 'RS512',11+ PS256 = 'PS256',12+ PS384 = 'PS384',13+ PS512 = 'PS512',14+ ES256 = 'ES256',15+ ES384 = 'ES384',16+ ES512 = 'ES512',17+ EdDSA = 'EdDSA',18+}19+20+export type SignatureAlgorithm = keyof typeof AlgorithmTypesadded:deno_dist/utils/jwt/jws.ts+224 added
1+import { getRuntimeKey } from '../../helper.ts'2+import { decodeBase64 } from '../encode.ts'3+import type { SignatureAlgorithm } from './jwa.ts'4+import { JwtAlgorithmNotImplemented } from './types.ts'5+import { CryptoKeyUsage } from './types.ts'6+import { utf8Encoder } from './utf8.ts'7+8+// JSON Web Signature (JWS)9+// https://datatracker.ietf.org/doc/html/rfc751510+11+type KeyImporterAlgorithm = Parameters<typeof crypto.subtle.importKey>[2]12+type KeyAlgorithm =13+ | AlgorithmIdentifier14+ | RsaHashedImportParams15+ | (RsaPssParams & RsaHashedImportParams)16+ | (EcdsaParams & EcKeyImportParams)17+ | HmacImportParams18+19+export type SignatureKey = string | JsonWebKey | CryptoKey20+21+export async function signing(22+ privateKey: SignatureKey,23+ alg: SignatureAlgorithm,24+ data: BufferSource25+): Promise<ArrayBuffer> {26+ const algorithm = getKeyAlgorithm(alg)27+ const cryptoKey = await importPrivateKey(privateKey, algorithm)28+ return await crypto.subtle.sign(algorithm, cryptoKey, data)29+}30+31+export async function verifying(32+ publicKey: SignatureKey,33+ alg: SignatureAlgorithm,34+ signature: BufferSource,35+ data: BufferSource36+): Promise<boolean> {37+ const algorithm = getKeyAlgorithm(alg)38+ const cryptoKey = await importPublicKey(publicKey, algorithm)39+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data)40+}41+42+function pemToBinary(pem: string): Uint8Array {43+ return decodeBase64(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))44+}45+46+async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {47+ if (!crypto.subtle || !crypto.subtle.importKey) {48+ throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')49+ }50+ if (isCryptoKey(key)) {51+ if (key.type !== 'private') {52+ throw new Error(`unexpected non private key: CryptoKey.type is ${key.type}`)53+ }54+ return key55+ }56+ const usages = [CryptoKeyUsage.Sign]57+ if (typeof key === 'object') {58+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import59+ return await crypto.subtle.importKey('jwk', key, alg, false, usages)60+ }61+ if (key.includes('PRIVATE')) {62+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import63+ return await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, false, usages)64+ }65+ return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)66+}67+68+async function importPublicKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {69+ if (!crypto.subtle || !crypto.subtle.importKey) {70+ throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')71+ }72+ if (isCryptoKey(key)) {73+ if (key.type === 'public' || key.type === 'secret') {74+ return key75+ }76+ key = await exportPublicJwkFrom(key)77+ }78+ if (typeof key === 'string' && key.includes('PRIVATE')) {79+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import80+ const privateKey = await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, true, [81+ CryptoKeyUsage.Sign,82+ ])83+ key = await exportPublicJwkFrom(privateKey)84+ }85+ const usages = [CryptoKeyUsage.Verify]86+ if (typeof key === 'object') {87+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import88+ return await crypto.subtle.importKey('jwk', key, alg, false, usages)89+ }90+ if (key.includes('PUBLIC')) {91+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#subjectpublickeyinfo_import92+ return await crypto.subtle.importKey('spki', pemToBinary(key), alg, false, usages)93+ }94+ return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)95+}96+97+// https://datatracker.ietf.org/doc/html/rfc751798+async function exportPublicJwkFrom(privateKey: CryptoKey): Promise<JsonWebKey> {99+ if (privateKey.type !== 'private') {100+ throw new Error(`unexpected key type: ${privateKey.type}`)101+ }102+ if (!privateKey.extractable) {103+ throw new Error('unexpected private key is unextractable')104+ }105+ const jwk = await crypto.subtle.exportKey('jwk', privateKey)106+ const { kty } = jwk // common107+ const { alg, e, n } = jwk // rsa108+ const { crv, x, y } = jwk // elliptic-curve109+ return { kty, alg, e, n, crv, x, y, key_ops: [CryptoKeyUsage.Verify] }110+}111+112+function getKeyAlgorithm(name: SignatureAlgorithm): KeyAlgorithm {113+ switch (name) {114+ case 'HS256':115+ return {116+ name: 'HMAC',117+ hash: {118+ name: 'SHA-256',119+ },120+ } satisfies HmacImportParams121+ case 'HS384':122+ return {123+ name: 'HMAC',124+ hash: {125+ name: 'SHA-384',126+ },127+ } satisfies HmacImportParams128+ case 'HS512':129+ return {130+ name: 'HMAC',131+ hash: {132+ name: 'SHA-512',133+ },134+ } satisfies HmacImportParams135+ case 'RS256':136+ return {137+ name: 'RSASSA-PKCS1-v1_5',138+ hash: {139+ name: 'SHA-256',140+ },141+ } satisfies RsaHashedImportParams142+ case 'RS384':143+ return {144+ name: 'RSASSA-PKCS1-v1_5',145+ hash: {146+ name: 'SHA-384',147+ },148+ } satisfies RsaHashedImportParams149+ case 'RS512':150+ return {151+ name: 'RSASSA-PKCS1-v1_5',152+ hash: {153+ name: 'SHA-512',154+ },155+ } satisfies RsaHashedImportParams156+ case 'PS256':157+ return {158+ name: 'RSA-PSS',159+ hash: {160+ name: 'SHA-256',161+ },162+ saltLength: 32, // 256 >> 3163+ } satisfies RsaPssParams & RsaHashedImportParams164+ case 'PS384':165+ return {166+ name: 'RSA-PSS',167+ hash: {168+ name: 'SHA-384',169+ },170+ saltLength: 48, // 384 >> 3171+ } satisfies RsaPssParams & RsaHashedImportParams172+ case 'PS512':173+ return {174+ name: 'RSA-PSS',175+ hash: {176+ name: 'SHA-512',177+ },178+ saltLength: 64, // 512 >> 3,179+ } satisfies RsaPssParams & RsaHashedImportParams180+ case 'ES256':181+ return {182+ name: 'ECDSA',183+ hash: {184+ name: 'SHA-256',185+ },186+ namedCurve: 'P-256',187+ } satisfies EcdsaParams & EcKeyImportParams188+ case 'ES384':189+ return {190+ name: 'ECDSA',191+ hash: {192+ name: 'SHA-384',193+ },194+ namedCurve: 'P-384',195+ } satisfies EcdsaParams & EcKeyImportParams196+ case 'ES512':197+ return {198+ name: 'ECDSA',199+ hash: {200+ name: 'SHA-512',201+ },202+ namedCurve: 'P-521',203+ } satisfies EcdsaParams & EcKeyImportParams204+ case 'EdDSA':205+ // Currently, supported only Safari and Deno, Node.js.206+ // See: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify207+ return {208+ name: 'Ed25519',209+ namedCurve: 'Ed25519',210+ }211+ default:212+ throw new JwtAlgorithmNotImplemented(name)213+ }214+}215+216+function isCryptoKey(key: SignatureKey): key is CryptoKey {217+ const runtime = getRuntimeKey()218+ // @ts-expect-error CryptoKey hasn't exported to global in node v18219+ if (runtime === 'node' && !!crypto.webcrypto) {220+ // @ts-expect-error CryptoKey hasn't exported to global in node v18221+ return key instanceof crypto.webcrypto.CryptoKey222+ }223+ return key instanceof CryptoKey224+}modified:deno_dist/utils/jwt/jwt.ts+38 added-89 removed
1 import { encodeBase64Url, decodeBase64Url } from '../../utils/encode.ts'2-import type { AlgorithmTypes } from './types.ts'3-import { JwtTokenIssuedAt } from './types.ts'2+import type { SignatureAlgorithm } from './jwa.ts'3+import { AlgorithmTypes } from './jwa.ts'4+import type { SignatureKey } from './jws.ts'5+import { signing, verifying } from './jws.ts'6+import { JwtHeaderInvalid, type JWTPayload } from './types.ts'7 import {8 JwtTokenInvalid,9 JwtTokenNotBefore,10 JwtTokenExpired,11 JwtTokenSignatureMismatched,9- JwtAlgorithmNotImplemented,12+ JwtTokenIssuedAt,13 } from './types.ts'14+import { utf8Decoder, utf8Encoder } from './utf8.ts'15 12-interface AlgorithmParams {13- name: string14- namedCurve?: string15- hash?: {16- name: string17- }18-}19-20-enum CryptoKeyFormat {21- RAW = 'raw',22- PKCS8 = 'pkcs8',23- SPKI = 'spki',24- JWK = 'jwk',25-}26-27-enum CryptoKeyUsage {28- Ecrypt = 'encrypt',29- Decrypt = 'decrypt',30- Sign = 'sign',31- Verify = 'verify',32- Deriverkey = 'deriveKey',33- DeriveBits = 'deriveBits',34- WrapKey = 'wrapKey',35- UnwrapKey = 'unwrapKey',36-}37-38-type AlgorithmTypeName = keyof typeof AlgorithmTypes39-40-const utf8Encoder = new TextEncoder()41-const utf8Decoder = new TextDecoder()42-16 const encodeJwtPart = (part: unknown): string =>17 encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')18 const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')19 20 const decodeJwtPart = (part: string): unknown =>21 JSON.parse(utf8Decoder.decode(decodeBase64Url(part)))22 50-const param = (name: AlgorithmTypeName): AlgorithmParams => {51- switch (name.toUpperCase()) {52- case 'HS256':53- return {54- name: 'HMAC',55- hash: {56- name: 'SHA-256',57- },58- }59- case 'HS384':60- return {61- name: 'HMAC',62- hash: {63- name: 'SHA-384',64- },65- }66- case 'HS512':67- return {68- name: 'HMAC',69- hash: {70- name: 'SHA-512',71- },72- }73- default:74- throw new JwtAlgorithmNotImplemented(name)75- }23+export interface TokenHeader {24+ alg: SignatureAlgorithm25+ typ: 'JWT'26 }27 78-const signing = async (79- data: string,80- secret: string,81- alg: AlgorithmTypeName = 'HS256'82-): Promise<ArrayBuffer> => {83- if (!crypto.subtle || !crypto.subtle.importKey) {84- throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')85- }86-87- const utf8Encoder = new TextEncoder()88- const cryptoKey = await crypto.subtle.importKey(89- CryptoKeyFormat.RAW,90- utf8Encoder.encode(secret),91- param(alg),92- false,93- [CryptoKeyUsage.Sign]28+// eslint-disable-next-line29+export function isTokenHeader(obj: any): obj is TokenHeader {30+ return (31+ typeof obj === 'object' &&32+ obj !== null &&33+ 'alg' in obj &&34+ Object.values(AlgorithmTypes).includes(obj.alg) &&35+ 'typ' in obj &&36+ obj.typ === 'JWT'37 )95- return await crypto.subtle.sign(param(alg), cryptoKey, utf8Encoder.encode(data))38 }39 40 export const sign = async (99- payload: unknown,100- secret: string,101- alg: AlgorithmTypeName = 'HS256'41+ payload: JWTPayload,42+ privateKey: SignatureKey,43+ alg: SignatureAlgorithm = 'HS256'44 ): Promise<string> => {45 const encodedPayload = encodeJwtPart(payload)104- const encodedHeader = encodeJwtPart({ alg, typ: 'JWT' })46+ const encodedHeader = encodeJwtPart({ alg, typ: 'JWT' } satisfies TokenHeader)47 48 const partialToken = `${encodedHeader}.${encodedPayload}`49 108- const signaturePart = await signing(partialToken, secret, alg)50+ const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken))51 const signature = encodeSignaturePart(signaturePart)52 53 return `${partialToken}.${signature}`54 }55 56 export const verify = async (57 token: string,116- secret: string,117- alg: AlgorithmTypeName = 'HS256'58+ publicKey: SignatureKey,59+ alg: SignatureAlgorithm = 'HS256'60 // eslint-disable-next-line @typescript-eslint/no-explicit-any61 ): Promise<any> => {62 const tokenParts = token.split('.')63 if (tokenParts.length !== 3) {64 throw new JwtTokenInvalid(token)65 }66 125- const { payload } = decode(token)67+ const { header, payload } = decode(token)68+ if (!isTokenHeader(header)) {69+ throw new JwtHeaderInvalid(header)70+ }71 const now = Math.floor(Date.now() / 1000)72 if (payload.nbf && payload.nbf > now) {73 throw new JwtTokenNotBefore(token)74 }3 unmodified lines78 if (payload.iat && now < payload.iat) {79 throw new JwtTokenIssuedAt(now, payload.iat)80 }81 137- const signaturePart = tokenParts.slice(0, 2).join('.')138- const signature = await signing(signaturePart, secret, alg)139- const encodedSignature = encodeSignaturePart(signature)140- if (encodedSignature !== tokenParts[2]) {82+ const headerPayload = token.substring(0, token.lastIndexOf('.'))83+ const verified = await verifying(84+ publicKey,85+ alg,86+ decodeBase64Url(tokenParts[2]),87+ utf8Encoder.encode(headerPayload)88+ )89+ if (!verified) {90 throw new JwtTokenSignatureMismatched(token)91 }92 93 return payload16 unmodified linesmodified:deno_dist/utils/jwt/types.ts+37 added-4 removed
31 unmodified lines32 this.name = 'JwtTokenIssuedAt'33 }34 }35 36+export class JwtHeaderInvalid extends Error {37+ constructor(header: object) {38+ super(`jwt header is invalid: ${JSON.stringify(header)}`)39+ this.name = 'JwtHeaderInvalid'40+ }41+}42+43 export class JwtTokenSignatureMismatched extends Error {44 constructor(token: string) {45 super(`token(${token}) signature mismatched`)46 this.name = 'JwtTokenSignatureMismatched'47 }48 }49 43-export enum AlgorithmTypes {44- HS256 = 'HS256',45- HS384 = 'HS384',46- HS512 = 'HS512',50+export enum CryptoKeyUsage {51+ Encrypt = 'encrypt',52+ Decrypt = 'decrypt',53+ Sign = 'sign',54+ Verify = 'verify',55+ DeriveKey = 'deriveKey',56+ DeriveBits = 'deriveBits',57+ WrapKey = 'wrapKey',58+ UnwrapKey = 'unwrapKey',59 }60+61+/**62+ * JWT Payload63+ */64+export type JWTPayload =65+ | (unknown & {})66+ | {67+ [key: string]: unknown68+ /**69+ * The token is checked to ensure it has not expired.70+ */71+ exp?: number72+ /**73+ * The token is checked to ensure it is not being used before a specified time.74+ */75+ nbf?: number76+ /**77+ * The token is checked to ensure it is not issued in the future.78+ */79+ iat?: number80+ }added:deno_dist/utils/jwt/utf8.ts+2 added
1+export const utf8Encoder = new TextEncoder()2+export const utf8Decoder = new TextDecoder()modified:deno_dist/validator/validator.ts+2 added-31 removed
58 unmodified lines59 ): MiddlewareHandler<E, P, V> => {60 return async (c, next) => {61 let value = {}62 const contentType = c.req.header('Content-Type')63- const bodyTypes = ['text', 'arrayBuffer', 'blob']63 64 switch (target) {65 case 'json':66 if (!contentType || !contentType.startsWith('application/json')) {67 const message = `Invalid HTTP header: Content-Type=${contentType}`68 throw new HTTPException(400, { message })69 }71-72- if (c.req.bodyCache.json) {73- value = await c.req.bodyCache.json74- break75- }76-70 try {78- let arrayBuffer: ArrayBuffer | undefined = undefined79- for (const type of bodyTypes) {80- // @ts-expect-error bodyCache[type] is not typed81- const body = c.req.bodyCache[type]82- if (body) {83- arrayBuffer = await new Response(await body).arrayBuffer()84- break85- }86- }87- arrayBuffer ??= await c.req.raw.arrayBuffer()88- value = await new Response(arrayBuffer).json()89- c.req.bodyCache.json = value90- c.req.bodyCache.arrayBuffer = arrayBuffer71+ value = await c.req.json()72 } catch {73 const message = 'Malformed JSON in request body'74 throw new HTTPException(400, { message })75 }8 unmodified lines84 break85 }86 87 try {107- let arrayBuffer: ArrayBuffer | undefined = undefined108- for (const type of bodyTypes) {109- // @ts-expect-error bodyCache[type] is not typed110- const body = c.req.bodyCache[type]111- if (body) {112- arrayBuffer = await new Response(await body).arrayBuffer()113- break114- }115- }116- arrayBuffer ??= await c.req.arrayBuffer()88+ const arrayBuffer = await c.req.arrayBuffer()89 const formData = await bufferToFormData(arrayBuffer, contentType)90 const form: BodyData = {}91 formData.forEach((value, key) => {92 form[key] = value93 })94 value = form95 c.req.bodyCache.formData = formData124- c.req.bodyCache.arrayBuffer = arrayBuffer96 } catch (e) {97 let message = 'Malformed FormData request.'98 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`99 throw new HTTPException(400, { message })32 unmodified linesmodified:deno_dist/middleware.ts+2 added
9 unmodified lines10 export * from './jsx/index.ts'11 export * from './middleware/jsx-renderer/index.ts'12 export { jwt } from './middleware/jwt/index.ts'13 export * from './middleware/logger/index.ts'14+export * from './middleware/method-override/index.ts'15 export * from './middleware/powered-by/index.ts'16 export * from './middleware/timing/index.ts'17 export * from './middleware/pretty-json/index.ts'18 export * from './middleware/secure-headers/index.ts'19+export * from './middleware/trailing-slash/index.ts'20 export * from './adapter/deno/serve-static.ts'modified:deno_dist/request.ts+17 added-8 removed
192 unmodified lines193 194 private cachedBody = (key: keyof Body) => {195 const { bodyCache, raw } = this196 const cachedBody = bodyCache[key]197+198 if (cachedBody) {199 return cachedBody200 }200- /**201- * If an arrayBuffer cache is exist,202- * use it for creating a text, json, and others.203- */204- if (bodyCache.arrayBuffer) {205- return (async () => {206- return await new Response(bodyCache.arrayBuffer)[key]()207- })()201+202+ if (!bodyCache[key]) {203+ for (const keyOfBodyCache of Object.keys(bodyCache)) {204+ if (keyOfBodyCache === 'parsedBody') {205+ continue206+ }207+ return (async () => {208+ // @ts-expect-error bodyCache[keyOfBodyCache] can be passed as a body209+ let body = await bodyCache[keyOfBodyCache]210+ if (keyOfBodyCache === 'json') {211+ body = JSON.stringify(body)212+ }213+ return await new Response(body)[key]()214+ })()215+ }216 }217+218 return (bodyCache[key] = raw[key]())219 }220 221 /**126 unmodified linesmodified:src/helper/ssg/ssg.test.tsx+80 added-1 removed
2 unmodified lines3 // eslint-disable-next-line @typescript-eslint/no-unused-vars4 import { jsx } from '../../jsx'5 import { poweredBy } from '../../middleware/powered-by'6 import { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'7-import { fetchRoutesContent, saveContentToFile, toSSG } from './ssg'7+import { fetchRoutesContent, saveContentToFile, toSSG, defaultExtensionMap } from './ssg'8 import type {9 BeforeRequestHook,10 AfterResponseHook,11 AfterGenerateHook,278 unmodified lines290 291 beforeEach(() => {292 app = new Hono()293 app.get('/text', (c) => c.text('Text Response'))294+ app.get('/text-utf8', (c) => {295+ return c.text('Text Response', 200, { 'Content-Type': 'text/plain;charset=UTF-8' })296+ })297 app.get('/html', (c) => c.html('<p>HTML Response</p>'))298 app.get('/json', (c) => c.json({ message: 'JSON Response' }))299 app.use('*', poweredBy())300 })4 unmodified lines305 expect(htmlMap.get('/text')).toEqual({306 content: 'Text Response',307 mimeType: 'text/plain',308 })309+ expect(htmlMap.get('/text-utf8')).toEqual({310+ content: 'Text Response',311+ mimeType: 'text/plain',312+ })313 expect(htmlMap.get('/html')).toEqual({314 content: '<p>HTML Response</p>',315 mimeType: 'text/html',316 })147 unmodified lines464 await saveContentToFile(Promise.resolve(data), fsMock, './static-check-extensions')465 }466 expect(fsMock.mkdir).toHaveBeenCalledWith('static-check-extensions', { recursive: true })467 })468+469+ it('should correctly create .yaml files for YAML content', async () => {470+ const yamlContent = 'title: YAML Example\nvalue: This is a YAML file.'471+ const mimeType = 'application/yaml'472+ const routePath = '/example'473+474+ const yamlData = {475+ routePath: routePath,476+ content: yamlContent,477+ mimeType: mimeType,478+ }479+480+ const fsMock: FileSystemModule = {481+ writeFile: vi.fn(() => Promise.resolve()),482+ mkdir: vi.fn(() => Promise.resolve()),483+ }484+485+ await saveContentToFile(Promise.resolve(yamlData), fsMock, './static')486+487+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/example.yaml', yamlContent)488+ })489+490+ it('should correctly create .yml files for YAML content', async () => {491+ const yamlContent = 'title: YAML Example\nvalue: This is a YAML file.'492+ const yamlMimeType = 'application/yaml'493+ const yamlRoutePath = '/yaml'494+495+ const yamlData = {496+ routePath: yamlRoutePath,497+ content: yamlContent,498+ mimeType: yamlMimeType,499+ }500+501+ const yamlMimeType2 = 'x-yaml'502+ const yamlRoutePath2 = '/yaml2'503+ const yamlData2 = {504+ routePath: yamlRoutePath2,505+ content: yamlContent,506+ mimeType: yamlMimeType2,507+ }508+509+ const htmlMimeType = 'text/html'510+ const htmlRoutePath = '/html'511+512+ const htmlData = {513+ routePath: htmlRoutePath,514+ content: yamlContent,515+ mimeType: htmlMimeType,516+ }517+518+ const fsMock: FileSystemModule = {519+ writeFile: vi.fn(() => Promise.resolve()),520+ mkdir: vi.fn(() => Promise.resolve()),521+ }522+523+ const extensionMap = {524+ 'application/yaml': 'yml',525+ 'x-yaml': 'xyml',526+ }527+ await saveContentToFile(Promise.resolve(yamlData), fsMock, './static', extensionMap)528+ await saveContentToFile(Promise.resolve(yamlData2), fsMock, './static', extensionMap)529+ await saveContentToFile(Promise.resolve(htmlData), fsMock, './static', extensionMap)530+ await saveContentToFile(Promise.resolve(htmlData), fsMock, './static', {531+ ...defaultExtensionMap,532+ ...extensionMap,533+ })534+535+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/yaml.yml', yamlContent)536+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/yaml2.xyml', yamlContent)537+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/html.htm', yamlContent) // extensionMap538+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/html.html', yamlContent) // default + extensionMap539+ })540 })541 542 describe('Dynamic route handling', () => {543 let app: Hono77 unmodified linesmodified:src/helper/ssg/ssg.ts+26 added-14 removed
28 unmodified lines29 files: string[]30 error?: Error31 }32 33-const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34- const extension = determineExtension(mimeType)33+const generateFilePath = (34+ routePath: string,35+ outDir: string,36+ mimeType: string,37+ extensionMap?: Record<string, string>38+) => {39+ const extension = determineExtension(mimeType, extensionMap)40 41 if (routePath.endsWith(`.${extension}`)) {42 return joinPaths(outDir, routePath)43 }22 unmodified lines66 )67 }68 }69 65-const determineExtension = (mimeType: string): string => {66- switch (mimeType) {67- case 'text/html':68- return 'html'69- case 'text/xml':70- case 'application/xml':71- return 'xml'72- default: {73- return getExtension(mimeType) || 'html'74- }70+export const defaultExtensionMap: Record<string, string> = {71+ 'text/html': 'html',72+ 'text/xml': 'xml',73+ 'application/xml': 'xml',74+ 'application/yaml': 'yaml',75+}76+77+const determineExtension = (78+ mimeType: string,79+ userExtensionMap?: Record<string, string>80+): string => {81+ const extensionMap = userExtensionMap || defaultExtensionMap82+ if (mimeType in extensionMap) {83+ return extensionMap[mimeType]84 }85+ return getExtension(mimeType) || 'html'86 }87 88 export type BeforeRequestHook = (req: Request) => Request | false | Promise<Request | false>89 export type AfterResponseHook = (res: Response) => Response | false | Promise<Response | false>4 unmodified lines94 beforeRequestHook?: BeforeRequestHook95 afterResponseHook?: AfterResponseHook96 afterGenerateHook?: AfterGenerateHook97 concurrency?: number98+ extensionMap?: Record<string, string>99 }100 101 /**102 * @experimental111 unmodified lines214 const createdDirs: Set<string> = new Set()215 export const saveContentToFile = async (216 data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,217 fsModule: FileSystemModule,207- outDir: string218+ outDir: string,219+ extensionMap?: Record<string, string>220 ): Promise<string | undefined> => {221 const awaitedData = await data222 if (!awaitedData) {223 return224 }225 const { routePath, content, mimeType } = awaitedData214- const filePath = generateFilePath(routePath, outDir, mimeType)226+ const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap)227 const dirPath = dirname(filePath)228 229 if (!createdDirs.has(dirPath)) {230 await fsModule.mkdir(dirPath, { recursive: true })86 unmodified linesmodified:src/jsx/dom/index.ts+3 added
13 unmodified lines14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18+ useId,19 useDebugValue,20 } from '../hooks'21 import { Suspense, ErrorBoundary } from './components'22 import { createContext } from './context'46 unmodified lines69 useViewTransition,70 useMemo,71 useLayoutEffect,72 useReducer,73+ useId,74 useDebugValue,75 Suspense,76 ErrorBoundary,77 createContext,17 unmodified lines95 useViewTransition,96 useMemo,97 useLayoutEffect,98 useReducer,99+ useId,100 useDebugValue,101 Suspense,102 ErrorBoundary,103 createContext,8 unmodified linesmodified:src/jsx/hooks/dom.test.tsx+360 added-394 removed
12 unmodified lines13 useTransition,14 useDeferredValue,15 startViewTransition,16 useViewTransition,17+ useId,18 useDebugValue,19 } from '.'20 20-describe('useReducer()', () => {21+describe('Hooks', () => {22 beforeAll(() => {23 global.requestAnimationFrame = (cb) => setTimeout(cb)24 })25 8 unmodified lines34 global.Text = dom.window.Text35 root = document.getElementById('root') as HTMLElement36 })37 38+ describe('useReducer()', () => {37- it('simple', async () => {38- const App = () => {39- const [state, dispatch] = useReducer((state: number, action: number) => state + action, 0)40- return (41- <div>42- <button onClick={() => dispatch(1)}>{state}</button>43- </div>44- )45- }46- render(<App />, root)47- expect(root.innerHTML).toBe('<div><button>0</button></div>')48- root.querySelector('button')?.click()49- await Promise.resolve()50- expect(root.innerHTML).toBe('<div><button>1</button></div>')39+ it('simple', async () => {40+ const App = () => {41+ const [state, dispatch] = useReducer((state: number, action: number) => state + action, 0)42+ return (43+ <div>44+ <button onClick={() => dispatch(1)}>{state}</button>45+ </div>46+ )47+ }48+ render(<App />, root)49+ expect(root.innerHTML).toBe('<div><button>0</button></div>')50+ root.querySelector('button')?.click()51+ await Promise.resolve()52+ expect(root.innerHTML).toBe('<div><button>1</button></div>')53+ })54 })52-})55 54-describe('startTransition()', () => {55- beforeAll(() => {56- global.requestAnimationFrame = (cb) => setTimeout(cb)57- })56+ describe('startTransition()', () => {57+ it('no error', async () => {58+ const App = () => {59+ const [count, setCount] = useState(0)60+ return (61+ <Suspense fallback={<div>Loading...</div>}>62+ <div>63+ <button64+ onClick={() => {65+ startTransition(() => {66+ setCount((c) => c + 1)67+ })68+ }}69+ >70+ {count}71+ </button>72+ </div>73+ </Suspense>74+ )75+ }76+ render(<App />, root)77+ expect(root.innerHTML).toBe('<div><button>0</button></div>')78+ root.querySelector('button')?.click()79+ await Promise.resolve()80+ expect(root.innerHTML).toBe('<div><button>1</button></div>')81+ })82 59- let dom: JSDOM60- let root: HTMLElement61- beforeEach(() => {62- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {63- runScripts: 'dangerously',83+ it('got an error', async () => {84+ let resolve: () => void85+ const promise = new Promise<void>((r) => (resolve = r))86+87+ const Counter = ({ count }: { count: number }) => {88+ use(promise)89+ return <div>{count}</div>90+ }91+92+ const App = () => {93+ const [count, setCount] = useState(0)94+ return (95+ <Suspense fallback={<div>Loading...</div>}>96+ <div>97+ <button98+ onClick={() => {99+ startTransition(() => {100+ setCount((c) => c + 1)101+ })102+ }}103+ >104+ {count ? <Counter count={count} /> : count}105+ </button>106+ </div>107+ </Suspense>108+ )109+ }110+ render(<App />, root)111+ expect(root.innerHTML).toBe('<div><button>0</button></div>')112+ root.querySelector('button')?.click()113+ expect(root.innerHTML).toBe('<div><button>0</button></div>')114+ resolve!()115+ await new Promise((r) => setTimeout(r))116+ expect(root.innerHTML).toBe('<div><button><div>1</div></button></div>')117 })65- global.document = dom.window.document66- global.HTMLElement = dom.window.HTMLElement67- global.Text = dom.window.Text68- root = document.getElementById('root') as HTMLElement118 })119 71- it('no error', async () => {72- const App = () => {73- const [count, setCount] = useState(0)74- return (75- <Suspense fallback={<div>Loading...</div>}>120+ describe('useTransition()', () => {121+ it('pending', async () => {122+ let called = 0123+ const App = () => {124+ const [count, setCount] = useState(0)125+ const [isPending, startTransition] = useTransition()126+ called++127+128+ return (129 <div>130 <button131 onClick={() => {132 startTransition(() => {133 setCount((c) => c + 1)134 })135 }}136 >84- {count}137+ {isPending ? 'Pending...' : count}138 </button>139 </div>87- </Suspense>88- )89- }90- render(<App />, root)91- expect(root.innerHTML).toBe('<div><button>0</button></div>')92- root.querySelector('button')?.click()93- await Promise.resolve()94- expect(root.innerHTML).toBe('<div><button>1</button></div>')95- })140+ )141+ }142+ render(<App />, root)143+ expect(root.innerHTML).toBe('<div><button>0</button></div>')144+ root.querySelector('button')?.click()145+ await Promise.resolve()146+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')147+ expect(called).toBe(2)148+ await new Promise((r) => setTimeout(r))149+ await new Promise((r) => setTimeout(r))150+ expect(root.innerHTML).toBe('<div><button>1</button></div>')151+ expect(called).toBe(3)152+ })153 97- it('got an error', async () => {98- let resolve: () => void99- const promise = new Promise<void>((r) => (resolve = r))154+ it('multiple setState at once', async () => {155+ let called = 0156+ const App = () => {157+ const [count1, setCount1] = useState(0)158+ const [count2, setCount2] = useState(0)159+ const [isPending, startTransition] = useTransition()160+ called++161 101- const Counter = ({ count }: { count: number }) => {102- use(promise)103- return <div>{count}</div>104- }105-106- const App = () => {107- const [count, setCount] = useState(0)108- return (162+ return (109- <Suspense fallback={<div>Loading...</div>}>163 <div>164 <button165 onClick={() => {166 startTransition(() => {114- setCount((c) => c + 1)167+ setCount1((c) => c + 1)168+ setCount2((c) => c + 2)169 })170 }}171 >118- {count ? <Counter count={count} /> : count}172+ {isPending ? 'Pending...' : count1 + count2}173 </button>174 </div>121- </Suspense>122- )123- }124- render(<App />, root)125- expect(root.innerHTML).toBe('<div><button>0</button></div>')126- root.querySelector('button')?.click()127- expect(root.innerHTML).toBe('<div><button>0</button></div>')128- resolve!()129- await new Promise((r) => setTimeout(r))130- expect(root.innerHTML).toBe('<div><button><div>1</div></button></div>')131- })132-})133-134-describe('useTransition()', () => {135- let dom: JSDOM136- let root: HTMLElement137- beforeEach(() => {138- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {139- runScripts: 'dangerously',175+ )176+ }177+ render(<App />, root)178+ expect(root.innerHTML).toBe('<div><button>0</button></div>')179+ root.querySelector('button')?.click()180+ await Promise.resolve()181+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')182+ expect(called).toBe(2)183+ await new Promise((r) => setTimeout(r))184+ await new Promise((r) => setTimeout(r))185+ expect(root.innerHTML).toBe('<div><button>3</button></div>')186+ expect(called).toBe(3)187 })141- global.document = dom.window.document142- global.HTMLElement = dom.window.HTMLElement143- global.requestAnimationFrame = (cb: Function) => setTimeout(cb)144- global.Text = dom.window.Text145- root = document.getElementById('root') as HTMLElement146- })188 148- it('pending', async () => {149- let called = 0150- const App = () => {151- const [count, setCount] = useState(0)152- const [isPending, startTransition] = useTransition()153- called++189+ it('multiple startTransaction at once', async () => {190+ let called = 0191+ const App = () => {192+ const [count1, setCount1] = useState(0)193+ const [count2, setCount2] = useState(0)194+ const [isPending, startTransition] = useTransition()195+ called++196 155- return (156- <div>157- <button158- onClick={() => {159- startTransition(() => {160- setCount((c) => c + 1)161- })162- }}163- >164- {isPending ? 'Pending...' : count}165- </button>166- </div>167- )168- }169- render(<App />, root)170- expect(root.innerHTML).toBe('<div><button>0</button></div>')171- root.querySelector('button')?.click()172- await Promise.resolve()173- expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')174- expect(called).toBe(2)175- await new Promise((r) => setTimeout(r))176- await new Promise((r) => setTimeout(r))177- expect(root.innerHTML).toBe('<div><button>1</button></div>')178- expect(called).toBe(3)197+ return (198+ <div>199+ <button200+ onClick={() => {201+ startTransition(() => {202+ setCount1((c) => c + 1)203+ })204+ startTransition(() => {205+ setCount2((c) => c + 2)206+ })207+ }}208+ >209+ {isPending ? 'Pending...' : count1 + count2}210+ </button>211+ </div>212+ )213+ }214+ render(<App />, root)215+ expect(root.innerHTML).toBe('<div><button>0</button></div>')216+ expect(called).toBe(1)217+ root.querySelector('button')?.click()218+ await Promise.resolve()219+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')220+ expect(called).toBe(2)221+ await new Promise((r) => setTimeout(r))222+ await new Promise((r) => setTimeout(r))223+ expect(root.innerHTML).toBe('<div><button>3</button></div>')224+ expect(called).toBe(3) // + isPending=true + isPending=false225+ })226 })227 181- it('multiple setState at once', async () => {182- let called = 0183- const App = () => {184- const [count1, setCount1] = useState(0)185- const [count2, setCount2] = useState(0)186- const [isPending, startTransition] = useTransition()187- called++228+ describe('useDeferredValue()', () => {229+ it('deferred', async () => {230+ const promiseMap = {} as Record<number, Promise<number>>231+ const getPromise = (count: number) => {232+ return (promiseMap[count] ||= new Promise((r) => setTimeout(() => r(count + 1))))233+ }234+ const ShowCount = ({ count }: { count: number }) => {235+ if (count === 0) {236+ return <div>0</div>237+ }238 189- return (190- <div>191- <button192- onClick={() => {193- startTransition(() => {194- setCount1((c) => c + 1)195- setCount2((c) => c + 2)196- })197- }}198- >199- {isPending ? 'Pending...' : count1 + count2}200- </button>201- </div>202- )203- }204- render(<App />, root)205- expect(root.innerHTML).toBe('<div><button>0</button></div>')206- root.querySelector('button')?.click()207- await Promise.resolve()208- expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')209- expect(called).toBe(2)210- await new Promise((r) => setTimeout(r))211- await new Promise((r) => setTimeout(r))212- expect(root.innerHTML).toBe('<div><button>3</button></div>')213- expect(called).toBe(3)214- })239+ const c = use(getPromise(count))240+ return <div>{c}</div>241+ }242 216- it('multiple startTransaction at once', async () => {217- let called = 0218- const App = () => {219- const [count1, setCount1] = useState(0)220- const [count2, setCount2] = useState(0)221- const [isPending, startTransition] = useTransition()222- called++223-224- return (225- <div>226- <button227- onClick={() => {228- startTransition(() => {229- setCount1((c) => c + 1)230- })231- startTransition(() => {232- setCount2((c) => c + 2)233- })234- }}235- >236- {isPending ? 'Pending...' : count1 + count2}237- </button>238- </div>239- )240- }241- render(<App />, root)242- expect(root.innerHTML).toBe('<div><button>0</button></div>')243- expect(called).toBe(1)244- root.querySelector('button')?.click()245- await Promise.resolve()246- expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')247- expect(called).toBe(2)248- await new Promise((r) => setTimeout(r))249- await new Promise((r) => setTimeout(r))250- expect(root.innerHTML).toBe('<div><button>3</button></div>')251- expect(called).toBe(3) // + isPending=true + isPending=false243+ const App = () => {244+ const [count, setCount] = useState(0)245+ const c = useDeferredValue(count)246+ return (247+ <>248+ <div>249+ <button onClick={() => setCount((c) => c + 1)}>+1</button>250+ </div>251+ <Suspense fallback={<div>Loading...</div>}>252+ <ShowCount count={c} />253+ </Suspense>254+ </>255+ )256+ }257+ render(<App />, root)258+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')259+ root.querySelector('button')?.click()260+ await Promise.resolve()261+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')262+ await new Promise((r) => setTimeout(r))263+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>2</div>')264+ })265 })253-})266 255-describe('useDeferredValue()', () => {256- let dom: JSDOM257- let root: HTMLElement258- beforeEach(() => {259- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {260- runScripts: 'dangerously',267+ describe('startViewTransition()', () => {268+ afterEach(() => {269+ // eslint-disable-next-line @typescript-eslint/no-explicit-any270+ delete (dom.window.document as any).startViewTransition271 })262- global.document = dom.window.document263- global.HTMLElement = dom.window.HTMLElement264- global.Text = dom.window.Text265- root = document.getElementById('root') as HTMLElement266- })272 268- it('deferred', async () => {269- const promiseMap = {} as Record<number, Promise<number>>270- const getPromise = (count: number) => {271- return (promiseMap[count] ||= new Promise((r) => setTimeout(() => r(count + 1))))272- }273- const ShowCount = ({ count }: { count: number }) => {274- if (count === 0) {275- return <div>0</div>276- }273+ it('supported browser', async () => {274+ // eslint-disable-next-line @typescript-eslint/no-explicit-any275+ ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {276+ Promise.resolve().then(() => cb())277+ return { finished: Promise.resolve() }278+ })279 278- const c = use(getPromise(count))279- return <div>{c}</div>280- }281-282- const App = () => {283- const [count, setCount] = useState(0)284- const c = useDeferredValue(count)280+ const App = () => {281+ const [count, setCount] = useState(0)282+ return (285- return (286- <>287- <div>288- <button onClick={() => setCount((c) => c + 1)}>+1</button>289- </div>283 <Suspense fallback={<div>Loading...</div>}>291- <ShowCount count={c} />284+ <div>285+ <button286+ onClick={() => {287+ startViewTransition(() => {288+ setCount((c) => c + 1)289+ })290+ }}291+ >292+ {count}293+ </button>294+ </div>295 </Suspense>293- </>294- )295- }296- render(<App />, root)297- expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')298- root.querySelector('button')?.click()299- await Promise.resolve()300- expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')301- await new Promise((r) => setTimeout(r))302- expect(root.innerHTML).toBe('<div><button>+1</button></div><div>2</div>')296+ )297+ }298+ render(<App />, root)299+ expect(root.innerHTML).toBe('<div><button>0</button></div>')300+ root.querySelector('button')?.click()301+ await Promise.resolve()302+ expect(root.innerHTML).toBe('<div><button>0</button></div>')303+ await Promise.resolve() // updated in microtask304+ expect(root.innerHTML).toBe('<div><button>1</button></div>')303- })304-})305-306-describe('startViewTransition()', () => {307- let dom: JSDOM308- let root: HTMLElement309- beforeEach(() => {310- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {311- runScripts: 'dangerously',305 })313- global.document = dom.window.document314- global.HTMLElement = dom.window.HTMLElement315- global.Text = dom.window.Text316- root = document.getElementById('root') as HTMLElement317- })318- afterEach(() => {319- // eslint-disable-next-line @typescript-eslint/no-explicit-any320- delete (dom.window.document as any).startViewTransition321- })306 323- it('supported browser', async () => {324- // eslint-disable-next-line @typescript-eslint/no-explicit-any325- ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {326- Promise.resolve().then(() => cb())327- return { finished: Promise.resolve() }307+ it('unsupported browser', async () => {308+ const App = () => {309+ const [count, setCount] = useState(0)310+ return (311+ <Suspense fallback={<div>Loading...</div>}>312+ <div>313+ <button314+ onClick={() => {315+ startViewTransition(() => {316+ setCount((c) => c + 1)317+ })318+ }}319+ >320+ {count}321+ </button>322+ </div>323+ </Suspense>324+ )325+ }326+ render(<App />, root)327+ expect(root.innerHTML).toBe('<div><button>0</button></div>')328+ root.querySelector('button')?.click()329+ await Promise.resolve()330+ expect(root.innerHTML).toBe('<div><button>1</button></div>')331 })332 330- const App = () => {331- const [count, setCount] = useState(0)332- return (333- <Suspense fallback={<div>Loading...</div>}>333+ it('with useTransition()', async () => {334+ // eslint-disable-next-line @typescript-eslint/no-explicit-any335+ ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {336+ Promise.resolve().then(() => cb())337+ return { finished: Promise.resolve() }338+ })339+340+ let called = 0341+ const App = () => {342+ const [count, setCount] = useState(0)343+ const [isPending, startTransition] = useTransition()344+ called++345+346+ return (347 <div>348 <button349 onClick={() => {350 startViewTransition(() => {351+ startTransition(() => {338- setCount((c) => c + 1)352+ setCount((c) => c + 1)353+ })354 })355 }}356 >342- {count}357+ {isPending ? 'Pending...' : count}358 </button>359 </div>345- </Suspense>346- )347- }348- render(<App />, root)349- expect(root.innerHTML).toBe('<div><button>0</button></div>')350- root.querySelector('button')?.click()351- await Promise.resolve()352- expect(root.innerHTML).toBe('<div><button>0</button></div>')353- await Promise.resolve() // updated in microtask354- expect(root.innerHTML).toBe('<div><button>1</button></div>')360+ )361+ }362+ render(<App />, root)363+ expect(root.innerHTML).toBe('<div><button>0</button></div>')364+ root.querySelector('button')?.click()365+ await new Promise((r) => setTimeout(r))366+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')367+ expect(called).toBe(2)368+ await new Promise((r) => setTimeout(r))369+ await new Promise((r) => setTimeout(r))370+ expect(root.innerHTML).toBe('<div><button>1</button></div>')371+ expect(called).toBe(3)372+ })373 })374 357- it('unsupported browser', async () => {358- const App = () => {359- const [count, setCount] = useState(0)360- return (361- <Suspense fallback={<div>Loading...</div>}>375+ describe('useViewTransition()', () => {376+ afterEach(() => {377+ // eslint-disable-next-line @typescript-eslint/no-explicit-any378+ delete (dom.window.document as any).startViewTransition379+ })380+381+ it('supported browser', async () => {382+ let resolved: (() => void) | undefined383+ const promise = new Promise<void>((r) => (resolved = r))384+ let called = 0385+ // eslint-disable-next-line @typescript-eslint/no-explicit-any386+ ;(global.document as any).startViewTransition = vi.fn((cb: Function) => {387+ Promise.resolve().then(() => cb())388+ return { finished: promise }389+ })390+391+ const App = () => {392+ const [count, setCount] = useState(0)393+ const [isUpdating, startViewTransition] = useViewTransition()394+ called++395+396+ return (397 <div>398 <button399 onClick={() => {400 startViewTransition(() => {401 setCount((c) => c + 1)402 })403 }}404 >370- {count}405+ {isUpdating ? 'Pending...' : count}406 </button>407 </div>373- </Suspense>374- )375- }376- render(<App />, root)377- expect(root.innerHTML).toBe('<div><button>0</button></div>')378- root.querySelector('button')?.click()379- await Promise.resolve()380- expect(root.innerHTML).toBe('<div><button>1</button></div>')381- })382-383- it('with useTransition()', async () => {384- // eslint-disable-next-line @typescript-eslint/no-explicit-any385- ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {386- Promise.resolve().then(() => cb())387- return { finished: Promise.resolve() }408+ )409+ }410+ render(<App />, root)411+ expect(root.innerHTML).toBe('<div><button>0</button></div>')412+ root.querySelector('button')?.click()413+ await new Promise((r) => setTimeout(r))414+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')415+ expect(called).toBe(2)416+ resolved?.()417+ await new Promise((r) => setTimeout(r))418+ expect(root.innerHTML).toBe('<div><button>1</button></div>')419+ expect(called).toBe(3)420 })389-390- let called = 0391- const App = () => {392- const [count, setCount] = useState(0)393- const [isPending, startTransition] = useTransition()394- called++395-396- return (397- <div>398- <button399- onClick={() => {400- startViewTransition(() => {401- startTransition(() => {402- setCount((c) => c + 1)403- })404- })405- }}406- >407- {isPending ? 'Pending...' : count}408- </button>409- </div>410- )411- }412- render(<App />, root)413- expect(root.innerHTML).toBe('<div><button>0</button></div>')414- root.querySelector('button')?.click()415- await new Promise((r) => setTimeout(r))416- expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')417- expect(called).toBe(2)418- await new Promise((r) => setTimeout(r))419- await new Promise((r) => setTimeout(r))420- expect(root.innerHTML).toBe('<div><button>1</button></div>')421- expect(called).toBe(3)421 })423-})422 425-describe('useViewTransition()', () => {426- let dom: JSDOM427- let root: HTMLElement428- beforeEach(() => {429- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {430- runScripts: 'dangerously',423+ describe('useId()', () => {424+ let dom: JSDOM425+ let root: HTMLElement426+ beforeEach(() => {427+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {428+ runScripts: 'dangerously',429+ })430+ global.document = dom.window.document431+ global.HTMLElement = dom.window.HTMLElement432+ global.Text = dom.window.Text433+ root = document.getElementById('root') as HTMLElement434 })432- global.document = dom.window.document433- global.HTMLElement = dom.window.HTMLElement434- global.Text = dom.window.Text435- root = document.getElementById('root') as HTMLElement436- })437- afterEach(() => {438- // eslint-disable-next-line @typescript-eslint/no-explicit-any439- delete (dom.window.document as any).startViewTransition440- })435 442- it('supported browser', async () => {443- let resolved: (() => void) | undefined444- const promise = new Promise<void>((r) => (resolved = r))445- let called = 0446- // eslint-disable-next-line @typescript-eslint/no-explicit-any447- ;(global.document as any).startViewTransition = vi.fn((cb: Function) => {448- Promise.resolve().then(() => cb())449- return { finished: promise }436+ it('simple', () => {437+ const App = () => {438+ const id = useId()439+ return <div id={id} />440+ }441+ render(<App />, root)442+ expect(root.innerHTML).toBe('<div id=":r0:"></div>')443 })444 452- const App = () => {453- const [count, setCount] = useState(0)454- const [isUpdating, startViewTransition] = useViewTransition()455- called++456-457- return (458- <div>459- <button460- onClick={() => {461- startViewTransition(() => {462- setCount((c) => c + 1)463- })464- }}465- >466- {isUpdating ? 'Pending...' : count}467- </button>468- </div>469- )470- }471- render(<App />, root)472- expect(root.innerHTML).toBe('<div><button>0</button></div>')473- root.querySelector('button')?.click()474- await new Promise((r) => setTimeout(r))475- expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')476- expect(called).toBe(2)477- resolved?.()478- await new Promise((r) => setTimeout(r))479- expect(root.innerHTML).toBe('<div><button>1</button></div>')480- expect(called).toBe(3)445+ it('memoized', async () => {446+ let setCount: (c: number) => void = () => {}447+ const App = () => {448+ const id = useId()449+ const [count, _setCount] = useState(0)450+ setCount = _setCount451+ return <div id={id}>{count}</div>452+ }453+ render(<App />, root)454+ expect(root.innerHTML).toBe('<div id=":r1:">0</div>')455+ setCount(1)456+ await Promise.resolve()457+ expect(root.innerHTML).toBe('<div id=":r1:">1</div>')458+ })459 })482-})460 484-describe('useDebugValue()', () => {485- let dom: JSDOM486- let root: HTMLElement487- beforeEach(() => {488- dom = new JSDOM('<html><body><div id="root"></div></body></html>', {489- runScripts: 'dangerously',461+ describe('useDebugValue()', () => {462+ it('simple', () => {463+ const spy = vi.fn()464+ const App = () => {465+ useDebugValue('hello', spy)466+ return <div />467+ }468+ render(<App />, root)469+ expect(root.innerHTML).toBe('<div></div>')470+ expect(spy).not.toBeCalled()471 })491- global.document = dom.window.document492- global.HTMLElement = dom.window.HTMLElement493- global.Text = dom.window.Text494- root = document.getElementById('root') as HTMLElement472 })496-497- it('simple', () => {498- const spy = vi.fn()499- const App = () => {500- useDebugValue('hello', spy)501- return <div />502- }503- render(<App />, root)504- expect(root.innerHTML).toBe('<div></div>')505- expect(spy).not.toBeCalled()506- })473 })modified:src/jsx/hooks/index.ts+3 added
347 unmodified lines348 }349 return memoArray[hookIndex][0] as T350 }351 352+let idCounter = 0353+export const useId = (): string => useMemo(() => `:r${(idCounter++).toString(32)}:`, [])354+355 // Define to avoid errors. This hook currently does nothing.356 // eslint-disable-next-line @typescript-eslint/no-unused-vars357 export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}modified:src/jsx/index.ts+3 added
13 unmodified lines14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18+ useId,19 useDebugValue,20 } from './hooks'21 import { Suspense } from './streaming'22 11 unmodified lines34 useEffect,35 useRef,36 useCallback,37 useReducer,38+ useId,39 useDebugValue,40 use,41 startTransition,42 useTransition,18 unmodified lines61 useEffect,62 useRef,63 useCallback,64 useReducer,65+ useId,66 useDebugValue,67 use,68 startTransition,69 useTransition,11 unmodified linesmodified:src/middleware/basic-auth/index.test.ts+42 added
68 unmodified lines69 const auth = basicAuth({ username: username, password: password })70 return auth(c, next)71 })72 73+ app.use('/verify-user/*', async (c, next) => {74+ const auth = basicAuth({75+ verifyUser: (username, password, c) => {76+ return (77+ c.req.path === '/verify-user' &&78+ username === 'dynamic-user' &&79+ password === 'hono-password'80+ )81+ },82+ })83+ return auth(c, next)84+ })85+86 app.get('/auth/*', (c) => {87 handlerExecuted = true88 return c.text('auth')89 })14 unmodified lines104 handlerExecuted = true105 return c.text('nested')106 })107 108+ app.get('/verify-user', (c) => {109+ handlerExecuted = true110+ return c.text('verify-user')111+ })112+113 it('Should not authorize', async () => {114 const req = new Request('http://localhost/auth/a')115 const res = await app.request(req)116 expect(res).not.toBeNull()84 unmodified lines201 expect(res).not.toBeNull()202 expect(res.status).toBe(401)203 expect(await res.text()).toBe('Unauthorized')204 })205+206+ it('Should authorize - verifyUser', async () => {207+ const credential = Buffer.from('dynamic-user' + ':' + 'hono-password').toString('base64')208+209+ const req = new Request('http://localhost/verify-user')210+ req.headers.set('Authorization', `Basic ${credential}`)211+ const res = await app.request(req)212+ expect(handlerExecuted).toBeTruthy()213+ expect(res).not.toBeNull()214+ expect(res.status).toBe(200)215+ expect(await res.text()).toBe('verify-user')216+ })217+218+ it('Should not authorize - verifyUser', async () => {219+ const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')220+221+ const req = new Request('http://localhost/verify-user')222+ req.headers.set('Authorization', `Basic ${credential}`)223+ const res = await app.request(req)224+ expect(handlerExecuted).toBeFalsy()225+ expect(res).not.toBeNull()226+ expect(res.status).toBe(401)227+ expect(await res.text()).toBe('Unauthorized')228+ })229 })modified:src/middleware/basic-auth/index.ts+39 added-10 removed
1+import type { Context } from '../../context'2 import { HTTPException } from '../../http-exception'3 import type { HonoRequest } from '../../request'4 import type { MiddlewareHandler } from '../../types'5 import { timingSafeEqual } from '../../utils/buffer'20 unmodified lines26 27 return { username: userPass[1], password: userPass[2] }28 }29 30+type BasicAuthOptions =31+ | {32+ username: string33+ password: string34+ realm?: string35+ hashFunction?: Function36+ }37+ | {38+ verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean>39+ realm?: string40+ hashFunction?: Function41+ }42+43 export const basicAuth = (30- options: { username: string; password: string; realm?: string; hashFunction?: Function },44+ options: BasicAuthOptions,45 ...users: { username: string; password: string }[]46 ): MiddlewareHandler => {33- if (!options) {34- throw new Error('basic auth middleware requires options for "username and password"')47+ const usernamePasswordInOptions = 'username' in options && 'password' in options48+ const verifyUserInOptions = 'verifyUser' in options49+50+ if (!(usernamePasswordInOptions || verifyUserInOptions)) {51+ throw new Error(52+ 'basic auth middleware requires options for "username and password" or "verifyUser"'53+ )54 }55 56 if (!options.realm) {57 options.realm = 'Secure Area'58 }40- users.unshift({ username: options.username, password: options.password })59 60+ if (usernamePasswordInOptions) {61+ users.unshift({ username: options.username, password: options.password })62+ }63+64 return async function basicAuth(ctx, next) {65 const requestUser = auth(ctx.req)66 if (requestUser) {45- for (const user of users) {46- const [usernameEqual, passwordEqual] = await Promise.all([47- timingSafeEqual(user.username, requestUser.username, options.hashFunction),48- timingSafeEqual(user.password, requestUser.password, options.hashFunction),49- ])50- if (usernameEqual && passwordEqual) {67+ if (verifyUserInOptions) {68+ if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) {69 await next()70 return71 }72+ } else {73+ for (const user of users) {74+ const [usernameEqual, passwordEqual] = await Promise.all([75+ timingSafeEqual(user.username, requestUser.username, options.hashFunction),76+ timingSafeEqual(user.password, requestUser.password, options.hashFunction),77+ ])78+ if (usernameEqual && passwordEqual) {79+ await next()80+ return81+ }82+ }83 }84 }85 const res = new Response('Unauthorized', {86 status: 401,7 unmodified linesmodified:src/middleware/bearer-auth/index.test.ts+32 added
41 unmodified lines42 app.get('/auths/*', (c) => {43 handlerExecuted = true44 return c.text('auths')45 })46+47+ app.use(48+ '/auth-verify-token/*',49+ bearerAuth({50+ verifyToken: async (token, c) => {51+ return c.req.path === '/auth-verify-token' && token === 'dynamic-token'52+ },53+ })54+ )55+ app.get('/auth-verify-token/*', (c) => {56+ handlerExecuted = true57+ return c.text('auth-verify-token')58+ })59 })60 61 it('Should authorize', async () => {62 const req = new Request('http://localhost/auth/a')93 unmodified lines156 expect(res2.status).toBe(200)157 expect(handlerExecuted).toBeTruthy()158 expect(await res2.text()).toBe('auths')159 })160+161+ it('Should authorize - verifyToken option', async () => {162+ const res = await app.request('/auth-verify-token', {163+ headers: { Authorization: 'Bearer dynamic-token' },164+ })165+ expect(res).not.toBeNull()166+ expect(res.status).toBe(200)167+ expect(handlerExecuted).toBeTruthy()168+ expect(await res.text()).toBe('auth-verify-token')169+ })170+171+ it('Should not authorize - verifyToken option', async () => {172+ const res = await app.request('/auth-verify-token', {173+ headers: { Authorization: 'Bearer invalid-token' },174+ })175+ expect(res).not.toBeNull()176+ expect(handlerExecuted).toBeFalsy()177+ expect(res.status).toBe(401)178+ })179 })modified:src/middleware/bearer-auth/index.ts+20 added-8 removed
1+import type { Context } from '../../context'2 import { HTTPException } from '../../http-exception'3 import type { MiddlewareHandler } from '../../types'4 import { timingSafeEqual } from '../../utils/buffer'5 6 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7 const PREFIX = 'Bearer'8 9+type BearerAuthOptions =8-export const bearerAuth = (options: {9- token: string | string[]10- realm?: string11- prefix?: string12- hashFunction?: Function13-}): MiddlewareHandler => {14- if (!options.token) {10+ | {11+ token: string | string[]12+ realm?: string13+ prefix?: string14+ hashFunction?: Function15+ }16+ | {17+ realm?: string18+ prefix?: string19+ verifyToken: (token: string, c: Context) => boolean | Promise<boolean>20+ hashFunction?: Function21+ }22+23+export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {24+ if (!('token' in options || 'verifyToken' in options)) {25 throw new Error('bearer auth middleware requires options for "token"')26 }27 if (!options.realm) {28 options.realm = ''29 unmodified lines58 })59 throw new HTTPException(400, { res })60 } else {61 let equal = false62+ if ('verifyToken' in options) {63+ equal = await options.verifyToken(match[1], c)52- if (typeof options.token === 'string') {64+ } else if (typeof options.token === 'string') {65 equal = await timingSafeEqual(options.token, match[1], options.hashFunction)66 } else if (Array.isArray(options.token) && options.token.length > 0) {67 for (const token of options.token) {68 if (await timingSafeEqual(token, match[1], options.hashFunction)) {20 unmodified linesmodified:src/middleware/cache/index.test.ts+104 added-1 removed
49 unmodified lines50 c.header('Cache-Control', 'private')51 return c.text('cached')52 })53 54- app.use('/not-found/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))54+ app.use('/vary1/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))55+ app.get('/vary1/', (c) => {56+ return c.text('cached')57+ })58 59+ app.use('/vary2/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))60+ app.get('/vary2/', (c) => {61+ c.header('Vary', 'Accept-Encoding')62+ return c.text('cached')63+ })64+65+ app.use(66+ '/vary3/*',67+ cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept', 'Accept-Encoding'] })68+ )69+ app.get('/vary3/', (c) => {70+ c.header('Vary', 'Accept-Language')71+ return c.text('cached')72+ })73+74+ app.use(75+ '/vary4/*',76+ cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept', 'Accept-Encoding'] })77+ )78+ app.get('/vary4/', (c) => {79+ c.header('Vary', 'Accept, Accept-Language')80+ return c.text('cached')81+ })82+83+ app.use('/vary5/*', cache({ cacheName: 'my-app-v1', wait: true, vary: 'Accept' }))84+ app.get('/vary5/', (c) => {85+ return c.text('cached with Accept and Accept-Encoding headers')86+ })87+88+ app.use(89+ '/vary6/*',90+ cache({ cacheName: 'my-app-v1', wait: true, vary: 'Accept, Accept-Encoding' })91+ )92+ app.get('/vary6/', (c) => {93+ c.header('Vary', 'Accept, Accept-Language')94+ return c.text('cached with Accept and Accept-Encoding headers as array')95+ })96+97+ app.use('/vary7/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))98+ app.get('/vary7/', (c) => {99+ c.header('Vary', '*')100+ return c.text('cached')101+ })102+103+ app.use(104+ '/not-found/*',105+ cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10', vary: ['Accept'] })106+ )107+108 const ctx = new Context()109 110 it('Should return cached response', async () => {111 await app.request('http://localhost/wait/')32 unmodified lines144 expect(res.status).toBe(200)145 expect(res.headers.get('cache-control')).toBe('private, max-age=10')146 })147 148+ it('Should correctly apply a single Vary header from middleware', async () => {149+ const res = await app.request('http://localhost/vary1/')150+ expect(res).not.toBeNull()151+ expect(res.status).toBe(200)152+ expect(res.headers.get('vary')).toBe('accept')153+ })154+155+ it('Should merge Vary headers from middleware and handler without duplicating', async () => {156+ const res = await app.request('http://localhost/vary2/')157+ expect(res).not.toBeNull()158+ expect(res.status).toBe(200)159+ expect(res.headers.get('vary')).toBe('accept, accept-encoding')160+ })161+162+ it('Should deduplicate while merging multiple Vary headers from middleware and handler', async () => {163+ const res = await app.request('http://localhost/vary3/')164+ expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')165+ })166+167+ it('Should prevent duplication of Vary headers when identical ones are set by both middleware and handler', async () => {168+ const res = await app.request('http://localhost/vary4/')169+ expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')170+ })171+172+ it('Should correctly apply and return a single Vary header with Accept specified by middleware', async () => {173+ const res = await app.request('http://localhost/vary5/')174+ expect(res).not.toBeNull()175+ expect(res.status).toBe(200)176+ expect(res.headers.get('vary')).toBe('accept')177+ })178+179+ it('Should merge Vary headers specified by middleware as a string with additional headers added by handler', async () => {180+ const res = await app.request('http://localhost/vary6/')181+ expect(res).not.toBeNull()182+ expect(res.status).toBe(200)183+ expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')184+ })185+186+ it('Should prioritize the "*" Vary header from handler over any set by middleware', async () => {187+ const res = await app.request('http://localhost/vary7/')188+ expect(res).not.toBeNull()189+ expect(res.status).toBe(200)190+ expect(res.headers.get('vary')).toBe('*')191+ })192+193+ it('Should not allow "*" as a Vary header in middleware configuration due to its impact on caching effectiveness', async () => {194+ expect(() => cache({ cacheName: 'my-app-v1', wait: true, vary: ['*'] })).toThrow()195+ expect(() => cache({ cacheName: 'my-app-v1', wait: true, vary: '*' })).toThrow()196+ })197+198 it('Should not cache if it is not found', async () => {199 const res = await app.request('/not-found/')200 expect(res).not.toBeNull()201 expect(res.status).toBe(404)202 expect(res.headers.get('cache-control')).toBeFalsy()203+ expect(res.headers.get('vary')).toBeFalsy()204 })205 206 it('Should not be enabled if caches is not defined', async () => {207 vi.stubGlobal('caches', undefined)12 unmodified linesmodified:src/middleware/cache/index.ts+36 added-3 removed
3 unmodified lines4 export const cache = (options: {5 cacheName: string6 wait?: boolean7 cacheControl?: string8+ vary?: string | string[]9 }): MiddlewareHandler => {10 if (!globalThis.caches) {11 console.log('Cache Middleware is not enabled because caches is not defined.')12 return async (_c, next) => await next()2 unmodified lines15 if (options.wait === undefined) {16 options.wait = false17 }18 18- const directives = options.cacheControl?.split(',').map((directive) => directive.toLowerCase())19+ const cacheControlDirectives = options.cacheControl20+ ?.split(',')21+ .map((directive) => directive.toLowerCase())22+ const varyDirectives = Array.isArray(options.vary)23+ ? options.vary24+ : options.vary?.split(',').map((directive) => directive.trim())25+ // RFC 7231 Section 7.1.4 specifies that "*" is not allowed in Vary header.26+ // See: https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.427+ if (options.vary?.includes('*')) {28+ throw new Error(29+ 'Middleware vary configuration cannot include "*", as it disallows effective caching.'30+ )31+ }32 33 const addHeader = (c: Context) => {21- if (directives) {34+ if (cacheControlDirectives) {35 const existingDirectives =36 c.res.headers37 .get('Cache-Control')38 ?.split(',')39 .map((d) => d.trim().split('=', 1)[0]) ?? []27- for (const directive of directives) {40+ for (const directive of cacheControlDirectives) {41 let [name, value] = directive.trim().split('=', 2)42 name = name.toLowerCase()43 if (!existingDirectives.includes(name)) {44 c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true })45 }46 }47 }48+49+ if (varyDirectives) {50+ const existingDirectives =51+ c.res.headers52+ .get('Vary')53+ ?.split(',')54+ .map((d) => d.trim()) ?? []55+56+ const vary = Array.from(57+ new Set(58+ [...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase())59+ )60+ ).sort()61+62+ if (vary.includes('*')) {63+ c.header('Vary', '*')64+ } else {65+ c.header('Vary', vary.join(', '))66+ }67+ }68 }69 70 return async function cache(c, next) {71 const key = c.req.url19 unmodified linesmodified:src/middleware/cors/index.ts+3 added-2 removed
1+import type { Context } from '../../context'2 import type { MiddlewareHandler } from '../../types'3 4 type CORSOptions = {4- origin: string | string[] | ((origin: string) => string | undefined | null)5+ origin: string | string[] | ((origin: string, c: Context) => string | undefined | null)6 allowMethods?: string[]7 allowHeaders?: string[]8 maxAge?: number9 credentials?: boolean26 unmodified lines36 function set(key: string, value: string) {37 c.res.headers.set(key, value)38 }39 39- const allowOrigin = findAllowOrigin(c.req.header('origin') || '')40+ const allowOrigin = findAllowOrigin(c.req.header('origin') || '', c)41 if (allowOrigin) {42 set('Access-Control-Allow-Origin', allowOrigin)43 }44 47 unmodified linesmodified:src/middleware/jwt/index.test.ts+27 added
1 import { Hono } from '../../hono'2+import { HTTPException } from '../../http-exception'3 import { jwt } from '.'4 5 describe('JWT', () => {6 describe('Credentials in header', () => {207 unmodified lines214 )215 expect(handlerExecuted).toBeFalsy()216 })217 })218+219+ describe('Error handling with `cause`', () => {220+ const app = new Hono()221+222+ app.use('/auth/*', jwt({ secret: 'a-secret' }))223+ app.get('/auth/*', (c) => c.text('Authorized'))224+225+ app.onError((e, c) => {226+ if (e instanceof HTTPException && e.cause instanceof Error) {227+ return c.json({ name: e.cause.name, message: e.cause.message }, 401)228+ }229+ return c.text(e.message, 401)230+ })231+232+ it('Should not authorize', async () => {233+ const credential = 'abc.def.ghi'234+ const req = new Request('http://localhost/auth')235+ req.headers.set('Authorization', `Bearer ${credential}`)236+ const res = await app.request(req)237+ expect(res.status).toBe(401)238+ expect(await res.json()).toEqual({239+ name: 'JwtTokenInvalid',240+ message: `invalid JWT token: ${credential}`,241+ })242+ })243+ })244 })modified:src/middleware/jwt/index.ts+14 added-8 removed
1 unmodified line2 import { getCookie } from '../../helper/cookie'3 import { HTTPException } from '../../http-exception'4 import type { MiddlewareHandler } from '../../types'5 import { Jwt } from '../../utils/jwt'6-import type { AlgorithmTypes } from '../../utils/jwt/types'6 import '../../context'7+import type { SignatureAlgorithm } from '../../utils/jwt/jwa'8 9 declare module '../../context' {10 interface ContextVariableMap {11 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 unmodified lines15 16 export const jwt = (options: {17 secret: string18 cookie?: string19- alg?: string19+ alg?: SignatureAlgorithm20 }): MiddlewareHandler => {21 if (!options) {22 throw new Error('JWT auth middleware requires options for "secret')23 }7 unmodified lines31 let token32 if (credentials) {33 const parts = credentials.split(/\s+/)34 if (parts.length !== 2) {35+ const errDescription = 'invalid credentials structure'36 throw new HTTPException(401, {37+ message: errDescription,38 res: unauthorizedResponse({39 ctx,40 error: 'invalid_request',39- errDescription: 'invalid credentials structure',41+ errDescription,42 }),43 })44 } else {45 token = parts[1]2 unmodified lines48 token = getCookie(ctx)[options.cookie]49 }50 51 if (!token) {52+ const errDescription = 'no authorization included in request'53 throw new HTTPException(401, {54+ message: errDescription,55 res: unauthorizedResponse({56 ctx,57 error: 'invalid_request',54- errDescription: 'no authorization included in request',58+ errDescription,59 }),60 })61 }62 63 let payload60- let msg = ''64+ let cause65 try {62- payload = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes)66+ payload = await Jwt.verify(token, options.secret, options.alg)67 } catch (e) {64- msg = `${e}`68+ cause = e69 }70 if (!payload) {71 throw new HTTPException(401, {72+ message: 'Unauthorized',73 res: unauthorizedResponse({74 ctx,75 error: 'invalid_token',71- statusText: msg,76+ statusText: 'Unauthorized',77 errDescription: 'token verification failure',78 }),79+ cause,80 })81 }82 83 ctx.set('jwtPayload', payload)23 unmodified linesadded:src/middleware/method-override/index.test.ts+182 added
1+import { Hono } from '../../hono'2+import { methodOverride } from './index'3+4+describe('Method Override Middleware', () => {5+ describe('Form', () => {6+ const app = new Hono()7+ app.use('/posts/*', methodOverride({ app }))8+ app.use('/posts-custom/*', methodOverride({ app, form: 'custom-input-name' }))9+ app.on(['post', 'delete'], ['/posts', '/posts-custom'], async (c) => {10+ const form = await c.req.formData()11+ return c.json({12+ method: c.req.method,13+ message: form.get('message'),14+ contentType: c.req.header('content-type') ?? '',15+ })16+ })17+18+ describe('multipart/form-data', () => {19+ it('Should override POST to DELETE', async () => {20+ const form = new FormData()21+ form.append('message', 'Hello')22+ form.append('_method', 'DELETE')23+ const res = await app.request('/posts', {24+ body: form,25+ method: 'POST',26+ })27+ expect(res.status).toBe(200)28+ const data = await res.json()29+ expect(data.method).toBe('DELETE')30+ expect(data.message).toBe('Hello')31+ expect(data.contentType).toMatch(/^multipart\/form-data;/)32+ })33+34+ it('Should override POST to DELETE - with a custom form input name', async () => {35+ const form = new FormData()36+ form.append('message', 'Hello')37+ form.append('custom-input-name', 'DELETE')38+ const res = await app.request('/posts-custom', {39+ body: form,40+ method: 'POST',41+ })42+ expect(res.status).toBe(200)43+ const data = await res.json()44+ expect(data.method).toBe('DELETE')45+ expect(data.message).toBe('Hello')46+ expect(data.contentType).toMatch(/^multipart\/form-data;/)47+ })48+49+ it('Should override POST to PATCH - not found', async () => {50+ const form = new FormData()51+ form.append('message', 'Hello')52+ form.append('_method', 'PATCH')53+ const res = await app.request('/posts', {54+ body: form,55+ method: 'POST',56+ })57+ expect(res.status).toBe(404)58+ })59+ })60+61+ describe('application/x-www-form-urlencoded', () => {62+ it('Should override POST to DELETE', async () => {63+ const params = new URLSearchParams()64+ params.append('message', 'Hello')65+ params.append('_method', 'DELETE')66+ const res = await app.request('/posts', {67+ body: params,68+ headers: {69+ 'Content-Type': 'application/x-www-form-urlencoded',70+ },71+ method: 'POST',72+ })73+ expect(res.status).toBe(200)74+ const data = await res.json()75+ expect(data.method).toBe('DELETE')76+ expect(data.message).toBe('Hello')77+ expect(data.contentType).toBe('application/x-www-form-urlencoded')78+ })79+80+ it('Should override POST to DELETE - with a custom form input name', async () => {81+ const params = new URLSearchParams()82+ params.append('message', 'Hello')83+ params.append('custom-input-name', 'DELETE')84+ const res = await app.request('/posts-custom', {85+ body: params,86+ headers: {87+ 'Content-Type': 'application/x-www-form-urlencoded',88+ },89+ method: 'POST',90+ })91+ expect(res.status).toBe(200)92+ const data = await res.json()93+ expect(data.method).toBe('DELETE')94+ expect(data.message).toBe('Hello')95+ expect(data.contentType).toBe('application/x-www-form-urlencoded')96+ })97+98+ it('Should override POST to PATCH - not found', async () => {99+ const form = new FormData()100+ form.append('message', 'Hello')101+ form.append('_method', 'PATCH')102+ const res = await app.request('/posts', {103+ body: form,104+ method: 'POST',105+ })106+ expect(res.status).toBe(404)107+ })108+ })109+ })110+111+ describe('Header', () => {112+ const app = new Hono()113+ app.use('/posts/*', methodOverride({ app, header: 'X-METHOD-OVERRIDE' }))114+ app.on(['get', 'post', 'delete'], '/posts', async (c) => {115+ return c.json({116+ method: c.req.method,117+ headerValue: c.req.header('X-METHOD-OVERRIDE') ?? null,118+ })119+ })120+121+ it('Should override POST to DELETE', async () => {122+ const res = await app.request('/posts', {123+ method: 'POST',124+ headers: {125+ 'X-METHOD-OVERRIDE': 'DELETE',126+ },127+ })128+ expect(res.status).toBe(200)129+ expect(await res.json()).toEqual({130+ method: 'DELETE',131+ headerValue: null,132+ })133+ })134+135+ it('Should not override GET request', async () => {136+ const res = await app.request('/posts', {137+ method: 'GET',138+ headers: {139+ 'X-METHOD-OVERRIDE': 'DELETE',140+ },141+ })142+ expect(res.status).toBe(200)143+ expect(await res.json()).toEqual({144+ method: 'GET',145+ headerValue: 'DELETE', // It does not modify the headers.146+ })147+ })148+ })149+150+ describe('Query', () => {151+ const app = new Hono()152+ app.use('/posts/*', methodOverride({ app, query: '_method' }))153+ app.on(['get', 'post', 'delete'], '/posts', async (c) => {154+ return c.json({155+ method: c.req.method,156+ queryValue: c.req.query('_method') ?? null,157+ })158+ })159+160+ it('Should override POST to DELETE', async () => {161+ const res = await app.request('/posts?_method=delete', {162+ method: 'POST',163+ })164+ expect(res.status).toBe(200)165+ expect(await res.json()).toEqual({166+ method: 'DELETE',167+ queryValue: null,168+ })169+ })170+171+ it('Should not override GET request', async () => {172+ const res = await app.request('/posts?_method=delete', {173+ method: 'GET',174+ })175+ expect(res.status).toBe(200)176+ expect(await res.json()).toEqual({177+ method: 'GET',178+ queryValue: 'delete', // It does not modify the queries.179+ })180+ })181+ })182+})added:src/middleware/method-override/index.ts+134 added
1+import { URLSearchParams } from 'url'2+import type { Context } from '../../context'3+import type { Hono } from '../../hono'4+import type { MiddlewareHandler } from '../../types'5+import { parseBody } from '../../utils/body'6+7+type MethodOverrideOptions = {8+ // eslint-disable-next-line @typescript-eslint/no-explicit-any9+ app: Hono<any, any, any>10+} & (11+ | {12+ // Default is 'form' and the value is `_method`13+ form?: string14+ header?: never15+ query?: never16+ }17+ | {18+ form?: never19+ header: string20+ query?: never21+ }22+ | {23+ form?: never24+ header?: never25+ query: string26+ }27+)28+29+const DEFAULT_METHOD_FORM_NAME = '_method'30+31+/**32+ * Method Override Middleware33+ *34+ * @example35+ * // with form input method36+ * const app = new Hono()37+ * app.use('/books/*', methodOverride({ app })) // the default `form` value is `_method`38+ * app.use('/authors/*', methodOverride({ app, form: 'method' }))39+ *40+ * @example41+ * // with custom header42+ * app.use('/books/*', methodOverride({ app, header: 'X-HTTP-METHOD-OVERRIDE' }))43+ *44+ * @example45+ * // with query parameter46+ * app.use('/books/*', methodOverride({ app, query: '_method' }))47+ */48+export const methodOverride = (options: MethodOverrideOptions): MiddlewareHandler =>49+ async function methodOverride(c, next) {50+ if (c.req.method === 'GET') {51+ return await next()52+ }53+54+ const app = options.app55+ // Method override by form56+ if (!(options.header || options.query)) {57+ const contentType = c.req.header('content-type')58+ const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME59+ const clonedRequest = c.req.raw.clone()60+ const newRequest = clonedRequest.clone()61+ // Content-Type is `multipart/form-data`62+ if (contentType?.startsWith('multipart/form-data')) {63+ const form = await clonedRequest.formData()64+ const method = form.get(methodFormName)65+ if (method) {66+ const newForm = await newRequest.formData()67+ newForm.delete(methodFormName)68+ const newHeaders = new Headers(clonedRequest.headers)69+ newHeaders.delete('content-type')70+ newHeaders.delete('content-length')71+ const request = new Request(c.req.url, {72+ body: newForm,73+ headers: newHeaders,74+ method: method as string,75+ })76+ return app.fetch(request, c.env, getExecutionCtx(c))77+ }78+ }79+ // Content-Type is `application/x-www-form-urlencoded`80+ if (contentType === 'application/x-www-form-urlencoded') {81+ const params = await parseBody<Record<string, string>>(clonedRequest)82+ const method = params[methodFormName]83+ if (method) {84+ delete params[methodFormName]85+ const newParams = new URLSearchParams(params)86+ const request = new Request(newRequest, {87+ body: newParams,88+ method: method as string,89+ })90+ return app.fetch(request, c.env, getExecutionCtx(c))91+ }92+ }93+ }94+ // Method override by header95+ else if (options.header) {96+ const headerName = options.header97+ const method = c.req.header(headerName)98+ if (method) {99+ const newHeaders = new Headers(c.req.raw.headers)100+ newHeaders.delete(headerName)101+ const request = new Request(c.req.raw, {102+ headers: newHeaders,103+ method,104+ })105+ return app.fetch(request, c.env, getExecutionCtx(c))106+ }107+ }108+ // Method override by query109+ else if (options.query) {110+ const queryName = options.query111+ const method = c.req.query(queryName)112+ if (method) {113+ const url = new URL(c.req.url)114+ url.searchParams.delete(queryName)115+ const request = new Request(url.toString(), {116+ body: c.req.raw.body,117+ headers: c.req.raw.headers,118+ method,119+ })120+ return app.fetch(request, c.env, getExecutionCtx(c))121+ }122+ }123+ await next()124+ }125+126+const getExecutionCtx = (c: Context) => {127+ let executionCtx: ExecutionContext | undefined128+ try {129+ executionCtx = c.executionCtx130+ } catch {131+ // Do nothing132+ }133+ return executionCtx134+}added:src/middleware/trailing-slash/index.test.ts+85 added
1+import { Hono } from '../../hono'2+import { trimTrailingSlash, appendTrailingSlash } from '.'3+4+describe('Resolve trailing slash', () => {5+ let app: Hono6+7+ it('Trim', async () => {8+ app = new Hono({ strict: true })9+10+ app.use('*', trimTrailingSlash())11+12+ app.get('/', async (c) => {13+ return c.text('ok')14+ })15+ app.get('/the/example/endpoint/without/trailing/slash', async (c) => {16+ return c.text('ok')17+ })18+19+ let resp: Response, loc: URL20+21+ resp = await app.request('/')22+ expect(resp).not.toBeNull()23+ expect(resp.status).toBe(200)24+25+ resp = await app.request('/the/example/endpoint/without/trailing/slash')26+ expect(resp).not.toBeNull()27+ expect(resp.status).toBe(200)28+29+ resp = await app.request('/the/example/endpoint/without/trailing/slash/')30+ loc = new URL(resp.headers.get('location')!)31+ expect(resp).not.toBeNull()32+ expect(resp.status).toBe(301)33+ expect(loc.pathname).toBe('/the/example/endpoint/without/trailing/slash')34+35+ resp = await app.request('/the/example/endpoint/without/trailing/slash/?exampleParam=1')36+ loc = new URL(resp.headers.get('location')!)37+ expect(resp).not.toBeNull()38+ expect(resp.status).toBe(301)39+ expect(loc.pathname).toBe('/the/example/endpoint/without/trailing/slash')40+ expect(loc.searchParams.get('exampleParam')).toBe('1')41+ })42+43+ it('Append', async () => {44+ app = new Hono({ strict: true })45+46+ app.use('*', appendTrailingSlash())47+48+ app.get('/', async (c) => {49+ return c.text('ok')50+ })51+ app.get('/the/example/endpoint/with/trailing/slash/', async (c) => {52+ return c.text('ok')53+ })54+ app.get('/the/example/simulate/a.file', async (c) => {55+ return c.text('ok')56+ })57+58+ let resp: Response, loc: URL59+60+ resp = await app.request('/')61+ expect(resp).not.toBeNull()62+ expect(resp.status).toBe(200)63+64+ resp = await app.request('/the/example/simulate/a.file')65+ expect(resp).not.toBeNull()66+ expect(resp.status).toBe(200)67+68+ resp = await app.request('/the/example/endpoint/with/trailing/slash/')69+ expect(resp).not.toBeNull()70+ expect(resp.status).toBe(200)71+72+ resp = await app.request('/the/example/endpoint/with/trailing/slash')73+ loc = new URL(resp.headers.get('location')!)74+ expect(resp).not.toBeNull()75+ expect(resp.status).toBe(301)76+ expect(loc.pathname).toBe('/the/example/endpoint/with/trailing/slash/')77+78+ resp = await app.request('/the/example/endpoint/with/trailing/slash?exampleParam=1')79+ loc = new URL(resp.headers.get('location')!)80+ expect(resp).not.toBeNull()81+ expect(resp.status).toBe(301)82+ expect(loc.pathname).toBe('/the/example/endpoint/with/trailing/slash/')83+ expect(loc.searchParams.get('exampleParam')).toBe('1')84+ })85+})added:src/middleware/trailing-slash/index.ts+46 added
1+import type { MiddlewareHandler } from '../../types'2+3+/**4+ * Trim the trailing slash from the URL if it does have one. For example, `/path/to/page/` will be redirected to `/path/to/page`.5+ * @access public6+ * @example app.use(trimTrailingSlash())7+ */8+export const trimTrailingSlash = (): MiddlewareHandler => {9+ return async function trimTrailingSlash(c, next) {10+ await next()11+12+ if (13+ c.res.status === 404 &&14+ c.req.method === 'GET' &&15+ c.req.path !== '/' &&16+ c.req.path[c.req.path.length - 1] === '/'17+ ) {18+ const url = new URL(c.req.url)19+ url.pathname = url.pathname.substring(0, url.pathname.length - 1)20+21+ c.res = c.redirect(url.toString(), 301)22+ }23+ }24+}25+26+/**27+ * Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`.28+ * @access public29+ * @example app.use(appendTrailingSlash())30+ */31+export const appendTrailingSlash = (): MiddlewareHandler => {32+ return async function appendTrailingSlash(c, next) {33+ await next()34+35+ if (36+ c.res.status === 404 &&37+ c.req.method === 'GET' &&38+ c.req.path[c.req.path.length - 1] !== '/'39+ ) {40+ const url = new URL(c.req.url)41+ url.pathname += '/'42+43+ c.res = c.redirect(url.toString(), 301)44+ }45+ }46+}modified:src/test-utils/setup-vitest.ts+5 added-2 removed
1 // @denoify-ignore2-import crypto from 'node:crypto'2+import * as nodeCrypto from 'node:crypto'3 import { vi } from 'vitest'4 5 /**6 * crypto7 */8+if (!globalThis.crypto) {8-vi.stubGlobal('crypto', crypto)9+ vi.stubGlobal('crypto', nodeCrypto)10+ vi.stubGlobal('CryptoKey', nodeCrypto.webcrypto.CryptoKey)11+}12 13 /**14 * Cache API15 */29 unmodified linesmodified:src/utils/jwt/index.ts+2 added-1 removed
1-export * as Jwt from './jwt'1+import { sign, verify, decode } from './jwt'2+export const Jwt = { sign, verify, decode }added:src/utils/jwt/jwa.test.ts+17 added
1+import { AlgorithmTypes } from './jwa'2+3+describe('Types', () => {4+ it('AlgorithmTypes', () => {5+ expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)6+ expect('HS384' as AlgorithmTypes).toBe(AlgorithmTypes.HS384)7+ expect('HS512' as AlgorithmTypes).toBe(AlgorithmTypes.HS512)8+ expect('RS256' as AlgorithmTypes).toBe(AlgorithmTypes.RS256)9+ expect('RS384' as AlgorithmTypes).toBe(AlgorithmTypes.RS384)10+ expect('RS512' as AlgorithmTypes).toBe(AlgorithmTypes.RS512)11+12+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment13+ // @ts-ignore14+ expect(undefined as AlgorithmTypes).toBe(undefined)15+ expect('' as AlgorithmTypes).toBe('')16+ })17+})added:src/utils/jwt/jwa.ts+20 added
1+// JSON Web Algorithms (JWA)2+// https://datatracker.ietf.org/doc/html/rfc75183+4+export enum AlgorithmTypes {5+ HS256 = 'HS256',6+ HS384 = 'HS384',7+ HS512 = 'HS512',8+ RS256 = 'RS256',9+ RS384 = 'RS384',10+ RS512 = 'RS512',11+ PS256 = 'PS256',12+ PS384 = 'PS384',13+ PS512 = 'PS512',14+ ES256 = 'ES256',15+ ES384 = 'ES384',16+ ES512 = 'ES512',17+ EdDSA = 'EdDSA',18+}19+20+export type SignatureAlgorithm = keyof typeof AlgorithmTypesadded:src/utils/jwt/jws.ts+224 added
1+import { getRuntimeKey } from '../../helper'2+import { decodeBase64 } from '../encode'3+import type { SignatureAlgorithm } from './jwa'4+import { JwtAlgorithmNotImplemented } from './types'5+import { CryptoKeyUsage } from './types'6+import { utf8Encoder } from './utf8'7+8+// JSON Web Signature (JWS)9+// https://datatracker.ietf.org/doc/html/rfc751510+11+type KeyImporterAlgorithm = Parameters<typeof crypto.subtle.importKey>[2]12+type KeyAlgorithm =13+ | AlgorithmIdentifier14+ | RsaHashedImportParams15+ | (RsaPssParams & RsaHashedImportParams)16+ | (EcdsaParams & EcKeyImportParams)17+ | HmacImportParams18+19+export type SignatureKey = string | JsonWebKey | CryptoKey20+21+export async function signing(22+ privateKey: SignatureKey,23+ alg: SignatureAlgorithm,24+ data: BufferSource25+): Promise<ArrayBuffer> {26+ const algorithm = getKeyAlgorithm(alg)27+ const cryptoKey = await importPrivateKey(privateKey, algorithm)28+ return await crypto.subtle.sign(algorithm, cryptoKey, data)29+}30+31+export async function verifying(32+ publicKey: SignatureKey,33+ alg: SignatureAlgorithm,34+ signature: BufferSource,35+ data: BufferSource36+): Promise<boolean> {37+ const algorithm = getKeyAlgorithm(alg)38+ const cryptoKey = await importPublicKey(publicKey, algorithm)39+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data)40+}41+42+function pemToBinary(pem: string): Uint8Array {43+ return decodeBase64(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))44+}45+46+async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {47+ if (!crypto.subtle || !crypto.subtle.importKey) {48+ throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')49+ }50+ if (isCryptoKey(key)) {51+ if (key.type !== 'private') {52+ throw new Error(`unexpected non private key: CryptoKey.type is ${key.type}`)53+ }54+ return key55+ }56+ const usages = [CryptoKeyUsage.Sign]57+ if (typeof key === 'object') {58+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import59+ return await crypto.subtle.importKey('jwk', key, alg, false, usages)60+ }61+ if (key.includes('PRIVATE')) {62+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import63+ return await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, false, usages)64+ }65+ return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)66+}67+68+async function importPublicKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {69+ if (!crypto.subtle || !crypto.subtle.importKey) {70+ throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')71+ }72+ if (isCryptoKey(key)) {73+ if (key.type === 'public' || key.type === 'secret') {74+ return key75+ }76+ key = await exportPublicJwkFrom(key)77+ }78+ if (typeof key === 'string' && key.includes('PRIVATE')) {79+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import80+ const privateKey = await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, true, [81+ CryptoKeyUsage.Sign,82+ ])83+ key = await exportPublicJwkFrom(privateKey)84+ }85+ const usages = [CryptoKeyUsage.Verify]86+ if (typeof key === 'object') {87+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import88+ return await crypto.subtle.importKey('jwk', key, alg, false, usages)89+ }90+ if (key.includes('PUBLIC')) {91+ // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#subjectpublickeyinfo_import92+ return await crypto.subtle.importKey('spki', pemToBinary(key), alg, false, usages)93+ }94+ return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)95+}96+97+// https://datatracker.ietf.org/doc/html/rfc751798+async function exportPublicJwkFrom(privateKey: CryptoKey): Promise<JsonWebKey> {99+ if (privateKey.type !== 'private') {100+ throw new Error(`unexpected key type: ${privateKey.type}`)101+ }102+ if (!privateKey.extractable) {103+ throw new Error('unexpected private key is unextractable')104+ }105+ const jwk = await crypto.subtle.exportKey('jwk', privateKey)106+ const { kty } = jwk // common107+ const { alg, e, n } = jwk // rsa108+ const { crv, x, y } = jwk // elliptic-curve109+ return { kty, alg, e, n, crv, x, y, key_ops: [CryptoKeyUsage.Verify] }110+}111+112+function getKeyAlgorithm(name: SignatureAlgorithm): KeyAlgorithm {113+ switch (name) {114+ case 'HS256':115+ return {116+ name: 'HMAC',117+ hash: {118+ name: 'SHA-256',119+ },120+ } satisfies HmacImportParams121+ case 'HS384':122+ return {123+ name: 'HMAC',124+ hash: {125+ name: 'SHA-384',126+ },127+ } satisfies HmacImportParams128+ case 'HS512':129+ return {130+ name: 'HMAC',131+ hash: {132+ name: 'SHA-512',133+ },134+ } satisfies HmacImportParams135+ case 'RS256':136+ return {137+ name: 'RSASSA-PKCS1-v1_5',138+ hash: {139+ name: 'SHA-256',140+ },141+ } satisfies RsaHashedImportParams142+ case 'RS384':143+ return {144+ name: 'RSASSA-PKCS1-v1_5',145+ hash: {146+ name: 'SHA-384',147+ },148+ } satisfies RsaHashedImportParams149+ case 'RS512':150+ return {151+ name: 'RSASSA-PKCS1-v1_5',152+ hash: {153+ name: 'SHA-512',154+ },155+ } satisfies RsaHashedImportParams156+ case 'PS256':157+ return {158+ name: 'RSA-PSS',159+ hash: {160+ name: 'SHA-256',161+ },162+ saltLength: 32, // 256 >> 3163+ } satisfies RsaPssParams & RsaHashedImportParams164+ case 'PS384':165+ return {166+ name: 'RSA-PSS',167+ hash: {168+ name: 'SHA-384',169+ },170+ saltLength: 48, // 384 >> 3171+ } satisfies RsaPssParams & RsaHashedImportParams172+ case 'PS512':173+ return {174+ name: 'RSA-PSS',175+ hash: {176+ name: 'SHA-512',177+ },178+ saltLength: 64, // 512 >> 3,179+ } satisfies RsaPssParams & RsaHashedImportParams180+ case 'ES256':181+ return {182+ name: 'ECDSA',183+ hash: {184+ name: 'SHA-256',185+ },186+ namedCurve: 'P-256',187+ } satisfies EcdsaParams & EcKeyImportParams188+ case 'ES384':189+ return {190+ name: 'ECDSA',191+ hash: {192+ name: 'SHA-384',193+ },194+ namedCurve: 'P-384',195+ } satisfies EcdsaParams & EcKeyImportParams196+ case 'ES512':197+ return {198+ name: 'ECDSA',199+ hash: {200+ name: 'SHA-512',201+ },202+ namedCurve: 'P-521',203+ } satisfies EcdsaParams & EcKeyImportParams204+ case 'EdDSA':205+ // Currently, supported only Safari and Deno, Node.js.206+ // See: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify207+ return {208+ name: 'Ed25519',209+ namedCurve: 'Ed25519',210+ }211+ default:212+ throw new JwtAlgorithmNotImplemented(name)213+ }214+}215+216+function isCryptoKey(key: SignatureKey): key is CryptoKey {217+ const runtime = getRuntimeKey()218+ // @ts-expect-error CryptoKey hasn't exported to global in node v18219+ if (runtime === 'node' && !!crypto.webcrypto) {220+ // @ts-expect-error CryptoKey hasn't exported to global in node v18221+ return key instanceof crypto.webcrypto.CryptoKey222+ }223+ return key instanceof CryptoKey224+}modified:src/utils/jwt/jwt.test.ts+283 added-2 removed
1 /* eslint-disable @typescript-eslint/ban-ts-comment */2 import { vi } from 'vitest'3+import { encodeBase64 } from '../encode'4+import { AlgorithmTypes } from './jwa'5 import * as JWT from './jwt'6 import {5- AlgorithmTypes,7 JwtAlgorithmNotImplemented,8 JwtTokenExpired,9 JwtTokenInvalid,10 JwtTokenIssuedAt,11 JwtTokenNotBefore,12 JwtTokenSignatureMismatched,13 } from './types'14 15+describe('isTokenHeader', () => {16+ it('should return true for valid TokenHeader', () => {17+ const validTokenHeader: JWT.TokenHeader = {18+ alg: AlgorithmTypes.HS256,19+ typ: 'JWT',20+ }21+22+ expect(JWT.isTokenHeader(validTokenHeader)).toBe(true)23+ })24+25+ it('should return false for invalid TokenHeader', () => {26+ const invalidTokenHeader = {27+ alg: 'invalid',28+ typ: 'JWT',29+ }30+31+ expect(JWT.isTokenHeader(invalidTokenHeader)).toBe(false)32+ })33+})34+35 describe('JWT', () => {36 it('JwtAlgorithmNotImplemented', async () => {37 const payload = { message: 'hello world' }38 const secret = 'a-secret'42 unmodified lines81 })82 83 it('JwtTokenExpired', async () => {84 const tok =64- 'eyJraWQiOiJFemF6bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJleHAiOjE2MzMwNDY0MDB9.Gmq_dozOnwzqkMUMEm7uny7cMZuF1d0QkCnmRXAbTEk'85+ 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MzMwNDYxMDAsImV4cCI6MTYzMzA0NjQwMH0.H-OI1TWAbmK8RonvcpPaQcNvOKS9sxinEOsgKwjoiVo'86 const secret = 'a-secret'87 let err88 let authorized89 try {126 unmodified lines216 }217 expect(authorized).toBeUndefined()218 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)219 })220+221+ const rsTestCases = [222+ {223+ alg: AlgorithmTypes.RS256,224+ hash: 'SHA-256',225+ },226+ {227+ alg: AlgorithmTypes.RS384,228+ hash: 'SHA-384',229+ },230+ {231+ alg: AlgorithmTypes.RS512,232+ hash: 'SHA-512',233+ },234+ ]235+ for (const tc of rsTestCases) {236+ it(`${tc.alg} sign & verify`, async () => {237+ const alg = tc.alg238+ const payload = { message: 'hello world' }239+ const keyPair = await generateRSAKey(tc.hash)240+ const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)241+ const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)242+ const jwkPublicKey = await exportJWK(keyPair.publicKey)243+244+ const tok = await JWT.sign(payload, pemPrivateKey, alg)245+ expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)246+ expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)247+ expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)248+249+ const keyPair2 = await generateRSAKey(tc.hash)250+ const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)251+252+ let err = null253+ let authorized254+ try {255+ authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)256+ } catch (e) {257+ err = e258+ }259+ expect(authorized).toBeUndefined()260+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)261+ })262+263+ it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {264+ const alg = tc.alg265+ const payload = { message: 'hello world' }266+ const keyPair = await generateRSAKey(tc.hash)267+268+ const tok = await JWT.sign(payload, keyPair.privateKey, alg)269+ expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)270+ expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)271+ })272+ }273+274+ const psTestCases = [275+ {276+ alg: AlgorithmTypes.PS256,277+ hash: 'SHA-256',278+ },279+ {280+ alg: AlgorithmTypes.PS384,281+ hash: 'SHA-384',282+ },283+ {284+ alg: AlgorithmTypes.PS512,285+ hash: 'SHA-512',286+ },287+ ]288+ for (const tc of psTestCases) {289+ it(`${tc.alg} sign & verify`, async () => {290+ const alg = tc.alg291+ const payload = { message: 'hello world' }292+ const keyPair = await generateRSAPSSKey(tc.hash)293+ const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)294+ const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)295+ const jwkPublicKey = await exportJWK(keyPair.publicKey)296+297+ const tok = await JWT.sign(payload, pemPrivateKey, alg)298+ expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)299+ expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)300+ expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)301+302+ const keyPair2 = await generateRSAPSSKey(tc.hash)303+ const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)304+305+ let err = null306+ let authorized307+ try {308+ authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)309+ } catch (e) {310+ err = e311+ }312+ expect(authorized).toBeUndefined()313+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)314+ })315+316+ it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {317+ const alg = tc.alg318+ const payload = { message: 'hello world' }319+ const keyPair = await generateRSAPSSKey(tc.hash)320+321+ const tok = await JWT.sign(payload, keyPair.privateKey, alg)322+ expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)323+ expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)324+ })325+ }326+327+ const esTestCases = [328+ {329+ alg: AlgorithmTypes.ES256,330+ namedCurve: 'P-256',331+ },332+ {333+ alg: AlgorithmTypes.ES384,334+ namedCurve: 'P-384',335+ },336+ {337+ alg: AlgorithmTypes.ES512,338+ namedCurve: 'P-521',339+ },340+ ]341+ for (const tc of esTestCases) {342+ it(`${tc.alg} sign & verify`, async () => {343+ const alg = tc.alg344+ const payload = { message: 'hello world' }345+ const keyPair = await generateECDSAKey(tc.namedCurve)346+ const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)347+ const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)348+ const jwkPublicKey = await exportJWK(keyPair.publicKey)349+350+ const tok = await JWT.sign(payload, pemPrivateKey, alg)351+ expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)352+ expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)353+ expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)354+355+ const keyPair2 = await generateECDSAKey(tc.namedCurve)356+ const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)357+358+ let err = null359+ let authorized360+ try {361+ authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)362+ } catch (e) {363+ err = e364+ }365+ expect(authorized).toBeUndefined()366+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)367+ })368+369+ it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {370+ const alg = tc.alg371+ const payload = { message: 'hello world' }372+ const keyPair = await generateECDSAKey(tc.namedCurve)373+374+ const tok = await JWT.sign(payload, keyPair.privateKey, alg)375+ expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)376+ expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)377+ })378+ }379+380+ it('EdDSA sign & verify', async () => {381+ const alg = 'EdDSA'382+ const payload = { message: 'hello world' }383+ const keyPair = await generateEd25519Key()384+ const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)385+ const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)386+ const jwkPublicKey = await exportJWK(keyPair.publicKey)387+388+ const tok = await JWT.sign(payload, pemPrivateKey, alg)389+ expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)390+ expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)391+ expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)392+393+ const keyPair2 = await generateEd25519Key()394+ const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)395+396+ let err = null397+ let authorized398+ try {399+ authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)400+ } catch (e) {401+ err = e402+ }403+ expect(authorized).toBeUndefined()404+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)405+ })406+407+ it('EdDSA sign & verify w/ CryptoKey', async () => {408+ const alg = 'EdDSA'409+ const payload = { message: 'hello world' }410+ const keyPair = await generateEd25519Key()411+412+ const tok = await JWT.sign(payload, keyPair.privateKey, alg)413+ expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)414+ expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)415+ })416 })417+418+async function exportPEMPrivateKey(key: CryptoKey): Promise<string> {419+ const exported = await crypto.subtle.exportKey('pkcs8', key)420+ const pem = `-----BEGIN PRIVATE KEY-----\n${encodeBase64(exported)}\n-----END PRIVATE KEY-----`421+ return pem422+}423+424+async function exportPEMPublicKey(key: CryptoKey): Promise<string> {425+ const exported = await crypto.subtle.exportKey('spki', key)426+ const pem = `-----BEGIN PUBLIC KEY-----\n${encodeBase64(exported)}\n-----END PUBLIC KEY-----`427+ return pem428+}429+430+async function exportJWK(key: CryptoKey): Promise<JsonWebKey> {431+ return await crypto.subtle.exportKey('jwk', key)432+}433+434+async function generateRSAKey(hash: string): Promise<CryptoKeyPair> {435+ return await crypto.subtle.generateKey(436+ {437+ hash,438+ modulusLength: 2048,439+ publicExponent: new Uint8Array([1, 0, 1]),440+ name: 'RSASSA-PKCS1-v1_5',441+ },442+ true,443+ ['sign', 'verify']444+ )445+}446+447+async function generateRSAPSSKey(hash: string): Promise<CryptoKeyPair> {448+ return await crypto.subtle.generateKey(449+ {450+ hash,451+ modulusLength: 2048,452+ publicExponent: new Uint8Array([1, 0, 1]),453+ name: 'RSA-PSS',454+ },455+ true,456+ ['sign', 'verify']457+ )458+}459+460+async function generateECDSAKey(namedCurve: string): Promise<CryptoKeyPair> {461+ return await crypto.subtle.generateKey(462+ {463+ name: 'ECDSA',464+ namedCurve,465+ },466+ true,467+ ['sign', 'verify']468+ )469+}470+471+async function generateEd25519Key(): Promise<CryptoKeyPair> {472+ return await crypto.subtle.generateKey(473+ {474+ name: 'Ed25519',475+ namedCurve: 'Ed25519',476+ },477+ true,478+ ['sign', 'verify']479+ )480+}modified:src/utils/jwt/jwt.ts+38 added-89 removed
1 import { encodeBase64Url, decodeBase64Url } from '../../utils/encode'2-import type { AlgorithmTypes } from './types'3-import { JwtTokenIssuedAt } from './types'2+import type { SignatureAlgorithm } from './jwa'3+import { AlgorithmTypes } from './jwa'4+import type { SignatureKey } from './jws'5+import { signing, verifying } from './jws'6+import { JwtHeaderInvalid, type JWTPayload } from './types'7 import {8 JwtTokenInvalid,9 JwtTokenNotBefore,10 JwtTokenExpired,11 JwtTokenSignatureMismatched,9- JwtAlgorithmNotImplemented,12+ JwtTokenIssuedAt,13 } from './types'14+import { utf8Decoder, utf8Encoder } from './utf8'15 12-interface AlgorithmParams {13- name: string14- namedCurve?: string15- hash?: {16- name: string17- }18-}19-20-enum CryptoKeyFormat {21- RAW = 'raw',22- PKCS8 = 'pkcs8',23- SPKI = 'spki',24- JWK = 'jwk',25-}26-27-enum CryptoKeyUsage {28- Ecrypt = 'encrypt',29- Decrypt = 'decrypt',30- Sign = 'sign',31- Verify = 'verify',32- Deriverkey = 'deriveKey',33- DeriveBits = 'deriveBits',34- WrapKey = 'wrapKey',35- UnwrapKey = 'unwrapKey',36-}37-38-type AlgorithmTypeName = keyof typeof AlgorithmTypes39-40-const utf8Encoder = new TextEncoder()41-const utf8Decoder = new TextDecoder()42-16 const encodeJwtPart = (part: unknown): string =>17 encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')18 const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')19 20 const decodeJwtPart = (part: string): unknown =>21 JSON.parse(utf8Decoder.decode(decodeBase64Url(part)))22 50-const param = (name: AlgorithmTypeName): AlgorithmParams => {51- switch (name.toUpperCase()) {52- case 'HS256':53- return {54- name: 'HMAC',55- hash: {56- name: 'SHA-256',57- },58- }59- case 'HS384':60- return {61- name: 'HMAC',62- hash: {63- name: 'SHA-384',64- },65- }66- case 'HS512':67- return {68- name: 'HMAC',69- hash: {70- name: 'SHA-512',71- },72- }73- default:74- throw new JwtAlgorithmNotImplemented(name)75- }23+export interface TokenHeader {24+ alg: SignatureAlgorithm25+ typ: 'JWT'26 }27 78-const signing = async (79- data: string,80- secret: string,81- alg: AlgorithmTypeName = 'HS256'82-): Promise<ArrayBuffer> => {83- if (!crypto.subtle || !crypto.subtle.importKey) {84- throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')85- }86-87- const utf8Encoder = new TextEncoder()88- const cryptoKey = await crypto.subtle.importKey(89- CryptoKeyFormat.RAW,90- utf8Encoder.encode(secret),91- param(alg),92- false,93- [CryptoKeyUsage.Sign]28+// eslint-disable-next-line29+export function isTokenHeader(obj: any): obj is TokenHeader {30+ return (31+ typeof obj === 'object' &&32+ obj !== null &&33+ 'alg' in obj &&34+ Object.values(AlgorithmTypes).includes(obj.alg) &&35+ 'typ' in obj &&36+ obj.typ === 'JWT'37 )95- return await crypto.subtle.sign(param(alg), cryptoKey, utf8Encoder.encode(data))38 }39 40 export const sign = async (99- payload: unknown,100- secret: string,101- alg: AlgorithmTypeName = 'HS256'41+ payload: JWTPayload,42+ privateKey: SignatureKey,43+ alg: SignatureAlgorithm = 'HS256'44 ): Promise<string> => {45 const encodedPayload = encodeJwtPart(payload)104- const encodedHeader = encodeJwtPart({ alg, typ: 'JWT' })46+ const encodedHeader = encodeJwtPart({ alg, typ: 'JWT' } satisfies TokenHeader)47 48 const partialToken = `${encodedHeader}.${encodedPayload}`49 108- const signaturePart = await signing(partialToken, secret, alg)50+ const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken))51 const signature = encodeSignaturePart(signaturePart)52 53 return `${partialToken}.${signature}`54 }55 56 export const verify = async (57 token: string,116- secret: string,117- alg: AlgorithmTypeName = 'HS256'58+ publicKey: SignatureKey,59+ alg: SignatureAlgorithm = 'HS256'60 // eslint-disable-next-line @typescript-eslint/no-explicit-any61 ): Promise<any> => {62 const tokenParts = token.split('.')63 if (tokenParts.length !== 3) {64 throw new JwtTokenInvalid(token)65 }66 125- const { payload } = decode(token)67+ const { header, payload } = decode(token)68+ if (!isTokenHeader(header)) {69+ throw new JwtHeaderInvalid(header)70+ }71 const now = Math.floor(Date.now() / 1000)72 if (payload.nbf && payload.nbf > now) {73 throw new JwtTokenNotBefore(token)74 }3 unmodified lines78 if (payload.iat && now < payload.iat) {79 throw new JwtTokenIssuedAt(now, payload.iat)80 }81 137- const signaturePart = tokenParts.slice(0, 2).join('.')138- const signature = await signing(signaturePart, secret, alg)139- const encodedSignature = encodeSignaturePart(signature)140- if (encodedSignature !== tokenParts[2]) {82+ const headerPayload = token.substring(0, token.lastIndexOf('.'))83+ const verified = await verifying(84+ publicKey,85+ alg,86+ decodeBase64Url(tokenParts[2]),87+ utf8Encoder.encode(headerPayload)88+ )89+ if (!verified) {90 throw new JwtTokenSignatureMismatched(token)91 }92 93 return payload16 unmodified linesdeleted:src/utils/jwt/types.test.ts-13 removed
1-import { AlgorithmTypes } from './types'2-3-describe('Types', () => {4- it('AlgorithmTypes', () => {5- expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)6- expect('HS384' as AlgorithmTypes).toBe(AlgorithmTypes.HS384)7- expect('HS512' as AlgorithmTypes).toBe(AlgorithmTypes.HS512)8- // eslint-disable-next-line @typescript-eslint/ban-ts-comment9- // @ts-ignore10- expect(undefined as AlgorithmTypes).toBe(undefined)11- expect('' as AlgorithmTypes).toBe('')12- })13-})modified:src/utils/jwt/types.ts+37 added-4 removed
31 unmodified lines32 this.name = 'JwtTokenIssuedAt'33 }34 }35 36+export class JwtHeaderInvalid extends Error {37+ constructor(header: object) {38+ super(`jwt header is invalid: ${JSON.stringify(header)}`)39+ this.name = 'JwtHeaderInvalid'40+ }41+}42+43 export class JwtTokenSignatureMismatched extends Error {44 constructor(token: string) {45 super(`token(${token}) signature mismatched`)46 this.name = 'JwtTokenSignatureMismatched'47 }48 }49 43-export enum AlgorithmTypes {44- HS256 = 'HS256',45- HS384 = 'HS384',46- HS512 = 'HS512',50+export enum CryptoKeyUsage {51+ Encrypt = 'encrypt',52+ Decrypt = 'decrypt',53+ Sign = 'sign',54+ Verify = 'verify',55+ DeriveKey = 'deriveKey',56+ DeriveBits = 'deriveBits',57+ WrapKey = 'wrapKey',58+ UnwrapKey = 'unwrapKey',59 }60+61+/**62+ * JWT Payload63+ */64+export type JWTPayload =65+ | (unknown & {})66+ | {67+ [key: string]: unknown68+ /**69+ * The token is checked to ensure it has not expired.70+ */71+ exp?: number72+ /**73+ * The token is checked to ensure it is not being used before a specified time.74+ */75+ nbf?: number76+ /**77+ * The token is checked to ensure it is not issued in the future.78+ */79+ iat?: number80+ }added:src/utils/jwt/utf8.ts+2 added
1+export const utf8Encoder = new TextEncoder()2+export const utf8Decoder = new TextDecoder()modified:src/validator/validator.ts+2 added-31 removed
58 unmodified lines59 ): MiddlewareHandler<E, P, V> => {60 return async (c, next) => {61 let value = {}62 const contentType = c.req.header('Content-Type')63- const bodyTypes = ['text', 'arrayBuffer', 'blob']63 64 switch (target) {65 case 'json':66 if (!contentType || !contentType.startsWith('application/json')) {67 const message = `Invalid HTTP header: Content-Type=${contentType}`68 throw new HTTPException(400, { message })69 }71-72- if (c.req.bodyCache.json) {73- value = await c.req.bodyCache.json74- break75- }76-70 try {78- let arrayBuffer: ArrayBuffer | undefined = undefined79- for (const type of bodyTypes) {80- // @ts-expect-error bodyCache[type] is not typed81- const body = c.req.bodyCache[type]82- if (body) {83- arrayBuffer = await new Response(await body).arrayBuffer()84- break85- }86- }87- arrayBuffer ??= await c.req.raw.arrayBuffer()88- value = await new Response(arrayBuffer).json()89- c.req.bodyCache.json = value90- c.req.bodyCache.arrayBuffer = arrayBuffer71+ value = await c.req.json()72 } catch {73 const message = 'Malformed JSON in request body'74 throw new HTTPException(400, { message })75 }8 unmodified lines84 break85 }86 87 try {107- let arrayBuffer: ArrayBuffer | undefined = undefined108- for (const type of bodyTypes) {109- // @ts-expect-error bodyCache[type] is not typed110- const body = c.req.bodyCache[type]111- if (body) {112- arrayBuffer = await new Response(await body).arrayBuffer()113- break114- }115- }116- arrayBuffer ??= await c.req.arrayBuffer()88+ const arrayBuffer = await c.req.arrayBuffer()89 const formData = await bufferToFormData(arrayBuffer, contentType)90 const form: BodyData = {}91 formData.forEach((value, key) => {92 form[key] = value93 })94 value = form95 c.req.bodyCache.formData = formData124- c.req.bodyCache.arrayBuffer = arrayBuffer96 } catch (e) {97 let message = 'Malformed FormData request.'98 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`99 throw new HTTPException(400, { message })32 unmodified linesmodified:src/middleware.ts+2 added
9 unmodified lines10 export * from './jsx'11 export * from './middleware/jsx-renderer'12 export { jwt } from './middleware/jwt'13 export * from './middleware/logger'14+export * from './middleware/method-override'15 export * from './middleware/powered-by'16 export * from './middleware/timing'17 export * from './middleware/pretty-json'18 export * from './middleware/secure-headers'19+export * from './middleware/trailing-slash'20 export * from './adapter/deno/serve-static'modified:src/request.test.ts+43 added-12 removed
157 unmodified lines158 expect(foo).toEqual('')159 })160 })161 162+const text = '{"foo":"bar"}'163+const json = { foo: 'bar' }164+const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer165+162-describe('Body methods', () => {166+describe('Body methods with caching', () => {167 test('req.text()', async () => {168 const req = new HonoRequest(169 new Request('http://localhost', {170 method: 'POST',167- body: 'foo',171+ body: text,172 })173 )170- expect(await req.text()).toBe('foo')171- expect(await req.text()).toBe('foo') // Should be cached174+ expect(await req.text()).toEqual(text)175+ expect(await req.text()).toEqual(text)176+ expect(await req.json()).toEqual(json)177+ expect(await req.arrayBuffer()).toEqual(buffer)178+ expect(await req.blob()).toEqual(179+ new Blob([text], {180+ type: 'text/plain;charset=utf-8',181+ })182+ )183 })184 185 test('req.json()', async () => {186 const req = new HonoRequest(1 unmodified line188 method: 'POST',189 body: '{"foo":"bar"}',190 })191 )181- expect(await req.json()).toEqual({ foo: 'bar' })182- expect(await req.json()).toEqual({ foo: 'bar' }) // Should be cached192+ expect(await req.json()).toEqual(json)193+ expect(await req.json()).toEqual(json)194+ expect(await req.text()).toEqual(text)195+ expect(await req.arrayBuffer()).toEqual(buffer)196+ expect(await req.blob()).toEqual(197+ new Blob([text], {198+ type: 'text/plain;charset=utf-8',199+ })200+ )201 })202 203 test('req.arrayBuffer()', async () => {186- const buffer = new ArrayBuffer(8)204+ const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer205 const req = new HonoRequest(206 new Request('http://localhost', {207 method: 'POST',208 body: buffer,209 })210 )211 expect(await req.arrayBuffer()).toEqual(buffer)194- expect(await req.arrayBuffer()).toEqual(buffer) // Should be cached212+ expect(await req.arrayBuffer()).toEqual(buffer)213+ expect(await req.text()).toEqual(text)214+ expect(await req.json()).toEqual(json)215+ expect(await req.blob()).toEqual(216+ new Blob([text], {217+ type: '',218+ })219+ )220 })221 222 test('req.blob()', async () => {198- const blob = new Blob(['foo'], {199- type: 'text/plain',223+ const blob = new Blob(['{"foo":"bar"}'], {224+ type: 'application/json',225 })226 const req = new HonoRequest(227 new Request('http://localhost', {228 method: 'POST',229 body: blob,230 })231 )232 expect(await req.blob()).toEqual(blob)208- expect(await req.blob()).toEqual(blob) // Should be cached233+ expect(await req.blob()).toEqual(blob)234+ expect(await req.text()).toEqual(text)235+ expect(await req.json()).toEqual(json)236+ expect(await req.arrayBuffer()).toEqual(buffer)237 })238 239 test('req.formData()', async () => {240 const data = new FormData()4 unmodified lines245 body: data,246 })247 )248 expect((await req.formData()).get('foo')).toBe('bar')221- expect((await req.formData()).get('foo')).toBe('bar') // Should be cached249+ expect((await req.formData()).get('foo')).toBe('bar')250+ expect(async () => await req.text()).not.toThrow()251+ expect(async () => await req.arrayBuffer()).not.toThrow()252+ expect(async () => await req.blob()).not.toThrow()253 })254 })modified:src/request.ts+17 added-8 removed
192 unmodified lines193 194 private cachedBody = (key: keyof Body) => {195 const { bodyCache, raw } = this196 const cachedBody = bodyCache[key]197+198 if (cachedBody) {199 return cachedBody200 }200- /**201- * If an arrayBuffer cache is exist,202- * use it for creating a text, json, and others.203- */204- if (bodyCache.arrayBuffer) {205- return (async () => {206- return await new Response(bodyCache.arrayBuffer)[key]()207- })()201+202+ if (!bodyCache[key]) {203+ for (const keyOfBodyCache of Object.keys(bodyCache)) {204+ if (keyOfBodyCache === 'parsedBody') {205+ continue206+ }207+ return (async () => {208+ // @ts-expect-error bodyCache[keyOfBodyCache] can be passed as a body209+ let body = await bodyCache[keyOfBodyCache]210+ if (keyOfBodyCache === 'json') {211+ body = JSON.stringify(body)212+ }213+ return await new Response(body)[key]()214+ })()215+ }216 }217+218 return (bodyCache[key] = raw[key]())219 }220 221 /**126 unmodified linesmodified:bun.lockbbinary
A binary file, modified.
modified:package.json+14 added-1 removed
1 {2 "name": "hono",3- "version": "4.1.7",3+ "version": "4.2.0-rc.1",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",105 unmodified lines113 "types": "./dist/types/middleware/etag/index.d.ts",114 "import": "./dist/middleware/etag/index.js",115 "require": "./dist/cjs/middleware/etag/index.js"116 },117+ "./trailing-slash": {118+ "types": "./dist/types/middleware/trailing-slash/index.d.ts",119+ "import": "./dist/middleware/trailing-slash/index.js",120+ "require": "./dist/cjs/middleware/trailing-slash/index.js"121+ },122 "./html": {123 "types": "./dist/types/helper/html/index.d.ts",124 "import": "./dist/helper/html/index.js",125 "require": "./dist/cjs/helper/html/index.js"62 unmodified lines188 "types": "./dist/types/middleware/logger/index.d.ts",189 "import": "./dist/middleware/logger/index.js",190 "require": "./dist/cjs/middleware/logger/index.js"191 },192+ "./method-override": {193+ "types": "./dist/types/middleware/method-override/index.d.ts",194+ "import": "./dist/middleware/method-override/index.js",195+ "require": "./dist/cjs/middleware/method-override/index.js"196+ },197 "./powered-by": {198 "types": "./dist/types/middleware/powered-by/index.d.ts",199 "import": "./dist/middleware/powered-by/index.js",200 "require": "./dist/cjs/middleware/powered-by/index.js"216 unmodified lines417 ],418 "logger": [419 "./dist/types/middleware/logger"420 ],421+ "method-override": [422+ "./dist/types/middleware/method-override"423+ ],424 "powered-by": [425 "./dist/types/middleware/powered-by"426 ],427 "pretty-json": [143 unmodified lines