Merge pull request #2327 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 4ca5f60, 6eaa696 · Browse files · 68 files·+3369 added−1160 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
68 files+3369 added−1160 removed
- tests:+1336 added−478 removed
- other:+2033 added−682 removed
Provenance
- Commit
c7afb2d- Tree
f509fc5- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
4ca5f60- Parent 2
6eaa696
68 files changed+3369 added−1160 removed
modified:deno_dist/adapter/deno/deno.d.ts+5 added
14 unmodified lines1516171819202122232414 unmodified lines * @param data The data to write to the file. * @returns A promise that resolves when the file is written. */ export function writeFile(path: string, data: Uint8Array): Promise<void>
export function upgradeWebSocket(req: Request): { response: Response socket: WebSocket }}modified:deno_dist/adapter/deno/index.ts+1 added
123export { serveStatic } from './serve-static.ts'export { toSSG, denoFileSystemModule } from './ssg.ts'export { upgradeWebSocket } from './websocket.ts'added:deno_dist/adapter/deno/websocket.ts+30 added
123456789101112131415161718192021222324252627282930import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket/index.ts'
export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => { if (c.req.header('upgrade') !== 'websocket') { return await next() } const { response, socket } = Deno.upgradeWebSocket(c.req.raw)
const events = await createEvents(c)
const wsContext: WSContext = { binaryType: 'arraybuffer', close: (code, reason) => socket.close(code, reason), get protocol() { return socket.protocol }, raw: socket, get readyState() { return socket.readyState as WSReadyState }, url: socket.url ? new URL(socket.url) : null, send: (source) => socket.send(source), } socket.onopen = (evt) => events.onOpen && events.onOpen(evt, wsContext) socket.onmessage = (evt) => events.onMessage && events.onMessage(evt, wsContext) socket.onclose = (evt) => events.onClose && events.onClose(evt, wsContext) socket.onerror = (evt) => events.onError && events.onError(evt, wsContext)
return response}modified:deno_dist/client/client.ts+5 added
140 unmodified linesExpand all1411421431441451461471481491501511521535 unmodified lines140 unmodified linesExpand all return new URL(replaceUrlParam(url, opts.args[0].param)) } return new URL(url) } if (method === 'ws') { const targetUrl = opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url return new WebSocket(targetUrl) }
const req = new ClientRequestImpl(url, method) if (method) { options ??= {}5 unmodified linesmodified:deno_dist/client/types.ts+8 added
1+import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket/index.ts'2 import type { Hono } from '../hono.ts'3 import type { Schema } from '../types.ts'4 import type { HasRequiredKeys } from '../utils/types.ts'5 24 unmodified lines30 ? { param: P }31 : {}32 : {}33 ) => URL34+} & {35+ // WebSocket36+ $ws: S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }37+ ? S['$get'] extends { input: infer I }38+ ? (args?: Omit<I, 'json'>) => WebSocket39+ : never40+ : never41 }42 43 // eslint-disable-next-line @typescript-eslint/no-explicit-any44 type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never84 unmodified linesmodified:deno_dist/helper/cookie/index.ts+65 added-9 removed
1 import type { Context } from '../../context.ts'2 import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie.ts'3-import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie.ts'3+import type { CookieOptions, Cookie, SignedCookie, CookiePrefixOptions } from '../../utils/cookie.ts'4 5 interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8+ (c: Context, key: string, prefixOptions: CookiePrefixOptions): string | undefined9 }10 11 interface GetSignedCookie {12 (c: Context, secret: string | BufferSource, key: string): Promise<string | undefined | false>13 (c: Context, secret: string): Promise<SignedCookie>14+ (15+ c: Context,16+ secret: string | BufferSource,17+ key: string,18+ prefixOptions: CookiePrefixOptions19+ ): Promise<string | undefined | false>20 }21 15-export const getCookie: GetCookie = (c, key?) => {22+export const getCookie: GetCookie = (c, key?, prefix?: CookiePrefixOptions) => {23 const cookie = c.req.raw.headers.get('Cookie')24 if (typeof key === 'string') {25 if (!cookie) {26 return undefined27 }28+ let finalKey = key29+ if (prefix === 'secure') {30+ finalKey = '__Secure-' + key31+ } else if (prefix === 'host') {32+ finalKey = '__Host-' + key33+ }21- const obj = parse(cookie, key)22- return obj[key]34+ const obj = parse(cookie, finalKey)35+ return obj[finalKey]36 }37 if (!cookie) {38 return {}39 }1 unmodified line41 // eslint-disable-next-line @typescript-eslint/no-explicit-any42 return obj as any43 }44 32-export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {45+export const getSignedCookie: GetSignedCookie = async (46+ c,47+ secret,48+ key?,49+ prefix?: CookiePrefixOptions50+) => {51 const cookie = c.req.raw.headers.get('Cookie')52 if (typeof key === 'string') {53 if (!cookie) {54 return undefined55 }56+ let finalKey = key57+ if (prefix === 'secure') {58+ finalKey = '__Secure-' + key59+ } else if (prefix === 'host') {60+ finalKey = '__Host-' + key61+ }38- const obj = await parseSigned(cookie, secret, key)39- return obj[key]62+ const obj = await parseSigned(cookie, secret, finalKey)63+ return obj[finalKey]64 }65 if (!cookie) {66 return {}67 }2 unmodified lines70 return obj as any71 }72 73 export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {74+ // Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.75+ // Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)76+ // and must not have a Domain attribute.77+ // Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'78+ let cookie79+ if (opt?.prefix === 'secure') {80+ cookie = serialize('__Secure-' + name, value, { path: '/', ...opt, secure: true })81+ } else if (opt?.prefix === 'host') {82+ cookie = serialize('__Host-' + name, value, {83+ ...opt,84+ path: '/',85+ secure: true,86+ domain: undefined,87+ })88+ } else {50- const cookie = serialize(name, value, { path: '/', ...opt })89+ cookie = serialize(name, value, { path: '/', ...opt })90+ }91 c.header('set-cookie', cookie, { append: true })92 }93 94 export const setSignedCookie = async (2 unmodified lines97 value: string,98 secret: string | BufferSource,99 opt?: CookieOptions100 ): Promise<void> => {101+ let cookie102+ if (opt?.prefix === 'secure') {103+ cookie = await serializeSigned('__Secure-' + name, value, secret, {104+ path: '/',105+ ...opt,106+ secure: true,107+ })108+ } else if (opt?.prefix === 'host') {109+ cookie = await serializeSigned('__Host-' + name, value, secret, {110+ ...opt,111+ path: '/',112+ secure: true,113+ domain: undefined,114+ })115+ } else {61- const cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })116+ cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })117+ }118 c.header('set-cookie', cookie, { append: true })119 }120 121 export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {2 unmodified linesmodified:deno_dist/helper/dev/index.ts+2 added-10 removed
1 import type { Hono } from '../../hono.ts'2 import type { Env, RouterRoute } from '../../types.ts'3+import { getColorEnabled } from '../../utils/color.ts'4 import { findTargetHandler, isMiddleware } from '../../utils/handler.ts'5 6 interface ShowRoutesOptions {7 verbose?: boolean23 unmodified lines31 })32 }33 34 export const showRoutes = <E extends Env>(hono: Hono<E>, opts?: ShowRoutesOptions) => {34- // eslint-disable-next-line @typescript-eslint/no-explicit-any35- const { process, Deno } = globalThis as any36- const isNoColor =37- typeof process !== 'undefined'38- ? // eslint-disable-next-line no-unsafe-optional-chaining39- 'NO_COLOR' in process?.env40- : typeof Deno?.noColor === 'boolean'41- ? (Deno.noColor as boolean)42- : false43- const colorEnabled = opts?.colorize ?? !isNoColor35+ const colorEnabled = opts?.colorize ?? getColorEnabled()36 const routeData: Record<string, RouteData[]> = {}37 let maxMethodLength = 038 let maxPathLength = 039 35 unmodified linesmodified:deno_dist/helper/ssg/index.ts+2 added-294 removed
1-import { replaceUrlParam } from '../../client/utils.ts'2-import type { Context } from '../../context.ts'3-import type { Hono } from '../../hono.ts'4-import type { Env, MiddlewareHandler, Schema } from '../../types.ts'5-import { getExtension } from '../../utils/mime.ts'6-import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'7-8-const SSG_CONTEXT = 'HONO_SSG_CONTEXT'9-export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })10-11-/**12- * @experimental13- * `FileSystemModule` is an experimental feature.14- * The API might be changed.15- */16-export interface FileSystemModule {17- writeFile(path: string, data: string | Uint8Array): Promise<void>18- mkdir(path: string, options: { recursive: boolean }): Promise<void | string>19-}20-21-/**22- * @experimental23- * `ToSSGResult` is an experimental feature.24- * The API might be changed.25- */26-export interface ToSSGResult {27- success: boolean28- files: string[]29- error?: Error30-}31-32-const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {33- const extension = determineExtension(mimeType)34-35- if (routePath.endsWith(`.${extension}`)) {36- return joinPaths(outDir, routePath)37- }38-39- if (routePath === '/') {40- return joinPaths(outDir, `index.${extension}`)41- }42- if (routePath.endsWith('/')) {43- return joinPaths(outDir, routePath, `index.${extension}`)44- }45- return joinPaths(outDir, `${routePath}.${extension}`)46-}47-48-const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {49- const contentType = response.headers.get('Content-Type')50-51- try {52- if (contentType?.includes('text') || contentType?.includes('json')) {53- return await response.text()54- } else {55- return await response.arrayBuffer()56- }57- } catch (error) {58- throw new Error(59- `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`60- )61- }62-}63-64-const determineExtension = (mimeType: string): string => {65- switch (mimeType) {66- case 'text/html':67- return 'html'68- case 'text/xml':69- case 'application/xml':70- return 'xml'71- default: {72- return getExtension(mimeType) || 'html'73- }74- }75-}76-77-interface SSGParam {78- [key: string]: string79-}80-type SSGParams = SSGParam[]81-82-interface SSGParamsMiddleware {83- <E extends Env = Env>(84- generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>85- ): MiddlewareHandler<E>86- <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>87-}88-89-type AddedSSGDataRequest = Request & {90- ssgParams?: SSGParams91-}92-/**93- * Define SSG Route94- */95-export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {96- ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)97- await next()98-}99-100-export type BeforeRequestHook = (req: Request) => Request | false101-export type AfterResponseHook = (res: Response) => Response | false102-export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>103-104-export interface ToSSGOptions {105- dir?: string106- beforeRequestHook?: BeforeRequestHook107- afterResponseHook?: AfterResponseHook108- afterGenerateHook?: AfterGenerateHook109-}110-111-/**112- * @experimental113- * `fetchRoutesContent` is an experimental feature.114- * The API might be changed.115- */116-export const fetchRoutesContent = async <117- E extends Env = Env,118- S extends Schema = {},119- BasePath extends string = '/'120->(121- app: Hono<E, S, BasePath>,122- beforeRequestHook?: BeforeRequestHook,123- afterResponseHook?: AfterResponseHook124-): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {125- const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()126- const baseURL = 'http://localhost'127-128- for (const route of filterStaticGenerateRoutes(app)) {129- // GET Route Info130- const thisRouteBaseURL = new URL(route.path, baseURL).toString()131-132- let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest133- if (beforeRequestHook) {134- const maybeRequest = beforeRequestHook(forGetInfoURLRequest)135- if (!maybeRequest) {136- continue137- }138- forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest139- }140- await app.fetch(forGetInfoURLRequest)141-142- if (!forGetInfoURLRequest.ssgParams) {143- if (isDynamicRoute(route.path)) {144- continue145- }146- forGetInfoURLRequest.ssgParams = [{}]147- }148-149- const requestInit = {150- method: forGetInfoURLRequest.method,151- headers: forGetInfoURLRequest.headers,152- }153- for (const param of forGetInfoURLRequest.ssgParams) {154- const replacedUrlParam = replaceUrlParam(route.path, param)155- let response = await app.request(replacedUrlParam, requestInit, {156- [SSG_CONTEXT]: true,157- })158- if (response === SSG_DISABLED_RESPONSE) {159- continue160- }161- if (afterResponseHook) {162- const maybeResponse = afterResponseHook(response)163- if (!maybeResponse) {164- continue165- }166- response = maybeResponse167- }168- const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'169- const content = await parseResponseContent(response)170- htmlMap.set(replacedUrlParam, {171- mimeType,172- content,173- })174- }175- }176-177- return htmlMap178-}179-180-const isDynamicRoute = (path: string): boolean => {181- return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))182-}183-184-/**185- * @experimental186- * `saveContentToFiles` is an experimental feature.187- * The API might be changed.188- */189-export const saveContentToFiles = async (190- htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,191- fsModule: FileSystemModule,192- outDir: string193-): Promise<string[]> => {194- const files: string[] = []195-196- for (const [routePath, { content, mimeType }] of htmlMap) {197- const filePath = generateFilePath(routePath, outDir, mimeType)198- const dirPath = dirname(filePath)199-200- await fsModule.mkdir(dirPath, { recursive: true })201- if (typeof content === 'string') {202- await fsModule.writeFile(filePath, content)203- } else if (content instanceof ArrayBuffer) {204- await fsModule.writeFile(filePath, new Uint8Array(content))205- }206- files.push(filePath)207- }208-209- return files210-}211-212-/**213- * @experimental214- * `ToSSGInterface` is an experimental feature.215- * The API might be changed.216- */217-export interface ToSSGInterface {218- (219- // eslint-disable-next-line @typescript-eslint/no-explicit-any220- app: Hono<any, any, any>,221- fsModule: FileSystemModule,222- options?: ToSSGOptions223- ): Promise<ToSSGResult>224-}225-226-/**227- * @experimental228- * `ToSSGAdaptorInterface` is an experimental feature.229- * The API might be changed.230- */231-export interface ToSSGAdaptorInterface<232- E extends Env = Env,233- S extends Schema = {},234- BasePath extends string = '/'235-> {236- (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>237-}238-239-/**240- * @experimental241- * `toSSG` is an experimental feature.242- * The API might be changed.243- */244-export const toSSG: ToSSGInterface = async (app, fs, options) => {245- let result: ToSSGResult | undefined = undefined246- try {247- const outputDir = options?.dir ?? './static'248- const maps = await fetchRoutesContent(249- app,250- options?.beforeRequestHook,251- options?.afterResponseHook252- )253- const files = await saveContentToFiles(maps, fs, outputDir)254- result = { success: true, files }255- } catch (error) {256- const errorObj = error instanceof Error ? error : new Error(String(error))257- result = { success: false, files: [], error: errorObj }258- }259- await options?.afterGenerateHook?.(result)260- return result261-}262-263-/**264- * @experimental265- * `isSSGContext` is an experimental feature.266- * The API might be changed.267- */268-export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]269-270-/**271- * @experimental272- * `disableSSG` is an experimental feature.273- * The API might be changed.274- */275-export const disableSSG = (): MiddlewareHandler =>276- async function disableSSG(c, next) {277- if (isSSGContext(c)) {278- return SSG_DISABLED_RESPONSE279- }280- await next()281- }282-283-/**284- * @experimental285- * `onlySSG` is an experimental feature.286- * The API might be changed.287- */288-export const onlySSG = (): MiddlewareHandler =>289- async function onlySSG(c, next) {290- if (!isSSGContext(c)) {291- return c.notFound()292- }293- await next()294- }1+export * from './ssg.ts'2+export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware.ts'added:deno_dist/helper/ssg/middleware.ts+62 added
1+import type { Context } from '../../context.ts'2+import type { Env, MiddlewareHandler } from '../../types.ts'3+4+export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })6+7+interface SSGParam {8+ [key: string]: string9+}10+export type SSGParams = SSGParam[]11+12+interface SSGParamsMiddleware {13+ <E extends Env = Env>(14+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15+ ): MiddlewareHandler<E>16+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17+}18+19+export type AddedSSGDataRequest = Request & {20+ ssgParams?: SSGParams21+}22+23+/**24+ * Define SSG Route25+ */26+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28+ await next()29+}30+31+/**32+ * @experimental33+ * `isSSGContext` is an experimental feature.34+ * The API might be changed.35+ */36+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]37+38+/**39+ * @experimental40+ * `disableSSG` is an experimental feature.41+ * The API might be changed.42+ */43+export const disableSSG = (): MiddlewareHandler =>44+ async function disableSSG(c, next) {45+ if (isSSGContext(c)) {46+ return SSG_DISABLED_RESPONSE47+ }48+ await next()49+ }50+51+/**52+ * @experimental53+ * `onlySSG` is an experimental feature.54+ * The API might be changed.55+ */56+export const onlySSG = (): MiddlewareHandler =>57+ async function onlySSG(c, next) {58+ if (!isSSGContext(c)) {59+ return c.notFound()60+ }61+ await next()62+ }added:deno_dist/helper/ssg/ssg.ts+302 added
1+import { replaceUrlParam } from '../../client/utils.ts'2+import type { Hono } from '../../hono.ts'3+import type { Env, Schema } from '../../types.ts'4+import { createPool } from '../../utils/concurrent.ts'5+import { getExtension } from '../../utils/mime.ts'6+import type { AddedSSGDataRequest, SSGParams } from './middleware.ts'7+import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware.ts'8+import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'9+10+const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg11+12+/**13+ * @experimental14+ * `FileSystemModule` is an experimental feature.15+ * The API might be changed.16+ */17+export interface FileSystemModule {18+ writeFile(path: string, data: string | Uint8Array): Promise<void>19+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20+}21+22+/**23+ * @experimental24+ * `ToSSGResult` is an experimental feature.25+ * The API might be changed.26+ */27+export interface ToSSGResult {28+ success: boolean29+ files: string[]30+ error?: Error31+}32+33+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34+ const extension = determineExtension(mimeType)35+36+ if (routePath.endsWith(`.${extension}`)) {37+ return joinPaths(outDir, routePath)38+ }39+40+ if (routePath === '/') {41+ return joinPaths(outDir, `index.${extension}`)42+ }43+ if (routePath.endsWith('/')) {44+ return joinPaths(outDir, routePath, `index.${extension}`)45+ }46+ return joinPaths(outDir, `${routePath}.${extension}`)47+}48+49+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50+ const contentType = response.headers.get('Content-Type')51+52+ try {53+ if (contentType?.includes('text') || contentType?.includes('json')) {54+ return await response.text()55+ } else {56+ return await response.arrayBuffer()57+ }58+ } catch (error) {59+ throw new Error(60+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61+ )62+ }63+}64+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+ }75+ }76+}77+78+export type BeforeRequestHook = (req: Request) => Request | false79+export type AfterResponseHook = (res: Response) => Response | false80+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>81+82+export interface ToSSGOptions {83+ dir?: string84+ beforeRequestHook?: BeforeRequestHook85+ afterResponseHook?: AfterResponseHook86+ afterGenerateHook?: AfterGenerateHook87+ concurrency?: number88+}89+90+/**91+ * @experimental92+ * `fetchRoutesContent` is an experimental feature.93+ * The API might be changed.94+ */95+export const fetchRoutesContent = function* <96+ E extends Env = Env,97+ S extends Schema = {},98+ BasePath extends string = '/'99+>(100+ app: Hono<E, S, BasePath>,101+ beforeRequestHook?: BeforeRequestHook,102+ afterResponseHook?: AfterResponseHook,103+ concurrency?: number104+): Generator<105+ Promise<106+ | Generator<107+ Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108+ >109+ | undefined110+ >111+> {112+ const baseURL = 'http://localhost'113+ const pool = createPool({ concurrency })114+115+ for (const route of filterStaticGenerateRoutes(app)) {116+ // GET Route Info117+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()118+119+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120+ if (beforeRequestHook) {121+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122+ if (!maybeRequest) {123+ continue124+ }125+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126+ }127+128+ // eslint-disable-next-line no-async-promise-executor129+ yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130+ try {131+ await pool.run(() => app.fetch(forGetInfoURLRequest))132+133+ if (!forGetInfoURLRequest.ssgParams) {134+ if (isDynamicRoute(route.path)) {135+ resolveGetInfo(undefined)136+ return137+ }138+ forGetInfoURLRequest.ssgParams = [{}]139+ }140+141+ const requestInit = {142+ method: forGetInfoURLRequest.method,143+ headers: forGetInfoURLRequest.headers,144+ }145+146+ resolveGetInfo(147+ (function* () {148+ for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149+ // eslint-disable-next-line no-async-promise-executor150+ yield new Promise(async (resolveReq, rejectReq) => {151+ try {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await pool.run(() =>154+ app.request(replacedUrlParam, requestInit, {155+ [SSG_CONTEXT]: true,156+ })157+ )158+ if (response === SSG_DISABLED_RESPONSE) {159+ resolveReq(undefined)160+ return161+ }162+ if (afterResponseHook) {163+ const maybeResponse = afterResponseHook(response)164+ if (!maybeResponse) {165+ resolveReq(undefined)166+ return167+ }168+ response = maybeResponse169+ }170+ const mimeType =171+ response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172+ const content = await parseResponseContent(response)173+ resolveReq({174+ routePath: replacedUrlParam,175+ mimeType,176+ content,177+ })178+ } catch (error) {179+ rejectReq(error)180+ }181+ })182+ }183+ })()184+ )185+ } catch (error) {186+ rejectGetInfo(error)187+ }188+ })189+ }190+}191+192+const isDynamicRoute = (path: string): boolean => {193+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194+}195+196+/**197+ * @experimental198+ * `saveContentToFile` is an experimental feature.199+ * The API might be changed.200+ */201+const createdDirs: Set<string> = new Set()202+export const saveContentToFile = async (203+ data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204+ fsModule: FileSystemModule,205+ outDir: string206+): Promise<string | undefined> => {207+ const awaitedData = await data208+ if (!awaitedData) {209+ return210+ }211+ const { routePath, content, mimeType } = awaitedData212+ const filePath = generateFilePath(routePath, outDir, mimeType)213+ const dirPath = dirname(filePath)214+215+ if (!createdDirs.has(dirPath)) {216+ await fsModule.mkdir(dirPath, { recursive: true })217+ createdDirs.add(dirPath)218+ }219+ if (typeof content === 'string') {220+ await fsModule.writeFile(filePath, content)221+ } else if (content instanceof ArrayBuffer) {222+ await fsModule.writeFile(filePath, new Uint8Array(content))223+ }224+ return filePath225+}226+227+/**228+ * @experimental229+ * `ToSSGInterface` is an experimental feature.230+ * The API might be changed.231+ */232+export interface ToSSGInterface {233+ (234+ // eslint-disable-next-line @typescript-eslint/no-explicit-any235+ app: Hono<any, any, any>,236+ fsModule: FileSystemModule,237+ options?: ToSSGOptions238+ ): Promise<ToSSGResult>239+}240+241+/**242+ * @experimental243+ * `ToSSGAdaptorInterface` is an experimental feature.244+ * The API might be changed.245+ */246+export interface ToSSGAdaptorInterface<247+ E extends Env = Env,248+ S extends Schema = {},249+ BasePath extends string = '/'250+> {251+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252+}253+254+/**255+ * @experimental256+ * `toSSG` is an experimental feature.257+ * The API might be changed.258+ */259+export const toSSG: ToSSGInterface = async (app, fs, options) => {260+ let result: ToSSGResult | undefined = undefined261+ const getInfoPromises: Promise<unknown>[] = []262+ const savePromises: Promise<string | undefined>[] = []263+ try {264+ const outputDir = options?.dir ?? './static'265+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266+267+ const getInfoGen = fetchRoutesContent(268+ app,269+ options?.beforeRequestHook,270+ options?.afterResponseHook,271+ concurrency272+ )273+ for (const getInfo of getInfoGen) {274+ getInfoPromises.push(275+ getInfo.then((getContentGen) => {276+ if (!getContentGen) {277+ return278+ }279+ for (const content of getContentGen) {280+ savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281+ }282+ })283+ )284+ }285+ await Promise.all(getInfoPromises)286+ const files: string[] = []287+ for (const savePromise of savePromises) {288+ const fileOrError = await savePromise289+ if (typeof fileOrError === 'string') {290+ files.push(fileOrError)291+ } else if (fileOrError) {292+ throw fileOrError293+ }294+ }295+ result = { success: true, files }296+ } catch (error) {297+ const errorObj = error instanceof Error ? error : new Error(String(error))298+ result = { success: false, files: [], error: errorObj }299+ }300+ await options?.afterGenerateHook?.(result)301+ return result302+}added:deno_dist/helper/websocket/index.ts+55 added
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+import type { Context } from '../../context.ts'3+import type { MiddlewareHandler } from '../../types.ts'4+5+/**6+ * WebSocket Event Listeners type7+ */8+export interface WSEvents {9+ onOpen?: (evt: Event, ws: WSContext) => void10+ onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext) => void11+ onClose?: (evt: CloseEvent, ws: WSContext) => void12+ onError?: (evt: Event, ws: WSContext) => void13+}14+15+export type UpgradedWebSocketResponseInputJSONType = '__websocket' | undefined16+17+/**18+ * Upgrade WebSocket Type19+ */20+export type UpgradeWebSocket = (21+ createEvents: (c: Context) => WSEvents | Promise<WSEvents>22+) => MiddlewareHandler<23+ any,24+ string,25+ {26+ in: {27+ json: UpgradedWebSocketResponseInputJSONType28+ }29+ }30+>31+32+export type WSReadyState = 0 | 1 | 2 | 333+34+export type WSContext = {35+ send(36+ source: string | ArrayBuffer | Uint8Array,37+ options?: {38+ compress: boolean39+ }40+ ): void41+ raw?: unknown42+ binaryType: BinaryType43+ readyState: WSReadyState44+ url: URL | null45+ protocol: string | null46+ close(code?: number, reason?: string): void47+}48+49+export type WSMessageReceive = string | Blob | ArrayBufferLike50+51+export const createWSMessageEvent = (source: WSMessageReceive): MessageEvent<WSMessageReceive> => {52+ return new MessageEvent<WSMessageReceive>('message', {53+ data: source,54+ })55+}modified:deno_dist/jsx/dom/index.ts+79 added-9 removed
1+import type { Props, Child, JSXNode } from '../base.ts'2+import { memo, isValidElement } from '../base.ts'3+import { useContext } from '../context.ts'1-export {4+import {5 useState,6 useEffect,7 useRef,8 useCallback,4 unmodified lines13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17+ useReducer,18+ useDebugValue,19 } from '../hooks/index.ts'20+import { Suspense, ErrorBoundary } from './components.ts'21+import { createContext } from './context.ts'22+import { jsx } from './jsx-runtime.ts'23+24 export { render } from './render.ts'16-export { Suspense, ErrorBoundary } from './components.ts'17-export { useContext } from '../context.ts'18-export type { Context } from '../context.ts'19-export { createContext } from './context.ts'20-export { memo, isValidElement } from '../base.ts'25 22-import type { Props, Child, JSXNode } from '../base.ts'23-import { jsx } from './jsx-runtime.ts'24-export const cloneElement = <T extends JSXNode | JSX.Element>(26+const createElement = (27+ tag: string | ((props: Props) => JSXNode),28+ props: Props,29+ ...children: Child[]30+): JSXNode => {31+ const jsxProps: Props = { ...props, children }32+ let key = undefined33+ if ('key' in jsxProps) {34+ key = jsxProps.key35+ delete jsxProps.key36+ }37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any38+ return jsx(tag, jsxProps, key) as any39+}40+41+const cloneElement = <T extends JSXNode | JSX.Element>(42 element: T,43 props: Props,44 ...children: Child[]45 ): T => {6 unmodified lines52 },53 (element as JSXNode).key54 ) as T55 }56+57+export {58+ createElement as jsx,59+ useState,60+ useEffect,61+ useRef,62+ useCallback,63+ use,64+ startTransition,65+ useTransition,66+ useDeferredValue,67+ startViewTransition,68+ useViewTransition,69+ useMemo,70+ useLayoutEffect,71+ useReducer,72+ useDebugValue,73+ Suspense,74+ ErrorBoundary,75+ createContext,76+ useContext,77+ memo,78+ isValidElement,79+ createElement,80+ cloneElement,81+}82+83+export default {84+ useState,85+ useEffect,86+ useRef,87+ useCallback,88+ use,89+ startTransition,90+ useTransition,91+ useDeferredValue,92+ startViewTransition,93+ useViewTransition,94+ useMemo,95+ useLayoutEffect,96+ useReducer,97+ useDebugValue,98+ Suspense,99+ ErrorBoundary,100+ createContext,101+ useContext,102+ memo,103+ isValidElement,104+ createElement,105+ cloneElement,106+}107+108+export type { Context } from '../context.ts'modified:deno_dist/jsx/hooks/index.ts+18 added
203 unmodified lines204 },205 ])206 }207 208+export const useReducer = <T, A>(209+ reducer: (state: T, action: A) => T,210+ initialArg: T,211+ init?: (initialState: T) => T212+): [T, (action: A) => void] => {213+ const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))214+ return [215+ state,216+ (action: A) => {217+ setState((state) => reducer(state, action))218+ },219+ ]220+}221+222 const useEffectCommon = (223 index: number,224 effect: () => void | (() => void),225 deps?: readonly unknown[]121 unmodified lines347 memoArray[hookIndex] = [factory(), deps]348 }349 return memoArray[hookIndex][0] as T350 }351+352+// Define to avoid errors. This hook currently does nothing.353+// eslint-disable-next-line @typescript-eslint/no-unused-vars354+export const useDebugValue = (value: unknown, formatter?: (value: unknown) => string): void => {}modified:deno_dist/jsx/index.ts+60 added-5 removed
1-export { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2-export { ErrorBoundary } from './components.ts'3-export { Suspense } from './streaming.ts'4-export {1+import { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2+import { ErrorBoundary } from './components.ts'3+import { createContext, useContext } from './context.ts'4+import {5 useState,6 useEffect,7 useRef,8 useCallback,4 unmodified lines13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17+ useReducer,18+ useDebugValue,19 } from './hooks/index.ts'18-export { createContext, useContext } from './context.ts'20+import { Suspense } from './streaming.ts'21 22+export {23+ jsx,24+ memo,25+ Fragment,26+ isValidElement,27+ jsx as createElement,28+ cloneElement,29+ ErrorBoundary,30+ createContext,31+ useContext,32+ useState,33+ useEffect,34+ useRef,35+ useCallback,36+ useReducer,37+ useDebugValue,38+ use,39+ startTransition,40+ useTransition,41+ useDeferredValue,42+ startViewTransition,43+ useViewTransition,44+ useMemo,45+ useLayoutEffect,46+ Suspense,47+}48+49+export default {50+ memo,51+ Fragment,52+ isValidElement,53+ createElement: jsx,54+ cloneElement,55+ ErrorBoundary,56+ createContext,57+ useContext,58+ useState,59+ useEffect,60+ useRef,61+ useCallback,62+ useReducer,63+ useDebugValue,64+ use,65+ startTransition,66+ useTransition,67+ useDeferredValue,68+ startViewTransition,69+ useViewTransition,70+ useMemo,71+ useLayoutEffect,72+ Suspense,73+}74+75 // TODO: change to `export type *` after denoify bug is fixed76 // https://github.com/garronej/denoify/issues/12477 export * from './types.ts'added:deno_dist/middleware/body-limit/index.ts+96 added
1+import type { Context } from '../../context.ts'2+import { HTTPException } from '../../http-exception.ts'3+import type { MiddlewareHandler } from '../../types.ts'4+5+const ERROR_MESSAGE = 'Payload Too Large'6+7+type OnError = (c: Context) => Response | Promise<Response>8+type BodyLimitOptions = {9+ maxSize: number10+ onError?: OnError11+}12+13+class BodyLimitError extends Error {14+ constructor(message: string) {15+ super(message)16+ this.name = 'BodyLimitError'17+ }18+}19+20+/**21+ * Body Limit Middleware22+ *23+ * @example24+ * ```ts25+ * app.post(26+ * '/hello',27+ * bodyLimit({28+ * maxSize: 100 * 1024, // 100kb29+ * onError: (c) => {30+ * return c.text('overflow :(', 413)31+ * }32+ * }),33+ * (c) => {34+ * return c.text('pass :)')35+ * }36+ * )37+ * ```38+ */39+export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40+ const onError: OnError =41+ options.onError ||42+ (() => {43+ const res = new Response(ERROR_MESSAGE, {44+ status: 413,45+ })46+ throw new HTTPException(413, { res })47+ })48+ const maxSize = options.maxSize49+50+ return async function bodyLimit(c, next) {51+ if (!c.req.raw.body) {52+ // maybe GET or HEAD request53+ return next()54+ }55+56+ if (c.req.raw.headers.has('content-length')) {57+ // we can trust content-length header because it's already validated by server58+ const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59+ return contentLength > maxSize ? onError(c) : next()60+ }61+62+ // maybe chunked transfer encoding63+64+ let size = 065+ const rawReader = c.req.raw.body.getReader()66+ const reader = new ReadableStream({67+ async start(controller) {68+ try {69+ for (;;) {70+ const { done, value } = await rawReader.read()71+ if (done) {72+ break73+ }74+ size += value.length75+ if (size > maxSize) {76+ controller.error(new BodyLimitError(ERROR_MESSAGE))77+ break78+ }79+80+ controller.enqueue(value)81+ }82+ } finally {83+ controller.close()84+ }85+ },86+ })87+88+ c.req.raw = new Request(c.req.raw, { body: reader })89+90+ await next()91+92+ if (c.error instanceof BodyLimitError) {93+ c.res = await onError(c)94+ }95+ }96+}modified:deno_dist/middleware/logger/index.ts+9 added-7 removed
1 import type { MiddlewareHandler } from '../../types.ts'2+import { getColorEnabled } from '../../utils/color.ts'3 import { getPath } from '../../utils/url.ts'4 5 enum LogPrefix {6 Outgoing = '-->',14 unmodified lines21 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])22 }23 24 const colorStatus = (status: number) => {25+ const colorEnabled = getColorEnabled()26 const out: { [key: string]: string } = {25- 7: `\x1b[35m${status}\x1b[0m`,26- 5: `\x1b[31m${status}\x1b[0m`,27- 4: `\x1b[33m${status}\x1b[0m`,28- 3: `\x1b[36m${status}\x1b[0m`,29- 2: `\x1b[32m${status}\x1b[0m`,30- 1: `\x1b[32m${status}\x1b[0m`,31- 0: `\x1b[33m${status}\x1b[0m`,27+ 7: colorEnabled ? `\x1b[35m${status}\x1b[0m` : `${status}`,28+ 5: colorEnabled ? `\x1b[31m${status}\x1b[0m` : `${status}`,29+ 4: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,30+ 3: colorEnabled ? `\x1b[36m${status}\x1b[0m` : `${status}`,31+ 2: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,32+ 1: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,33+ 0: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,34 }35 36 const calculateStatus = (status / 100) | 037 35 unmodified linesadded:deno_dist/utils/color.ts+12 added
1+export function getColorEnabled() {2+ // eslint-disable-next-line @typescript-eslint/no-explicit-any3+ const { process, Deno } = globalThis as any4+ const isNoColor =5+ typeof process !== 'undefined'6+ ? // eslint-disable-next-line no-unsafe-optional-chaining7+ 'NO_COLOR' in process?.env8+ : typeof Deno?.noColor === 'boolean'9+ ? (Deno.noColor as boolean)10+ : false11+ return !isNoColor12+}added:deno_dist/utils/concurrent.ts+50 added
1+const DEFAULT_CONCURRENCY = 10242+3+export interface Pool {4+ run<T>(fn: () => T): Promise<T>5+}6+7+export const createPool = ({8+ concurrency,9+ interval,10+}: {11+ concurrency?: number12+ interval?: number13+} = {}): Pool => {14+ concurrency ||= DEFAULT_CONCURRENCY15+16+ if (concurrency === Infinity) {17+ // unlimited18+ return {19+ run: async (fn) => fn(),20+ }21+ }22+23+ const pool: Set<{}> = new Set()24+ const run = async <T>(25+ fn: () => T,26+ promise?: Promise<T>,27+ resolve?: (result: T) => void28+ ): Promise<T> => {29+ if (pool.size >= (concurrency as number)) {30+ promise ||= new Promise<T>((r) => (resolve = r))31+ setTimeout(() => run(fn, promise, resolve))32+ return promise33+ }34+ const marker = {}35+ pool.add(marker)36+ const result = await fn()37+ if (interval) {38+ setTimeout(() => pool.delete(marker), interval)39+ } else {40+ pool.delete(marker)41+ }42+ if (resolve) {43+ resolve(result)44+ return promise as Promise<T>45+ } else {46+ return result47+ }48+ }49+ return { run }50+}modified:deno_dist/utils/cookie.ts+44 added-1 removed
10 unmodified lines11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15+ prefix?: CookiePrefixOptions16 }17+export type CookiePrefixOptions = 'host' | 'secure'18 19 const algorithm = { name: 'HMAC', hash: 'SHA-256' }20 21 const getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {91 unmodified lines113 114 const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {115 let cookie = `${name}=${value}`116 117+ if (name.startsWith('__Secure-') && !opt.secure) {118+ // FIXME: replace link to RFC119+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1120+ throw new Error('__Secure- Cookie must have Secure attributes')121+ }122+123+ if (name.startsWith('__Host-')) {124+ // FIXME: replace link to RFC125+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2126+ if (!opt.secure) {127+ throw new Error('__Host- Cookie must have Secure attributes')128+ }129+130+ if (opt.path !== '/') {131+ throw new Error('__Host- Cookie must have Path attributes with "/"')132+ }133+134+ if (opt.domain) {135+ throw new Error('__Host- Cookie must not have Domain attributes')136+ }137+ }138+139 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {140+ if (opt.maxAge > 34560000) {141+ // FIXME: replace link to RFC142+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2143+ throw new Error(144+ 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'145+ )146+ }147 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`148 }149 119- if (opt.domain) {150+ if (opt.domain && opt.prefix !== 'host') {151 cookie += `; Domain=${opt.domain}`152 }153 154 if (opt.path) {155 cookie += `; Path=${opt.path}`156 }157 158 if (opt.expires) {159+ if (opt.expires.getTime() - Date.now() > 34560000_000) {160+ // FIXME: replace link to RFC161+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1162+ throw new Error(163+ 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'164+ )165+ }166 cookie += `; Expires=${opt.expires.toUTCString()}`167 }168 169 if (opt.httpOnly) {8 unmodified lines178 cookie += `; SameSite=${opt.sameSite}`179 }180 181 if (opt.partitioned) {182+ // FIXME: replace link to RFC183+ // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3184+ if (!opt.secure) {185+ throw new Error('Partitioned Cookie must have Secure attributes')186+ }187 cookie += '; Partitioned'188 }189 190 return cookie18 unmodified linesmodified:deno_dist/helper.ts+1 added
7 unmodified lines8 export * from './helper/streaming/index.ts'9 export * from './helper/testing/index.ts'10 export * from './helper/dev/index.ts'11 export * from './adapter/deno/ssg.ts'12+export * from './adapter/deno/websocket.ts'modified:deno_dist/http-exception.ts+4 added-1 removed
1 unmodified line2 3 type HTTPExceptionOptions = {4 res?: Response5 message?: string6+ cause?: unknown7 }8 9 /**10 * `HTTPException` must be used when a fatal error such as authentication failure occurs.15 unmodified lines26 */27 export class HTTPException extends Error {28 readonly res?: Response29 readonly status: StatusCode30+31 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {30- super(options?.message)32+ super(options?.message, { cause: options?.cause })33 this.res = options?.res34 this.status = status35 }36+37 getResponse(): Response {38 if (this.res) {39 return this.res40 }5 unmodified linesmodified:deno_dist/middleware.ts+1 added
1 // This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth/index.ts'3 export * from './middleware/bearer-auth/index.ts'4+export * from './middleware/body-limit/index.ts'5 export * from './middleware/cache/index.ts'6 export * from './middleware/compress/index.ts'7 export * from './middleware/cors/index.ts'8 export * from './middleware/csrf/index.ts'10 unmodified linesmodified:runtime_tests/bun/index.test.tsx+38 added
1 import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'2 import { serveStatic, toSSG } from '../../src/adapter/bun'3+import { createBunWebSocket, type BunWebSocketData } from '../../src/adapter/bun/websocket'4 import { Context } from '../../src/context'5 import { env, getRuntimeKey } from '../../src/helper/adapter'6+import type { WSMessageReceive } from '../../src/helper/websocket'7 import { Hono } from '../../src/index'8 // eslint-disable-next-line @typescript-eslint/no-unused-vars9 import { jsx } from '../../src/jsx'10 import { basicAuth } from '../../src/middleware/basic-auth'248 unmodified lines259 })260 })261 })262 263+describe('WebSockets Helper', () => {264+ const app = new Hono()265+ const { websocket, upgradeWebSocket } = createBunWebSocket()266+267+ it('Should websockets is working', async () => {268+ const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>269+ app.get(270+ '/ws',271+ upgradeWebSocket(() => ({272+ onMessage(evt) {273+ resolve(evt.data)274+ },275+ }))276+ )277+ )278+ const upgradedData = await new Promise<BunWebSocketData>((resolve) =>279+ app.fetch(new Request('http://localhost/ws'), {280+ upgrade: (_req: Request, data: { data: BunWebSocketData }) => {281+ resolve(data.data)282+ },283+ })284+ )285+ const message = Math.random().toString()286+ websocket.message(287+ {288+ close: () => undefined,289+ readyState: 3,290+ data: upgradedData,291+ send: () => undefined,292+ },293+ message294+ )295+ const receivedMessage = await receivedMessagePromise296+ expect(receivedMessage).toBe(message)297+ })298+})299 const fs = require('fs').promises300 const path = require('path')301 302 async function deleteDirectory(dirPath) {15 unmodified linesmodified:src/adapter/bun/index.ts+1 added
1 // @denoify-ignore2 export { serveStatic } from './serve-static'3 export { bunFileSystemModule, toSSG } from './ssg'4+export { createBunWebSocket } from './websocket'added:src/adapter/bun/websocket.ts+115 added
1+// @denoify-ignore2+import {3+ createWSMessageEvent,4+ type UpgradeWebSocket,5+ type WSContext,6+ type WSEvents,7+ type WSMessageReceive,8+} from '../../helper/websocket'9+10+interface BunServerWebSocket<T> {11+ send(data: string | ArrayBufferLike, compress?: boolean): void12+ close(code?: number, reason?: string): void13+ data: T14+ readyState: 0 | 1 | 2 | 315+}16+interface BunServer {17+ upgrade<T>(18+ req: Request,19+ options?: {20+ data: T21+ }22+ ): boolean23+}24+interface BunWebSocketHandler<T> {25+ open(ws: BunServerWebSocket<T>): void26+ close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void27+ message(ws: BunServerWebSocket<T>, message: string | Buffer): void28+}29+interface CreateWebSocket {30+ (): {31+ upgradeWebSocket: UpgradeWebSocket32+ websocket: BunWebSocketHandler<BunWebSocketData>33+ }34+}35+export interface BunWebSocketData {36+ connId: number37+ url: URL38+ protocol: string39+}40+41+const createWSContext = (ws: BunServerWebSocket<BunWebSocketData>): WSContext => {42+ return {43+ send: (source, options) => {44+ const sendingData =45+ typeof source === 'string' ? source : source instanceof Uint8Array ? source.buffer : source46+ ws.send(sendingData, options?.compress)47+ },48+ raw: ws,49+ binaryType: 'arraybuffer',50+ readyState: ws.readyState,51+ url: ws.data.url,52+ protocol: ws.data.protocol,53+ close(code, reason) {54+ ws.close(code, reason)55+ },56+ }57+}58+59+export const createBunWebSocket: CreateWebSocket = () => {60+ const websocketConns: WSEvents[] = []61+62+ const upgradeWebSocket: UpgradeWebSocket = (createEvents) => {63+ return async (c, next) => {64+ const server = c.env as BunServer65+ const connId = websocketConns.push(await createEvents(c)) - 166+ const upgradeResult = server.upgrade<BunWebSocketData>(c.req.raw, {67+ data: {68+ connId,69+ url: new URL(c.req.url),70+ protocol: c.req.url,71+ },72+ })73+ if (upgradeResult) {74+ return new Response(null)75+ }76+ await next() // Failed77+ }78+ }79+ const websocket: BunWebSocketHandler<BunWebSocketData> = {80+ open(ws) {81+ const websocketListeners = websocketConns[ws.data.connId]82+ if (websocketListeners.onOpen) {83+ websocketListeners.onOpen(new Event('open'), createWSContext(ws))84+ }85+ },86+ close(ws, code, reason) {87+ const websocketListeners = websocketConns[ws.data.connId]88+ if (websocketListeners.onClose) {89+ websocketListeners.onClose(90+ new CloseEvent('close', {91+ code,92+ reason,93+ }),94+ createWSContext(ws)95+ )96+ }97+ },98+ message(ws, message) {99+ const websocketListeners = websocketConns[ws.data.connId]100+ if (websocketListeners.onMessage) {101+ const normalizedReceiveData =102+ typeof message === 'string' ? message : (message.buffer satisfies WSMessageReceive)103+104+ websocketListeners.onMessage(105+ createWSMessageEvent(normalizedReceiveData),106+ createWSContext(ws)107+ )108+ }109+ },110+ }111+ return {112+ upgradeWebSocket,113+ websocket,114+ }115+}modified:src/adapter/cloudflare-workers/index.ts+1 added
1 // @denoify-ignore2 export { serveStatic } from './serve-static-module'3+export { upgradeWebSocket } from './websocket'added:src/adapter/cloudflare-workers/websocket.test.ts+45 added
1+import { Hono } from '../..'2+import { upgradeWebSocket } from '.'3+4+describe('upgradeWebSocket middleware', () => {5+ const server = new EventTarget()6+7+ // @ts-expect-error Cloudflare API8+ globalThis.WebSocketPair = class {9+ 0: WebSocket // client10+ 1: WebSocket // server11+ constructor() {12+ this[0] = {} as WebSocket13+ this[1] = server as WebSocket14+ }15+ }16+17+ const app = new Hono()18+19+ const wsPromise = new Promise((resolve) =>20+ app.get(21+ '/ws',22+ upgradeWebSocket(() => ({23+ onMessage(evt, ws) {24+ console.log('evt')25+ resolve(evt.data)26+ },27+ }))28+ )29+ )30+ it('Should receive message is valid', async () => {31+ const sendingData = Math.random().toString()32+ await app.request('/ws', {33+ headers: {34+ Upgrade: 'websocket',35+ },36+ })37+ server.dispatchEvent(38+ new MessageEvent('message', {39+ data: sendingData,40+ })41+ )42+43+ expect(sendingData).toBe(await wsPromise)44+ })45+})added:src/adapter/cloudflare-workers/websocket.ts+68 added
1+// @denoify-ignore2+/* eslint-disable @typescript-eslint/ban-ts-comment */3+import type { WebSocketPair } from '@cloudflare/workers-types'4+import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'5+6+// Based on https://github.com/honojs/hono/issues/1153#issuecomment-17673213327+export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {8+ const CFWebSocketPair = (9+ globalThis as unknown as {10+ WebSocketPair: typeof WebSocketPair11+ }12+ ).WebSocketPair13+14+ const events = await createEvents(c)15+16+ const upgradeHeader = c.req.header('Upgrade')17+ if (upgradeHeader !== 'websocket') {18+ return await next()19+ }20+21+ const webSocketPair = new CFWebSocketPair()22+ const client = webSocketPair[0]23+ const server = webSocketPair[1]24+25+ const wsContext: WSContext = {26+ binaryType: 'arraybuffer',27+ close: (code, reason) => server.close(code, reason),28+ get protocol() {29+ return server.protocol30+ },31+ raw: server,32+ get readyState() {33+ return server.readyState as WSReadyState34+ },35+ url: server.url ? new URL(server.url) : null,36+ send: (source) => server.send(source),37+ }38+ if (events.onOpen) {39+ server.addEventListener(40+ 'open',41+ (evt) => events.onOpen && events.onOpen(evt as Event, wsContext)42+ )43+ }44+ if (events.onClose) {45+ server.addEventListener(46+ 'close',47+ (evt) => events.onClose && events.onClose(evt as CloseEvent, wsContext)48+ )49+ }50+ if (events.onMessage) {51+ server.addEventListener(52+ 'message',53+ (evt) => events.onMessage && events.onMessage(evt as MessageEvent, wsContext)54+ )55+ }56+ if (events.onError) {57+ server.addEventListener(58+ 'error',59+ (evt) => events.onError && events.onError(evt as ErrorEvent as Event, wsContext)60+ )61+ }62+ server.accept()63+ return new Response(null, {64+ status: 101,65+ // @ts-expect-error Cloudflare Workers API66+ webSocket: client,67+ })68+}modified:src/adapter/deno/deno.d.ts+5 added
14 unmodified lines15 * @param data The data to write to the file.16 * @returns A promise that resolves when the file is written.17 */18 export function writeFile(path: string, data: Uint8Array): Promise<void>19+20+ export function upgradeWebSocket(req: Request): {21+ response: Response22+ socket: WebSocket23+ }24 }modified:src/adapter/deno/index.ts+1 added
1 export { serveStatic } from './serve-static'2 export { toSSG, denoFileSystemModule } from './ssg'3+export { upgradeWebSocket } from './websocket'added:src/adapter/deno/websocket.test.ts+42 added
1+import { Hono } from '../..'2+import { upgradeWebSocket } from './websocket'3+4+globalThis.Deno = {} as typeof Deno5+6+describe('WebSockets', () => {7+ let app: Hono8+ beforeEach(() => {9+ app = new Hono()10+ })11+12+ it('Should receive data is valid', async () => {13+ const messagePromise = new Promise((resolve) =>14+ app.get(15+ '/ws',16+ upgradeWebSocket(() => ({17+ onMessage: (evt) => resolve(evt.data),18+ }))19+ )20+ )21+ const socket = new EventTarget() as WebSocket22+ Deno.upgradeWebSocket = () => {23+ return {24+ response: new Response(),25+ socket,26+ }27+ }28+ await app.request('/ws', {29+ headers: {30+ upgrade: 'websocket',31+ },32+ })33+ const data = Math.random().toString()34+ socket.onmessage &&35+ socket.onmessage(36+ new MessageEvent('message', {37+ data,38+ })39+ )40+ expect(await messagePromise).toBe(data)41+ })42+})added:src/adapter/deno/websocket.ts+30 added
1+import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'2+3+export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {4+ if (c.req.header('upgrade') !== 'websocket') {5+ return await next()6+ }7+ const { response, socket } = Deno.upgradeWebSocket(c.req.raw)8+9+ const events = await createEvents(c)10+11+ const wsContext: WSContext = {12+ binaryType: 'arraybuffer',13+ close: (code, reason) => socket.close(code, reason),14+ get protocol() {15+ return socket.protocol16+ },17+ raw: socket,18+ get readyState() {19+ return socket.readyState as WSReadyState20+ },21+ url: socket.url ? new URL(socket.url) : null,22+ send: (source) => socket.send(source),23+ }24+ socket.onopen = (evt) => events.onOpen && events.onOpen(evt, wsContext)25+ socket.onmessage = (evt) => events.onMessage && events.onMessage(evt, wsContext)26+ socket.onclose = (evt) => events.onClose && events.onClose(evt, wsContext)27+ socket.onerror = (evt) => events.onError && events.onError(evt, wsContext)28+29+ return response30+}modified:src/client/client.ts+5 added
140 unmodified lines141 return new URL(replaceUrlParam(url, opts.args[0].param))142 }143 return new URL(url)144 }145+ if (method === 'ws') {146+ const targetUrl =147+ opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url148+ return new WebSocket(targetUrl)149+ }150 151 const req = new ClientRequestImpl(url, method)152 if (method) {153 options ??= {}5 unmodified linesmodified:src/client/types.ts+8 added
1+import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket'2 import type { Hono } from '../hono'3 import type { Schema } from '../types'4 import type { HasRequiredKeys } from '../utils/types'5 24 unmodified lines30 ? { param: P }31 : {}32 : {}33 ) => URL34+} & {35+ // WebSocket36+ $ws: S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }37+ ? S['$get'] extends { input: infer I }38+ ? (args?: Omit<I, 'json'>) => WebSocket39+ : never40+ : never41 }42 43 // eslint-disable-next-line @typescript-eslint/no-explicit-any44 type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never84 unmodified linesmodified:src/helper/cookie/index.test.ts+117 added
193 unmodified lines194 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D; Path=/a'195 )196 })197 198+ app.get('/get-secure-prefix-cookie', async (c) => {199+ const cookie = getCookie(c, 'delicious_cookie', 'secure')200+ if (cookie) {201+ return c.text(cookie)202+ } else {203+ return c.notFound()204+ }205+ })206+207+ app.get('/get-host-prefix-cookie', async (c) => {208+ const cookie = getCookie(c, 'delicious_cookie', 'host')209+ if (cookie) {210+ return c.text(cookie)211+ } else {212+ return c.notFound()213+ }214+ })215+216+ app.get('/set-secure-prefix-cookie', (c) => {217+ setCookie(c, 'delicious_cookie', 'macha', {218+ prefix: 'secure',219+ secure: false, // this will be ignore220+ })221+ return c.text('Set secure prefix cookie')222+ })223+224+ it('Set cookie with secure prefix', async () => {225+ const res = await app.request('http://localhost/set-secure-prefix-cookie')226+ expect(res.status).toBe(200)227+ const header = res.headers.get('Set-Cookie')228+ expect(header).toBe('__Secure-delicious_cookie=macha; Path=/; Secure')229+ })230+231+ it('Get cookie with secure prefix', async () => {232+ const setCookie = await app.request('http://localhost/set-secure-prefix-cookie')233+ const header = setCookie.headers.get('Set-Cookie')234+ if (!header) {235+ assert.fail('invalid header')236+ }237+ const res = await app.request('http://localhost/get-secure-prefix-cookie', {238+ headers: {239+ Cookie: header,240+ },241+ })242+ const response = await res.text()243+ expect(res.status).toBe(200)244+ expect(response).toBe('macha')245+ })246+247+ app.get('/set-host-prefix-cookie', (c) => {248+ setCookie(c, 'delicious_cookie', 'macha', {249+ prefix: 'host',250+ path: '/foo', // this will be ignored251+ domain: 'example.com', // this will be ignored252+ secure: false, // this will be ignored253+ })254+ return c.text('Set host prefix cookie')255+ })256+257+ it('Set cookie with host prefix', async () => {258+ const res = await app.request('http://localhost/set-host-prefix-cookie')259+ expect(res.status).toBe(200)260+ const header = res.headers.get('Set-Cookie')261+ expect(header).toBe('__Host-delicious_cookie=macha; Path=/; Secure')262+ })263+264+ it('Get cookie with host prefix', async () => {265+ const setCookie = await app.request('http://localhost/set-host-prefix-cookie')266+ const header = setCookie.headers.get('Set-Cookie')267+ if (!header) {268+ assert.fail('invalid header')269+ }270+ const res = await app.request('http://localhost/get-host-prefix-cookie', {271+ headers: {272+ Cookie: header,273+ },274+ })275+ const response = await res.text()276+ expect(res.status).toBe(200)277+ expect(response).toBe('macha')278+ })279+280+ app.get('/set-signed-secure-prefix-cookie', async (c) => {281+ await setSignedCookie(c, 'delicious_cookie', 'macha', 'secret choco chips', {282+ prefix: 'secure',283+ })284+ return c.text('Set secure prefix cookie')285+ })286+287+ it('Set signed cookie with secure prefix', async () => {288+ const res = await app.request('http://localhost/set-signed-secure-prefix-cookie')289+ expect(res.status).toBe(200)290+ const header = res.headers.get('Set-Cookie')291+ expect(header).toBe(292+ '__Secure-delicious_cookie=macha.i225faTyCrJUY8TvpTuJHI20HBWbQ89B4GV7lT4E%2FB0%3D; Path=/; Secure'293+ )294+ })295+296+ app.get('/set-signed-host-prefix-cookie', async (c) => {297+ await setSignedCookie(c, 'delicious_cookie', 'macha', 'secret choco chips', {298+ prefix: 'host',299+ domain: 'example.com', // this will be ignored300+ path: 'example.com', // thi will be ignored301+ secure: false, // this will be ignored302+ })303+ return c.text('Set host prefix cookie')304+ })305+306+ it('Set signed cookie with host prefix', async () => {307+ const res = await app.request('http://localhost/set-signed-host-prefix-cookie')308+ expect(res.status).toBe(200)309+ const header = res.headers.get('Set-Cookie')310+ expect(header).toBe(311+ '__Host-delicious_cookie=macha.i225faTyCrJUY8TvpTuJHI20HBWbQ89B4GV7lT4E%2FB0%3D; Path=/; Secure'312+ )313+ })314+315 app.get('/set-cookie-complex', (c) => {316 setCookie(c, 'great_cookie', 'banana', {317 path: '/',318 secure: true,102 unmodified linesmodified:src/helper/cookie/index.ts+65 added-9 removed
1 import type { Context } from '../../context'2 import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3-import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'3+import type { CookieOptions, Cookie, SignedCookie, CookiePrefixOptions } from '../../utils/cookie'4 5 interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8+ (c: Context, key: string, prefixOptions: CookiePrefixOptions): string | undefined9 }10 11 interface GetSignedCookie {12 (c: Context, secret: string | BufferSource, key: string): Promise<string | undefined | false>13 (c: Context, secret: string): Promise<SignedCookie>14+ (15+ c: Context,16+ secret: string | BufferSource,17+ key: string,18+ prefixOptions: CookiePrefixOptions19+ ): Promise<string | undefined | false>20 }21 15-export const getCookie: GetCookie = (c, key?) => {22+export const getCookie: GetCookie = (c, key?, prefix?: CookiePrefixOptions) => {23 const cookie = c.req.raw.headers.get('Cookie')24 if (typeof key === 'string') {25 if (!cookie) {26 return undefined27 }28+ let finalKey = key29+ if (prefix === 'secure') {30+ finalKey = '__Secure-' + key31+ } else if (prefix === 'host') {32+ finalKey = '__Host-' + key33+ }21- const obj = parse(cookie, key)22- return obj[key]34+ const obj = parse(cookie, finalKey)35+ return obj[finalKey]36 }37 if (!cookie) {38 return {}39 }1 unmodified line41 // eslint-disable-next-line @typescript-eslint/no-explicit-any42 return obj as any43 }44 32-export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {45+export const getSignedCookie: GetSignedCookie = async (46+ c,47+ secret,48+ key?,49+ prefix?: CookiePrefixOptions50+) => {51 const cookie = c.req.raw.headers.get('Cookie')52 if (typeof key === 'string') {53 if (!cookie) {54 return undefined55 }56+ let finalKey = key57+ if (prefix === 'secure') {58+ finalKey = '__Secure-' + key59+ } else if (prefix === 'host') {60+ finalKey = '__Host-' + key61+ }38- const obj = await parseSigned(cookie, secret, key)39- return obj[key]62+ const obj = await parseSigned(cookie, secret, finalKey)63+ return obj[finalKey]64 }65 if (!cookie) {66 return {}67 }2 unmodified lines70 return obj as any71 }72 73 export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {74+ // Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.75+ // Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)76+ // and must not have a Domain attribute.77+ // Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'78+ let cookie79+ if (opt?.prefix === 'secure') {80+ cookie = serialize('__Secure-' + name, value, { path: '/', ...opt, secure: true })81+ } else if (opt?.prefix === 'host') {82+ cookie = serialize('__Host-' + name, value, {83+ ...opt,84+ path: '/',85+ secure: true,86+ domain: undefined,87+ })88+ } else {50- const cookie = serialize(name, value, { path: '/', ...opt })89+ cookie = serialize(name, value, { path: '/', ...opt })90+ }91 c.header('set-cookie', cookie, { append: true })92 }93 94 export const setSignedCookie = async (2 unmodified lines97 value: string,98 secret: string | BufferSource,99 opt?: CookieOptions100 ): Promise<void> => {101+ let cookie102+ if (opt?.prefix === 'secure') {103+ cookie = await serializeSigned('__Secure-' + name, value, secret, {104+ path: '/',105+ ...opt,106+ secure: true,107+ })108+ } else if (opt?.prefix === 'host') {109+ cookie = await serializeSigned('__Host-' + name, value, secret, {110+ ...opt,111+ path: '/',112+ secure: true,113+ domain: undefined,114+ })115+ } else {61- const cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })116+ cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })117+ }118 c.header('set-cookie', cookie, { append: true })119 }120 121 export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {2 unmodified linesmodified:src/helper/dev/index.ts+2 added-10 removed
1 import type { Hono } from '../../hono'2 import type { Env, RouterRoute } from '../../types'3+import { getColorEnabled } from '../../utils/color'4 import { findTargetHandler, isMiddleware } from '../../utils/handler'5 6 interface ShowRoutesOptions {7 verbose?: boolean23 unmodified lines31 })32 }33 34 export const showRoutes = <E extends Env>(hono: Hono<E>, opts?: ShowRoutesOptions) => {34- // eslint-disable-next-line @typescript-eslint/no-explicit-any35- const { process, Deno } = globalThis as any36- const isNoColor =37- typeof process !== 'undefined'38- ? // eslint-disable-next-line no-unsafe-optional-chaining39- 'NO_COLOR' in process?.env40- : typeof Deno?.noColor === 'boolean'41- ? (Deno.noColor as boolean)42- : false43- const colorEnabled = opts?.colorize ?? !isNoColor35+ const colorEnabled = opts?.colorize ?? getColorEnabled()36 const routeData: Record<string, RouteData[]> = {}37 let maxMethodLength = 038 let maxPathLength = 039 35 unmodified linesdeleted:src/helper/ssg/index.test.tsx-470 removed
1-import { beforeEach, describe, expect, it } from 'vitest'2-import { Hono } from '../../hono'3-// eslint-disable-next-line @typescript-eslint/no-unused-vars4-import { jsx } from '../../jsx'5-import { poweredBy } from '../../middleware/powered-by'6-import {7- SSG_DISABLED_RESPONSE,8- fetchRoutesContent,9- saveContentToFiles,10- ssgParams,11- toSSG,12- isSSGContext,13- disableSSG,14- onlySSG,15-} from './index'16-import type {17- BeforeRequestHook,18- AfterResponseHook,19- AfterGenerateHook,20- FileSystemModule,21-} from './index'22-23-describe('toSSG function', () => {24- let app: Hono25-26- const postParams = [{ post: '1' }, { post: '2' }]27-28- beforeEach(() => {29- app = new Hono()30- app.all('/', (c) => c.html('Hello, World!'))31- app.get('/about', (c) => c.html('About Page'))32- app.get('/about/some', (c) => c.text('About Page 2tier'))33- app.post('/about/some/thing', (c) => c.text('About Page 3tier'))34- app.get('/bravo', (c) => c.html('Bravo Page'))35- app.get('/Charlie', async (c, next) => {36- c.setRenderer((content, head) => {37- return c.html(38- <html>39- <head>40- <title>{head.title || ''}</title>41- </head>42- <body>43- <p>{content}</p>44- </body>45- </html>46- )47- })48- await next()49- })50- app.get('/Charlie', (c) => {51- return c.render('Hello!', { title: 'Charlies Page' })52- })53-54- // Included params55- app.get(56- '/post/:post',57- ssgParams(() => postParams),58- (c) => c.html(<h1>{c.req.param('post')}</h1>)59- )60-61- app.get(62- '/user/:user_id',63- ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),64- (c) => c.html(<h1>{c.req.param('user_id')}</h1>)65- )66-67- type Env = {68- Bindings: {69- FOO_DB: string70- }71- Variables: {72- FOO_VAR: string73- }74- }75-76- app.get(77- '/env-type-check',78- ssgParams<Env>((c) => {79- expectTypeOf<typeof c.env.FOO_DB>().toBeString()80- expectTypeOf<typeof c.var.FOO_VAR>().toBeString()81- return []82- })83- )84- })85- it('Should correctly generate static HTML files for Hono routes', async () => {86- const fsMock: FileSystemModule = {87- writeFile: vi.fn(() => Promise.resolve()),88- mkdir: vi.fn(() => Promise.resolve()),89- }90-91- const htmlMap = await fetchRoutesContent(app)92-93- for (const postParam of postParams) {94- const html = htmlMap.get(`/post/${postParam.post}`)95- expect(html?.content).toBe(`<h1>${postParam.post}</h1>`)96- }97-98- for (let i = 1; i <= 3; i++) {99- const html = htmlMap.get(`/user/${i}`)100- expect(html?.content).toBe(`<h1>${i}</h1>`)101- }102-103- const files = await saveContentToFiles(htmlMap, fsMock, './static')104-105- expect(files.length).toBeGreaterThan(0)106- expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {107- recursive: true,108- })109- expect(fsMock.writeFile).toHaveBeenCalled()110- })111-112- it('Should handle file system errors correctly in saveContentToFiles', async () => {113- const fsMock: FileSystemModule = {114- writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),115- mkdir: vi.fn(() => Promise.resolve()),116- }117-118- try {119- const htmlMap = await fetchRoutesContent(app)120- await saveContentToFiles(htmlMap, fsMock, './static')121- expect(true).toBe(false) // This should not be reached122- } catch (error) {123- if (error instanceof Error) {124- expect(error.message).toBe('Write error')125- } else {126- throw error127- }128- }129- })130-131- it('Should handle overall process errors correctly in toSSG', async () => {132- const fsMock: FileSystemModule = {133- writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),134- mkdir: vi.fn(() => Promise.resolve()),135- }136-137- const result = await toSSG(app, fsMock, { dir: './static' })138-139- expect(result.success).toBe(false)140- expect(result.error).toBeDefined()141- expect(result.files).toStrictEqual([])142- })143-144- it('Should correctly generate files with the expected paths', async () => {145- const fsMock: FileSystemModule = {146- writeFile: vi.fn(() => Promise.resolve()),147- mkdir: vi.fn(() => Promise.resolve()),148- }149-150- const htmlMap = await fetchRoutesContent(app)151- await saveContentToFiles(htmlMap, fsMock, './static')152-153- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))154- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))155- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))156- expect(fsMock.writeFile).not.toHaveBeenCalledWith(157- 'static/about/some/thing.txt',158- expect.any(String)159- )160- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))161- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))162- expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))163- })164-165- it('should modify the request if the hook is provided', async () => {166- const fsMock: FileSystemModule = {167- writeFile: vi.fn(() => Promise.resolve()),168- mkdir: vi.fn(() => Promise.resolve()),169- }170- const beforeRequestHook: BeforeRequestHook = (req) => {171- if (req.method === 'GET') {172- return req173- }174- return false175- }176- const result = await toSSG(app, fsMock, { beforeRequestHook })177- expect(result.files).toHaveLength(10)178- })179-180- it('should skip the route if the request hook returns false', async () => {181- const beforeRequest: BeforeRequestHook = () => false182- const htmlMap = await fetchRoutesContent(app, beforeRequest)183- expect(htmlMap.size).toBe(0)184- })185-186- it('should modify the response if the hook is provided', async () => {187- const afterResponseHook: AfterResponseHook = (res) => {188- if (res.status === 200 || res.status === 500) {189- return res190- }191- return false192- }193- const fsMock: FileSystemModule = {194- writeFile: vi.fn(() => Promise.resolve()),195- mkdir: vi.fn(() => Promise.resolve()),196- }197- const result = await toSSG(app, fsMock, { afterResponseHook })198- expect(result.files).toHaveLength(10)199- })200-201- it('should skip the route if the response hook returns false', async () => {202- const afterResponse: AfterResponseHook = () => false203- const htmlMap = await fetchRoutesContent(app, undefined, afterResponse)204- expect(htmlMap.size).toBe(0)205- })206-207- it('should execute additional processing using afterGenerateHook', async () => {208- const fsMock: FileSystemModule = {209- writeFile: vi.fn(() => Promise.resolve()),210- mkdir: vi.fn(() => Promise.resolve()),211- }212- const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {213- if (result.files) {214- result.files.forEach((file) => console.log(file))215- }216- })217-218- await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })219-220- expect(afterGenerateHookMock).toHaveBeenCalled()221- expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())222- })223-224- it('should avoid memory leak from `req.signal.addEventListener()`', async () => {225- const fsMock: FileSystemModule = {226- writeFile: vi.fn(() => Promise.resolve()),227- mkdir: vi.fn(() => Promise.resolve()),228- }229-230- const signalAddEventListener = vi.fn(() => {})231- const app = new Hono()232- app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>233- c.html(<h1>{c.req.param('post')}</h1>)234- )235- await toSSG(app, fsMock, {236- beforeRequestHook: (req) => {237- req.signal.addEventListener = signalAddEventListener238- return req239- },240- })241-242- expect(signalAddEventListener).not.toHaveBeenCalled()243- })244-})245-246-describe('fetchRoutesContent function', () => {247- let app: Hono248-249- beforeEach(() => {250- app = new Hono()251- app.get('/text', (c) => c.text('Text Response'))252- app.get('/html', (c) => c.html('<p>HTML Response</p>'))253- app.get('/json', (c) => c.json({ message: 'JSON Response' }))254- app.use('*', poweredBy())255- })256-257- it('should fetch the correct content and MIME type for each route', async () => {258- const htmlMap = await fetchRoutesContent(app)259- expect(htmlMap.get('/text')).toEqual({260- content: 'Text Response',261- mimeType: 'text/plain',262- })263- expect(htmlMap.get('/html')).toEqual({264- content: '<p>HTML Response</p>',265- mimeType: 'text/html',266- })267- expect(htmlMap.get('/json')).toEqual({268- content: '{"message":"JSON Response"}',269- mimeType: 'application/json',270- })271- })272-273- it('should skip middleware routes', async () => {274- const htmlMap = await fetchRoutesContent(app)275- expect(htmlMap.has('*')).toBeFalsy()276- })277-278- it('should handle errors correctly', async () => {279- vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))280- await expect(fetchRoutesContent(app)).rejects.toThrow('Network error')281- vi.restoreAllMocks()282- })283-})284-285-describe('saveContentToFiles function', () => {286- let fsMock: FileSystemModule287- let htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>288- // tar.gz, testdir/test.txt289- const gzFileBuffer = Buffer.from(290- 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',291- 'base64'292- )293- const gzFileArrayBuffer = gzFileBuffer.buffer.slice(294- gzFileBuffer.byteOffset,295- gzFileBuffer.byteLength + gzFileBuffer.byteOffset296- )297- // PNG, red dot (1x1)298- const pngFileBuffer = Buffer.from(299- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',300- 'base64'301- )302- const pngFileArrayBuffer = pngFileBuffer.buffer.slice(303- pngFileBuffer.byteOffset,304- pngFileBuffer.byteLength + pngFileBuffer.byteOffset305- )306-307- beforeEach(() => {308- fsMock = {309- writeFile: vi.fn(() => Promise.resolve()),310- mkdir: vi.fn(() => Promise.resolve()),311- }312- htmlMap = new Map([313- ['/', { content: 'Home Page', mimeType: 'text/html' }],314- ['/index.html', { content: 'Home Page2', mimeType: 'text/html' }],315- ['/about', { content: 'About Page', mimeType: 'text/html' }],316- ['/about/', { content: 'About Page', mimeType: 'text/html' }],317- ['/bravo/index.html', { content: 'About Page', mimeType: 'text/html' }],318- ['/bravo/release-4.0.0', { content: 'Release 4.0.0', mimeType: 'text/html' }],319- ['/bravo/2024.02.18-sweet-memories', { content: 'Sweet Memories', mimeType: 'text/html' }],320- ['/bravo/deep.dive.to.html', { content: 'Deep Dive To HTML', mimeType: 'text/html' }],321- ['/bravo/alert.js', { content: 'alert("evil content")', mimeType: 'text/html' }],322- [323- '/bravo/index.tar.gz',324- {325- content: gzFileArrayBuffer,326- mimeType: 'application/gzip',327- },328- ],329- [330- '/bravo/dot.png',331- {332- content: pngFileArrayBuffer,333- mimeType: 'image/png',334- },335- ],336- ['/bravo.text/index.html', { content: 'About Page', mimeType: 'text/html' }],337- ['/bravo.text/', { content: 'Bravo Page', mimeType: 'text/html' }],338- ])339- })340-341- it('should correctly create files with the right content and paths', async () => {342- await saveContentToFiles(htmlMap, fsMock, './static')343-344- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')345- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')346- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')347- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')348- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')349- expect(fsMock.writeFile).toHaveBeenCalledWith(350- 'static/bravo/release-4.0.0.html',351- 'Release 4.0.0'352- )353- expect(fsMock.writeFile).toHaveBeenCalledWith(354- 'static/bravo/deep.dive.to.html',355- 'Deep Dive To HTML'356- )357- expect(fsMock.writeFile).toHaveBeenCalledWith(358- 'static/bravo/2024.02.18-sweet-memories.html',359- 'Sweet Memories'360- )361- expect(fsMock.writeFile).toHaveBeenCalledWith(362- 'static/bravo/alert.js.html',363- 'alert("evil content")'364- )365- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')366- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')367-368- // binary files369- expect(fsMock.writeFile).toHaveBeenCalledWith(370- 'static/bravo/index.tar.gz',371- new Uint8Array(gzFileArrayBuffer)372- )373- expect(fsMock.writeFile).toHaveBeenCalledWith(374- 'static/bravo/dot.png',375- new Uint8Array(pngFileArrayBuffer)376- )377- })378-379- it('should correctly create directories if they do not exist', async () => {380- await saveContentToFiles(htmlMap, fsMock, './static')381-382- expect(fsMock.mkdir).toHaveBeenCalledWith('static', { recursive: true })383- })384-385- it('should handle file writing or directory creation errors', async () => {386- const fsMock: FileSystemModule = {387- writeFile: vi.fn(() => Promise.resolve()),388- mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),389- }390-391- await expect(saveContentToFiles(htmlMap, fsMock, './static')).rejects.toThrow(392- 'File write error'393- )394- })395- it('check extensions', async () => {396- await saveContentToFiles(htmlMap, fsMock, './static')397-398- expect(fsMock.mkdir).toHaveBeenCalledWith('static', { recursive: true })399- })400-})401-402-describe('Dynamic route handling', () => {403- let app: Hono404- beforeEach(() => {405- app = new Hono()406- app.get('/shops/:id', (c) => c.html('Shop Page'))407- app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))408- app.get('/foo/*', (c) => c.html('Foo Page'))409- app.get('/foo:bar', (c) => c.html('Foo Bar Page'))410- })411-412- it('should skip /shops/:id dynamic route', async () => {413- const htmlMap = await fetchRoutesContent(app)414- expect(htmlMap.has('/shops/:id')).toBeFalsy()415- })416-417- it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {418- const htmlMap = await fetchRoutesContent(app)419- expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()420- })421-422- it('should skip /foo/* dynamic route', async () => {423- const htmlMap = await fetchRoutesContent(app)424- expect(htmlMap.has('/foo/*')).toBeFalsy()425- })426-427- it('should not skip /foo:bar dynamic route', async () => {428- const htmlMap = await fetchRoutesContent(app)429- expect(htmlMap.has('/foo:bar')).toBeTruthy()430- })431-})432-433-describe('isSSGContext()', () => {434- const app = new Hono()435- app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))436-437- it('Should not generate the page if disableSSG is set', async () => {438- const htmlMap = await fetchRoutesContent(app)439- expect(await htmlMap.get('/')).toEqual({440- content: '<h1>SSG</h1>',441- mimeType: 'text/html',442- })443- })444-445- it('Should return 404 response if onlySSG() is set', async () => {446- const res = await app.request('/')447- expect(await res.text()).toBe('<h1>noSSG</h1>')448- })449-})450-451-describe('disableSSG/onlySSG middlewares', () => {452- const app = new Hono()453- app.get('/', (c) => c.html(<h1>Hello</h1>))454- app.get('/api', disableSSG(), (c) => c.text('an-api'))455- app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)456- app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))457-458- it('Should not generate the page if disableSSG is set', async () => {459- const htmlMap = await fetchRoutesContent(app)460- expect(htmlMap.has('/')).toBe(true)461- expect(htmlMap.has('/static-page')).toBe(true)462- expect(htmlMap.has('/api')).toBe(false)463- expect(htmlMap.has('/disable-by-response')).toBe(false)464- })465-466- it('Should return 404 response if onlySSG() is set', async () => {467- const res = await app.request('/static-page')468- expect(res.status).toBe(404)469- })470-})modified:src/helper/ssg/index.ts+2 added-294 removed
1-import { replaceUrlParam } from '../../client/utils'2-import type { Context } from '../../context'3-import type { Hono } from '../../hono'4-import type { Env, MiddlewareHandler, Schema } from '../../types'5-import { getExtension } from '../../utils/mime'6-import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'7-8-const SSG_CONTEXT = 'HONO_SSG_CONTEXT'9-export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })10-11-/**12- * @experimental13- * `FileSystemModule` is an experimental feature.14- * The API might be changed.15- */16-export interface FileSystemModule {17- writeFile(path: string, data: string | Uint8Array): Promise<void>18- mkdir(path: string, options: { recursive: boolean }): Promise<void | string>19-}20-21-/**22- * @experimental23- * `ToSSGResult` is an experimental feature.24- * The API might be changed.25- */26-export interface ToSSGResult {27- success: boolean28- files: string[]29- error?: Error30-}31-32-const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {33- const extension = determineExtension(mimeType)34-35- if (routePath.endsWith(`.${extension}`)) {36- return joinPaths(outDir, routePath)37- }38-39- if (routePath === '/') {40- return joinPaths(outDir, `index.${extension}`)41- }42- if (routePath.endsWith('/')) {43- return joinPaths(outDir, routePath, `index.${extension}`)44- }45- return joinPaths(outDir, `${routePath}.${extension}`)46-}47-48-const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {49- const contentType = response.headers.get('Content-Type')50-51- try {52- if (contentType?.includes('text') || contentType?.includes('json')) {53- return await response.text()54- } else {55- return await response.arrayBuffer()56- }57- } catch (error) {58- throw new Error(59- `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`60- )61- }62-}63-64-const determineExtension = (mimeType: string): string => {65- switch (mimeType) {66- case 'text/html':67- return 'html'68- case 'text/xml':69- case 'application/xml':70- return 'xml'71- default: {72- return getExtension(mimeType) || 'html'73- }74- }75-}76-77-interface SSGParam {78- [key: string]: string79-}80-type SSGParams = SSGParam[]81-82-interface SSGParamsMiddleware {83- <E extends Env = Env>(84- generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>85- ): MiddlewareHandler<E>86- <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>87-}88-89-type AddedSSGDataRequest = Request & {90- ssgParams?: SSGParams91-}92-/**93- * Define SSG Route94- */95-export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {96- ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)97- await next()98-}99-100-export type BeforeRequestHook = (req: Request) => Request | false101-export type AfterResponseHook = (res: Response) => Response | false102-export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>103-104-export interface ToSSGOptions {105- dir?: string106- beforeRequestHook?: BeforeRequestHook107- afterResponseHook?: AfterResponseHook108- afterGenerateHook?: AfterGenerateHook109-}110-111-/**112- * @experimental113- * `fetchRoutesContent` is an experimental feature.114- * The API might be changed.115- */116-export const fetchRoutesContent = async <117- E extends Env = Env,118- S extends Schema = {},119- BasePath extends string = '/'120->(121- app: Hono<E, S, BasePath>,122- beforeRequestHook?: BeforeRequestHook,123- afterResponseHook?: AfterResponseHook124-): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {125- const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()126- const baseURL = 'http://localhost'127-128- for (const route of filterStaticGenerateRoutes(app)) {129- // GET Route Info130- const thisRouteBaseURL = new URL(route.path, baseURL).toString()131-132- let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest133- if (beforeRequestHook) {134- const maybeRequest = beforeRequestHook(forGetInfoURLRequest)135- if (!maybeRequest) {136- continue137- }138- forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest139- }140- await app.fetch(forGetInfoURLRequest)141-142- if (!forGetInfoURLRequest.ssgParams) {143- if (isDynamicRoute(route.path)) {144- continue145- }146- forGetInfoURLRequest.ssgParams = [{}]147- }148-149- const requestInit = {150- method: forGetInfoURLRequest.method,151- headers: forGetInfoURLRequest.headers,152- }153- for (const param of forGetInfoURLRequest.ssgParams) {154- const replacedUrlParam = replaceUrlParam(route.path, param)155- let response = await app.request(replacedUrlParam, requestInit, {156- [SSG_CONTEXT]: true,157- })158- if (response === SSG_DISABLED_RESPONSE) {159- continue160- }161- if (afterResponseHook) {162- const maybeResponse = afterResponseHook(response)163- if (!maybeResponse) {164- continue165- }166- response = maybeResponse167- }168- const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'169- const content = await parseResponseContent(response)170- htmlMap.set(replacedUrlParam, {171- mimeType,172- content,173- })174- }175- }176-177- return htmlMap178-}179-180-const isDynamicRoute = (path: string): boolean => {181- return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))182-}183-184-/**185- * @experimental186- * `saveContentToFiles` is an experimental feature.187- * The API might be changed.188- */189-export const saveContentToFiles = async (190- htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,191- fsModule: FileSystemModule,192- outDir: string193-): Promise<string[]> => {194- const files: string[] = []195-196- for (const [routePath, { content, mimeType }] of htmlMap) {197- const filePath = generateFilePath(routePath, outDir, mimeType)198- const dirPath = dirname(filePath)199-200- await fsModule.mkdir(dirPath, { recursive: true })201- if (typeof content === 'string') {202- await fsModule.writeFile(filePath, content)203- } else if (content instanceof ArrayBuffer) {204- await fsModule.writeFile(filePath, new Uint8Array(content))205- }206- files.push(filePath)207- }208-209- return files210-}211-212-/**213- * @experimental214- * `ToSSGInterface` is an experimental feature.215- * The API might be changed.216- */217-export interface ToSSGInterface {218- (219- // eslint-disable-next-line @typescript-eslint/no-explicit-any220- app: Hono<any, any, any>,221- fsModule: FileSystemModule,222- options?: ToSSGOptions223- ): Promise<ToSSGResult>224-}225-226-/**227- * @experimental228- * `ToSSGAdaptorInterface` is an experimental feature.229- * The API might be changed.230- */231-export interface ToSSGAdaptorInterface<232- E extends Env = Env,233- S extends Schema = {},234- BasePath extends string = '/'235-> {236- (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>237-}238-239-/**240- * @experimental241- * `toSSG` is an experimental feature.242- * The API might be changed.243- */244-export const toSSG: ToSSGInterface = async (app, fs, options) => {245- let result: ToSSGResult | undefined = undefined246- try {247- const outputDir = options?.dir ?? './static'248- const maps = await fetchRoutesContent(249- app,250- options?.beforeRequestHook,251- options?.afterResponseHook252- )253- const files = await saveContentToFiles(maps, fs, outputDir)254- result = { success: true, files }255- } catch (error) {256- const errorObj = error instanceof Error ? error : new Error(String(error))257- result = { success: false, files: [], error: errorObj }258- }259- await options?.afterGenerateHook?.(result)260- return result261-}262-263-/**264- * @experimental265- * `isSSGContext` is an experimental feature.266- * The API might be changed.267- */268-export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]269-270-/**271- * @experimental272- * `disableSSG` is an experimental feature.273- * The API might be changed.274- */275-export const disableSSG = (): MiddlewareHandler =>276- async function disableSSG(c, next) {277- if (isSSGContext(c)) {278- return SSG_DISABLED_RESPONSE279- }280- await next()281- }282-283-/**284- * @experimental285- * `onlySSG` is an experimental feature.286- * The API might be changed.287- */288-export const onlySSG = (): MiddlewareHandler =>289- async function onlySSG(c, next) {290- if (!isSSGContext(c)) {291- return c.notFound()292- }293- await next()294- }1+export * from './ssg'2+export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'added:src/helper/ssg/middleware.ts+62 added
1+import type { Context } from '../../context'2+import type { Env, MiddlewareHandler } from '../../types'3+4+export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })6+7+interface SSGParam {8+ [key: string]: string9+}10+export type SSGParams = SSGParam[]11+12+interface SSGParamsMiddleware {13+ <E extends Env = Env>(14+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15+ ): MiddlewareHandler<E>16+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17+}18+19+export type AddedSSGDataRequest = Request & {20+ ssgParams?: SSGParams21+}22+23+/**24+ * Define SSG Route25+ */26+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28+ await next()29+}30+31+/**32+ * @experimental33+ * `isSSGContext` is an experimental feature.34+ * The API might be changed.35+ */36+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]37+38+/**39+ * @experimental40+ * `disableSSG` is an experimental feature.41+ * The API might be changed.42+ */43+export const disableSSG = (): MiddlewareHandler =>44+ async function disableSSG(c, next) {45+ if (isSSGContext(c)) {46+ return SSG_DISABLED_RESPONSE47+ }48+ await next()49+ }50+51+/**52+ * @experimental53+ * `onlySSG` is an experimental feature.54+ * The API might be changed.55+ */56+export const onlySSG = (): MiddlewareHandler =>57+ async function onlySSG(c, next) {58+ if (!isSSGContext(c)) {59+ return c.notFound()60+ }61+ await next()62+ }added:src/helper/ssg/ssg.test.tsx+500 added
1+import { beforeEach, describe, expect, it } from 'vitest'2+import { Hono } from '../../hono'3+// 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'8+import type {9+ BeforeRequestHook,10+ AfterResponseHook,11+ AfterGenerateHook,12+ FileSystemModule,13+} from './ssg'14+15+const resolveRoutesContent = async (res: ReturnType<typeof fetchRoutesContent>) => {16+ const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()17+ for (const getInfoPromise of res) {18+ const getInfo = await getInfoPromise19+ if (!getInfo) {20+ continue21+ }22+ for (const dataPromise of getInfo) {23+ const data = await dataPromise24+ if (!data) {25+ continue26+ }27+ htmlMap.set(data.routePath, {28+ content: data.content,29+ mimeType: data.mimeType,30+ })31+ }32+ }33+ return htmlMap34+}35+36+describe('toSSG function', () => {37+ let app: Hono38+ let fsMock: FileSystemModule39+40+ const postParams = [{ post: '1' }, { post: '2' }]41+42+ beforeEach(() => {43+ app = new Hono()44+ app.all('/', (c) => c.html('Hello, World!'))45+ app.get('/about', (c) => c.html('About Page'))46+ app.get('/about/some', (c) => c.text('About Page 2tier'))47+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))48+ app.get('/bravo', (c) => c.html('Bravo Page'))49+ app.get('/Charlie', async (c, next) => {50+ c.setRenderer((content, head) => {51+ return c.html(52+ <html>53+ <head>54+ <title>{head.title || ''}</title>55+ </head>56+ <body>57+ <p>{content}</p>58+ </body>59+ </html>60+ )61+ })62+ await next()63+ })64+ app.get('/Charlie', (c) => {65+ return c.render('Hello!', { title: 'Charlies Page' })66+ })67+68+ // Included params69+ app.get(70+ '/post/:post',71+ ssgParams(() => postParams),72+ (c) => c.html(<h1>{c.req.param('post')}</h1>)73+ )74+75+ app.get(76+ '/user/:user_id',77+ ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),78+ (c) => c.html(<h1>{c.req.param('user_id')}</h1>)79+ )80+81+ type Env = {82+ Bindings: {83+ FOO_DB: string84+ }85+ Variables: {86+ FOO_VAR: string87+ }88+ }89+90+ app.get(91+ '/env-type-check',92+ ssgParams<Env>((c) => {93+ expectTypeOf<typeof c.env.FOO_DB>().toBeString()94+ expectTypeOf<typeof c.var.FOO_VAR>().toBeString()95+ return []96+ })97+ )98+99+ fsMock = {100+ writeFile: vi.fn(() => Promise.resolve()),101+ mkdir: vi.fn(() => Promise.resolve()),102+ }103+ })104+ it('Should correctly generate static HTML files for Hono routes', async () => {105+ const writtenFiles: Record<string, string> = {}106+ const fsMock: FileSystemModule = {107+ writeFile: (path, data) => {108+ writtenFiles[path] = typeof data === 'string' ? data : data.toString()109+ return Promise.resolve()110+ },111+ mkdir: vi.fn(() => Promise.resolve()),112+ }113+114+ const result = await toSSG(app, fsMock, { dir: './static' })115+116+ for (const postParam of postParams) {117+ const html = writtenFiles[`static/post/${postParam.post}.html`]118+ expect(html).toBe(`<h1>${postParam.post}</h1>`)119+ }120+121+ for (let i = 1; i <= 3; i++) {122+ const html = writtenFiles[`static/user/${i}.html`]123+ expect(html).toBe(`<h1>${i}</h1>`)124+ }125+126+ expect(result.files.length).toBe(10)127+ expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {128+ recursive: true,129+ })130+ })131+132+ it('Should handle file system errors correctly in saveContentToFiles', async () => {133+ const fsMock: FileSystemModule = {134+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),135+ mkdir: vi.fn(() => Promise.resolve()),136+ }137+138+ const result = await toSSG(app, fsMock, { dir: './static' })139+ expect(result.success).toBe(false)140+ expect(result.files).toStrictEqual([])141+ expect(result.error?.message).toBe('Write error')142+ })143+144+ it('Should handle overall process errors correctly in toSSG', async () => {145+ const fsMock: FileSystemModule = {146+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),147+ mkdir: vi.fn(() => Promise.resolve()),148+ }149+150+ const result = await toSSG(app, fsMock, { dir: './static' })151+152+ expect(result.success).toBe(false)153+ expect(result.error).toBeDefined()154+ expect(result.files).toStrictEqual([])155+ })156+157+ it('Should correctly generate files with the expected paths', async () => {158+ await toSSG(app, fsMock, { dir: './static' })159+160+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))161+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))162+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))163+ expect(fsMock.writeFile).not.toHaveBeenCalledWith(164+ 'static/about/some/thing.txt',165+ expect.any(String)166+ )167+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))168+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))169+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))170+ })171+172+ it('should modify the request if the hook is provided', async () => {173+ const beforeRequestHook: BeforeRequestHook = (req) => {174+ if (req.method === 'GET') {175+ return req176+ }177+ return false178+ }179+ const result = await toSSG(app, fsMock, { beforeRequestHook })180+ expect(result.files).toHaveLength(10)181+ })182+183+ it('should skip the route if the request hook returns false', async () => {184+ const beforeRequest: BeforeRequestHook = () => false185+ const result = await toSSG(app, fsMock, { beforeRequestHook: beforeRequest })186+ expect(result.success).toBe(true)187+ expect(result.files).toStrictEqual([])188+ })189+190+ it('should modify the response if the hook is provided', async () => {191+ const afterResponseHook: AfterResponseHook = (res) => {192+ if (res.status === 200 || res.status === 500) {193+ return res194+ }195+ return false196+ }197+ const result = await toSSG(app, fsMock, { afterResponseHook })198+ expect(result.files).toHaveLength(10)199+ })200+201+ it('should skip the route if the response hook returns false', async () => {202+ const afterResponse: AfterResponseHook = () => false203+ const result = await toSSG(app, fsMock, { afterResponseHook: afterResponse })204+ expect(result.success).toBe(true)205+ expect(result.files).toStrictEqual([])206+ })207+208+ it('should execute additional processing using afterGenerateHook', async () => {209+ const fsMock: FileSystemModule = {210+ writeFile: vi.fn(() => Promise.resolve()),211+ mkdir: vi.fn(() => Promise.resolve()),212+ }213+ const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {214+ if (result.files) {215+ result.files.forEach((file) => console.log(file))216+ }217+ })218+219+ await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })220+221+ expect(afterGenerateHookMock).toHaveBeenCalled()222+ expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())223+ })224+225+ it('should avoid memory leak from `req.signal.addEventListener()`', async () => {226+ const fsMock: FileSystemModule = {227+ writeFile: vi.fn(() => Promise.resolve()),228+ mkdir: vi.fn(() => Promise.resolve()),229+ }230+231+ const signalAddEventListener = vi.fn(() => {})232+ const app = new Hono()233+ app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>234+ c.html(<h1>{c.req.param('post')}</h1>)235+ )236+ await toSSG(app, fsMock, {237+ beforeRequestHook: (req) => {238+ req.signal.addEventListener = signalAddEventListener239+ return req240+ },241+ })242+243+ expect(signalAddEventListener).not.toHaveBeenCalled()244+ })245+})246+247+describe('fetchRoutesContent function', () => {248+ let app: Hono249+250+ beforeEach(() => {251+ app = new Hono()252+ app.get('/text', (c) => c.text('Text Response'))253+ app.get('/html', (c) => c.html('<p>HTML Response</p>'))254+ app.get('/json', (c) => c.json({ message: 'JSON Response' }))255+ app.use('*', poweredBy())256+ })257+258+ it('should fetch the correct content and MIME type for each route', async () => {259+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))260+261+ expect(htmlMap.get('/text')).toEqual({262+ content: 'Text Response',263+ mimeType: 'text/plain',264+ })265+ expect(htmlMap.get('/html')).toEqual({266+ content: '<p>HTML Response</p>',267+ mimeType: 'text/html',268+ })269+ expect(htmlMap.get('/json')).toEqual({270+ content: '{"message":"JSON Response"}',271+ mimeType: 'application/json',272+ })273+ })274+275+ it('should skip middleware routes', async () => {276+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))277+ expect(htmlMap.has('*')).toBeFalsy()278+ })279+280+ it('should handle errors correctly', async () => {281+ vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))282+ await expect(resolveRoutesContent(fetchRoutesContent(app))).rejects.toThrow('Network error')283+ vi.restoreAllMocks()284+ })285+})286+287+describe('saveContentToFile function', () => {288+ // tar.gz, testdir/test.txt289+ const gzFileBuffer = Buffer.from(290+ 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',291+ 'base64'292+ )293+ const gzFileArrayBuffer = gzFileBuffer.buffer.slice(294+ gzFileBuffer.byteOffset,295+ gzFileBuffer.byteLength + gzFileBuffer.byteOffset296+ )297+ // PNG, red dot (1x1)298+ const pngFileBuffer = Buffer.from(299+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',300+ 'base64'301+ )302+ const pngFileArrayBuffer = pngFileBuffer.buffer.slice(303+ pngFileBuffer.byteOffset,304+ pngFileBuffer.byteLength + pngFileBuffer.byteOffset305+ )306+307+ const fileData = [308+ { routePath: '/', content: 'Home Page', mimeType: 'text/html' },309+ { routePath: '/index.html', content: 'Home Page2', mimeType: 'text/html' },310+ { routePath: '/about', content: 'About Page', mimeType: 'text/html' },311+ { routePath: '/about/', content: 'About Page', mimeType: 'text/html' },312+ { routePath: '/bravo/index.html', content: 'About Page', mimeType: 'text/html' },313+ { routePath: '/bravo/release-4.0.0', content: 'Release 4.0.0', mimeType: 'text/html' },314+ {315+ routePath: '/bravo/2024.02.18-sweet-memories',316+ content: 'Sweet Memories',317+ mimeType: 'text/html',318+ },319+ { routePath: '/bravo/deep.dive.to.html', content: 'Deep Dive To HTML', mimeType: 'text/html' },320+ { routePath: '/bravo/alert.js', content: 'alert("evil content")', mimeType: 'text/html' },321+ { routePath: '/bravo.text/index.html', content: 'About Page', mimeType: 'text/html' },322+ { routePath: '/bravo.text/', content: 'Bravo Page', mimeType: 'text/html' },323+ {324+ routePath: '/bravo/index.tar.gz',325+ content: gzFileArrayBuffer,326+ mimeType: 'application/gzip',327+ },328+ {329+ routePath: '/bravo/dot.png',330+ content: pngFileArrayBuffer,331+ mimeType: 'image/png',332+ },333+ ]334+335+ let fsMock: FileSystemModule336+337+ beforeEach(() => {338+ fsMock = {339+ writeFile: vi.fn(() => Promise.resolve()),340+ mkdir: vi.fn(() => Promise.resolve()),341+ }342+ })343+344+ it('should correctly create files with the right content and paths', async () => {345+ for (const data of fileData) {346+ await saveContentToFile(Promise.resolve(data), fsMock, './static')347+ }348+349+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')350+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')351+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')352+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')353+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')354+ expect(fsMock.writeFile).toHaveBeenCalledWith(355+ 'static/bravo/release-4.0.0.html',356+ 'Release 4.0.0'357+ )358+ expect(fsMock.writeFile).toHaveBeenCalledWith(359+ 'static/bravo/deep.dive.to.html',360+ 'Deep Dive To HTML'361+ )362+ expect(fsMock.writeFile).toHaveBeenCalledWith(363+ 'static/bravo/2024.02.18-sweet-memories.html',364+ 'Sweet Memories'365+ )366+ expect(fsMock.writeFile).toHaveBeenCalledWith(367+ 'static/bravo/alert.js.html',368+ 'alert("evil content")'369+ )370+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')371+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')372+ // binary files373+ expect(fsMock.writeFile).toHaveBeenCalledWith(374+ 'static/bravo/index.tar.gz',375+ new Uint8Array(gzFileArrayBuffer)376+ )377+ expect(fsMock.writeFile).toHaveBeenCalledWith(378+ 'static/bravo/dot.png',379+ new Uint8Array(pngFileArrayBuffer)380+ )381+ })382+383+ it('should correctly create directories if they do not exist', async () => {384+ await saveContentToFile(385+ Promise.resolve({386+ routePath: '/new-dir/index.html',387+ content: 'New Page',388+ mimeType: 'text/html',389+ }),390+ fsMock,391+ './static'392+ )393+ expect(fsMock.mkdir).toHaveBeenCalledWith('static/new-dir', { recursive: true })394+ })395+396+ it('should handle file writing or directory creation errors', async () => {397+ const fsMock: FileSystemModule = {398+ writeFile: vi.fn(() => Promise.resolve()),399+ mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),400+ }401+402+ await expect(403+ saveContentToFile(404+ Promise.resolve({405+ routePath: '/error-dir/index.html',406+ content: 'New Page',407+ mimeType: 'text/html',408+ }),409+ fsMock,410+ './static'411+ )412+ ).rejects.toThrow('File write error')413+ })414+ it('check extensions', async () => {415+ for (const data of fileData) {416+ await saveContentToFile(Promise.resolve(data), fsMock, './static-check-extensions')417+ }418+ expect(fsMock.mkdir).toHaveBeenCalledWith('static-check-extensions', { recursive: true })419+ })420+})421+422+describe('Dynamic route handling', () => {423+ let app: Hono424+ beforeEach(() => {425+ app = new Hono()426+ app.get('/shops/:id', (c) => c.html('Shop Page'))427+ app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))428+ app.get('/foo/*', (c) => c.html('Foo Page'))429+ app.get('/foo:bar', (c) => c.html('Foo Bar Page'))430+ })431+432+ it('should skip /shops/:id dynamic route', async () => {433+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))434+ expect(htmlMap.has('/shops/:id')).toBeFalsy()435+ })436+437+ it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {438+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))439+ expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()440+ })441+442+ it('should skip /foo/* dynamic route', async () => {443+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))444+ expect(htmlMap.has('/foo/*')).toBeFalsy()445+ })446+447+ it('should not skip /foo:bar dynamic route', async () => {448+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))449+ expect(htmlMap.has('/foo:bar')).toBeTruthy()450+ })451+})452+453+describe('isSSGContext()', () => {454+ const app = new Hono()455+ app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))456+457+ const fsMock: FileSystemModule = {458+ writeFile: vi.fn(() => Promise.resolve()),459+ mkdir: vi.fn(() => Promise.resolve()),460+ }461+462+ it('Should not generate the page if disableSSG is set', async () => {463+ await toSSG(app, fsMock, { dir: './static' })464+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', '<h1>SSG</h1>')465+ })466+467+ it('Should return 404 response if onlySSG() is set', async () => {468+ const res = await app.request('/')469+ expect(await res.text()).toBe('<h1>noSSG</h1>')470+ })471+})472+473+describe('disableSSG/onlySSG middlewares', () => {474+ const app = new Hono()475+ app.get('/', (c) => c.html(<h1>Hello</h1>))476+ app.get('/api', disableSSG(), (c) => c.text('an-api'))477+ app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)478+ app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))479+480+ const fsMock: FileSystemModule = {481+ writeFile: vi.fn(() => Promise.resolve()),482+ mkdir: vi.fn(() => Promise.resolve()),483+ }484+485+ it('Should not generate the page if disableSSG is set', async () => {486+ await toSSG(app, fsMock, { dir: './static' })487+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))488+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/static-page.html', expect.any(String))489+ expect(fsMock.writeFile).not.toHaveBeenCalledWith('static/api.html', expect.any(String))490+ expect(fsMock.writeFile).not.toHaveBeenCalledWith(491+ 'static/disable-by-response.html',492+ expect.any(String)493+ )494+ })495+496+ it('Should return 404 response if onlySSG() is set', async () => {497+ const res = await app.request('/static-page')498+ expect(res.status).toBe(404)499+ })500+})added:src/helper/ssg/ssg.ts+302 added
1+import { replaceUrlParam } from '../../client/utils'2+import type { Hono } from '../../hono'3+import type { Env, Schema } from '../../types'4+import { createPool } from '../../utils/concurrent'5+import { getExtension } from '../../utils/mime'6+import type { AddedSSGDataRequest, SSGParams } from './middleware'7+import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware'8+import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'9+10+const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg11+12+/**13+ * @experimental14+ * `FileSystemModule` is an experimental feature.15+ * The API might be changed.16+ */17+export interface FileSystemModule {18+ writeFile(path: string, data: string | Uint8Array): Promise<void>19+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20+}21+22+/**23+ * @experimental24+ * `ToSSGResult` is an experimental feature.25+ * The API might be changed.26+ */27+export interface ToSSGResult {28+ success: boolean29+ files: string[]30+ error?: Error31+}32+33+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34+ const extension = determineExtension(mimeType)35+36+ if (routePath.endsWith(`.${extension}`)) {37+ return joinPaths(outDir, routePath)38+ }39+40+ if (routePath === '/') {41+ return joinPaths(outDir, `index.${extension}`)42+ }43+ if (routePath.endsWith('/')) {44+ return joinPaths(outDir, routePath, `index.${extension}`)45+ }46+ return joinPaths(outDir, `${routePath}.${extension}`)47+}48+49+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50+ const contentType = response.headers.get('Content-Type')51+52+ try {53+ if (contentType?.includes('text') || contentType?.includes('json')) {54+ return await response.text()55+ } else {56+ return await response.arrayBuffer()57+ }58+ } catch (error) {59+ throw new Error(60+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61+ )62+ }63+}64+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+ }75+ }76+}77+78+export type BeforeRequestHook = (req: Request) => Request | false79+export type AfterResponseHook = (res: Response) => Response | false80+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>81+82+export interface ToSSGOptions {83+ dir?: string84+ beforeRequestHook?: BeforeRequestHook85+ afterResponseHook?: AfterResponseHook86+ afterGenerateHook?: AfterGenerateHook87+ concurrency?: number88+}89+90+/**91+ * @experimental92+ * `fetchRoutesContent` is an experimental feature.93+ * The API might be changed.94+ */95+export const fetchRoutesContent = function* <96+ E extends Env = Env,97+ S extends Schema = {},98+ BasePath extends string = '/'99+>(100+ app: Hono<E, S, BasePath>,101+ beforeRequestHook?: BeforeRequestHook,102+ afterResponseHook?: AfterResponseHook,103+ concurrency?: number104+): Generator<105+ Promise<106+ | Generator<107+ Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108+ >109+ | undefined110+ >111+> {112+ const baseURL = 'http://localhost'113+ const pool = createPool({ concurrency })114+115+ for (const route of filterStaticGenerateRoutes(app)) {116+ // GET Route Info117+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()118+119+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120+ if (beforeRequestHook) {121+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122+ if (!maybeRequest) {123+ continue124+ }125+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126+ }127+128+ // eslint-disable-next-line no-async-promise-executor129+ yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130+ try {131+ await pool.run(() => app.fetch(forGetInfoURLRequest))132+133+ if (!forGetInfoURLRequest.ssgParams) {134+ if (isDynamicRoute(route.path)) {135+ resolveGetInfo(undefined)136+ return137+ }138+ forGetInfoURLRequest.ssgParams = [{}]139+ }140+141+ const requestInit = {142+ method: forGetInfoURLRequest.method,143+ headers: forGetInfoURLRequest.headers,144+ }145+146+ resolveGetInfo(147+ (function* () {148+ for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149+ // eslint-disable-next-line no-async-promise-executor150+ yield new Promise(async (resolveReq, rejectReq) => {151+ try {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await pool.run(() =>154+ app.request(replacedUrlParam, requestInit, {155+ [SSG_CONTEXT]: true,156+ })157+ )158+ if (response === SSG_DISABLED_RESPONSE) {159+ resolveReq(undefined)160+ return161+ }162+ if (afterResponseHook) {163+ const maybeResponse = afterResponseHook(response)164+ if (!maybeResponse) {165+ resolveReq(undefined)166+ return167+ }168+ response = maybeResponse169+ }170+ const mimeType =171+ response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172+ const content = await parseResponseContent(response)173+ resolveReq({174+ routePath: replacedUrlParam,175+ mimeType,176+ content,177+ })178+ } catch (error) {179+ rejectReq(error)180+ }181+ })182+ }183+ })()184+ )185+ } catch (error) {186+ rejectGetInfo(error)187+ }188+ })189+ }190+}191+192+const isDynamicRoute = (path: string): boolean => {193+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194+}195+196+/**197+ * @experimental198+ * `saveContentToFile` is an experimental feature.199+ * The API might be changed.200+ */201+const createdDirs: Set<string> = new Set()202+export const saveContentToFile = async (203+ data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204+ fsModule: FileSystemModule,205+ outDir: string206+): Promise<string | undefined> => {207+ const awaitedData = await data208+ if (!awaitedData) {209+ return210+ }211+ const { routePath, content, mimeType } = awaitedData212+ const filePath = generateFilePath(routePath, outDir, mimeType)213+ const dirPath = dirname(filePath)214+215+ if (!createdDirs.has(dirPath)) {216+ await fsModule.mkdir(dirPath, { recursive: true })217+ createdDirs.add(dirPath)218+ }219+ if (typeof content === 'string') {220+ await fsModule.writeFile(filePath, content)221+ } else if (content instanceof ArrayBuffer) {222+ await fsModule.writeFile(filePath, new Uint8Array(content))223+ }224+ return filePath225+}226+227+/**228+ * @experimental229+ * `ToSSGInterface` is an experimental feature.230+ * The API might be changed.231+ */232+export interface ToSSGInterface {233+ (234+ // eslint-disable-next-line @typescript-eslint/no-explicit-any235+ app: Hono<any, any, any>,236+ fsModule: FileSystemModule,237+ options?: ToSSGOptions238+ ): Promise<ToSSGResult>239+}240+241+/**242+ * @experimental243+ * `ToSSGAdaptorInterface` is an experimental feature.244+ * The API might be changed.245+ */246+export interface ToSSGAdaptorInterface<247+ E extends Env = Env,248+ S extends Schema = {},249+ BasePath extends string = '/'250+> {251+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252+}253+254+/**255+ * @experimental256+ * `toSSG` is an experimental feature.257+ * The API might be changed.258+ */259+export const toSSG: ToSSGInterface = async (app, fs, options) => {260+ let result: ToSSGResult | undefined = undefined261+ const getInfoPromises: Promise<unknown>[] = []262+ const savePromises: Promise<string | undefined>[] = []263+ try {264+ const outputDir = options?.dir ?? './static'265+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266+267+ const getInfoGen = fetchRoutesContent(268+ app,269+ options?.beforeRequestHook,270+ options?.afterResponseHook,271+ concurrency272+ )273+ for (const getInfo of getInfoGen) {274+ getInfoPromises.push(275+ getInfo.then((getContentGen) => {276+ if (!getContentGen) {277+ return278+ }279+ for (const content of getContentGen) {280+ savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281+ }282+ })283+ )284+ }285+ await Promise.all(getInfoPromises)286+ const files: string[] = []287+ for (const savePromise of savePromises) {288+ const fileOrError = await savePromise289+ if (typeof fileOrError === 'string') {290+ files.push(fileOrError)291+ } else if (fileOrError) {292+ throw fileOrError293+ }294+ }295+ result = { success: true, files }296+ } catch (error) {297+ const errorObj = error instanceof Error ? error : new Error(String(error))298+ result = { success: false, files: [], error: errorObj }299+ }300+ await options?.afterGenerateHook?.(result)301+ return result302+}added:src/helper/websocket/index.test.ts+14 added
1+import { createWSMessageEvent } from '.'2+3+describe('`createWSMessageEvent`', () => {4+ it('Should `createWSMessageEvent` is working for string', () => {5+ const randomString = Math.random().toString()6+ const event = createWSMessageEvent(randomString)7+8+ expect(event.data).toBe(randomString)9+ })10+ it('Should `createWSMessageEvent` type is `message`', () => {11+ const event = createWSMessageEvent('')12+ expect(event.type).toBe('message')13+ })14+})added:src/helper/websocket/index.ts+55 added
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+import type { Context } from '../../context'3+import type { MiddlewareHandler } from '../../types'4+5+/**6+ * WebSocket Event Listeners type7+ */8+export interface WSEvents {9+ onOpen?: (evt: Event, ws: WSContext) => void10+ onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext) => void11+ onClose?: (evt: CloseEvent, ws: WSContext) => void12+ onError?: (evt: Event, ws: WSContext) => void13+}14+15+export type UpgradedWebSocketResponseInputJSONType = '__websocket' | undefined16+17+/**18+ * Upgrade WebSocket Type19+ */20+export type UpgradeWebSocket = (21+ createEvents: (c: Context) => WSEvents | Promise<WSEvents>22+) => MiddlewareHandler<23+ any,24+ string,25+ {26+ in: {27+ json: UpgradedWebSocketResponseInputJSONType28+ }29+ }30+>31+32+export type WSReadyState = 0 | 1 | 2 | 333+34+export type WSContext = {35+ send(36+ source: string | ArrayBuffer | Uint8Array,37+ options?: {38+ compress: boolean39+ }40+ ): void41+ raw?: unknown42+ binaryType: BinaryType43+ readyState: WSReadyState44+ url: URL | null45+ protocol: string | null46+ close(code?: number, reason?: string): void47+}48+49+export type WSMessageReceive = string | Blob | ArrayBufferLike50+51+export const createWSMessageEvent = (source: WSMessageReceive): MessageEvent<WSMessageReceive> => {52+ return new MessageEvent<WSMessageReceive>('message', {53+ data: source,54+ })55+}modified:src/jsx/dom/index.test.tsx+75 added-2 removed
1 unmodified line2 import type { FC } from '..'3 // run tests by old style jsx default4 // hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings5 // eslint-disable-next-line @typescript-eslint/no-unused-vars6-import { jsx, Fragment } from '..'6+import { jsx, Fragment, createElement } from '..'7+import DefaultExport from '..'8 import type { RefObject } from '../hooks'9 import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from '../hooks'10 import { memo, isValidElement, cloneElement } from '.'10-import { render, cloneElement as cloneElementForDom } from '.'11+import { render, createElement as createElementForDom, cloneElement as cloneElementForDom } from '.'12 13 describe('DOM', () => {14 beforeAll(() => {15 global.requestAnimationFrame = (cb) => setTimeout(cb)1285 unmodified lines1301 expect(isValidElement({})).toBe(false)1302 })1303 })1304 1305+ describe('createElement', () => {1306+ it('simple', async () => {1307+ const App = () => {1308+ const [count, setCount] = useState(0)1309+ return (1310+ <div>{createElement('p', { onClick: () => setCount(count + 1) }, String(count))}</div>1311+ )1312+ }1313+ const app = <App />1314+ render(app, root)1315+ expect(root.innerHTML).toBe('<div><p>0</p></div>')1316+ root.querySelector('p')?.click()1317+ await Promise.resolve()1318+ expect(root.innerHTML).toBe('<div><p>1</p></div>')1319+ })1320+ })1321+1322+ describe('dom-specific createElement', () => {1323+ it('simple', async () => {1324+ const App = () => {1325+ const [count, setCount] = useState(0)1326+ return <div>{createElementForDom('p', { onClick: () => setCount(count + 1) }, count)}</div>1327+ }1328+ const app = <App />1329+ render(app, root)1330+ expect(root.innerHTML).toBe('<div><p>0</p></div>')1331+ root.querySelector('p')?.click()1332+ await Promise.resolve()1333+ expect(root.innerHTML).toBe('<div><p>1</p></div>')1334+ })1335+ })1336+1337 describe('cloneElement', () => {1338 it('simple', async () => {1339 const App = () => {1340 const [count, setCount] = useState(0)82 unmodified lines1423 expect(createElementNSSpy).toHaveBeenCalledWith('http://www.w3.org/1998/Math/MathML', 'mrow')1424 })1425 })1426 })1427+1428+describe('jsx', () => {1429+ it('exported as an alias of createElement', () => {1430+ expect(jsx).toBeDefined()1431+ expect(jsx('div', {}, 'Hello')).toBeInstanceOf(Object)1432+ })1433+})1434+1435+describe('default export', () => {1436+ ;[1437+ 'memo',1438+ 'Fragment',1439+ 'isValidElement',1440+ 'createElement',1441+ 'cloneElement',1442+ 'ErrorBoundary',1443+ 'createContext',1444+ 'useContext',1445+ 'useState',1446+ 'useEffect',1447+ 'useRef',1448+ 'useCallback',1449+ 'useReducer',1450+ 'useDebugValue',1451+ 'use',1452+ 'startTransition',1453+ 'useTransition',1454+ 'useDeferredValue',1455+ 'startViewTransition',1456+ 'useViewTransition',1457+ 'useMemo',1458+ 'useLayoutEffect',1459+ 'Suspense',1460+ ].forEach((key) => {1461+ it(key, () => {1462+ // eslint-disable-next-line @typescript-eslint/no-explicit-any1463+ expect((DefaultExport as any)[key]).toBeDefined()1464+ })1465+ })1466+})modified:src/jsx/dom/index.ts+79 added-9 removed
1+import type { Props, Child, JSXNode } from '../base'2+import { memo, isValidElement } from '../base'3+import { useContext } from '../context'1-export {4+import {5 useState,6 useEffect,7 useRef,8 useCallback,4 unmodified lines13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17+ useReducer,18+ useDebugValue,19 } from '../hooks'20+import { Suspense, ErrorBoundary } from './components'21+import { createContext } from './context'22+import { jsx } from './jsx-runtime'23+24 export { render } from './render'16-export { Suspense, ErrorBoundary } from './components'17-export { useContext } from '../context'18-export type { Context } from '../context'19-export { createContext } from './context'20-export { memo, isValidElement } from '../base'25 22-import type { Props, Child, JSXNode } from '../base'23-import { jsx } from './jsx-runtime'24-export const cloneElement = <T extends JSXNode | JSX.Element>(26+const createElement = (27+ tag: string | ((props: Props) => JSXNode),28+ props: Props,29+ ...children: Child[]30+): JSXNode => {31+ const jsxProps: Props = { ...props, children }32+ let key = undefined33+ if ('key' in jsxProps) {34+ key = jsxProps.key35+ delete jsxProps.key36+ }37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any38+ return jsx(tag, jsxProps, key) as any39+}40+41+const cloneElement = <T extends JSXNode | JSX.Element>(42 element: T,43 props: Props,44 ...children: Child[]45 ): T => {6 unmodified lines52 },53 (element as JSXNode).key54 ) as T55 }56+57+export {58+ createElement as jsx,59+ useState,60+ useEffect,61+ useRef,62+ useCallback,63+ use,64+ startTransition,65+ useTransition,66+ useDeferredValue,67+ startViewTransition,68+ useViewTransition,69+ useMemo,70+ useLayoutEffect,71+ useReducer,72+ useDebugValue,73+ Suspense,74+ ErrorBoundary,75+ createContext,76+ useContext,77+ memo,78+ isValidElement,79+ createElement,80+ cloneElement,81+}82+83+export default {84+ useState,85+ useEffect,86+ useRef,87+ useCallback,88+ use,89+ startTransition,90+ useTransition,91+ useDeferredValue,92+ startViewTransition,93+ useViewTransition,94+ useMemo,95+ useLayoutEffect,96+ useReducer,97+ useDebugValue,98+ Suspense,99+ ErrorBoundary,100+ createContext,101+ useContext,102+ memo,103+ isValidElement,104+ createElement,105+ cloneElement,106+}107+108+export type { Context } from '../context'modified:src/jsx/hooks/dom.test.tsx+61 added
5 unmodified lines6 import { Suspense } from '../dom'7 import { render } from '../dom'8 import {9 useState,10+ useReducer,11 use,12 startTransition,13 useTransition,14 useDeferredValue,15 startViewTransition,16 useViewTransition,17+ useDebugValue,18 } from '.'19 20+describe('useReducer()', () => {21+ beforeAll(() => {22+ global.requestAnimationFrame = (cb) => setTimeout(cb)23+ })24+25+ let dom: JSDOM26+ let root: HTMLElement27+ beforeEach(() => {28+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {29+ runScripts: 'dangerously',30+ })31+ global.document = dom.window.document32+ global.HTMLElement = dom.window.HTMLElement33+ global.Text = dom.window.Text34+ root = document.getElementById('root') as HTMLElement35+ })36+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>')51+ })52+})53+54 describe('startTransition()', () => {55 beforeAll(() => {56 global.requestAnimationFrame = (cb) => setTimeout(cb)57 })421 unmodified lines479 expect(root.innerHTML).toBe('<div><button>1</button></div>')480 expect(called).toBe(3)481 })482 })483+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',490+ })491+ global.document = dom.window.document492+ global.HTMLElement = dom.window.HTMLElement493+ global.Text = dom.window.Text494+ root = document.getElementById('root') as HTMLElement495+ })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+ })507+})modified:src/jsx/hooks/index.ts+18 added
203 unmodified lines204 },205 ])206 }207 208+export const useReducer = <T, A>(209+ reducer: (state: T, action: A) => T,210+ initialArg: T,211+ init?: (initialState: T) => T212+): [T, (action: A) => void] => {213+ const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))214+ return [215+ state,216+ (action: A) => {217+ setState((state) => reducer(state, action))218+ },219+ ]220+}221+222 const useEffectCommon = (223 index: number,224 effect: () => void | (() => void),225 deps?: readonly unknown[]121 unmodified lines347 memoArray[hookIndex] = [factory(), deps]348 }349 return memoArray[hookIndex][0] as T350 }351+352+// Define to avoid errors. This hook currently does nothing.353+// eslint-disable-next-line @typescript-eslint/no-unused-vars354+export const useDebugValue = (value: unknown, formatter?: (value: unknown) => string): void => {}modified:src/jsx/index.test.tsx+34 added-1 removed
2 unmodified lines3 import { html } from '../helper/html'4 import { Hono } from '../hono'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7-import { jsx, memo, Fragment, createContext, useContext } from '.'7+import DefaultExport, { jsx, memo, Fragment, createContext, useContext } from '.'8 import type { Context, FC, PropsWithChildren } from '.'9 10 interface SiteData {11 title: string707 unmodified lines719 expect(nextRequest.toString()).toBe('<span>light</span>')720 })721 })722 })723+724+describe('default export', () => {725+ ;[726+ 'memo',727+ 'Fragment',728+ 'isValidElement',729+ 'createElement',730+ 'cloneElement',731+ 'ErrorBoundary',732+ 'createContext',733+ 'useContext',734+ 'useState',735+ 'useEffect',736+ 'useRef',737+ 'useCallback',738+ 'useReducer',739+ 'useDebugValue',740+ 'use',741+ 'startTransition',742+ 'useTransition',743+ 'useDeferredValue',744+ 'startViewTransition',745+ 'useViewTransition',746+ 'useMemo',747+ 'useLayoutEffect',748+ 'Suspense',749+ ].forEach((key) => {750+ it(key, () => {751+ // eslint-disable-next-line @typescript-eslint/no-explicit-any752+ expect((DefaultExport as any)[key]).toBeDefined()753+ })754+ })755+})modified:src/jsx/index.ts+60 added-5 removed
1-export { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2-export { ErrorBoundary } from './components'3-export { Suspense } from './streaming'4-export {1+import { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2+import { ErrorBoundary } from './components'3+import { createContext, useContext } from './context'4+import {5 useState,6 useEffect,7 useRef,8 useCallback,4 unmodified lines13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17+ useReducer,18+ useDebugValue,19 } from './hooks'18-export { createContext, useContext } from './context'20+import { Suspense } from './streaming'21 22+export {23+ jsx,24+ memo,25+ Fragment,26+ isValidElement,27+ jsx as createElement,28+ cloneElement,29+ ErrorBoundary,30+ createContext,31+ useContext,32+ useState,33+ useEffect,34+ useRef,35+ useCallback,36+ useReducer,37+ useDebugValue,38+ use,39+ startTransition,40+ useTransition,41+ useDeferredValue,42+ startViewTransition,43+ useViewTransition,44+ useMemo,45+ useLayoutEffect,46+ Suspense,47+}48+49+export default {50+ memo,51+ Fragment,52+ isValidElement,53+ createElement: jsx,54+ cloneElement,55+ ErrorBoundary,56+ createContext,57+ useContext,58+ useState,59+ useEffect,60+ useRef,61+ useCallback,62+ useReducer,63+ useDebugValue,64+ use,65+ startTransition,66+ useTransition,67+ useDeferredValue,68+ startViewTransition,69+ useViewTransition,70+ useMemo,71+ useLayoutEffect,72+ Suspense,73+}74+75 // TODO: change to `export type *` after denoify bug is fixed76 // https://github.com/garronej/denoify/issues/12477 export * from './types'added:src/middleware/body-limit/index.test.ts+143 added
1+import { Hono } from '../../hono'2+import { bodyLimit } from '.'3+4+const GlobalRequest = globalThis.Request5+globalThis.Request = class Request extends GlobalRequest {6+ constructor(input: Request | string, init: RequestInit) {7+ if (init) {8+ // eslint-disable-next-line @typescript-eslint/no-explicit-any9+ ;(init as any).duplex ??= 'half'10+ }11+ super(input, init)12+ }13+} as typeof GlobalRequest14+15+const buildRequestInit = (init: RequestInit = {}): RequestInit => {16+ const headers: Record<string, string> = {17+ 'Content-Type': 'text/plain',18+ }19+ if (typeof init.body === 'string') {20+ headers['Content-Length'] = init.body.length.toString()21+ }22+ return {23+ method: 'POST',24+ headers,25+ body: null,26+ ...init,27+ }28+}29+30+describe('Body Limit Middleware', () => {31+ let app: Hono32+33+ const exampleText = 'hono is so cool' // 15byte34+ const exampleText2 = 'hono is so cool and cute' // 24byte35+36+ beforeEach(() => {37+ app = new Hono()38+ app.use('*', bodyLimit({ maxSize: 15 }))39+ app.get('/', (c) => c.text('index'))40+ app.post('/body-limit-15byte', async (c) => {41+ return c.text(await c.req.raw.text())42+ })43+ })44+45+ describe('GET request', () => {46+ it('should return 200 response', async () => {47+ const res = await app.request('/')48+ expect(res).not.toBeNull()49+ expect(res.status).toBe(200)50+ expect(await res.text()).toBe('index')51+ })52+ })53+54+ describe('POST request', () => {55+ describe('string body', () => {56+ it('should return 200 response', async () => {57+ const res = await app.request('/body-limit-15byte', buildRequestInit({ body: exampleText }))58+59+ expect(res).not.toBeNull()60+ expect(res.status).toBe(200)61+ expect(await res.text()).toBe(exampleText)62+ })63+64+ it('should return 413 response', async () => {65+ const res = await app.request(66+ '/body-limit-15byte',67+ buildRequestInit({ body: exampleText2 })68+ )69+70+ expect(res).not.toBeNull()71+ expect(res.status).toBe(413)72+ expect(await res.text()).toBe('Payload Too Large')73+ })74+ })75+76+ describe('ReadableStream body', () => {77+ it('should return 200 response', async () => {78+ const contents = ['a', 'b', 'c']79+ const stream = new ReadableStream({80+ start(controller) {81+ while (contents.length) {82+ controller.enqueue(new TextEncoder().encode(contents.shift() as string))83+ }84+ controller.close()85+ },86+ })87+ const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))88+89+ expect(res).not.toBeNull()90+ expect(res.status).toBe(200)91+ expect(await res.text()).toBe('abc')92+ })93+94+ it('should return 413 response', async () => {95+ const readSpy = vi.fn().mockImplementation(() => {96+ return {97+ done: false,98+ value: new TextEncoder().encode(exampleText),99+ }100+ })101+ const stream = new ReadableStream()102+ vi.spyOn(stream, 'getReader').mockReturnValue({103+ read: readSpy,104+ } as unknown as ReadableStreamDefaultReader)105+ const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))106+107+ expect(res).not.toBeNull()108+ expect(res.status).toBe(413)109+ expect(readSpy).toHaveBeenCalledTimes(2)110+ expect(await res.text()).toBe('Payload Too Large')111+ })112+ })113+ })114+115+ describe('custom error handler', () => {116+ beforeEach(() => {117+ app = new Hono()118+ app.post(119+ '/text-limit-15byte-custom',120+ bodyLimit({121+ maxSize: 15,122+ onError: (c) => {123+ return c.text('no', 413)124+ },125+ }),126+ (c) => {127+ return c.text('yes')128+ }129+ )130+ })131+132+ it('should return the custom error handler', async () => {133+ const res = await app.request(134+ '/text-limit-15byte-custom',135+ buildRequestInit({ body: exampleText2 })136+ )137+138+ expect(res).not.toBeNull()139+ expect(res.status).toBe(413)140+ expect(await res.text()).toBe('no')141+ })142+ })143+})added:src/middleware/body-limit/index.ts+96 added
1+import type { Context } from '../../context'2+import { HTTPException } from '../../http-exception'3+import type { MiddlewareHandler } from '../../types'4+5+const ERROR_MESSAGE = 'Payload Too Large'6+7+type OnError = (c: Context) => Response | Promise<Response>8+type BodyLimitOptions = {9+ maxSize: number10+ onError?: OnError11+}12+13+class BodyLimitError extends Error {14+ constructor(message: string) {15+ super(message)16+ this.name = 'BodyLimitError'17+ }18+}19+20+/**21+ * Body Limit Middleware22+ *23+ * @example24+ * ```ts25+ * app.post(26+ * '/hello',27+ * bodyLimit({28+ * maxSize: 100 * 1024, // 100kb29+ * onError: (c) => {30+ * return c.text('overflow :(', 413)31+ * }32+ * }),33+ * (c) => {34+ * return c.text('pass :)')35+ * }36+ * )37+ * ```38+ */39+export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40+ const onError: OnError =41+ options.onError ||42+ (() => {43+ const res = new Response(ERROR_MESSAGE, {44+ status: 413,45+ })46+ throw new HTTPException(413, { res })47+ })48+ const maxSize = options.maxSize49+50+ return async function bodyLimit(c, next) {51+ if (!c.req.raw.body) {52+ // maybe GET or HEAD request53+ return next()54+ }55+56+ if (c.req.raw.headers.has('content-length')) {57+ // we can trust content-length header because it's already validated by server58+ const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59+ return contentLength > maxSize ? onError(c) : next()60+ }61+62+ // maybe chunked transfer encoding63+64+ let size = 065+ const rawReader = c.req.raw.body.getReader()66+ const reader = new ReadableStream({67+ async start(controller) {68+ try {69+ for (;;) {70+ const { done, value } = await rawReader.read()71+ if (done) {72+ break73+ }74+ size += value.length75+ if (size > maxSize) {76+ controller.error(new BodyLimitError(ERROR_MESSAGE))77+ break78+ }79+80+ controller.enqueue(value)81+ }82+ } finally {83+ controller.close()84+ }85+ },86+ })87+88+ c.req.raw = new Request(c.req.raw, { body: reader })89+90+ await next()91+92+ if (c.error instanceof BodyLimitError) {93+ c.res = await onError(c)94+ }95+ }96+}modified:src/middleware/logger/index.test.ts+77 added
72 unmodified lines73 expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)74 expect(log).toMatch(/m?s$/)75 })76 })77+78+describe('Logger by Middleware in NO_COLOR', () => {79+ let app: Hono80+ let log: string81+82+ beforeEach(() => {83+ vi.stubEnv('NO_COLOR', '1')84+ function sleep(time: number) {85+ return new Promise((resolve) => setTimeout(resolve, time))86+ }87+88+ app = new Hono()89+90+ const logFn = (str: string) => {91+ log = str92+ }93+94+ const shortRandomString = 'hono'95+ const longRandomString = 'hono'.repeat(1000)96+97+ app.use('*', logger(logFn))98+ app.get('/short', (c) => c.text(shortRandomString))99+ app.get('/long', (c) => c.text(longRandomString))100+ app.get('/seconds', async (c) => {101+ await sleep(1000)102+103+ return c.text(longRandomString)104+ })105+ app.get('/empty', (c) => c.text(''))106+ })107+ afterAll(() => {108+ vi.unstubAllEnvs()109+ })110+ it('Log status 200 with empty body', async () => {111+ const res = await app.request('http://localhost/empty')112+ expect(res).not.toBeNull()113+ expect(res.status).toBe(200)114+ expect(log.startsWith(' --> GET /empty 200')).toBe(true)115+ expect(log).toMatch(/m?s$/)116+ })117+118+ it('Log status 200 with small body', async () => {119+ const res = await app.request('http://localhost/short')120+ expect(res).not.toBeNull()121+ expect(res.status).toBe(200)122+ expect(log.startsWith(' --> GET /short 200')).toBe(true)123+ expect(log).toMatch(/m?s$/)124+ })125+126+ it('Log status 200 with big body', async () => {127+ const res = await app.request('http://localhost/long')128+ expect(res).not.toBeNull()129+ expect(res.status).toBe(200)130+ expect(log.startsWith(' --> GET /long 200')).toBe(true)131+ expect(log).toMatch(/m?s$/)132+ })133+134+ it('Time in seconds', async () => {135+ const res = await app.request('http://localhost/seconds')136+ expect(res).not.toBeNull()137+ expect(res.status).toBe(200)138+ expect(log.startsWith(' --> GET /seconds 200')).toBe(true)139+ expect(log).toMatch(/1s/)140+ })141+142+ it('Log status 404', async () => {143+ const msg = 'Default 404 Not Found'144+ app.all('*', (c) => {145+ return c.text(msg, 404)146+ })147+ const res = await app.request('http://localhost/notfound')148+ expect(res).not.toBeNull()149+ expect(res.status).toBe(404)150+ expect(log.startsWith(' --> GET /notfound 404')).toBe(true)151+ expect(log).toMatch(/m?s$/)152+ })153+})modified:src/middleware/logger/index.ts+9 added-7 removed
1 import type { MiddlewareHandler } from '../../types'2+import { getColorEnabled } from '../../utils/color'3 import { getPath } from '../../utils/url'4 5 enum LogPrefix {6 Outgoing = '-->',14 unmodified lines21 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])22 }23 24 const colorStatus = (status: number) => {25+ const colorEnabled = getColorEnabled()26 const out: { [key: string]: string } = {25- 7: `\x1b[35m${status}\x1b[0m`,26- 5: `\x1b[31m${status}\x1b[0m`,27- 4: `\x1b[33m${status}\x1b[0m`,28- 3: `\x1b[36m${status}\x1b[0m`,29- 2: `\x1b[32m${status}\x1b[0m`,30- 1: `\x1b[32m${status}\x1b[0m`,31- 0: `\x1b[33m${status}\x1b[0m`,27+ 7: colorEnabled ? `\x1b[35m${status}\x1b[0m` : `${status}`,28+ 5: colorEnabled ? `\x1b[31m${status}\x1b[0m` : `${status}`,29+ 4: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,30+ 3: colorEnabled ? `\x1b[36m${status}\x1b[0m` : `${status}`,31+ 2: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,32+ 1: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,33+ 0: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,34 }35 36 const calculateStatus = (status / 100) | 037 35 unmodified linesadded:src/utils/color.test.ts+18 added
1+import { getColorEnabled } from './color'2+3+describe('getColorEnabled()', () => {4+ it('getColorEnabled() is true', async () => {5+ expect(getColorEnabled()).toBe(true)6+ })7+})8+describe('getColorEnabled() in NO_COLOR', () => {9+ beforeAll(() => {10+ vi.stubEnv('NO_COLOR', '1')11+ })12+ afterAll(() => {13+ vi.unstubAllEnvs()14+ })15+ it('getColorEnabled() is false', async () => {16+ expect(getColorEnabled()).toBe(false)17+ })18+})added:src/utils/color.ts+12 added
1+export function getColorEnabled() {2+ // eslint-disable-next-line @typescript-eslint/no-explicit-any3+ const { process, Deno } = globalThis as any4+ const isNoColor =5+ typeof process !== 'undefined'6+ ? // eslint-disable-next-line no-unsafe-optional-chaining7+ 'NO_COLOR' in process?.env8+ : typeof Deno?.noColor === 'boolean'9+ ? (Deno.noColor as boolean)10+ : false11+ return !isNoColor12+}added:src/utils/concurrent.test.ts+69 added
1+import { createPool } from './concurrent'2+3+describe('concurrent execution', () => {4+ test.each`5+ concurrency | count6+ ${1} | ${10}7+ ${10} | ${10}8+ ${100} | ${10}9+ ${Infinity} | ${2000}10+ `('concurrency $concurrency, count $count', async ({ concurrency, count }) => {11+ const running = new Set()12+13+ const pool = createPool({ concurrency })14+ let resolve: (() => void) | undefined15+ const promise = new Promise<void>((r) => {16+ resolve = r17+ })18+ const fn = async (i: number) => {19+ if (running.size > concurrency) {20+ throw new Error('concurrency exceeded')21+ }22+23+ running.add(i)24+ await promise25+ running.delete(i)26+ return i27+ }28+29+ const jobs = new Array(count).fill(0).map((_, i) => () => fn(i))30+ const expectedResults = new Array(count).fill(0).map((_, i) => i)31+ const resultPromises = jobs.map((job) => pool.run(job))32+33+ expect(running.size).toBe(Math.min(concurrency, count))34+ resolve?.()35+ const results = await Promise.all(resultPromises)36+ expect(running.size).toBe(0)37+ expect(results).toEqual(expectedResults)38+ })39+40+ describe('with interval', () => {41+ test.each`42+ concurrency | interval43+ ${1} | ${10}44+ ${2} | ${10}45+ `('concurrency $concurrency, interval $interval', async ({ concurrency, interval }) => {46+ const workingTimeQueue: number[] = []47+ const pool = createPool({ concurrency, interval })48+ const fn = async (i: number) => {49+ const now = Date.now()50+ if (workingTimeQueue.length >= concurrency) {51+ const last = workingTimeQueue.shift()52+ // Not so accurate, -1 ms is acceptable53+ if (last && now - last < interval - 1) {54+ throw new Error('interval violated')55+ }56+ }57+ workingTimeQueue.push(now)58+ return i59+ }60+61+ const jobs = new Array(10).fill(0).map((_, i) => () => fn(i))62+ const expectedResults = new Array(10).fill(0).map((_, i) => i)63+ const resultPromises = jobs.map((job) => pool.run(job))64+65+ const results = await Promise.all(resultPromises)66+ expect(results).toEqual(expectedResults)67+ })68+ })69+})added:src/utils/concurrent.ts+50 added
1+const DEFAULT_CONCURRENCY = 10242+3+export interface Pool {4+ run<T>(fn: () => T): Promise<T>5+}6+7+export const createPool = ({8+ concurrency,9+ interval,10+}: {11+ concurrency?: number12+ interval?: number13+} = {}): Pool => {14+ concurrency ||= DEFAULT_CONCURRENCY15+16+ if (concurrency === Infinity) {17+ // unlimited18+ return {19+ run: async (fn) => fn(),20+ }21+ }22+23+ const pool: Set<{}> = new Set()24+ const run = async <T>(25+ fn: () => T,26+ promise?: Promise<T>,27+ resolve?: (result: T) => void28+ ): Promise<T> => {29+ if (pool.size >= (concurrency as number)) {30+ promise ||= new Promise<T>((r) => (resolve = r))31+ setTimeout(() => run(fn, promise, resolve))32+ return promise33+ }34+ const marker = {}35+ pool.add(marker)36+ const result = await fn()37+ if (interval) {38+ setTimeout(() => pool.delete(marker), interval)39+ } else {40+ pool.delete(marker)41+ }42+ if (resolve) {43+ resolve(result)44+ return promise as Promise<T>45+ } else {46+ return result47+ }48+ }49+ return { run }50+}modified:src/utils/cookie.test.ts+81 added-2 removed
152 unmodified lines153 expect(serialized).toBe('delicious_cookie=macha')154 })155 156 it('Should serialize cookie with all options', () => {157- const serialized = serialize('great_cookie', 'banana', {157+ const serialized = serialize('__Secure-great_cookie', 'banana', {158 path: '/',159 secure: true,160 domain: 'example.com',161 httpOnly: true,2 unmodified lines164 sameSite: 'Strict',165 partitioned: true,166 })167 expect(serialized).toBe(168- 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'168+ '__Secure-great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'169 )170 })171 172+ it('Should serialize __Host- cookie with all valid options', () => {173+ const serialized = serialize('__Host-great_cookie', 'banana', {174+ path: '/',175+ secure: true,176+ httpOnly: true,177+ maxAge: 1000,178+ expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),179+ sameSite: 'Strict',180+ partitioned: true,181+ })182+ expect(serialized).toBe(183+ '__Host-great_cookie=banana; Max-Age=1000; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'184+ )185+ })186+187 it('Should serialize a signed cookie', async () => {188 const secret = 'secret chocolate chips'189 const serialized = await serializeSigned('delicious_cookie', 'macha', secret)190 expect(serialized).toBe(30 unmodified lines221 maxAge: -1,222 })223 expect(serialized).toBe('great_cookie=banana')224 })225+226+ it('Should throw Error cookie with maxAge grater than 400days', () => {227+ expect(() => {228+ serialize('great_cookie', 'banana', {229+ maxAge: 3600 * 24 * 401,230+ })231+ }).toThrowError(232+ 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'233+ )234+ })235+236+ it('Should throw Error cookie with expires grater than 400days', () => {237+ const now = Date.now()238+ const day401 = new Date(now + 1000 * 3600 * 24 * 401)239+ expect(() => {240+ serialize('great_cookie', 'banana', {241+ expires: day401,242+ })243+ }).toThrowError(244+ 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'245+ )246+ })247+248+ it('Should throw Error __Secure- cookie without Secure attributes', () => {249+ expect(() => {250+ serialize('__Secure-great_cookie', 'banana', {})251+ }).toThrowError('__Secure- Cookie must have Secure attributes')252+ })253+254+ it('Should throw Error __Host- cookie without Secure attributes', () => {255+ expect(() => {256+ serialize('__Host-great_cookie', 'banana', {257+ secure: false,258+ path: '/',259+ })260+ }).toThrowError('__Host- Cookie must have Secure attributes')261+ })262+263+ it('Should throw Error __Host- cookie without Path attributes with "/"', () => {264+ expect(() => {265+ serialize('__Host-great_cookie', 'banana', {266+ secure: true,267+ path: '/admin',268+ })269+ }).toThrowError('__Host- Cookie must have Path attributes with "/"')270+ })271+272+ it('Should throw Error __Host- cookie with Domain attributes', () => {273+ expect(() => {274+ serialize('__Host-great_cookie', 'banana', {275+ secure: true,276+ path: '/',277+ domain: 'site.example',278+ })279+ }).toThrowError('__Host- Cookie must not have Domain attributes')280+ })281+282+ it('Should throw Error Partitioned cookie without Secure attributes', () => {283+ expect(() => {284+ serialize('great_cookie', 'banana', {285+ partitioned: true,286+ })287+ }).toThrowError('Partitioned Cookie must have Secure attributes')288+ })289 })modified:src/utils/cookie.ts+44 added-1 removed
10 unmodified lines11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15+ prefix?: CookiePrefixOptions16 }17+export type CookiePrefixOptions = 'host' | 'secure'18 19 const algorithm = { name: 'HMAC', hash: 'SHA-256' }20 21 const getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {91 unmodified lines113 114 const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {115 let cookie = `${name}=${value}`116 117+ if (name.startsWith('__Secure-') && !opt.secure) {118+ // FIXME: replace link to RFC119+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1120+ throw new Error('__Secure- Cookie must have Secure attributes')121+ }122+123+ if (name.startsWith('__Host-')) {124+ // FIXME: replace link to RFC125+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2126+ if (!opt.secure) {127+ throw new Error('__Host- Cookie must have Secure attributes')128+ }129+130+ if (opt.path !== '/') {131+ throw new Error('__Host- Cookie must have Path attributes with "/"')132+ }133+134+ if (opt.domain) {135+ throw new Error('__Host- Cookie must not have Domain attributes')136+ }137+ }138+139 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {140+ if (opt.maxAge > 34560000) {141+ // FIXME: replace link to RFC142+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2143+ throw new Error(144+ 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'145+ )146+ }147 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`148 }149 119- if (opt.domain) {150+ if (opt.domain && opt.prefix !== 'host') {151 cookie += `; Domain=${opt.domain}`152 }153 154 if (opt.path) {155 cookie += `; Path=${opt.path}`156 }157 158 if (opt.expires) {159+ if (opt.expires.getTime() - Date.now() > 34560000_000) {160+ // FIXME: replace link to RFC161+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1162+ throw new Error(163+ 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'164+ )165+ }166 cookie += `; Expires=${opt.expires.toUTCString()}`167 }168 169 if (opt.httpOnly) {8 unmodified lines178 cookie += `; SameSite=${opt.sameSite}`179 }180 181 if (opt.partitioned) {182+ // FIXME: replace link to RFC183+ // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3184+ if (!opt.secure) {185+ throw new Error('Partitioned Cookie must have Secure attributes')186+ }187 cookie += '; Partitioned'188 }189 190 return cookie18 unmodified linesmodified:src/helper.ts+1 added
7 unmodified lines8 export * from './helper/streaming'9 export * from './helper/testing'10 export * from './helper/dev'11 export * from './adapter/deno/ssg'12+export * from './adapter/deno/websocket'modified:src/http-exception.test.ts+22 added-3 removed
1 import { HTTPException } from './http-exception'2 3-describe('HTTPFatalError', () => {4- it('Should be 401 HTTP exception object', () => {3+describe('HTTPException', () => {4+ it('Should be 401 HTTP exception object', async () => {5 // We should throw an exception if is not authorized6 // because next handlers should not be fired.7 const exception = new HTTPException(401, {8 message: 'Unauthorized',9 })10+ const res = exception.getResponse()11+12+ expect(res.status).toBe(401)13+ expect(await res.text()).toBe('Unauthorized')14 expect(exception.status).toBe(401)15 expect(exception.message).toBe('Unauthorized')16+ })17+18+ it('Should be accessible to the object causing the exception', async () => {19+ // We should pass the cause of the error to the cause option20+ // because it makes debugging easier.21+ const error = new Error('Server Error')22+ const exception = new HTTPException(500, {23+ message: 'Internal Server Error',24+ cause: error,25+ })26 const res = exception.getResponse()27+13- expect(res.status).toBe(401)28+ expect(res.status).toBe(500)29+ expect(await res.text()).toBe('Internal Server Error')30+ expect(exception.status).toBe(500)31+ expect(exception.message).toBe('Internal Server Error')32+ expect(exception.cause).toBe(error)33 })34 })modified:src/http-exception.ts+4 added-1 removed
1 unmodified line2 3 type HTTPExceptionOptions = {4 res?: Response5 message?: string6+ cause?: unknown7 }8 9 /**10 * `HTTPException` must be used when a fatal error such as authentication failure occurs.15 unmodified lines26 */27 export class HTTPException extends Error {28 readonly res?: Response29 readonly status: StatusCode30+31 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {30- super(options?.message)32+ super(options?.message, { cause: options?.cause })33 this.res = options?.res34 this.status = status35 }36+37 getResponse(): Response {38 if (this.res) {39 return this.res40 }5 unmodified linesmodified:src/middleware.ts+1 added
1 // This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth'3 export * from './middleware/bearer-auth'4+export * from './middleware/body-limit'5 export * from './middleware/cache'6 export * from './middleware/compress'7 export * from './middleware/cors'8 export * from './middleware/csrf'10 unmodified linesmodified:bun.lockbbinary
A binary file, modified.
modified:package.json+19 added-3 removed
1 {2 "name": "hono",3- "version": "4.0.10",3+ "version": "4.1.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",65 unmodified lines73 "types": "./dist/types/middleware/bearer-auth/index.d.ts",74 "import": "./dist/middleware/bearer-auth/index.js",75 "require": "./dist/cjs/middleware/bearer-auth/index.js"76 },77+ "./body-limit": {78+ "types": "./dist/types/middleware/body-limit/index.d.ts",79+ "import": "./dist/middleware/body-limit/index.js",80+ "require": "./dist/cjs/middleware/body-limit/index.js"81+ },82 "./cache": {83 "types": "./dist/types/middleware/cache/index.d.ts",84 "import": "./dist/middleware/cache/index.js",85 "require": "./dist/cjs/middleware/cache/index.js"231 unmodified lines317 "./dev": {318 "types": "./dist/types/helper/dev/index.d.ts",319 "import": "./dist/helper/dev/index.js",320 "require": "./dist/cjs/helper/dev/index.js"321+ },322+ "./ws": {323+ "types": "./dist/types/helper/websocket/index.d.ts",324+ "import": "./dist/helper/websocket/index.js",325+ "require": "./dist/cjs/helper/websocket/index.js"326 }327 },328 "typesVersions": {329 "*": {17 unmodified lines347 ],348 "bearer-auth": [349 "./dist/types/middleware/bearer-auth"350 ],351+ "body-limit": [352+ "./dist/types/middleware/body-limit"353+ ],354 "cache": [355 "./dist/types/middleware/cache"356 ],357 "cookie": [129 unmodified lines487 "./dist/types/helper/testing"488 ],489 "dev": [490 "./dist/types/helper/dev"491+ ],492+ "ws": [493+ "./dist/types/helper/websocket"494 ]495 }496 },497 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",25 unmodified lines523 ],524 "devDependencies": {525 "@cloudflare/workers-types": "^4.20231121.0",526 "@hono/eslint-config": "^0.0.4",511- "@hono/node-server": "^1.3.3",527+ "@hono/node-server": "^1.8.2",528 "@types/crypto-js": "^4.1.1",529 "@types/glob": "^8.0.0",530 "@types/jsdom": "^21.1.4",531 "@types/node": "20.11.4",21 unmodified lines553 },554 "engines": {555 "node": ">=16.0.0"556 }541-}557+}modified:tsconfig.json+2 added-2 removed
1 {2 "compilerOptions": {3- "target": "ES2020",3+ "target": "ES2022",4 "declaration": true,5 "moduleResolution": "Bundler",6 "outDir": "./dist",7 "esModuleInterop": true,16 unmodified lines24 "src/**/*.mts",25 "src/**/*.test.ts",26 "src/**/*.test.tsx"27 ],28-}28+}modified:yarn.lock+5 added-5 removed
1 # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2 # yarn lockfile v13-# bun ./bun.lockb --hash: 71DE5A52207AB6DA-7e1bfe1f417d1f54-AEA1FB1F9EC7B654-4b7f874b4eade45b3+# bun ./bun.lockb --hash: 03E95F4C55D78A53-2aac63394bface86-D16648EEBEA28A46-92573638c505f9254 5 6 "@aashutoshrathi/word-wrap@^1.2.3":7 version "1.2.6"466 unmodified lines474 eslint-import-resolver-typescript "^3.6.1"475 eslint-plugin-import "^2.29.0"476 eslint-plugin-node "^11.1.0"477 478-"@hono/node-server@^1.3.3":479- version "1.5.0"480- resolved "https://registry.npmjs.org/@hono/node-server/-/node-server-1.5.0.tgz"481- integrity sha512-xMZW2tuHLdUtx5B28E5bsLazJe9NVU2z4QW/Xefgvg41U84r4L1mTxNutTMNwt6BrRujy7hs1aKyUpIuSqcXtQ==478+"@hono/node-server@^1.8.2":479+ version "1.8.2"480+ resolved "https://registry.npmjs.org/@hono/node-server/-/node-server-1.8.2.tgz"481+ integrity sha512-h8l2TBLCPHZBUrrkosZ6L5CpBLj6zdESyF4B+zngiCDF7aZFQJ0alVbLx7jn8PCVi9EyoFf8a4hOZFi1tD95EA==482 483 "@humanwhocodes/config-array@^0.11.13":484 version "0.11.14"485 resolved "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz"6013 unmodified lines