Merge pull request #3144 from honojs/next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parents 2d01359, c632511 · Browse files · 75 files·+5289 added−253 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
75 files+5289 added−253 removed
- tests:+3403 added−28 removed
- other:+1886 added−225 removed
Provenance
- Commit
2f4bb3e- Tree
9336ecb- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
2d01359- Parent 2
c632511
75 files changed+5289 added−253 removed
modified:runtime_tests/deno-jsx/deno.precompile.json+2 added-1 removed
2 unmodified lines345677891011125 unmodified lines2 unmodified lines "jsx": "precompile", "jsxImportSource": "hono/jsx", "lib": [ "deno.ns", "dom" "dom", "dom.iterable" ] }, "unstable": [ "sloppy-imports"5 unmodified linesmodified:runtime_tests/deno-jsx/deno.react-jsx.json+2 added-1 removed
2 unmodified lines345677891011125 unmodified lines2 unmodified lines "jsx": "react-jsx", "jsxImportSource": "hono/jsx", "lib": [ "deno.ns", "dom" "dom", "dom.iterable" ] }, "unstable": [ "sloppy-imports"5 unmodified linesmodified:src/adapter/bun/conninfo.test.ts+19 added-4 removed
123445656789101112131415161718192014212223242520 unmodified lines4647484950515253545556575859606110 unmodified linesimport { Context } from '../../context'import { getConnInfo } from './conninfo'import type { AddressType } from '../../helper/conninfo'
const createRandomBunServer = () => { const address = Math.random().toString() const port = Math.floor(Math.random() * (65535 + 1))const createRandomBunServer = ({ address = Math.random().toString(), port = Math.floor(Math.random() * (65535 + 1)), family = 'IPv6',}: { address?: string port?: number family?: AddressType | string} = {}) => { return { address, port, server: { requestIP() { return { address, family: 'IPv6', family, port, } }, },20 unmodified lines expect(info.remote.address).toBe(address) expect(info.remote.addressType).toBe('IPv6') expect(info.remote.transport).toBeUndefined() }) it('should return undefined when addressType is invalid string', () => { const { server } = createRandomBunServer({ family: 'invalid' }) const c = new Context(new Request('http://localhost/'), { env: { server } })
const info = getConnInfo(c)
expect(info.remote.addressType).toBeUndefined() }) it('Should throw error when user did not give server', () => { const c = new Context(new Request('http://localhost/'), { env: {} })
expect(() => getConnInfo(c)).toThrowError(TypeError)10 unmodified linesmodified:src/adapter/bun/conninfo.ts+1 added-1 removed
19 unmodified lines2021222324242526272819 unmodified lines
return { remote: { address: info.address, addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : 'unknown', addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : undefined, port: info.port, }, }}modified:src/adapter/cloudflare-pages/handler.test.ts+231 added-10 removed
1+import { getCookie } from '../../helper/cookie'2 import { Hono } from '../../hono'3+import { HTTPException } from '../../http-exception'4 import type { EventContext } from './handler'3-import { handle } from './handler'5+import { handle, handleMiddleware, serveStatic } from './handler'6 7 type Env = {8 Bindings: {9 TOKEN: string8- eventContext: EventContext10 }11 }12 13+function createEventContext(14+ context: Partial<EventContext<Env['Bindings']>>15+): EventContext<Env['Bindings']> {16+ return {17+ data: {},18+ env: {19+ ...context.env,20+ ASSETS: { fetch: vi.fn(), ...context.env?.ASSETS },21+ TOKEN: context.env?.TOKEN ?? 'HONOISCOOL',22+ },23+ functionPath: '_worker.js',24+ next: vi.fn(),25+ params: {},26+ passThroughOnException: vi.fn(),27+ request: new Request('http://localhost/api/foo'),28+ waitUntil: vi.fn(),29+ ...context,30+ }31+}32+33 describe('Adapter for Cloudflare Pages', () => {34 it('Should return 200 response', async () => {35 const request = new Request('http://localhost/api/foo')36 const env = {37+ ASSETS: { fetch },38 TOKEN: 'HONOISCOOL',39 }40+ const waitUntil = vi.fn()41+ const passThroughOnException = vi.fn()42+ const eventContext = createEventContext({43+ request,44+ env,45+ waitUntil,46+ passThroughOnException,47+ })48 const app = new Hono<Env>()49+ const appFetchSpy = vi.spyOn(app, 'fetch')50 app.get('/api/foo', (c) => {20- const reqInEventContext = c.env.eventContext.request21- return c.json({ TOKEN: c.env.TOKEN, requestURL: reqInEventContext.url })51+ return c.json({ TOKEN: c.env.TOKEN, requestURL: c.req.url })52 })53 const handler = handle(app)24- // eslint-disable-next-line @typescript-eslint/ban-ts-comment25- // @ts-ignore26- const res = await handler({ request, env })54+ const res = await handler(eventContext)55+ expect(appFetchSpy).toHaveBeenCalledWith(56+ request,57+ { ...env, eventContext },58+ { waitUntil, passThroughOnException }59+ )60 expect(res.status).toBe(200)61 expect(await res.json()).toEqual({62 TOKEN: 'HONOISCOOL',63 requestURL: 'http://localhost/api/foo',1 unmodified line65 })66 67 it('Should not use `basePath()` if path argument is not passed', async () => {68 const request = new Request('http://localhost/api/error')69+ const eventContext = createEventContext({ request })70 const app = new Hono().basePath('/api')71 72 app.onError((e) => {73 throw e3 unmodified lines77 })78 79 const handler = handle(app)80 // It does throw the error if app is NOT "subApp"47- // eslint-disable-next-line @typescript-eslint/ban-ts-comment48- // @ts-ignore49- expect(() => handler({ request })).toThrowError('Custom Error')81+ expect(() => handler(eventContext)).toThrowError('Custom Error')82 })83 })84+85+describe('Middleware adapter for Cloudflare Pages', () => {86+ it('Should return the middleware response', async () => {87+ const request = new Request('http://localhost/api/foo', {88+ headers: {89+ Cookie: 'my_cookie=1234',90+ },91+ })92+ const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))93+ const eventContext = createEventContext({ request, next })94+ const handler = handleMiddleware(async (c, next) => {95+ const cookie = getCookie(c, 'my_cookie')96+97+ await next()98+99+ return c.json({ cookie, response: await c.res.json() })100+ })101+102+ const res = await handler(eventContext)103+104+ expect(next).toHaveBeenCalled()105+106+ expect(await res.json()).toEqual({107+ cookie: '1234',108+ response: 'From Cloudflare Pages',109+ })110+ })111+112+ it('Should return the middleware response when exceptions are handled', async () => {113+ const request = new Request('http://localhost/api/foo')114+ const handler = handleMiddleware(async (c, next) => {115+ await next()116+117+ return c.json({ error: c.error?.message })118+ })119+120+ const next = vi.fn().mockRejectedValue(new Error('Error from next()'))121+ const eventContext = createEventContext({ request, next })122+ const res = await handler(eventContext)123+124+ expect(next).toHaveBeenCalled()125+126+ expect(await res.json()).toEqual({127+ error: 'Error from next()',128+ })129+ })130+131+ it('Should return the middleware response if next() is not called', async () => {132+ const request = new Request('http://localhost/api/foo')133+ const handler = handleMiddleware(async (c) => {134+ return c.json({ response: 'Skip Cloudflare Pages' })135+ })136+137+ const next = vi.fn()138+ const eventContext = createEventContext({ request, next })139+ const res = await handler(eventContext)140+141+ expect(next).not.toHaveBeenCalled()142+143+ expect(await res.json()).toEqual({144+ response: 'Skip Cloudflare Pages',145+ })146+ })147+148+ it('Should return the Pages response if the middleware does not return a response', async () => {149+ const request = new Request('http://localhost/api/foo')150+ const handler = handleMiddleware((c, next) => next())151+152+ const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))153+ const eventContext = createEventContext({ request, next })154+ const res = await handler(eventContext)155+156+ expect(next).toHaveBeenCalled()157+158+ expect(await res.json()).toEqual('From Cloudflare Pages')159+ })160+161+ it('Should handle a HTTPException by returning error.getResponse()', async () => {162+ const request = new Request('http://localhost/api/foo')163+ const handler = handleMiddleware(() => {164+ const res = new Response('Unauthorized', { status: 401 })165+ throw new HTTPException(401, { res })166+ })167+168+ const next = vi.fn()169+ const eventContext = createEventContext({ request, next })170+ const res = await handler(eventContext)171+172+ expect(next).not.toHaveBeenCalled()173+174+ expect(res.status).toBe(401)175+ expect(await res.text()).toBe('Unauthorized')176+ })177+178+ it('Should handle an HTTPException thrown by next()', async () => {179+ const request = new Request('http://localhost/api/foo')180+ const handler = handleMiddleware((c, next) => next())181+182+ const next = vi183+ .fn()184+ .mockRejectedValue(new HTTPException(401, { res: Response.json('Unauthorized') }))185+ const eventContext = createEventContext({ request, next })186+ const res = await handler(eventContext)187+188+ expect(next).toHaveBeenCalled()189+190+ expect(await res.json()).toEqual('Unauthorized')191+ })192+193+ it('Should handle an Error thrown by next()', async () => {194+ const request = new Request('http://localhost/api/foo')195+ const handler = handleMiddleware((c, next) => next())196+197+ const next = vi.fn().mockRejectedValue(new Error('Error from next()'))198+ const eventContext = createEventContext({ request, next })199+ await expect(handler(eventContext)).rejects.toThrowError('Error from next()')200+ expect(next).toHaveBeenCalled()201+ })202+203+ it('Should handle a non-Error thrown by next()', async () => {204+ const request = new Request('http://localhost/api/foo')205+ const handler = handleMiddleware((c, next) => next())206+207+ const next = vi.fn().mockRejectedValue('Error from next()')208+ const eventContext = createEventContext({ request, next })209+ await expect(handler(eventContext)).rejects.toThrowError('Error from next()')210+ expect(next).toHaveBeenCalled()211+ })212+213+ it('Should rethrow an Error', async () => {214+ const request = new Request('http://localhost/api/foo')215+ const handler = handleMiddleware(() => {216+ throw new Error('Something went wrong')217+ })218+219+ const next = vi.fn()220+ const eventContext = createEventContext({ request, next })221+ await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')222+ expect(next).not.toHaveBeenCalled()223+ })224+225+ it('Should rethrow non-Error exceptions', async () => {226+ const request = new Request('http://localhost/api/foo')227+ const handler = handleMiddleware(() => Promise.reject('Something went wrong'))228+ const next = vi.fn()229+ const eventContext = createEventContext({ request, next })230+ await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')231+ expect(next).not.toHaveBeenCalled()232+ })233+})234+235+describe('serveStatic()', () => {236+ it('Should pass the raw request to ASSETS.fetch', async () => {237+ const assetsFetch = vi.fn().mockResolvedValue(new Response('foo.png'))238+ const request = new Request('http://localhost/foo.png')239+ const env = {240+ ASSETS: { fetch: assetsFetch },241+ TOKEN: 'HONOISCOOL',242+ }243+244+ const eventContext = createEventContext({ request, env })245+ const app = new Hono<Env>()246+ app.use(serveStatic())247+ const handler = handle(app)248+ const res = await handler(eventContext)249+250+ expect(assetsFetch).toHaveBeenCalledWith(request)251+ expect(res.status).toBe(200)252+ expect(await res.text()).toBe('foo.png')253+ })254+255+ it('Should respond with 404 if ASSETS.fetch returns a 404 response', async () => {256+ const assetsFetch = vi.fn().mockResolvedValue(new Response(null, { status: 404 }))257+ const request = new Request('http://localhost/foo.png')258+ const env = {259+ ASSETS: { fetch: assetsFetch },260+ TOKEN: 'HONOISCOOL',261+ }262+263+ const eventContext = createEventContext({ request, env })264+ const app = new Hono<Env>()265+ app.use(serveStatic())266+ const handler = handle(app)267+ const res = await handler(eventContext)268+269+ expect(assetsFetch).toHaveBeenCalledWith(request)270+ expect(res.status).toBe(404)271+ })272+})modified:src/adapter/cloudflare-pages/handler.ts+68 added-12 removed
1+import { Context } from '../../context'2 import type { Hono } from '../../hono'2-import type { MiddlewareHandler } from '../../types'3+import { HTTPException } from '../../http-exception'4+import type { BlankSchema, Env, Input, MiddlewareHandler, Schema } from '../../types'5 6 // Ref: https://github.com/cloudflare/workerd/blob/main/types/defines/pages.d.ts7 8 // eslint-disable-next-line @typescript-eslint/no-explicit-any10 unmodified lines19 params: Params<P>20 data: Data21 }22 21-interface HandleInterface {23+declare type PagesFunction<24+ Env = unknown,25 // eslint-disable-next-line @typescript-eslint/no-explicit-any23- (app: Hono<any, any, any>): (eventContext: EventContext) => Response | Promise<Response>24-}26+ Params extends string = any,27+ Data extends Record<string, unknown> = Record<string, unknown>28+> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>29 30+export const handle =31+ <E extends Env = Env, S extends Schema = BlankSchema, BasePath extends string = '/'>(32+ app: Hono<E, S, BasePath>33+ ): PagesFunction<E['Bindings']> =>26-export const handle: HandleInterface = (app: Hono) => (eventContext: EventContext) => {27- return app.fetch(28- eventContext.request,29- { ...eventContext.env, eventContext },30- {31- waitUntil: eventContext.waitUntil,32- passThroughOnException: eventContext.passThroughOnException,34+ (eventContext) => {35+ return app.fetch(36+ eventContext.request,37+ { ...eventContext.env, eventContext },38+ {39+ waitUntil: eventContext.waitUntil,40+ passThroughOnException: eventContext.passThroughOnException,41+ }42+ )43+ }44+45+// eslint-disable-next-line @typescript-eslint/no-explicit-any46+export function handleMiddleware<E extends Env = any, P extends string = any, I extends Input = {}>(47+ middleware: MiddlewareHandler<E, P, I>48+): PagesFunction<E['Bindings']> {49+ return async (executionCtx) => {50+ const context = new Context(executionCtx.request, {51+ env: executionCtx.env,52+ executionCtx,53+ })54+55+ let response: Response | void = undefined56+57+ try {58+ response = await middleware(context, async () => {59+ try {60+ context.res = await executionCtx.next()61+ } catch (error) {62+ if (error instanceof Error) {63+ context.error = error64+ } else {65+ throw error66+ }67+ }68+ })69+ } catch (error) {70+ if (error instanceof Error) {71+ context.error = error72+ } else {73+ throw error74+ }75 }34- )76+77+ if (response) {78+ return response79+ }80+81+ if (context.error instanceof HTTPException) {82+ return context.error.getResponse()83+ }84+85+ if (context.error) {86+ throw context.error87+ }88+89+ return context.res90+ }91 }92 93 declare abstract class FetcherLike {94 fetch(input: RequestInfo, init?: RequestInit): Promise<Response>18 unmodified linesmodified:src/adapter/cloudflare-pages/index.ts+1 added-1 removed
12345667/** * @module * Cloudflare Pages Adapter for Hono. */
export { handle, serveStatic } from './handler'export { handle, handleMiddleware, serveStatic } from './handler'export type { EventContext } from './handler'modified:src/adapter/cloudflare-workers/conninfo.test.ts+1 added
12 unmodified lines1314151617181912 unmodified lines
const info = getConnInfo(c)
expect(info.remote.address).toBe(address) expect(info.remote.addressType).toBeUndefined() })})modified:src/adapter/cloudflare-workers/conninfo.ts-1 removed
1 unmodified line2 3 export const getConnInfo: GetConnInfo = (c) => ({4 remote: {5 address: c.req.header('cf-connecting-ip'),6- addressType: 'unknown',6 },7 })modified:src/adapter/deno/conninfo.test.ts+1 added
17 unmodified lines18 const info = getConnInfo(c)19 20 expect(info.remote.port).toBe(port)21 expect(info.remote.address).toBe(address)22+ expect(info.remote.addressType).toBeUndefined()23 expect(info.remote.transport).toBe(transport)24 })25 })modified:src/adapter/deno/conninfo.ts-1 removed
10 unmodified lines11 remote: {12 address: remoteAddr.hostname,13 port: remoteAddr.port,14 transport: remoteAddr.transport,15- addressType: 'unknown',15 },16 }17 }added:src/adapter/lambda-edge/conninfo.test.ts+27 added
1+import { Context } from '../../context'2+import type { CloudFrontEdgeEvent } from './handler'3+import { getConnInfo } from './conninfo'4+5+describe('getConnInfo', () => {6+ it('Should info is valid', () => {7+ const clientIp = Math.random().toString()8+ const env = {9+ event: {10+ Records: [11+ {12+ cf: {13+ request: {14+ clientIp,15+ },16+ },17+ },18+ ],19+ } as CloudFrontEdgeEvent,20+ }21+22+ const c = new Context(new Request('http://localhost/'), { env })23+ const info = getConnInfo(c)24+25+ expect(info.remote.address).toBe(clientIp)26+ })27+})added:src/adapter/lambda-edge/conninfo.ts+15 added
1+import type { GetConnInfo } from '../../helper/conninfo'2+import type { CloudFrontEdgeEvent } from './handler'3+import type { Context } from '../../context'4+5+type Env = {6+ Bindings: {7+ event: CloudFrontEdgeEvent8+ }9+}10+11+export const getConnInfo: GetConnInfo = (c: Context<Env>) => ({12+ remote: {13+ address: c.env.event.Records[0].cf.request.clientIp,14+ },15+})modified:src/adapter/lambda-edge/index.ts+1 added
2 unmodified lines3 * Lambda@Edge Adapter for Hono.4 */5 6 export { handle } from './handler'7+export { getConnInfo } from './conninfo'8 export type {9 Callback,10 CloudFrontConfig,11 CloudFrontRequest,3 unmodified linesadded:src/adapter/service-worker/handler.test.ts+57 added
1+import { Hono } from '../../hono'2+import { handle } from './handler'3+import type { FetchEvent } from './types'4+5+describe('handle', () => {6+ it('Success to fetch', async () => {7+ const app = new Hono()8+ app.get('/', (c) => {9+ return c.json({ hello: 'world' })10+ })11+ const handler = handle(app)12+ const json = await new Promise<Response>((resolve) => {13+ handler({14+ request: new Request('http://localhost/'),15+ respondWith(res) {16+ resolve(res)17+ },18+ } as FetchEvent)19+ }).then((res) => res.json())20+ expect(json).toStrictEqual({ hello: 'world' })21+ })22+ it('Fallback 404', async () => {23+ const app = new Hono()24+ const handler = handle(app, {25+ async fetch() {26+ return new Response('hello world')27+ },28+ })29+ const text = await new Promise<Response>((resolve) => {30+ handler({31+ request: new Request('http://localhost/'),32+ respondWith(res) {33+ resolve(res)34+ },35+ } as FetchEvent)36+ }).then((res) => res.text())37+ expect(text).toBe('hello world')38+ })39+ it('Do not fallback 404 when fetch is undefined', async () => {40+ const app = new Hono()41+ app.get('/', (c) => c.text('Not found', 404))42+ const handler = handle(app, {43+ fetch: undefined,44+ })45+ const result = await new Promise<Response>((resolve) =>46+ handler({47+ request: new Request('https://localhost/'),48+ respondWith(r) {49+ resolve(r)50+ },51+ } as FetchEvent)52+ )53+54+ expect(result.status).toBe(404)55+ expect(await result.text()).toBe('Not found')56+ })57+})added:src/adapter/service-worker/handler.ts+33 added
1+/**2+ * Handler for Service Worker3+ * @module4+ */5+6+import type { Hono } from '../../hono'7+import type { FetchEvent } from './types'8+9+type Handler = (evt: FetchEvent) => void10+11+/**12+ * Adapter for Service Worker13+ */14+export const handle = (15+ app: Hono,16+ opts: {17+ fetch?: typeof fetch18+ } = {19+ fetch: fetch,20+ }21+): Handler => {22+ return (evt) => {23+ evt.respondWith(24+ (async () => {25+ const res = await app.fetch(evt.request)26+ if (opts.fetch && res.status === 404) {27+ return await opts.fetch(evt.request)28+ }29+ return res30+ })()31+ )32+ }33+}added:src/adapter/service-worker/index.ts+5 added
1+/**2+ * Cloudflare Workers Adapter for Hono.3+ * @module4+ */5+export { handle } from './handler'added:src/adapter/service-worker/types.ts+14 added
1+interface ExtendableEvent extends Event {2+ // eslint-disable-next-line @typescript-eslint/no-explicit-any3+ waitUntil(f: Promise<any>): void4+}5+6+export interface FetchEvent extends ExtendableEvent {7+ readonly clientId: string8+ readonly handled: Promise<undefined>9+ // eslint-disable-next-line @typescript-eslint/no-explicit-any10+ readonly preloadResponse: Promise<any>11+ readonly request: Request12+ readonly resultingClientId: string13+ respondWith(r: Response | PromiseLike<Response>): void14+}added:src/adapter/vercel/conninfo.test.ts+18 added
1+import { Context } from '../../context'2+import { getConnInfo } from './conninfo'3+4+describe('getConnInfo', () => {5+ it('Should getConnInfo works', () => {6+ const address = Math.random().toString()7+ const req = new Request('http://localhost/', {8+ headers: {9+ 'x-real-ip': address,10+ },11+ })12+ const c = new Context(req)13+14+ const info = getConnInfo(c)15+16+ expect(info.remote.address).toBe(address)17+ })18+})added:src/adapter/vercel/conninfo.ts+8 added
1+import type { GetConnInfo } from '../../helper/conninfo'2+3+export const getConnInfo: GetConnInfo = (c) => ({4+ remote: {5+ // https://github.com/vercel/vercel/blob/b70bfb5fbf28a4650d4042ce68ca5c636d37cf44/packages/edge/src/edge-headers.ts#L10-L12C326+ address: c.req.header('x-real-ip'),7+ },8+})modified:src/adapter/vercel/index.ts+1 added
2 unmodified lines3 * Vercel Adapter for Hono.4 */5 6 export { handle } from './handler'7+export { getConnInfo } from './conninfo'modified:src/helper/conninfo/types.ts+1 added-1 removed
1 import type { Context } from '../../context'2 3-export type AddressType = 'IPv6' | 'IPv4' | 'unknown'3+export type AddressType = 'IPv6' | 'IPv4' | undefined4 5 export type NetAddrInfo = {6 /**7 * Transport protocol type38 unmodified linesmodified:src/helper/html/index.ts+8 added-4 removed
1 unmodified line2 * @module3 * html Helper for Hono.4 */5 6-import { escapeToBuffer, raw, stringBufferToString } from '../../utils/html'7-import type { HtmlEscaped, HtmlEscapedString, StringBuffer } from '../../utils/html'6+import { escapeToBuffer, raw, resolveCallbackSync, stringBufferToString } from '../../utils/html'7+import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../../utils/html'8 9 export { raw }10 11 export const html = (12 strings: TemplateStringsArray,13 ...values: unknown[]14 ): HtmlEscapedString | Promise<HtmlEscapedString> => {15- const buffer: StringBuffer = ['']15+ const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks16 17 for (let i = 0, len = strings.length - 1; i < len; i++) {18 buffer[0] += strings[i]19 27 unmodified lines47 }48 }49 buffer[0] += strings[strings.length - 1]50 51- return buffer.length === 1 ? raw(buffer[0]) : stringBufferToString(buffer)51+ return buffer.length === 152+ ? 'callbacks' in buffer53+ ? raw(resolveCallbackSync(raw(buffer[0], buffer.callbacks)))54+ : raw(buffer[0])55+ : stringBufferToString(buffer, buffer.callbacks)56 }added:src/jsx/dom/hooks/index.test.tsx+172 added
1+/** @jsxImportSource ../../ */2+import { JSDOM } from 'jsdom'3+import { render, useCallback, useState } from '..'4+import { useActionState, useFormStatus, useOptimistic } from '.'5+6+describe('Hooks', () => {7+ beforeAll(() => {8+ global.requestAnimationFrame = (cb) => setTimeout(cb)9+ })10+11+ let dom: JSDOM12+ let root: HTMLElement13+ beforeEach(() => {14+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {15+ runScripts: 'dangerously',16+ })17+ global.document = dom.window.document18+ global.HTMLElement = dom.window.HTMLElement19+ global.SVGElement = dom.window.SVGElement20+ global.Text = dom.window.Text21+ global.FormData = dom.window.FormData22+ root = document.getElementById('root') as HTMLElement23+ })24+25+ describe('useActionState', () => {26+ it('should return initial state', () => {27+ const [state] = useActionState(() => {}, 'initial')28+ expect(state).toBe('initial')29+ })30+31+ it('should return updated state', async () => {32+ const action = vi.fn().mockReturnValue('updated')33+34+ const App = () => {35+ const [state, formAction] = useActionState(action, 'initial')36+ return (37+ <>38+ <div>{state}</div>39+ <form action={formAction}>40+ <input type='text' name='name' value='updated' />41+ <button>Submit</button>42+ </form>43+ </>44+ )45+ }46+47+ render(<App />, root)48+ expect(root.innerHTML).toBe(49+ '<div>initial</div><form><input type="text" name="name" value="updated"><button>Submit</button></form>'50+ )51+ root.querySelector('button')?.click()52+ await Promise.resolve()53+ await Promise.resolve()54+ expect(root.innerHTML).toBe(55+ '<div>updated</div><form><input type="text" name="name" value="updated"><button>Submit</button></form>'56+ )57+58+ expect(action).toHaveBeenCalledOnce()59+ const [initialState, formData] = action.mock.calls[0]60+ expect(initialState).toBe('initial')61+ expect(formData).toBeInstanceOf(FormData)62+ expect(formData.get('name')).toBe('updated')63+ })64+ })65+66+ describe('useFormStatus', () => {67+ it('should return initial state', () => {68+ const status = useFormStatus()69+ expect(status).toEqual({70+ pending: false,71+ data: null,72+ method: null,73+ action: null,74+ })75+ })76+77+ it('should return updated state', async () => {78+ let formResolve: () => void = () => {}79+ const formPromise = new Promise<void>((r) => (formResolve = r))80+ let status: ReturnType<typeof useFormStatus> | undefined81+ const Status = () => {82+ status = useFormStatus()83+ return null84+ }85+ const App = () => {86+ const [, setCount] = useState(0)87+ const action = useCallback(() => {88+ setCount((count) => count + 1)89+ return formPromise90+ }, [])91+ return (92+ <>93+ <form action={action}>94+ <Status />95+ <input type='text' name='name' value='updated' />96+ <button>Submit</button>97+ </form>98+ </>99+ )100+ }101+102+ render(<App />, root)103+ expect(root.innerHTML).toBe(104+ '<form><input type="text" name="name" value="updated"><button>Submit</button></form>'105+ )106+ root.querySelector('button')?.click()107+ await Promise.resolve()108+ await Promise.resolve()109+ await Promise.resolve()110+ await Promise.resolve()111+ expect(status).toEqual({112+ pending: true,113+ data: expect.any(FormData),114+ method: 'post',115+ action: expect.any(Function),116+ })117+ formResolve?.()118+ await Promise.resolve()119+ await Promise.resolve()120+ expect(status).toEqual({121+ pending: false,122+ data: null,123+ method: null,124+ action: null,125+ })126+ })127+ })128+129+ describe('useOptimistic', () => {130+ it('should return updated state', async () => {131+ let formResolve: () => void = () => {}132+ const formPromise = new Promise<void>((r) => (formResolve = r))133+ const App = () => {134+ const [count, setCount] = useState(0)135+ const [optimisticCount, setOptimisticCount] = useOptimistic(count, (c, n: number) => n)136+ const action = useCallback(async () => {137+ setOptimisticCount(count + 1)138+ await formPromise139+ setCount((count) => count + 2)140+ }, [])141+142+ return (143+ <>144+ <form action={action}>145+ <div>{optimisticCount}</div>146+ <input type='text' name='name' value='updated' />147+ <button>Submit</button>148+ </form>149+ </>150+ )151+ }152+153+ render(<App />, root)154+ expect(root.innerHTML).toBe(155+ '<form><div>0</div><input type="text" name="name" value="updated"><button>Submit</button></form>'156+ )157+ root.querySelector('button')?.click()158+ await Promise.resolve()159+ expect(root.innerHTML).toBe(160+ '<form><div>1</div><input type="text" name="name" value="updated"><button>Submit</button></form>'161+ )162+ formResolve?.()163+ await Promise.resolve()164+ await Promise.resolve()165+ await Promise.resolve()166+ await Promise.resolve()167+ expect(root.innerHTML).toBe(168+ '<form><div>2</div><input type="text" name="name" value="updated"><button>Submit</button></form>'169+ )170+ })171+ })172+})added:src/jsx/dom/hooks/index.ts+91 added
1+/**2+ * Provide hooks used only in jsx/dom3+ */4+5+import type { Context } from '../../context'6+import { useContext } from '../../context'7+import { createContext } from '../context'8+import { useCallback, useState } from '../../hooks'9+import { PERMALINK } from '../../constants'10+11+type FormStatus =12+ | {13+ pending: false14+ data: null15+ method: null16+ action: null17+ }18+ | {19+ pending: true20+ data: FormData21+ method: 'get' | 'post'22+ action: string | ((formData: FormData) => void | Promise<void>)23+ }24+export const FormContext: Context<FormStatus> = createContext<FormStatus>({25+ pending: false,26+ data: null,27+ method: null,28+ action: null,29+})30+31+const actions: Set<Promise<unknown>> = new Set()32+export const registerAction = (action: Promise<unknown>) => {33+ actions.add(action)34+ action.finally(() => actions.delete(action))35+}36+37+/**38+ * This hook returns the current form status39+ * @returns FormStatus40+ */41+export const useFormStatus = (): FormStatus => {42+ return useContext(FormContext)43+}44+45+/**46+ * This hook returns the current state and a function to update the state optimistically47+ * The current state is updated optimistically and then reverted to the original state when all actions are resolved48+ * @param state49+ * @param updateState50+ * @returns [T, (action: N) => void]51+ */52+export const useOptimistic = <T, N>(53+ state: T,54+ updateState: (currentState: T, action: N) => T55+): [T, (action: N) => void] => {56+ const [optimisticState, setOptimisticState] = useState(state)57+ if (actions.size > 0) {58+ Promise.all(actions).finally(() => {59+ setOptimisticState(state)60+ })61+ } else {62+ setOptimisticState(state)63+ }64+65+ const cb = useCallback((newData: N) => {66+ setOptimisticState((currentState) => updateState(currentState, newData))67+ }, [])68+69+ return [optimisticState, cb]70+}71+72+/**73+ * This hook returns the current state and a function to update the state by form action74+ * @param fn75+ * @param initialState76+ * @param permalink77+ * @returns [T, (data: FormData) => void]78+ */79+export const useActionState = <T>(80+ fn: Function,81+ initialState: T,82+ permalink?: string83+): [T, Function] => {84+ const [state, setState] = useState(initialState)85+ const actionState = async (data: FormData) => {86+ setState(await fn(state, data))87+ }88+ // eslint-disable-next-line @typescript-eslint/no-explicit-any89+ ;(actionState as any)[PERMALINK] = permalink90+ return [state, actionState]91+}added:src/jsx/dom/intrinsic-element/components.test.tsx+1020 added
1+/** @jsxImportSource ../../ */2+import { JSDOM, ResourceLoader } from 'jsdom'3+import { useState } from '../../hooks'4+import { Suspense, render } from '..'5+import { clearCache, composeRef } from './components'6+7+describe('intrinsic element', () => {8+ let CustomResourceLoader: typeof ResourceLoader9+ beforeAll(() => {10+ global.requestAnimationFrame = (cb) => setTimeout(cb)11+12+ CustomResourceLoader = class CustomResourceLoader extends ResourceLoader {13+ // eslint-disable-next-line @typescript-eslint/no-explicit-any14+ fetch(url: string) {15+ return url.includes('invalid')16+ ? Promise.reject('Invalid URL')17+ : // eslint-disable-next-line @typescript-eslint/no-explicit-any18+ (Promise.resolve(Buffer.from('')) as any)19+ }20+ }21+ })22+23+ let dom: JSDOM24+ let root: HTMLElement25+ beforeEach(() => {26+ clearCache()27+28+ dom = new JSDOM('<html><head></head><body><div id="root"></div></body></html>', {29+ runScripts: 'dangerously',30+ resources: new CustomResourceLoader(),31+ })32+ global.document = dom.window.document33+ global.HTMLElement = dom.window.HTMLElement34+ global.SVGElement = dom.window.SVGElement35+ global.Text = dom.window.Text36+ global.FormData = dom.window.FormData37+ global.CustomEvent = dom.window.CustomEvent38+ root = document.getElementById('root') as HTMLElement39+ })40+41+ describe('document metadata', () => {42+ describe('title element', () => {43+ it('should be inserted into head', () => {44+ const App = () => {45+ return (46+ <div>47+ <title>Document Title</title>48+ Content49+ </div>50+ )51+ }52+ render(<App />, root)53+ expect(document.head.innerHTML).toBe('<title>Document Title</title>')54+ expect(root.innerHTML).toBe('<div>Content</div>')55+ })56+57+ it('should be updated', async () => {58+ const App = () => {59+ const [count, setCount] = useState(0)60+ return (61+ <div>62+ <title>Document Title {count}</title>63+ <button onClick={() => setCount(count + 1)}>+</button>64+ </div>65+ )66+ }67+ render(<App />, root)68+ expect(document.head.innerHTML).toBe('<title>Document Title 0</title>')69+ expect(root.innerHTML).toBe('<div><button>+</button></div>')70+ root.querySelector('button')?.click()71+ await Promise.resolve()72+ expect(document.head.innerHTML).toBe('<title>Document Title 1</title>')73+ })74+75+ it('should be removed when unmounted', async () => {76+ const App = () => {77+ const [count, setCount] = useState(0)78+ return (79+ <div>80+ {count === 1 && <title>Document Title {count}</title>}81+ <div>{count}</div>82+ <button onClick={() => setCount(count + 1)}>+</button>83+ </div>84+ )85+ }86+ render(<App />, root)87+ expect(document.head.innerHTML).toBe('')88+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')89+ root.querySelector('button')?.click()90+ await Promise.resolve()91+ expect(document.head.innerHTML).toBe('<title>Document Title 1</title>')92+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')93+ root.querySelector('button')?.click()94+ await Promise.resolve()95+ expect(document.head.innerHTML).toBe('')96+ expect(root.innerHTML).toBe('<div><div>2</div><button>+</button></div>')97+ })98+99+ it('should be inserted bottom of head if existing element is removed', async () => {100+ document.head.innerHTML = '<title>Existing Title</title>'101+102+ const App = () => {103+ const [count, setCount] = useState(0)104+ return (105+ <div>106+ {count === 1 && <title>Document Title {count}</title>}107+ <div>{count}</div>108+ <button onClick={() => setCount(count + 1)}>+</button>109+ </div>110+ )111+ }112+ render(<App />, root)113+ expect(document.head.innerHTML).toBe('<title>Existing Title</title>')114+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')115+ root.querySelector('button')?.click()116+ document.head.querySelector('title')?.remove()117+ await Promise.resolve()118+ expect(document.head.innerHTML).toBe('<title>Document Title 1</title>')119+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')120+ })121+122+ it('should be inserted before existing title element', async () => {123+ document.head.innerHTML = '<title>Existing Title</title>'124+125+ const App = () => {126+ const [count, setCount] = useState(0)127+ return (128+ <div>129+ {count === 1 && <title>Document Title {count}</title>}130+ <div>{count}</div>131+ <button onClick={() => setCount(count + 1)}>+</button>132+ </div>133+ )134+ }135+ render(<App />, root)136+ expect(document.head.innerHTML).toBe('<title>Existing Title</title>')137+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')138+ root.querySelector('button')?.click()139+ await Promise.resolve()140+ expect(document.head.innerHTML).toBe(141+ '<title>Document Title 1</title><title>Existing Title</title>'142+ )143+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')144+ root.querySelector('button')?.click()145+ await Promise.resolve()146+ expect(document.head.innerHTML).toBe('<title>Existing Title</title>')147+ expect(root.innerHTML).toBe('<div><div>2</div><button>+</button></div>')148+ })149+ })150+151+ describe('link element', () => {152+ it('should be inserted into head', () => {153+ const App = () => {154+ return (155+ <div>156+ <link rel='stylesheet' href='style.css' precedence='default' />157+ Content158+ </div>159+ )160+ }161+ render(<App />, root)162+ expect(document.head.innerHTML).toBe(163+ '<link href="style.css" rel="stylesheet" data-precedence="default">'164+ )165+ expect(root.innerHTML).toBe('<div>Content</div>')166+ })167+168+ it('should be updated', async () => {169+ const App = () => {170+ const [count, setCount] = useState(0)171+ return (172+ <div>173+ <link rel='stylesheet' href={`style${count}.css`} precedence='default' />174+ <button onClick={() => setCount(count + 1)}>+</button>175+ </div>176+ )177+ }178+ render(<App />, root)179+ expect(document.head.innerHTML).toBe(180+ '<link href="style0.css" rel="stylesheet" data-precedence="default">'181+ )182+ expect(root.innerHTML).toBe('<div><button>+</button></div>')183+ root.querySelector('button')?.click()184+ await Promise.resolve()185+ expect(document.head.innerHTML).toBe(186+ '<link href="style1.css" rel="stylesheet" data-precedence="default">'187+ )188+ })189+190+ it('should not do special behavior if disabled is present', () => {191+ const App = () => {192+ return (193+ <div>194+ <link rel='stylesheet' href={'style.css'} precedence='default' disabled={true} />195+ </div>196+ )197+ }198+ render(<App />, root)199+ expect(document.head.innerHTML).toBe('')200+ expect(root.innerHTML).toBe(201+ '<div><link rel="stylesheet" href="style.css" precedence="default" disabled=""></div>'202+ )203+ })204+205+ it('should be ordered by precedence attribute', () => {206+ const App = () => {207+ return (208+ <div>209+ <link rel='stylesheet' href='style-a.css' precedence='default' />210+ <link rel='stylesheet' href='style-b.css' precedence='high' />211+ <link rel='stylesheet' href='style-c.css' precedence='default' />212+ Content213+ </div>214+ )215+ }216+ render(<App />, root)217+ expect(document.head.innerHTML).toBe(218+ '<link href="style-a.css" rel="stylesheet" data-precedence="default"><link href="style-c.css" rel="stylesheet" data-precedence="default"><link href="style-b.css" rel="stylesheet" data-precedence="high">'219+ )220+ expect(root.innerHTML).toBe('<div>Content</div>')221+ })222+223+ it('should be de-duplicated by href attribute', async () => {224+ const App = () => {225+ const [count, setCount] = useState(0)226+ return (227+ <div>228+ <link rel='stylesheet' href='style-a.css' precedence='default' />229+ <link rel='stylesheet' href='style-b.css' precedence='high' />230+ {count === 1 && (231+ <>232+ <link rel='stylesheet' href='style-a.css' precedence='default' />233+ <link rel='stylesheet' href='style-c.css' precedence='other' />234+ </>235+ )}236+ <button onClick={() => setCount(count + 1)}>+</button>237+ {count}238+ </div>239+ )240+ }241+ render(<App />, root)242+ expect(document.head.innerHTML).toBe(243+ '<link href="style-a.css" rel="stylesheet" data-precedence="default"><link href="style-b.css" rel="stylesheet" data-precedence="high">'244+ )245+ expect(root.innerHTML).toBe('<div><button>+</button>0</div>')246+ root.querySelector('button')?.click()247+ await Promise.resolve()248+ expect(document.head.innerHTML).toBe(249+ '<link href="style-a.css" rel="stylesheet" data-precedence="default"><link href="style-b.css" rel="stylesheet" data-precedence="high"><link href="style-c.css" rel="stylesheet" data-precedence="other">'250+ )251+ expect(root.innerHTML).toBe('<div><button>+</button>1</div>')252+ })253+254+ it('should be preserved when unmounted', async () => {255+ const App = () => {256+ const [count, setCount] = useState(0)257+ return (258+ <div>259+ {count === 1 && <link rel='stylesheet' href='style.css' precedence='default' />}260+ <div>{count}</div>261+ <button onClick={() => setCount(count + 1)}>+</button>262+ </div>263+ )264+ }265+ render(<App />, root)266+ expect(document.head.innerHTML).toBe('')267+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')268+ root.querySelector('button')?.click()269+ await Promise.resolve()270+ expect(document.head.innerHTML).toBe(271+ '<link href="style.css" rel="stylesheet" data-precedence="default">'272+ )273+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')274+ root.querySelector('button')?.click()275+ await Promise.resolve()276+ expect(document.head.innerHTML).toBe(277+ '<link href="style.css" rel="stylesheet" data-precedence="default">'278+ )279+ expect(root.innerHTML).toBe('<div><div>2</div><button>+</button></div>')280+ })281+282+ it('should be blocked by blocking attribute', async () => {283+ const Component = () => {284+ return (285+ <Suspense fallback={<div>Loading...</div>}>286+ <div>287+ <link288+ rel='stylesheet'289+ href='http://localhost/style.css'290+ precedence='default'291+ blocking='render'292+ />293+ Content294+ </div>295+ </Suspense>296+ )297+ }298+ const App = () => {299+ const [show, setShow] = useState(false)300+ return (301+ <div>302+ {show && <Component />}303+ <button onClick={() => setShow(true)}>Show</button>304+ </div>305+ )306+ }307+ render(<App />, root)308+ expect(document.head.innerHTML).toBe('')309+ expect(root.innerHTML).toBe('<div><button>Show</button></div>')310+ root.querySelector('button')?.click()311+ await Promise.resolve()312+ expect(root.innerHTML).toBe('<div><div>Loading...</div><button>Show</button></div>')313+ await new Promise((resolve) => setTimeout(resolve))314+ await Promise.resolve()315+ expect(root.innerHTML).toBe('<div><div>Content</div><button>Show</button></div>')316+ })317+ })318+319+ describe('style element', () => {320+ it('should be inserted into head', () => {321+ const App = () => {322+ return (323+ <div>324+ <style href='red' precedence='default'>325+ {'body { color: red; }'}326+ </style>327+ Content328+ </div>329+ )330+ }331+ render(<App />, root)332+ expect(document.head.innerHTML).toBe(333+ '<style data-href="red" data-precedence="default">body { color: red; }</style>'334+ )335+ expect(root.innerHTML).toBe('<div>Content</div>')336+ })337+338+ it('should be updated', async () => {339+ const App = () => {340+ const [count, setCount] = useState(0)341+ return (342+ <div>343+ <style href='color' precedence='default'>{`body { color: ${344+ count % 2 ? 'red' : 'blue'345+ }; }`}</style>346+ <button onClick={() => setCount(count + 1)}>+</button>347+ </div>348+ )349+ }350+ render(<App />, root)351+ expect(document.head.innerHTML).toBe(352+ '<style data-href="color" data-precedence="default">body { color: blue; }</style>'353+ )354+ expect(root.innerHTML).toBe('<div><button>+</button></div>')355+ root.querySelector('button')?.click()356+ await Promise.resolve()357+ expect(document.head.innerHTML).toBe(358+ '<style data-href="color" data-precedence="default">body { color: red; }</style>'359+ )360+ })361+362+ it('should be preserved when unmounted', async () => {363+ const App = () => {364+ const [count, setCount] = useState(0)365+ return (366+ <div>367+ {count === 1 && (368+ <style href='red' precedence='default'>369+ {'body { color: red; }'}370+ </style>371+ )}372+ <div>{count}</div>373+ <button onClick={() => setCount(count + 1)}>+</button>374+ </div>375+ )376+ }377+ render(<App />, root)378+ expect(document.head.innerHTML).toBe('')379+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')380+ root.querySelector('button')?.click()381+ await Promise.resolve()382+ expect(document.head.innerHTML).toBe(383+ '<style data-href="red" data-precedence="default">body { color: red; }</style>'384+ )385+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')386+ root.querySelector('button')?.click()387+ await Promise.resolve()388+ expect(document.head.innerHTML).toBe(389+ '<style data-href="red" data-precedence="default">body { color: red; }</style>'390+ )391+ expect(root.innerHTML).toBe('<div><div>2</div><button>+</button></div>')392+ })393+394+ it('should be de-duplicated by href attribute', async () => {395+ const App = () => {396+ const [count, setCount] = useState(0)397+ return (398+ <div>399+ <style href='red' precedence='default'>400+ {'body { color: red; }'}401+ </style>402+ <style href='blue' precedence='default'>403+ {'body { color: blue; }'}404+ </style>405+ <style href='green' precedence='default'>406+ {'body { color: green; }'}407+ </style>408+ {count === 1 && (409+ <>410+ <style href='blue' precedence='default'>411+ {'body { color: blue; }'}412+ </style>413+ <style href='yellow' precedence='default'>414+ {'body { color: yellow; }'}415+ </style>416+ </>417+ )}418+ <button onClick={() => setCount(count + 1)}>+</button>419+ {count}420+ </div>421+ )422+ }423+ render(<App />, root)424+ expect(document.head.innerHTML).toBe(425+ '<style data-href="red" data-precedence="default">body { color: red; }</style><style data-href="blue" data-precedence="default">body { color: blue; }</style><style data-href="green" data-precedence="default">body { color: green; }</style>'426+ )427+ expect(root.innerHTML).toBe('<div><button>+</button>0</div>')428+ root.querySelector('button')?.click()429+ await Promise.resolve()430+ expect(document.head.innerHTML).toBe(431+ '<style data-href="red" data-precedence="default">body { color: red; }</style><style data-href="blue" data-precedence="default">body { color: blue; }</style><style data-href="green" data-precedence="default">body { color: green; }</style><style data-href="yellow" data-precedence="default">body { color: yellow; }</style>'432+ )433+ expect(root.innerHTML).toBe('<div><button>+</button>1</div>')434+ })435+436+ it('should be ordered by precedence attribute', () => {437+ const App = () => {438+ return (439+ <div>440+ <style href='red' precedence='default'>441+ {'body { color: red; }'}442+ </style>443+ <style href='green' precedence='high'>444+ {'body { color: green; }'}445+ </style>446+ <style href='blue' precedence='default'>447+ {'body { color: blue; }'}448+ </style>449+ Content450+ </div>451+ )452+ }453+ render(<App />, root)454+ expect(document.head.innerHTML).toBe(455+ '<style data-href="red" data-precedence="default">body { color: red; }</style><style data-href="blue" data-precedence="default">body { color: blue; }</style><style data-href="green" data-precedence="high">body { color: green; }</style>'456+ )457+ expect(root.innerHTML).toBe('<div>Content</div>')458+ })459+460+ it('should not do special behavior if href is present', () => {461+ const template = (462+ <html>463+ <head></head>464+ <body>465+ <style>{'body { color: red; }'}</style>466+ <h1>World</h1>467+ </body>468+ </html>469+ )470+ render(template, root)471+ expect(document.head.innerHTML).toBe('')472+ expect(root.innerHTML).toBe(473+ '<html><head></head><body><style>body { color: red; }</style><h1>World</h1></body></html>'474+ )475+ })476+ })477+478+ describe('meta element', () => {479+ it('should be inserted into head', () => {480+ const App = () => {481+ return (482+ <div>483+ <meta name='description' content='description' />484+ Content485+ </div>486+ )487+ }488+ render(<App />, root)489+ expect(document.head.innerHTML).toBe('<meta name="description" content="description">')490+ expect(root.innerHTML).toBe('<div>Content</div>')491+ })492+493+ it('should be updated', async () => {494+ const App = () => {495+ const [count, setCount] = useState(0)496+ return (497+ <div>498+ <meta name='description' content={`description ${count}`} />499+ <button onClick={() => setCount(count + 1)}>+</button>500+ </div>501+ )502+ }503+ render(<App />, root)504+ expect(document.head.innerHTML).toBe('<meta name="description" content="description 0">')505+ expect(root.innerHTML).toBe('<div><button>+</button></div>')506+ root.querySelector('button')?.click()507+ await Promise.resolve()508+ expect(document.head.innerHTML).toBe('<meta name="description" content="description 1">')509+ })510+511+ it('should not do special behavior if itemProp is present', () => {512+ const App = () => {513+ return (514+ <div>515+ <meta name='description' content='description' itemProp='test' />516+ Content517+ </div>518+ )519+ }520+ render(<App />, root)521+ expect(document.head.innerHTML).toBe('')522+ expect(root.innerHTML).toBe(523+ '<div><meta name="description" content="description" itemprop="test">Content</div>'524+ )525+ })526+527+ it('should be ordered by precedence attribute', () => {528+ const App = () => {529+ return (530+ <div>531+ <meta name='description-a' content='description-a' precedence='default' />532+ <meta name='description-b' content='description-b' precedence='high' />533+ <meta name='description-c' content='description-c' precedence='default' />534+ Content535+ </div>536+ )537+ }538+ render(<App />, root)539+ expect(document.head.innerHTML).toBe(540+ '<meta name="description-a" content="description-a"><meta name="description-b" content="description-b"><meta name="description-c" content="description-c">'541+ )542+ expect(root.innerHTML).toBe('<div>Content</div>')543+ })544+545+ it('should be de-duplicated by name attribute', async () => {546+ const App = () => {547+ const [count, setCount] = useState(0)548+ return (549+ <div>550+ <meta name='description-a' content='description-a' />551+ <meta name='description-b' content='description-b' />552+ {count === 1 && (553+ <>554+ <meta name='description-a' content='description-a' />555+ <meta name='description-c' content='description-c' />556+ </>557+ )}558+ <button onClick={() => setCount(count + 1)}>+</button>559+ {count}560+ </div>561+ )562+ }563+ render(<App />, root)564+ expect(document.head.innerHTML).toBe(565+ '<meta name="description-a" content="description-a"><meta name="description-b" content="description-b">'566+ )567+ expect(root.innerHTML).toBe('<div><button>+</button>0</div>')568+ root.querySelector('button')?.click()569+ await Promise.resolve()570+ expect(document.head.innerHTML).toBe(571+ '<meta name="description-a" content="description-a"><meta name="description-b" content="description-b"><meta name="description-c" content="description-c">'572+ )573+ expect(root.innerHTML).toBe('<div><button>+</button>1</div>')574+ })575+ })576+577+ describe('script element', () => {578+ it('should be inserted into head', async () => {579+ const App = () => {580+ return (581+ <div>582+ <script src='script.js' async={true} />583+ Content584+ </div>585+ )586+ }587+ render(<App />, root)588+ expect(document.head.innerHTML).toBe('<script src="script.js" async=""></script>')589+ expect(root.innerHTML).toBe('<div>Content</div>')590+ })591+592+ it('should be updated', async () => {593+ const App = () => {594+ const [count, setCount] = useState(0)595+ return (596+ <div>597+ <script src={`script${count}.js`} async={true} />598+ <button onClick={() => setCount(count + 1)}>+</button>599+ </div>600+ )601+ }602+ render(<App />, root)603+ expect(document.head.innerHTML).toBe('<script src="script0.js" async=""></script>')604+ expect(root.innerHTML).toBe('<div><button>+</button></div>')605+ root.querySelector('button')?.click()606+ await Promise.resolve()607+ expect(document.head.innerHTML).toBe('<script src="script1.js" async=""></script>')608+ })609+610+ it('should be de-duplicated by src attribute with async=true', async () => {611+ const App = () => {612+ const [count, setCount] = useState(0)613+ return (614+ <div>615+ <script src='script-a.js' async={true} />616+ <script src='script-b.js' async={true} />617+ {count === 1 && (618+ <>619+ <script src='script-a.js' async={true} />620+ <script src='script-c.js' async={true} />621+ </>622+ )}623+ <button onClick={() => setCount(count + 1)}>+</button>624+ {count}625+ </div>626+ )627+ }628+ render(<App />, root)629+ expect(document.head.innerHTML).toBe(630+ '<script src="script-a.js" async=""></script><script src="script-b.js" async=""></script>'631+ )632+ expect(root.innerHTML).toBe('<div><button>+</button>0</div>')633+ root.querySelector('button')?.click()634+ await Promise.resolve()635+ expect(document.head.innerHTML).toBe(636+ '<script src="script-a.js" async=""></script><script src="script-b.js" async=""></script><script src="script-c.js" async=""></script>'637+ )638+ expect(root.innerHTML).toBe('<div><button>+</button>1</div>')639+ })640+641+ it('should be preserved when unmounted', async () => {642+ const App = () => {643+ const [count, setCount] = useState(0)644+ return (645+ <div>646+ {count === 1 && <script src='script.js' async={true} />}647+ <div>{count}</div>648+ <button onClick={() => setCount(count + 1)}>+</button>649+ </div>650+ )651+ }652+ render(<App />, root)653+ expect(document.head.innerHTML).toBe('')654+ expect(root.innerHTML).toBe('<div><div>0</div><button>+</button></div>')655+ root.querySelector('button')?.click()656+ await Promise.resolve()657+ expect(document.head.innerHTML).toBe('<script src="script.js" async=""></script>')658+ expect(root.innerHTML).toBe('<div><div>1</div><button>+</button></div>')659+ root.querySelector('button')?.click()660+ await Promise.resolve()661+ expect(document.head.innerHTML).toBe('<script src="script.js" async=""></script>')662+ expect(root.innerHTML).toBe('<div><div>2</div><button>+</button></div>')663+ })664+665+ it('should be fired onLoad event', async () => {666+ const onLoad = vi.fn()667+ const onError = vi.fn()668+ const App = () => {669+ return (670+ <div>671+ <script672+ src='http://localhost/script.js'673+ async={true}674+ onLoad={onLoad}675+ onError={onError}676+ />677+ Content678+ </div>679+ )680+ }681+ render(<App />, root)682+ expect(document.head.innerHTML).toBe(683+ '<script src="http://localhost/script.js" async=""></script>'684+ )685+ await Promise.resolve()686+ await new Promise((resolve) => setTimeout(resolve))687+ expect(onLoad).toBeCalledTimes(1)688+ expect(onError).not.toBeCalled()689+ })690+691+ it('should be fired onError event', async () => {692+ const onLoad = vi.fn()693+ const onError = vi.fn()694+ const App = () => {695+ return (696+ <div>697+ <script698+ src='http://localhost/invalid.js'699+ async={true}700+ onLoad={onLoad}701+ onError={onError}702+ />703+ Content704+ </div>705+ )706+ }707+ render(<App />, root)708+ expect(document.head.innerHTML).toBe(709+ '<script src="http://localhost/invalid.js" async=""></script>'710+ )711+ await Promise.resolve()712+ await new Promise((resolve) => setTimeout(resolve))713+ await Promise.resolve()714+ await new Promise((resolve) => setTimeout(resolve))715+ await Promise.resolve()716+ await new Promise((resolve) => setTimeout(resolve))717+ await Promise.resolve()718+ await new Promise((resolve) => setTimeout(resolve))719+ expect(onLoad).not.toBeCalled()720+ expect(onError).toBeCalledTimes(1)721+ })722+723+ it('should be blocked by blocking attribute', async () => {724+ const Component = () => {725+ return (726+ <Suspense fallback={<div>Loading...</div>}>727+ <div>728+ <script src='http://localhost/script.js' async={true} blocking='render' />729+ Content730+ </div>731+ </Suspense>732+ )733+ }734+ const App = () => {735+ const [show, setShow] = useState(false)736+ return (737+ <div>738+ {show && <Component />}739+ <button onClick={() => setShow(true)}>Show</button>740+ </div>741+ )742+ }743+ render(<App />, root)744+ expect(document.head.innerHTML).toBe('')745+ expect(root.innerHTML).toBe('<div><button>Show</button></div>')746+ root.querySelector('button')?.click()747+ await Promise.resolve()748+ expect(root.innerHTML).toBe('<div><div>Loading...</div><button>Show</button></div>')749+ await new Promise((resolve) => setTimeout(resolve))750+ await Promise.resolve()751+ expect(root.innerHTML).toBe('<div><div>Content</div><button>Show</button></div>')752+ })753+ })754+755+ it('accept ref object', async () => {756+ const ref = { current: null }757+ const App = () => {758+ return (759+ <div>760+ <script src='script-a.js' ref={ref} async={true} />761+ </div>762+ )763+ }764+ render(<App />, root)765+ expect(ref.current).toBe(document.head.querySelector('script'))766+ })767+768+ it('accept ref function', async () => {769+ const ref = vi.fn()770+ const App = () => {771+ return (772+ <div>773+ <script src='script-a.js' ref={ref} async={true} />774+ </div>775+ )776+ }777+ render(<App />, root)778+ expect(ref).toHaveBeenCalledTimes(1)779+ })780+ })781+782+ describe('form element', () => {783+ it('should accept Function as action', () => {784+ const action = vi.fn()785+ const App = () => {786+ return (787+ <form action={action} method='post'>788+ <input type='text' name='name' value='Hello' />789+ <button type='submit'>Submit</button>790+ </form>791+ )792+ }793+ render(<App />, root)794+ root.querySelector('button')?.click()795+ expect(action).toBeCalledTimes(1)796+ const formData = action.mock.calls[0][0]797+ expect(formData.get('name')).toBe('Hello')798+ })799+800+ it('should accept string as action', () => {801+ const App = () => {802+ return (803+ <form action={'/entries'} method='post'>804+ <button type='submit'>Submit</button>805+ </form>806+ )807+ }808+ render(<App />, root)809+ expect(root.innerHTML).toBe(810+ '<form method="post" action="/entries"><button type="submit">Submit</button></form>'811+ )812+ })813+814+ it('toggle show / hide form', async () => {815+ const action = vi.fn()816+ const App = () => {817+ const [show, setShow] = useState(false)818+ return (819+ <div>820+ {show && (821+ <form action={action} method='post'>822+ <input type='text' name='name' value='Hello' />823+ </form>824+ )}825+ <button onClick={() => setShow((status) => !status)}>Toggle</button>826+ </div>827+ )828+ }829+ render(<App />, root)830+ expect(root.innerHTML).toBe('<div><button>Toggle</button></div>')831+ root.querySelector('button')?.click()832+ await Promise.resolve()833+ expect(root.innerHTML).toBe(834+ '<div><form method="post"><input type="text" name="name" value="Hello"></form><button>Toggle</button></div>'835+ )836+ root.querySelector('button')?.click()837+ await Promise.resolve()838+ await Promise.resolve()839+ await Promise.resolve()840+ expect(root.innerHTML).toBe('<div><button>Toggle</button></div>')841+ })842+ })843+844+ describe('input element', () => {845+ it('should accept Function as formAction', () => {846+ const action = vi.fn()847+ const App = () => {848+ return (849+ <form>850+ <input type='text' name='name' value='Hello' />851+ <input type='submit' value='Submit' formAction={action} />852+ </form>853+ )854+ }855+ render(<App />, root)856+ root.querySelector<HTMLInputElement>('input[type="submit"]')?.click()857+ expect(action).toBeCalledTimes(1)858+ const formData = action.mock.calls[0][0]859+ expect(formData.get('name')).toBe('Hello')860+ })861+862+ it('should accept string as formAction', () => {863+ const App = () => {864+ return (865+ <form method='post'>866+ <input type='submit' formAction={'/entries'} value='Submit' />867+ </form>868+ )869+ }870+ render(<App />, root)871+ expect(root.innerHTML).toBe('<form method="post"><input type="submit" value="Submit"></form>')872+ })873+874+ it('toggle show / hide input', async () => {875+ const action = vi.fn()876+ const App = () => {877+ const [show, setShow] = useState(false)878+ return (879+ <div>880+ {show && (881+ <form method='post'>882+ <input type='submit' formAction={action} value='Submit' />883+ </form>884+ )}885+ <button onClick={() => setShow((status) => !status)}>Toggle</button>886+ </div>887+ )888+ }889+ render(<App />, root)890+ expect(root.innerHTML).toBe('<div><button>Toggle</button></div>')891+ root.querySelector('button')?.click()892+ await Promise.resolve()893+ expect(root.innerHTML).toBe(894+ '<div><form method="post"><input type="submit" value="Submit"></form><button>Toggle</button></div>'895+ )896+ root.querySelector('button')?.click()897+ await Promise.resolve()898+ await Promise.resolve()899+ await Promise.resolve()900+ expect(root.innerHTML).toBe('<div><button>Toggle</button></div>')901+ })902+ })903+904+ describe('button element', () => {905+ it('should accept Function as formAction', () => {906+ const action = vi.fn()907+ const App = () => {908+ return (909+ <form>910+ <input type='text' name='name' value='Hello' />911+ <button type='submit' formAction={action}>912+ Submit913+ </button>914+ </form>915+ )916+ }917+ render(<App />, root)918+ root.querySelector('button')?.click()919+ expect(action).toBeCalledTimes(1)920+ const formData = action.mock.calls[0][0]921+ expect(formData.get('name')).toBe('Hello')922+ })923+924+ it('should accept string as formAction', () => {925+ const App = () => {926+ return (927+ <form method='post'>928+ <button type='submit' formAction={'/entries'}>929+ Submit930+ </button>931+ </form>932+ )933+ }934+ render(<App />, root)935+ expect(root.innerHTML).toBe(936+ '<form method="post"><button type="submit">Submit</button></form>'937+ )938+ })939+940+ it('toggle show / hide', async () => {941+ const action = vi.fn()942+ const App = () => {943+ const [show, setShow] = useState(false)944+ return (945+ <div>946+ {show && (947+ <form method='post'>948+ <button formAction={action}>Submit</button>949+ </form>950+ )}951+ <button id='toggle' onClick={() => setShow((status) => !status)}>952+ Toggle953+ </button>954+ </div>955+ )956+ }957+ render(<App />, root)958+ expect(root.innerHTML).toBe('<div><button id="toggle">Toggle</button></div>')959+ root.querySelector<HTMLButtonElement>('#toggle')?.click()960+ await Promise.resolve()961+ expect(root.innerHTML).toBe(962+ '<div><form method="post"><button>Submit</button></form><button id="toggle">Toggle</button></div>'963+ )964+ root.querySelector<HTMLButtonElement>('#toggle')?.click()965+ await Promise.resolve()966+ await Promise.resolve()967+ await Promise.resolve()968+ expect(root.innerHTML).toBe('<div><button id="toggle">Toggle</button></div>')969+ })970+ })971+})972+973+describe('internal utility method', () => {974+ describe('composeRef()', () => {975+ it('should compose a ref object', () => {976+ const ref = { current: null }977+ const cbCleanUp = vi.fn()978+ const cb = vi.fn().mockReturnValue(cbCleanUp)979+ const composed = composeRef(ref, cb)980+ const cleanup = composed('ref')981+ expect(ref.current).toBe('ref')982+ expect(cb).toBeCalledWith('ref')983+ expect(cbCleanUp).not.toBeCalled()984+ cleanup()985+ expect(ref.current).toBe(null)986+ expect(cbCleanUp).toBeCalledTimes(1)987+ })988+989+ it('should compose a function', () => {990+ const ref = vi.fn()991+ const cbCleanUp = vi.fn()992+ const cb = vi.fn().mockReturnValue(cbCleanUp)993+ const composed = composeRef(ref, cb)994+ const cleanup = composed('ref')995+ expect(ref).toBeCalledWith('ref')996+ expect(cb).toBeCalledWith('ref')997+ expect(cbCleanUp).not.toBeCalled()998+ cleanup()999+ expect(ref).toBeCalledWith(null)1000+ expect(cbCleanUp).toBeCalledTimes(1)1001+ })1002+1003+ it('should compose a function returns a cleanup function', () => {1004+ const refCleanUp = vi.fn()1005+ const ref = vi.fn().mockReturnValue(refCleanUp)1006+ const cbCleanUp = vi.fn()1007+ const cb = vi.fn().mockReturnValue(cbCleanUp)1008+ const composed = composeRef(ref, cb)1009+ const cleanup = composed('ref')1010+ expect(ref).toBeCalledWith('ref')1011+ expect(cb).toBeCalledWith('ref')1012+ expect(refCleanUp).not.toBeCalled()1013+ expect(cbCleanUp).not.toBeCalled()1014+ cleanup()1015+ expect(ref).toHaveBeenCalledTimes(1)1016+ expect(refCleanUp).toBeCalledTimes(1)1017+ expect(cbCleanUp).toBeCalledTimes(1)1018+ })1019+ })1020+})added:src/jsx/dom/intrinsic-element/components.ts+382 added
1+import type { Props } from '../../base'2+import type { FC, JSXNode, PropsWithChildren, RefObject } from '../../types'3+import { newJSXNode } from '../utils'4+import { createPortal, getNameSpaceContext } from '../render'5+import type { PreserveNodeType } from '../render'6+import { useContext } from '../../context'7+import { use, useCallback, useMemo, useState } from '../../hooks'8+import { FormContext, registerAction } from '../hooks'9+import { dataPrecedenceAttr, deDupeKeyMap, domRenderers } from '../../intrinsic-element/common'10+import type { IntrinsicElements } from '../../intrinsic-elements'11+12+// this function is a testing utility and should not be exported to the user13+export const clearCache = () => {14+ blockingPromiseMap = Object.create(null)15+ createdElements = Object.create(null)16+}17+18+// this function is exported for testing and should not be used by the user19+export const composeRef = <T>(20+ ref: RefObject<T> | Function | undefined,21+ cb: (e: T) => void | (() => void)22+): ((e: T) => () => void) => {23+ return useMemo(24+ () => (e: T) => {25+ let refCleanup: (() => void) | undefined26+ if (ref) {27+ if (typeof ref === 'function') {28+ refCleanup =29+ ref(e) ||30+ (() => {31+ ref(null)32+ })33+ } else if (ref && 'current' in ref) {34+ ref.current = e35+ refCleanup = () => {36+ ref.current = null37+ }38+ }39+ }40+41+ const cbCleanup = cb(e)42+ return () => {43+ cbCleanup?.()44+ refCleanup?.()45+ }46+ },47+ [ref]48+ )49+}50+51+let blockingPromiseMap: Record<string, Promise<Event> | undefined> = Object.create(null)52+let createdElements: Record<string, HTMLElement> = Object.create(null)53+const documentMetadataTag = (54+ tag: string,55+ props: Props,56+ preserveNodeType: PreserveNodeType | undefined,57+ supportSort: boolean,58+ supportBlocking: boolean59+) => {60+ if (props?.itemProp) {61+ return newJSXNode({62+ tag,63+ props,64+ })65+ }66+67+ const head = document.head68+69+ let { onLoad, onError, precedence, blocking, ...restProps } = props70+ let element: HTMLElement | null = null71+ let created = false72+73+ const deDupeKeys = deDupeKeyMap[tag]74+ let existingElements: NodeListOf<HTMLElement> | undefined = undefined75+ if (deDupeKeys.length > 0) {76+ const tags = head.querySelectorAll<HTMLElement>(tag)77+ LOOP: for (const e of tags) {78+ for (const key of deDupeKeyMap[tag]) {79+ if (e.getAttribute(key) === props[key]) {80+ element = e81+ break LOOP82+ }83+ }84+ }85+86+ if (!element) {87+ const cacheKey = deDupeKeys.reduce(88+ (acc, key) => (props[key] === undefined ? acc : `${acc}-${key}-${props[key]}`),89+ tag90+ )91+ created = !createdElements[cacheKey]92+ element = createdElements[cacheKey] ||= (() => {93+ const e = document.createElement(tag)94+ for (const key of deDupeKeys) {95+ if (props[key] !== undefined) {96+ e.setAttribute(key, props[key] as string)97+ }98+ // eslint-disable-next-line @typescript-eslint/no-explicit-any99+ if ((props as any).rel) {100+ e.setAttribute('rel', props.rel)101+ }102+ }103+ return e104+ })()105+ }106+ } else {107+ existingElements = head.querySelectorAll<HTMLElement>(tag)108+ }109+110+ precedence = supportSort ? precedence ?? '' : undefined111+ if (supportSort) {112+ restProps[dataPrecedenceAttr] = precedence113+ }114+115+ const insert = useCallback(116+ (e: HTMLElement) => {117+ if (deDupeKeys.length > 0) {118+ let found = false119+ for (const existingElement of head.querySelectorAll<HTMLElement>(tag)) {120+ if (found && existingElement.getAttribute(dataPrecedenceAttr) !== precedence) {121+ head.insertBefore(e, existingElement)122+ return123+ }124+ if (existingElement.getAttribute(dataPrecedenceAttr) === precedence) {125+ found = true126+ }127+ }128+129+ // if sentinel is not found, append to the end130+ head.appendChild(e)131+ } else if (existingElements) {132+ let found = false133+ for (const existingElement of existingElements!) {134+ if (existingElement === e) {135+ found = true136+ break137+ }138+ }139+ if (!found) {140+ // newly created element141+ head.insertBefore(142+ e,143+ head.contains(existingElements[0]) ? existingElements[0] : head.querySelector(tag)144+ )145+ }146+ existingElements = undefined147+ }148+ },149+ [precedence]150+ )151+152+ const ref = composeRef(props.ref, (e: HTMLElement) => {153+ const key = deDupeKeys[0]154+155+ if (preserveNodeType === 2) {156+ e.innerHTML = ''157+ }158+159+ if (created || existingElements) {160+ insert(e)161+ }162+163+ if (!onError && !onLoad) {164+ return165+ }166+167+ let promise = (blockingPromiseMap[e.getAttribute(key) as string] ||= new Promise<Event>(168+ (resolve, reject) => {169+ e.addEventListener('load', resolve)170+ e.addEventListener('error', reject)171+ }172+ ))173+ if (onLoad) {174+ promise = promise.then(onLoad)175+ }176+ if (onError) {177+ promise = promise.catch(onError)178+ }179+ promise.catch(() => {})180+ })181+182+ if (supportBlocking && blocking === 'render') {183+ const key = deDupeKeyMap[tag][0]184+ if (props[key]) {185+ const value = props[key]186+ const promise = (blockingPromiseMap[value] ||= new Promise<Event>((resolve, reject) => {187+ insert(element as HTMLElement)188+ element!.addEventListener('load', resolve)189+ element!.addEventListener('error', reject)190+ }))191+ use(promise)192+ }193+ }194+195+ const jsxNode = newJSXNode({196+ tag,197+ props: {198+ ...restProps,199+ ref,200+ },201+ }) as JSXNode & { e?: HTMLElement; p?: PreserveNodeType }202+203+ jsxNode.p = preserveNodeType // preserve for unmounting204+ if (element) {205+ jsxNode.e = element206+ }207+208+ return createPortal(209+ jsxNode,210+ head211+ // eslint-disable-next-line @typescript-eslint/no-explicit-any212+ ) as any213+}214+export const title: FC<PropsWithChildren> = (props) => {215+ const nameSpaceContext = getNameSpaceContext()216+ const ns = nameSpaceContext && useContext(nameSpaceContext)217+ if (ns?.endsWith('svg')) {218+ return newJSXNode({219+ tag: 'title',220+ props,221+ })222+ }223+ return documentMetadataTag('title', props, undefined, false, false)224+}225+226+export const script: FC<PropsWithChildren<IntrinsicElements['script']>> = (props) => {227+ if (!props || ['src', 'async'].some((k) => !props[k])) {228+ return newJSXNode({229+ tag: 'style',230+ props,231+ })232+ }233+ return documentMetadataTag('script', props, 1, false, true)234+}235+236+export const style: FC<PropsWithChildren<IntrinsicElements['style']>> = (props) => {237+ if (!props || !['href', 'precedence'].every((k) => k in props)) {238+ return newJSXNode({239+ tag: 'style',240+ props,241+ })242+ }243+ props['data-href'] = props.href244+ delete props.href245+ return documentMetadataTag('style', props, 2, true, true)246+}247+248+export const link: FC<PropsWithChildren<IntrinsicElements['link']>> = (props) => {249+ if (250+ !props ||251+ ['onLoad', 'onError'].some((k) => k in props) ||252+ (props.rel === 'stylesheet' && (!('precedence' in props) || 'disabled' in props))253+ ) {254+ return newJSXNode({255+ tag: 'link',256+ props,257+ })258+ }259+ return documentMetadataTag('link', props, 1, 'precedence' in props, true)260+}261+262+export const meta: FC<PropsWithChildren> = (props) => {263+ return documentMetadataTag('meta', props, undefined, false, false)264+}265+266+const customEventFormAction = Symbol()267+export const form: FC<268+ PropsWithChildren<{269+ action?: Function | string270+ method?: 'get' | 'post'271+ ref?: RefObject<HTMLFormElement> | ((e: HTMLFormElement | null) => void | (() => void))272+ }>273+> = (props) => {274+ const { action, ...restProps } = props275+ if (typeof action !== 'function') {276+ // eslint-disable-next-line @typescript-eslint/no-explicit-any277+ ;(restProps as any).action = action278+ }279+280+ const [state, setState] = useState<[FormData | null, boolean]>([null, false]) // [FormData, isDirty]281+ const onSubmit = useCallback<(ev: SubmitEvent | CustomEvent) => void>(282+ async (ev: SubmitEvent | CustomEvent) => {283+ const currentAction = ev.isTrusted284+ ? action285+ : (ev as CustomEvent).detail[customEventFormAction]286+ if (typeof currentAction !== 'function') {287+ return288+ }289+290+ ev.preventDefault()291+ const formData = new FormData(ev.target as HTMLFormElement)292+ setState([formData, true])293+ const actionRes = currentAction(formData)294+ if (actionRes instanceof Promise) {295+ registerAction(actionRes)296+ await actionRes297+ }298+ setState([null, true])299+ },300+ []301+ )302+303+ const ref = composeRef(props.ref, (el: HTMLFormElement) => {304+ el.addEventListener('submit', onSubmit)305+ return () => {306+ el.removeEventListener('submit', onSubmit)307+ }308+ })309+310+ const [data, isDirty] = state311+ state[1] = false312+ return newJSXNode({313+ tag: FormContext as unknown as Function,314+ props: {315+ value: {316+ pending: data !== null,317+ data,318+ method: data ? 'post' : null,319+ action: data ? action : null,320+ },321+ children: newJSXNode({322+ tag: 'form',323+ props: {324+ ...restProps,325+ ref,326+ },327+ }),328+ },329+ f: isDirty,330+ // eslint-disable-next-line @typescript-eslint/no-explicit-any331+ } as any) as any332+}333+334+const formActionableElement = (335+ tag: string,336+ {337+ formAction,338+ ...props339+ }: {340+ formAction?: Function | string341+ ref?: RefObject<HTMLInputElement> | ((e: HTMLInputElement) => void | (() => void))342+ }343+) => {344+ if (typeof formAction === 'function') {345+ const onClick = useCallback<(ev: MouseEvent) => void>((ev: MouseEvent) => {346+ ev.preventDefault()347+ ;(ev.currentTarget! as HTMLInputElement).form!.dispatchEvent(348+ new CustomEvent('submit', { detail: { [customEventFormAction]: formAction } })349+ )350+ }, [])351+352+ props.ref = composeRef(props.ref, (el: HTMLInputElement) => {353+ el.addEventListener('click', onClick)354+ return () => {355+ el.removeEventListener('click', onClick)356+ }357+ })358+ }359+360+ return newJSXNode({361+ tag,362+ props,363+ // eslint-disable-next-line @typescript-eslint/no-explicit-any364+ }) as any365+}366+367+export const input: FC<PropsWithChildren<IntrinsicElements['input']>> = (props) =>368+ formActionableElement('input', props)369+370+export const button: FC<PropsWithChildren<IntrinsicElements['button']>> = (props) =>371+ formActionableElement('button', props)372+373+Object.assign(domRenderers, {374+ title,375+ script,376+ style,377+ link,378+ meta,379+ form,380+ input,381+ button,382+})modified:src/jsx/dom/client.test.tsx+10 added-1 removed
1 /** @jsxImportSource ../ */2 import { JSDOM } from 'jsdom'3-import { createRoot, hydrateRoot } from './client'3+import DefaultExport, { createRoot, hydrateRoot } from './client'4 import { useEffect } from '.'5 6 describe('createRoot', () => {7 beforeAll(() => {108 unmodified lines116 root.unmount()117 expect(() => root.render(App2)).toThrow('Cannot update an unmounted root')118 })119 })120+121+describe('default export', () => {122+ ;['createRoot', 'hydrateRoot'].forEach((key) => {123+ it(key, () => {124+ // eslint-disable-next-line @typescript-eslint/no-explicit-any125+ expect((DefaultExport as any)[key]).toBeDefined()126+ })127+ })128+})modified:src/jsx/dom/client.ts+5 added
80 unmodified lines81 const root = createRoot(element, options)82 root.render(reactNode)83 return root84 }85+86+export default {87+ createRoot,88+ hydrateRoot,89+}modified:src/jsx/dom/components.test.tsx+109 added
58 unmodified lines59 await new Promise((resolve) => setTimeout(resolve))60 expect(root.innerHTML).toBe('<p>1</p>')61 })62 63+ it('with use() update', async () => {64+ const counterMap: Record<number, Promise<number>> = {}65+ const getCounter = (count: number) => (counterMap[count] ||= Promise.resolve(count + 1))66+ const Content = ({ count }: { count: number }) => {67+ const num = use(getCounter(count))68+ return (69+ <>70+ <div>{num}</div>71+ </>72+ )73+ }74+ const Component = () => {75+ const [count, setCount] = useState(0)76+ return (77+ <Suspense fallback={<div>Loading...</div>}>78+ <Content count={count} />79+ <button onClick={() => setCount(count + 1)}>Increment</button>80+ </Suspense>81+ )82+ }83+ const App = <Component />84+ render(App, root)85+ expect(root.innerHTML).toBe('<div>Loading...</div>')86+ await Promise.resolve()87+ await Promise.resolve()88+ expect(root.innerHTML).toBe('<div>1</div><button>Increment</button>')89+ root.querySelector('button')?.click()90+ await Promise.resolve()91+ expect(root.innerHTML).toBe('<div>Loading...</div>')92+ await Promise.resolve()93+ await Promise.resolve()94+ expect(root.innerHTML).toBe('<div>2</div><button>Increment</button>')95+ })96+97 it('with use() nested', async () => {98 let resolve: (value: number) => void = () => {}99 const promise = new Promise<number>((_resolve) => (resolve = _resolve))100 const Content = () => {63 unmodified lines164 await Promise.resolve()165 await Promise.resolve()166 expect(root.innerHTML).toBe('<div><button>Hide</button><p>2</p></div>')167 })168+169+ it('Suspense at child', async () => {170+ let resolve: (value: number) => void = () => {}171+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))172+ const Content = () => {173+ const num = use(promise)174+ return <p>{num}</p>175+ }176+177+ const Component = () => {178+ return (179+ <Suspense fallback={<div>Loading...</div>}>180+ <Content />181+ </Suspense>182+ )183+ }184+ const App = () => {185+ const [show, setShow] = useState(false)186+ return (187+ <div>188+ {show && <Component />}189+ <button onClick={() => setShow(true)}>Show</button>190+ </div>191+ )192+ }193+ render(<App />, root)194+ expect(root.innerHTML).toBe('<div><button>Show</button></div>')195+ root.querySelector('button')?.click()196+ await Promise.resolve()197+ expect(root.innerHTML).toBe('<div><div>Loading...</div><button>Show</button></div>')198+ resolve(2)199+ await Promise.resolve()200+ await Promise.resolve()201+ expect(root.innerHTML).toBe('<div><p>2</p><button>Show</button></div>')202+ })203+204+ it('Suspense at child counter', async () => {205+ const promiseMap: Record<number, Promise<number>> = {}206+ const Counter = () => {207+ const [count, setCount] = useState(0)208+ const promise = (promiseMap[count] ||= Promise.resolve(count))209+ const value = use(promise)210+ return (211+ <>212+ <p>{value}</p>213+ <button onClick={() => setCount(count + 1)}>Increment</button>214+ </>215+ )216+ }217+ const Component = () => {218+ return (219+ <Suspense fallback={<div>Loading...</div>}>220+ <Counter />221+ </Suspense>222+ )223+ }224+ const App = () => {225+ return (226+ <div>227+ <Component />228+ </div>229+ )230+ }231+ render(<App />, root)232+ expect(root.innerHTML).toBe('<div><div>Loading...</div></div>')233+ await Promise.resolve()234+ await Promise.resolve()235+ expect(root.innerHTML).toBe('<div><p>0</p><button>Increment</button></div>')236+ root.querySelector('button')?.click()237+ await Promise.resolve()238+ expect(root.innerHTML).toBe('<div><div>Loading...</div></div>')239+ await Promise.resolve()240+ await Promise.resolve()241+ expect(root.innerHTML).toBe('<div><p>1</p><button>Increment</button></div>')242+ })243 })244 245 describe('ErrorBoundary', () => {246 let dom: JSDOM84 unmodified linesmodified:src/jsx/dom/context.test.tsx+18 added
52 unmodified lines53 render(App, root)54 expect(root.innerHTML).toBe('<p>1</p>')55 })56 57+ it('<Context> as a provider ', async () => {58+ const Context = createContext(0)59+ const Content = () => {60+ const num = useContext(Context)61+ return <p>{num}</p>62+ }63+ const Component = () => {64+ return (65+ <Context value={1}>66+ <Content />67+ </Context>68+ )69+ }70+ const App = <Component />71+ render(App, root)72+ expect(root.innerHTML).toBe('<p>1</p>')73+ })74+75 it('simple context with state', async () => {76 const Context = createContext(0)77 const Content = () => {78 const [count, setCount] = useState(0)106 unmodified linesmodified:src/jsx/dom/context.ts+10 added-12 removed
1 import type { Child } from '../base'2 import { DOM_ERROR_HANDLER } from '../constants'3 import type { Context } from '../context'4 import { globalContexts } from '../context'5-import { Fragment } from './jsx-runtime'6-import { setInternalTagFlag } from './utils'5+import { newJSXNode, setInternalTagFlag } from './utils'6 8-export const createContextProviderFunction = <T>(values: T[]): Function =>9- setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {7+export const createContextProviderFunction =8+ <T>(values: T[]): Function =>9+ ({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }13 18 unmodified lines32 values.pop()33 }),34 props: {},35 })36- const res = Fragment(props)36+ const res = newJSXNode({ tag: '', props })37 // eslint-disable-next-line @typescript-eslint/no-explicit-any38 ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => {39 values.pop()40 throw err41 }42 return res43- })43+ }44 45 export const createContext = <T>(defaultValue: T): Context<T> => {46 const values = [defaultValue]47- const context = {48- values,49- // eslint-disable-next-line @typescript-eslint/no-explicit-any50- Provider: createContextProviderFunction(values) as any,51- }52- globalContexts.push(context)47+ const context: Context<T> = createContextProviderFunction(values) as Context<T>48+ context.values = values49+ context.Provider = context50+ globalContexts.push(context as Context<unknown>)51 return context52 }modified:src/jsx/dom/index.test.tsx+115 added-4 removed
238 unmodified lines239 await Promise.resolve()240 expect(root.innerHTML).toBe('<button>remove</button>')241 expect(ref).toHaveBeenLastCalledWith(null)242 })243+244+ it('ref cleanup function', async () => {245+ const cleanup = vi.fn()246+ const ref = vi.fn().mockReturnValue(cleanup)247+ const App = () => {248+ const [show, setShow] = useState(true)249+ return (250+ <>251+ {show && <div ref={ref} />}252+ <button onClick={() => setShow(false)}>remove</button>253+ </>254+ )255+ }256+ render(<App />, root)257+ expect(root.innerHTML).toBe('<div></div><button>remove</button>')258+ expect(ref).toHaveBeenLastCalledWith(expect.any(dom.window.HTMLDivElement))259+ root.querySelector('button')?.click()260+ await Promise.resolve()261+ expect(root.innerHTML).toBe('<button>remove</button>')262+ expect(ref).toBeCalledTimes(1)263+ expect(cleanup).toBeCalledTimes(1)264+ })265 })266 267+ describe('skip build child', () => {268+ it('simple', async () => {269+ const Child = vi.fn(({ count }: { count: number }) => <div>{count}</div>)270+ const App = () => {271+ const [count, setCount] = useState(0)272+ return (273+ <>274+ <div>{count}</div>275+ <Child count={Math.floor(count / 2)} />276+ <button onClick={() => setCount(count + 1)}>+</button>277+ </>278+ )279+ }280+ render(<App />, root)281+ expect(root.innerHTML).toBe('<div>0</div><div>0</div><button>+</button>')282+ expect(Child).toBeCalledTimes(1)283+ root.querySelector('button')?.click()284+ await Promise.resolve()285+ expect(root.innerHTML).toBe('<div>1</div><div>0</div><button>+</button>')286+ expect(Child).toBeCalledTimes(1)287+ root.querySelector('button')?.click()288+ await Promise.resolve()289+ expect(root.innerHTML).toBe('<div>2</div><div>1</div><button>+</button>')290+ expect(Child).toBeCalledTimes(2)291+ })292+ })293+294 describe('defaultProps', () => {295 it('simple', () => {296 const App: FC<{ name?: string }> = ({ name }) => <div>{name}</div>297 App.defaultProps = { name: 'default' }889 unmodified lines1187 1188 expect(createElementSpy).not.toHaveBeenCalled()1189 })1190 1142- it('setState for unnamed function', async () => {1191+ it('useState for unnamed function', async () => {1192 const Input = ({ label, onInput }: { label: string; onInput: (value: string) => void }) => {1193 return (1194 <div>1195 <label>{label}</label>33 unmodified lines1229 '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><span>{"name":"John","email":"john@example.com"}</span></form>'1230 )1231 })1232 1233+ it('useState for grand child function', async () => {1234+ const GrandChild = () => {1235+ const [count, setCount] = useState(0)1236+ return (1237+ <>1238+ {count === 0 ? <p>Zero</p> : <span>Not Zero</span>}1239+ <button onClick={() => setCount(count + 1)}>+</button>1240+ </>1241+ )1242+ }1243+ const Child = () => {1244+ return <GrandChild />1245+ }1246+ const App = () => {1247+ const [show, setShow] = useState(false)1248+ return (1249+ <div>1250+ {show && <Child />}1251+ <button onClick={() => setShow(!show)}>toggle</button>1252+ </div>1253+ )1254+ }1255+ render(<App />, root)1256+ expect(root.innerHTML).toBe('<div><button>toggle</button></div>')1257+ root.querySelector('button')?.click()1258+ await Promise.resolve()1259+ expect(root.innerHTML).toBe('<div><p>Zero</p><button>+</button><button>toggle</button></div>')1260+ root.querySelector('button')?.click()1261+ await Promise.resolve()1262+ expect(root.innerHTML).toBe(1263+ '<div><span>Not Zero</span><button>+</button><button>toggle</button></div>'1264+ )1265+ })1266+1267 describe('className', () => {1268 it('should convert to class attribute for intrinsic elements', () => {1269 const App = <h1 className='h1'>Hello</h1>1270 render(App, root)491 unmodified lines1762 await Promise.resolve()1763 expect(root.innerHTML).toBe('<div><p>0</p><button>+</button><p>1</p><button>+</button></div>')1764 expect(callbackSet.size).toBe(1)1765 })1766+1767+ it('deferent callbacks', async () => {1768+ const callbackSet = new Set<Function>()1769+ const Counter = () => {1770+ const [count, setCount] = useState(0)1771+ const double = useCallback((input: number): number => {1772+ return input * 21773+ }, [])1774+ callbackSet.add(double)1775+ return (1776+ <div>1777+ <p>{double(count)}</p>1778+ <button onClick={() => setCount((c) => c + 1)}>+</button>1779+ </div>1780+ )1781+ }1782+ const app = <Counter />1783+ render(app, root)1784+ expect(root.innerHTML).toBe('<div><p>0</p><button>+</button></div>')1785+ const button = root.querySelector('button') as HTMLButtonElement1786+ button.click()1787+ await Promise.resolve()1788+ expect(root.innerHTML).toBe('<div><p>2</p><button>+</button></div>')1789+ expect(callbackSet.size).toBe(1)1790+ })1791 })1792 1793 describe('useMemo', () => {1794 it('simple', async () => {240 unmodified lines2035 </>2036 )2037 }2038 render(<App />, root)1931- expect(root.innerHTML).toBe(1932- '<title>Document Title</title><svg><title>SVG Title</title></svg>'1933- )2039+ expect(document.head.innerHTML).toBe('<title>Document Title</title>')2040+ expect(root.innerHTML).toBe('<svg><title>SVG Title</title></svg>')2041 expect(document.querySelector('title')).toBeInstanceOf(dom.window.HTMLTitleElement)2042 expect(document.querySelector('svg title')).toBeInstanceOf(dom.window.SVGTitleElement)2043 })2044 218 unmodified lines2263 'useTransition',2264 'useDeferredValue',2265 'startViewTransition',2266 'useViewTransition',2267+ 'useActionState',2268+ 'useFormStatus',2269+ 'useOptimistic',2270 'useMemo',2271 'useLayoutEffect',2272 'Suspense',2273 'Fragment',2274 'flushSync',2275 'createPortal',2276+ 'StrictMode',2277 ].forEach((key) => {2278 it(key, () => {2279 // eslint-disable-next-line @typescript-eslint/no-explicit-any2280 expect((DefaultExport as any)[key]).toBeDefined()3 unmodified linesmodified:src/jsx/dom/index.ts+9 added
27 unmodified lines28 useSyncExternalStore,29 useTransition,30 useViewTransition,31 } from '../hooks'32+import { useActionState, useFormStatus, useOptimistic } from './hooks'33 import { ErrorBoundary, Suspense } from './components'34 import { createContext } from './context'35 import { Fragment, jsx } from './jsx-runtime'36 import { createPortal, flushSync } from './render'57 unmodified lines94 createRef,95 forwardRef,96 useImperativeHandle,97 useSyncExternalStore,98+ useFormStatus,99+ useActionState,100+ useOptimistic,101 Suspense,102 ErrorBoundary,103 createContext,104 useContext,2 unmodified lines107 createElement,108 cloneElement,109 Children,110 Fragment,111+ Fragment as StrictMode,112 DOMAttributes,113 flushSync,114 createPortal,115 }19 unmodified lines135 createRef,136 forwardRef,137 useImperativeHandle,138 useSyncExternalStore,139+ useFormStatus,140+ useActionState,141+ useOptimistic,142 Suspense,143 ErrorBoundary,144 createContext,145 useContext,2 unmodified lines148 createElement,149 cloneElement,150 Children,151 Fragment,152+ StrictMode: Fragment,153 flushSync,154 createPortal,155 }156 3 unmodified linesmodified:src/jsx/dom/jsx-dev-runtime.ts+4 added-1 removed
3 unmodified lines4 */5 6 import type { JSXNode, Props } from '../base'7 import { newJSXNode } from './utils'8+import * as intrinsicElementTags from './intrinsic-element/components'9 10 export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => {11 return newJSXNode({11- tag,12+ tag:13+ (typeof tag === 'string' && intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) ||14+ tag,15 props,16 key,17 })18 }2 unmodified linesmodified:src/jsx/dom/render.ts+133 added-59 removed
29 unmodified lines30 31 type Container = HTMLElement | DocumentFragment32 type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined33 type SupportedElement = HTMLElement | SVGElement | MathMLElement34+export type PreserveNodeType =35+ | 1 // preserve only self36+ | 2 // preserve self and children37 38 export type NodeObject = {39 pP: Props | undefined // previous props40 nN: Node | undefined // next node41 vC: Node[] // virtual dom children42+ pC?: Node[] // previous virtual dom children43 vR: Node[] // virtual dom children to remove44 s?: Node[] // shadow virtual dom children45 n?: string // namespace46+ f?: boolean // force build47 c: Container | undefined // container48 e: SupportedElement | Text | undefined // rendered element49+ p?: PreserveNodeType // preserve HTMLElement if it will be unmounted50+ a?: boolean // cancel apply() if true51 [DOM_STASH]:52 | [53 number, // current hook index54 // eslint-disable-next-line @typescript-eslint/no-explicit-any55 any[][], // stash for hooks49- LocalJSXContexts // context56+ LocalJSXContexts, // context57+ [Context, Function, NodeObject] // [context, error handler, node] for closest error boundary or suspense58 ]51- | [52- number,53- // eslint-disable-next-line @typescript-eslint/no-explicit-any54- any[][]59+ // eslint-disable-next-line @typescript-eslint/no-explicit-any60+ | [number, any[][]]55- ]61 } & JSXNode62 type NodeString = {63 t: string // text content64 d: boolean // is dirty1 unmodified line66 e?: Text67 // like a NodeObject68 vC: undefined69 nN: undefined70+ p?: true71 // from JSXNode72 key: undefined73 tag: undefined74 }13 unmodified lines88 PendingType, // PendingType89 boolean, // got an error90 UpdateHook, // update hook91 boolean, // is in view transition86- boolean // is in top level render92+ boolean, // is in top level render93+ [Context, Function, NodeObject][] // [context, error handler, node] stack for this context94 ]95 | [PendingType, boolean, UpdateHook, boolean]96 | [PendingType, boolean, UpdateHook]97 | [PendingType, boolean]1 unmodified line99 | []100 101 export const buildDataStack: [Context, Node][] = []102 103+const refCleanupMap: WeakMap<Element, () => void> = new WeakMap()104+105 let nameSpaceContext: JSXContext<string> | undefined = undefined106+export const getNameSpaceContext = () => nameSpaceContext107 108 const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)109 110 const getEventSpec = (key: string): [string, boolean] | undefined => {35 unmodified lines146 }147 } else if (key === 'dangerouslySetInnerHTML' && value) {148 container.innerHTML = value.__html149 } else if (key === 'ref') {150+ let cleanup151 if (typeof value === 'function') {141- value(container)152+ cleanup = value(container) || (() => value(null))153 } else if (value && 'current' in value) {154 value.current = container155+ cleanup = () => (value.current = null)156 }157+ refCleanupMap.set(container, cleanup)158 } else if (key === 'style') {159 const style = container.style160 if (typeof value === 'string') {161 style.cssText = value49 unmodified lines211 const eventSpec = getEventSpec(key)212 if (eventSpec) {213 container.removeEventListener(eventSpec[0], value, eventSpec[1])214 } else if (key === 'ref') {202- if (typeof value === 'function') {203- value(null)204- } else {205- value.current = null206- }215+ refCleanupMap.get(container)?.()216 } else {217 container.removeAttribute(toAttributeName(container, key))218 }219 }74 unmodified lines294 const removeNode = (node: Node): void => {295 if (!isNodeString(node)) {296 node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())297 289- if (node.e && node.props?.ref) {290- if (typeof node.props.ref === 'function') {291- node.props.ref(null)292- } else {293- node.props.ref.current = null294- }298+ refCleanupMap.get(node.e as Element)?.()299+ if (node.p === 2) {300+ node.vC?.forEach((n) => (n.p = 2))301 }302 node.vC?.forEach(removeNode)303 }298- if (node.tag !== HONO_PORTAL_ELEMENT) {304+ if (!node.p) {305 node.e?.remove()306+ delete node.e307 }308 if (typeof node.tag === 'function') {309 updateMap.delete(node)310 fallbackUpdateFnArrayMap.delete(node)311+ // eslint-disable-next-line @typescript-eslint/no-explicit-any312+ delete (node as any)[DOM_STASH][3] // delete explicitly for avoid circular reference313+ node.a = true314 }315 }316 317 const apply = (node: NodeObject, container: Container): void => {25 unmodified lines343 344 return345 }346 347+const cancelBuild: symbol = Symbol()348 const applyNodeObject = (node: NodeObject, container: Container): void => {349 const next: Node[] = []350 const remove: Node[] = []351 const callbacks: EffectData[] = []39 unmodified lines391 const fallbackUpdateFnArrayMap: WeakMap<392 NodeObject,393 Array<() => Promise<NodeObject | undefined>>394 > = new WeakMap<NodeObject, Array<() => Promise<NodeObject | undefined>>>()384-export const build = (385- context: Context,386- node: NodeObject,387- topLevelErrorHandlerNode: NodeObject | undefined,388- children?: Child[]389-): void => {390- let errorHandler: ErrorHandler | undefined391- children ||=392- typeof node.tag == 'function' ? invokeTag(context, node) : toArray(node.props.children)393- if ((children[0] as JSXNode)?.tag === '') {394- // eslint-disable-next-line @typescript-eslint/no-explicit-any395- errorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler396- topLevelErrorHandlerNode ||= node395+export const build = (context: Context, node: NodeObject, children?: Child[]): void => {396+ const buildWithPreviousChildren = !children && node.pC397+ if (children) {398+ node.pC ||= node.vC399 }398- const oldVChildren: Node[] = node.vC ? [...node.vC] : []399- const vChildren: Node[] = []400- node.vR = []401- let prevNode: Node | undefined400+401+ let foundErrorHandler: ErrorHandler | undefined402 try {403+ children ||=404+ typeof node.tag == 'function' ? invokeTag(context, node) : toArray(node.props.children)405+ // eslint-disable-next-line @typescript-eslint/no-explicit-any406+ if ((children[0] as JSXNode)?.tag === '' && (children[0] as any)[DOM_ERROR_HANDLER]) {407+ // eslint-disable-next-line @typescript-eslint/no-explicit-any408+ foundErrorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler409+ context[5]!.push([context, foundErrorHandler, node])410+ }411+ const oldVChildren: Node[] = buildWithPreviousChildren412+ ? [...(node.pC as Node[])]413+ : node.vC414+ ? [...node.vC]415+ : []416+ const vChildren: Node[] = []417+ node.vR = buildWithPreviousChildren ? [...node.vC] : []418+ let prevNode: Node | undefined419 children.flat().forEach((c: Child) => {420 let child = buildNode(c)421 if (child) {406- if (prevNode) {407- prevNode.nN = child408- }409- prevNode = child410-422 if (423 typeof child.tag === 'function' &&424 // eslint-disable-next-line @typescript-eslint/no-explicit-any414- !(child.tag as any)[DOM_INTERNAL_TAG] &&415- globalJSXContexts.length > 0425+ !(child.tag as any)[DOM_INTERNAL_TAG]426 ) {427+ if (globalJSXContexts.length > 0) {417- child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])428+ child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])429+ }430+ if (context[5]?.length) {431+ child[DOM_STASH][3] = context[5].at(-1) as [Context, ErrorHandler, NodeObject]432+ }433 }434 435 let oldChild: Node | undefined436 const i = oldVChildren.findIndex(7 unmodified lines444 oldChild = oldVChildren[i]445 oldVChildren.splice(i, 1)446 }447 448+ let skipBuild = false449 if (oldChild) {450 if (isNodeString(child)) {451 if ((oldChild as NodeString).t !== child.t) {452 ;(oldChild as NodeString).t = child.t // update text content2 unmodified lines455 child = oldChild456 } else if (oldChild.tag !== child.tag) {457 node.vR.push(oldChild)458 } else {443- oldChild.pP = oldChild.props459+ const pP = (oldChild.pP = oldChild.props)460 oldChild.props = child.props461+ oldChild.f ||= child.f || node.f462 if (typeof child.tag === 'function') {463 oldChild[DOM_STASH][2] = child[DOM_STASH][2] || []464+ oldChild[DOM_STASH][3] = child[DOM_STASH][3]465+466+ if (!oldChild.f) {467+ const prevPropsKeys = Object.keys(pP)468+ const currentProps = oldChild.props469+ skipBuild =470+ prevPropsKeys.length === Object.keys(currentProps).length &&471+ prevPropsKeys.every((k) => k in currentProps && currentProps[k] === pP[k])472+ }473 }474 child = oldChild475 }476 } else if (!isNodeString(child) && nameSpaceContext) {2 unmodified lines479 child.n = ns480 }481 }482 457- if (!isNodeString(child)) {458- build(context, child, topLevelErrorHandlerNode)483+ if (!isNodeString(child) && !skipBuild) {484+ build(context, child)485+ delete child.f486 }487 vChildren.push(child)488+489+ for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1) as NodeObject) {490+ p.nN = child491+ }492+ prevNode = child493 }494 })495 node.vC = vChildren496 node.vR.push(...oldVChildren)497+ if (buildWithPreviousChildren) {498+ delete node.pC499+ }500 } catch (e) {501+ node.f = true502+ if (e === cancelBuild) {503+ if (foundErrorHandler) {504+ return505+ } else {506+ throw e507+ }508+ }509+510+ const [errorHandlerContext, errorHandler, errorHandlerNode] =511+ node[DOM_STASH]?.[3] || ([] as unknown as [undefined, undefined])512+513 if (errorHandler) {514 const fallbackUpdateFn = () =>468- update([0, false, context[2] as UpdateHook], topLevelErrorHandlerNode as NodeObject)515+ update([0, false, context[2] as UpdateHook], errorHandlerNode as NodeObject)516 const fallbackUpdateFnArray =470- fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject) || []517+ fallbackUpdateFnArrayMap.get(errorHandlerNode as NodeObject) || []518 fallbackUpdateFnArray.push(fallbackUpdateFn)472- fallbackUpdateFnArrayMap.set(topLevelErrorHandlerNode as NodeObject, fallbackUpdateFnArray)519+ fallbackUpdateFnArrayMap.set(errorHandlerNode as NodeObject, fallbackUpdateFnArray)520 const fallback = errorHandler(e, () => {474- const fnArray = fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject)521+ const fnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode as NodeObject)522 if (fnArray) {523 const i = fnArray.indexOf(fallbackUpdateFn)524 if (i !== -1) {525 fnArray.splice(i, 1)2 unmodified lines528 }529 })530 if (fallback) {531 if (context[0] === 1) {532+ // low priority render533 context[1] = true534 } else {487- build(context, node, topLevelErrorHandlerNode, [fallback])535+ build(context, errorHandlerNode, [fallback])536+ if (537+ (errorHandler.length === 1 || context !== errorHandlerContext) &&538+ errorHandlerNode.c539+ ) {540+ // render error boundary immediately541+ apply(errorHandlerNode, errorHandlerNode.c as Container)542+ return543+ }544 }489- return545+ throw cancelBuild546 }547 }548+549 throw e550+ } finally {551+ if (foundErrorHandler) {552+ context[5]!.pop()553+ }554 }555 }556 557 export const buildNode = (node: Child): Node | undefined => {6 unmodified lines564 node = newJSXNode({565 tag: (node as NodeObject).tag,566 props: (node as NodeObject).props,567 key: (node as NodeObject).key,507- })568+ f: (node as NodeObject).f,569+ // eslint-disable-next-line @typescript-eslint/no-explicit-any570+ } as any)571 }572 if (typeof (node as JSXNode).tag === 'function') {573 ;(node as NodeObject)[DOM_STASH] = [0, []]574 } else {1 unmodified line576 if (ns) {577 nameSpaceContext ||= createContext('')578 ;(node as JSXNode).props.children = [579 {517- tag: nameSpaceContext.Provider,580+ tag: nameSpaceContext,581 props: {582 value: ((node as NodeObject).n = `http://www.w3.org/${ns}`),583 children: (node as JSXNode).props.children,584 },585 },523- // eslint-disable-next-line @typescript-eslint/no-explicit-any524- ] as any586+ ]587 }588 }589 return node as NodeObject590 }9 unmodified lines600 const updateSync = (context: Context, node: NodeObject): void => {601 node[DOM_STASH][2]?.forEach(([c, v]) => {602 c.values.push(v)603 })604+ try {542- build(context, node, undefined)605+ build(context, node, undefined)606+ } catch (e) {607+ return608+ }609+ if (node.a) {610+ delete node.a611+ return612+ }613 node[DOM_STASH][2]?.forEach(([c]) => {614 c.values.pop()615 })616 if (context[0] !== 1 || !context[1]) {10 unmodified lines627 export const update = async (628 context: Context,629 node: NodeObject630 ): Promise<NodeObject | undefined> => {631+ context[5] ||= []632+633 const existing = updateMap.get(node)634 if (existing) {635 // execute only the last update() call, so the previous update will be canceled.636 existing[0](undefined)31 unmodified lines668 }669 670 export const renderNode = (node: NodeObject, container: Container): void => {671 const context: Context = []672+ ;(context as Context)[5] = [] // error handler stack673 ;(context as Context)[4] = true // start top level render674 build(context, node, undefined)675 ;(context as Context)[4] = false // finish top level render676 29 unmodified lines706 children,707 },708 key,709 e: container,710+ p: 1,711 // eslint-disable-next-line @typescript-eslint/no-explicit-any712 } as any)added:src/jsx/dom/server.test.tsx+128 added
1+/** @jsxImportSource ../ */2+import { renderToReadableStream, renderToString } from './server'3+4+describe('renderToString', () => {5+ it('Should be able to render HTML element', () => {6+ expect(renderToString(<h1>Hello</h1>)).toBe('<h1>Hello</h1>')7+ })8+9+ it('Should be able to render null', () => {10+ expect(renderToString(null)).toBe('')11+ })12+13+ it('Should be able to render undefined', () => {14+ expect(renderToString(undefined)).toBe('')15+ })16+17+ it('Should be able to render number', () => {18+ expect(renderToString(1)).toBe('1')19+ })20+21+ it('Should be able to render string', () => {22+ expect(renderToString('Hono')).toBe('Hono')23+ })24+25+ it('Should omit options', () => {26+ expect(renderToString('Hono', { identifierPrefix: 'test' })).toBe('Hono')27+ })28+29+ it('Should raise error for async component', async () => {30+ const AsyncComponent = async () => <h1>Hello from async component</h1>31+ expect(() => renderToString(<AsyncComponent />)).toThrowError()32+ })33+})34+35+describe('renderToReadableStream', () => {36+ const textDecoder = new TextDecoder()37+ const getStringFromStream = async (stream: ReadableStream<Uint8Array>): Promise<string> => {38+ const reader = stream.getReader()39+ let str = ''40+ for (;;) {41+ const { done, value } = await reader.read()42+ if (done) {43+ break44+ }45+ str += textDecoder.decode(value)46+ }47+ return str48+ }49+50+ it('Should be able to render HTML element', async () => {51+ const stream = await renderToReadableStream(<h1>Hello</h1>)52+ const reader = stream.getReader()53+ let { done, value } = await reader.read()54+ expect(done).toBe(false)55+ expect(textDecoder.decode(value)).toBe('<h1>Hello</h1>')56+ done = (await reader.read()).done57+ expect(done).toBe(true)58+ })59+60+ it('Should be able to render null', async () => {61+ expect(await getStringFromStream(await renderToReadableStream(null))).toBe('')62+ })63+64+ it('Should be able to render undefined', async () => {65+ expect(await getStringFromStream(await renderToReadableStream(undefined))).toBe('')66+ })67+68+ it('Should be able to render number', async () => {69+ expect(await getStringFromStream(await renderToReadableStream(1))).toBe('1')70+ })71+72+ it('Should be able to render string', async () => {73+ expect(await getStringFromStream(await renderToReadableStream('Hono'))).toBe('Hono')74+ })75+76+ it('Should be called `onError` if there is an error', async () => {77+ const ErrorComponent = async () => {78+ throw new Error('Server error')79+ }80+81+ const onError = vi.fn()82+ expect(83+ await getStringFromStream(await renderToReadableStream(<ErrorComponent />, { onError }))84+ ).toBe('')85+ expect(onError).toBeCalledWith(new Error('Server error'))86+ })87+88+ it('Should not be called `onError` if there is no error', async () => {89+ const onError = vi.fn(() => 'error')90+ expect(await getStringFromStream(await renderToReadableStream('Hono', { onError }))).toBe(91+ 'Hono'92+ )93+ expect(onError).toBeCalledTimes(0)94+ })95+96+ it('Should omit options, except onError', async () => {97+ expect(98+ await getStringFromStream(await renderToReadableStream('Hono', { identifierPrefix: 'test' }))99+ ).toBe('Hono')100+ })101+102+ it('Should be able to render async component', async () => {103+ const ChildAsyncComponent = async () => {104+ await new Promise((resolve) => setTimeout(resolve, 10))105+ return <span>child async component</span>106+ }107+108+ const AsyncComponent = async () => {109+ await new Promise((resolve) => setTimeout(resolve, 10))110+ return (111+ <h1>112+ Hello from async component113+ <ChildAsyncComponent />114+ </h1>115+ )116+ }117+118+ const stream = await renderToReadableStream(<AsyncComponent />)119+ const reader = stream.getReader()120+ let { done, value } = await reader.read()121+ expect(done).toBe(false)122+ expect(textDecoder.decode(value)).toBe(123+ '<h1>Hello from async component<span>child async component</span></h1>'124+ )125+ done = (await reader.read()).done126+ expect(done).toBe(true)127+ })128+})added:src/jsx/dom/server.ts+70 added
1+/**2+ * @module3+ * This module provides APIs for `hono/jsx/server`, which is compatible with `react-dom/server`.4+ */5+6+import type { Child } from '../base'7+import { renderToReadableStream as renderToReadableStreamHono } from '../streaming'8+import version from './'9+import type { HtmlEscapedString } from '../../utils/html'10+11+export interface RenderToStringOptions {12+ identifierPrefix?: string13+}14+15+/**16+ * Render JSX element to string.17+ * @param element JSX element to render.18+ * @param options Options for rendering.19+ * @returns Rendered string.20+ */21+const renderToString = (element: Child, options: RenderToStringOptions = {}): string => {22+ if (Object.keys(options).length > 0) {23+ console.warn('options are not supported yet')24+ }25+ const res = element?.toString() ?? ''26+ if (typeof res !== 'string') {27+ throw new Error('Async component is not supported in renderToString')28+ }29+ return res30+}31+32+export interface RenderToReadableStreamOptions {33+ identifierPrefix?: string34+ namespaceURI?: string35+ nonce?: string36+ bootstrapScriptContent?: string37+ bootstrapScripts?: string[]38+ bootstrapModules?: string[]39+ progressiveChunkSize?: number40+ signal?: AbortSignal41+ onError?: (error: unknown) => string | void42+}43+44+/**45+ * Render JSX element to readable stream.46+ * @param element JSX element to render.47+ * @param options Options for rendering.48+ * @returns Rendered readable stream.49+ */50+const renderToReadableStream = async (51+ element: Child,52+ options: RenderToReadableStreamOptions = {}53+): Promise<ReadableStream<Uint8Array>> => {54+ if (Object.keys(options).some((key) => key !== 'onError')) {55+ console.warn('options are not supported yet, except onError')56+ }57+58+ if (!element || typeof element !== 'object') {59+ element = element?.toString() ?? ''60+ }61+62+ return renderToReadableStreamHono(element as HtmlEscapedString, options.onError)63+}64+65+export { renderToString, renderToReadableStream, version }66+export default {67+ renderToString,68+ renderToReadableStream,69+ version,70+}modified:src/jsx/hooks/dom.test.tsx+126 added-1 removed
1 /** @jsxImportSource ../ */2 import { JSDOM } from 'jsdom'3 // run tests by old style jsx default4 // hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings5-import { Suspense, render } from '../dom'5+import { ErrorBoundary, Suspense, render } from '../dom'6 import {7 createRef,8 forwardRef,9 startTransition,139 unmodified lines149 expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')150 expect(called).toBe(2)151 await new Promise((r) => setTimeout(r))152 await new Promise((r) => setTimeout(r))153+ await new Promise((r) => setTimeout(r))154 expect(root.innerHTML).toBe('<div><button>1</button></div>')155 expect(called).toBe(3)156 })157 158+ it('pending', async () => {159+ let resolve: (() => void) | undefined160+ const promise = new Promise<void>((r) => (resolve = r))161+ let called = 0162+ const App = () => {163+ const [isPending, startTransition] = useTransition()164+ called++165+166+ return (167+ <div>168+ <button169+ onClick={() => {170+ startTransition(async () => await promise)171+ }}172+ >173+ {isPending ? 'Pending...' : 'Click me'}174+ </button>175+ </div>176+ )177+ }178+ render(<App />, root)179+ expect(root.innerHTML).toBe('<div><button>Click me</button></div>')180+ root.querySelector('button')?.click()181+ await Promise.resolve()182+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')183+ expect(called).toBe(2)184+ resolve!()185+ await new Promise((r) => setTimeout(r))186+ await new Promise((r) => setTimeout(r))187+ await new Promise((r) => setTimeout(r))188+ expect(root.innerHTML).toBe('<div><button>Click me</button></div>')189+ expect(called).toBe(3)190+ })191+192+ it('pending - error', async () => {193+ let reject: (() => void) | undefined194+ const promise = new Promise<void>((_, r) => (reject = r))195+ let called = 0196+ const Component = () => {197+ const [isPending, startTransition] = useTransition()198+ called++199+200+ return (201+ <div>202+ <button203+ onClick={() => {204+ startTransition(async () => await promise)205+ }}206+ >207+ {isPending ? 'Pending...' : 'Click me'}208+ </button>209+ </div>210+ )211+ }212+ const App = () => (213+ <ErrorBoundary fallback={<div>Error</div>}>214+ <Component />215+ </ErrorBoundary>216+ )217+ render(<App />, root)218+ expect(root.innerHTML).toBe('<div><button>Click me</button></div>')219+ root.querySelector('button')?.click()220+ await Promise.resolve()221+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')222+ expect(called).toBe(2)223+ reject!()224+ await new Promise((r) => setTimeout(r))225+ await new Promise((r) => setTimeout(r))226+ await new Promise((r) => setTimeout(r))227+ expect(root.innerHTML).toBe('<div>Error</div>')228+ expect(called).toBe(2)229+ })230+231 it('multiple setState at once', async () => {232 let called = 0233 const App = () => {234 const [count1, setCount1] = useState(0)23 unmodified lines258 expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')259 expect(called).toBe(2)260 await new Promise((r) => setTimeout(r))261 await new Promise((r) => setTimeout(r))262+ await new Promise((r) => setTimeout(r))263 expect(root.innerHTML).toBe('<div><button>3</button></div>')264 expect(called).toBe(3)265 })266 30 unmodified lines297 expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')298 expect(called).toBe(2)299 await new Promise((r) => setTimeout(r))300 await new Promise((r) => setTimeout(r))301+ await new Promise((r) => setTimeout(r))302 expect(root.innerHTML).toBe('<div><button>3</button></div>')303 expect(called).toBe(3) // + isPending=true + isPending=false304 })305 })32 unmodified lines338 root.querySelector('button')?.click()339 await Promise.resolve()340 expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')341 await new Promise((r) => setTimeout(r))342+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')343+ await new Promise((r) => setTimeout(r))344+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')345+ await new Promise((r) => setTimeout(r))346+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')347+ await new Promise((r) => setTimeout(r))348 expect(root.innerHTML).toBe('<div><button>+1</button></div><div>2</div>')349 })350+351+ it('initial value', async () => {352+ const promiseMap = {} as Record<number, Promise<number>>353+ const getPromise = (count: number) => {354+ return (promiseMap[count] ||= new Promise((r) => setTimeout(() => r(count + 1))))355+ }356+ const ShowCount = ({ count }: { count: number }) => {357+ if (count === 0 || count === 99) {358+ return <div>{count}</div>359+ }360+361+ const c = use(getPromise(count))362+ return <div>{c}</div>363+ }364+365+ const App = () => {366+ const [count, setCount] = useState(1)367+ const c = useDeferredValue(count, 99)368+ return (369+ <>370+ <div>371+ <button onClick={() => setCount((c) => c + 1)}>+1</button>372+ </div>373+ <Suspense fallback={<div>Loading...</div>}>374+ <ShowCount count={c} />375+ </Suspense>376+ </>377+ )378+ }379+ render(<App />, root)380+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>99</div>')381+ await new Promise((r) => setTimeout(r))382+ await new Promise((r) => setTimeout(r))383+ await new Promise((r) => setTimeout(r))384+ await new Promise((r) => setTimeout(r))385+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>2</div>')386+ root.querySelector('button')?.click()387+ await new Promise((r) => setTimeout(r))388+ await new Promise((r) => setTimeout(r))389+ await new Promise((r) => setTimeout(r))390+ await new Promise((r) => setTimeout(r))391+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>3</div>')392+ })393 })394 395 describe('startViewTransition()', () => {396 afterEach(() => {335 unmodified linesmodified:src/jsx/hooks/index.ts+70 added-73 removed
1 import type { JSX } from '../base'2 import { DOM_STASH } from '../constants'3-import { build, buildDataStack, update } from '../dom/render'3+import { buildDataStack, update } from '../dom/render'4 import type { Context, Node, NodeObject, PendingType, UpdateHook } from '../dom/render'5 6 type UpdateStateFunction<T> = (newState: T | ((currentState: T) => T)) => void7 8 const STASH_SATE = 09 export const STASH_EFFECT = 110 const STASH_CALLBACK = 211-const STASH_USE = 312-const STASH_MEMO = 413-const STASH_REF = 511+const STASH_MEMO = 312+const STASH_REF = 413 14 export type EffectData = [15 readonly unknown[] | undefined, // deps16 (() => void | (() => void)) | undefined, // layout effect80 unmodified lines97 }98 return [!!viewTransitionState?.[0], startViewTransition]99 }100 102-const pendingStack: PendingType[] = []101+// PendingType is defined in "../dom/render", 3 is used for useDeferredValue102+const pendingStack: [PendingType | 3, Promise<void>][] = []103 const runCallback = (type: PendingType, callback: Function): void => {104+ let resolve: (() => void) | undefined105+ const promise = new Promise<void>((r) => (resolve = r))104- pendingStack.push(type)106+ pendingStack.push([type, promise])107 try {106- callback()108+ const res = callback()109+ if (res instanceof Promise) {110+ res.then(resolve, resolve)111+ } else {112+ resolve!()113+ }114 } finally {115 pendingStack.pop()116 }117 }118 119 export const startTransition = (callback: () => void): void => {120 runCallback(1, callback)121 }115-const startTransitionHook = (callback: () => void): void => {122+const startTransitionHook = (callback: () => void | Promise<void>): void => {123 runCallback(2, callback)124 }125 119-export const useTransition = (): [boolean, (callback: () => void) => void] => {126+export const useTransition = (): [boolean, (callback: () => void | Promise<void>) => void] => {127 const buildData = buildDataStack.at(-1) as [Context, NodeObject]128 if (!buildData) {129 return [false, () => {}]130 }131+132+ const [error, setError] = useState<[Error]>()133+ const [state, updateState] = useState<boolean>()134+ if (error) {135+ throw error[0]136+ }137+ const startTransitionLocalHook = useCallback<typeof startTransitionHook>(138+ (callback) => {139+ startTransitionHook(() => {140+ updateState((state) => !state)141+ let res = callback()142+ if (res instanceof Promise) {143+ res = res.catch((e) => {144+ setError([e])145+ })146+ }147+ return res148+ })149+ },150+ [state]151+ )152+153 const [context] = buildData125- return [context[0] === 2, startTransitionHook]154+ return [context[0] === 2, startTransitionLocalHook]155 }156 128-export const useDeferredValue = <T>(value: T): T => {129- const buildData = buildDataStack.at(-1) as [Context, NodeObject]130- if (buildData) {131- buildData[0][0] = 1157+type UseDeferredValue = <T>(value: T, initialValue?: T) => T158+export const useDeferredValue: UseDeferredValue = <T>(value: T, ...rest: [T | undefined]): T => {159+ const [values, setValues] = useState<[T, T]>(160+ (rest.length ? [rest[0], rest[0]] : [value, value]) as [T, T]161+ )162+ if (Object.is(values[1], value)) {163+ return values[1]164 }133- return value134-}165 136-const setShadow = (node: Node) => {137- if (node.vC) {138- node.s = node.vC139- // eslint-disable-next-line @typescript-eslint/no-explicit-any140- ;(node as any).vC = undefined166+ pendingStack.push([3, Promise.resolve()])167+ updateHook = async (context: Context, _, cb: (context: Context) => void) => {168+ cb(context)169+ values[0] = value170 }142- // eslint-disable-next-line @typescript-eslint/no-explicit-any143- ;(node as any).s?.forEach(setShadow)171+ setValues([values[0], value])172+ updateHook = undefined173+ pendingStack.pop()174+175+ return values[0]176 }177 178 type UseStateType = {179 <T>(initialState: T | (() => T)): [T, UpdateStateFunction<T>]25 unmodified lines205 206 if (!Object.is(newState, stateData[0])) {207 stateData[0] = newState208 if (pendingStack.length) {177- const pendingType = pendingStack.at(-1) as PendingType178- update([pendingType, false, localUpdateHook as UpdateHook], node).then((node) => {179- if (!node || pendingType !== 2) {209+ const [pendingType, pendingPromise] = pendingStack.at(-1) as [210+ PendingType | 3,211+ Promise<void>212+ ]213+ Promise.all([214+ pendingType === 3215+ ? node216+ : update([pendingType, false, localUpdateHook as UpdateHook], node),217+ pendingPromise,218+ ]).then(([node]) => {219+ if (!node || !(pendingType === 2 || pendingType === 3)) {220 return221 }222 223 const lastVC = node.vC224 225 const addUpdateTask = () => {226 setTimeout(() => {187- // `node` is not rerendered after current transition227+ // return if `node` is rerendered after current transition228 if (lastVC !== node.vC) {229 return230 }191-192- const shadowNode = Object.assign({}, node) as NodeObject193-194- // eslint-disable-next-line @typescript-eslint/no-explicit-any195- ;(shadowNode as any).vC = undefined // delete the prev build data and build with clean state196- build([], shadowNode, undefined)197- setShadow(shadowNode) // save the `shadowNode.vC` of the virtual DOM of the build result as a result of shadow virtual DOM `shadowNode.s`198-199- node.s = shadowNode.s200- update([0, false, localUpdateHook as UpdateHook], node)231+ update([pendingType === 3 ? 1 : 0, false, localUpdateHook as UpdateHook], node)232 })233 }234 204- if (localUpdateHook) {205- // wait for next animation frame, then invoke `update()`206- requestAnimationFrame(addUpdateTask)235+ requestAnimationFrame(addUpdateTask)207- } else {208- addUpdateTask()209- }236 })237 } else {238 update([0, false, localUpdateHook as UpdateHook], node)239 }54 unmodified lines294 effect: () => void | (() => void),295 deps?: readonly unknown[]296 ): void => useEffectCommon(4, effect, deps)297 272-export const useCallback = <T extends (...args: unknown[]) => unknown>(273- callback: T,274- deps: readonly unknown[]275-): T => {298+export const useCallback = <T extends Function>(callback: T, deps: readonly unknown[]): T => {299 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]300 if (!buildData) {301 return callback302 }37 unmodified lines340 (res) => resolvedPromiseValueMap.set(promise, [res]),341 (e) => resolvedPromiseValueMap.set(promise, [undefined, e])342 )343 321- const buildData = buildDataStack.at(-1) as [unknown, NodeObject]322- if (!buildData) {323- throw promise324- }325- const [, node] = buildData326-327- const promiseArray = (node[DOM_STASH][1][STASH_USE] ||= [])328- const hookIndex = node[DOM_STASH][0]++329-330- promise.then(331- (res) => {332- promiseArray[hookIndex] = [res]333- },334- (e) => {335- promiseArray[hookIndex] = [undefined, e]336- }337- )338-339- const res = promiseArray[hookIndex]340- if (res) {341- if (res.length === 2) {342- throw res[1]343- }344- return res[0] as T345- }346-344 throw promise345 }346 347 export const useMemo = <T>(factory: () => T, deps: readonly unknown[]): T => {78 unmodified linesadded:src/jsx/intrinsic-element/common.ts+11 added
1+export const deDupeKeyMap: Record<string, string[]> = {2+ title: [],3+ script: ['src'],4+ style: ['data-href'],5+ link: ['href'],6+ meta: ['name', 'httpEquiv', 'charset', 'itemProp'],7+}8+9+export const domRenderers: Record<string, Function> = {}10+11+export const dataPrecedenceAttr = 'data-precedence'added:src/jsx/intrinsic-element/components.test.tsx+399 added
1+/** @jsxImportSource ../ */2+import { useActionState } from '../'3+4+describe('intrinsic element', () => {5+ describe('document metadata', () => {6+ describe('title element', () => {7+ it('should be hoisted title tag', async () => {8+ const template = (9+ <html>10+ <head></head>11+ <body>12+ <title>Hello</title>13+ <h1>World</h1>14+ </body>15+ </html>16+ )17+ expect(template.toString()).toBe(18+ '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'19+ )20+ })21+ })22+23+ describe('link element', () => {24+ it('should be hoisted link tag', async () => {25+ const template = (26+ <html>27+ <head></head>28+ <body>29+ <link rel='stylesheet' href='style.css' precedence='default' />30+ <h1>World</h1>31+ </body>32+ </html>33+ )34+ expect(template.toString()).toBe(35+ '<html><head><link rel="stylesheet" href="style.css" data-precedence="default"/></head><body><h1>World</h1></body></html>'36+ )37+ })38+39+ it('should be ordered by precedence attribute', () => {40+ const template = (41+ <html>42+ <head></head>43+ <body>44+ <link rel='stylesheet' href='style1.css' precedence='default' />45+ <link rel='stylesheet' href='style2.css' precedence='high' />46+ <link rel='stylesheet' href='style3.css' precedence='default' />47+ <h1>World</h1>48+ </body>49+ </html>50+ )51+ expect(template.toString()).toBe(52+ '<html><head><link rel="stylesheet" href="style1.css" data-precedence="default"/><link rel="stylesheet" href="style3.css" data-precedence="default"/><link rel="stylesheet" href="style2.css" data-precedence="high"/></head><body><h1>World</h1></body></html>'53+ )54+ })55+56+ it('should be de-duped by href', () => {57+ const template = (58+ <html>59+ <head></head>60+ <body>61+ <link rel='stylesheet' href='style1.css' precedence='default' />62+ <link rel='stylesheet' href='style2.css' precedence='high' />63+ <link rel='stylesheet' href='style1.css' precedence='default' />64+ <h1>World</h1>65+ </body>66+ </html>67+ )68+ expect(template.toString()).toBe(69+ '<html><head><link rel="stylesheet" href="style1.css" data-precedence="default"/><link rel="stylesheet" href="style2.css" data-precedence="high"/></head><body><h1>World</h1></body></html>'70+ )71+ })72+73+ it('should be inserted as is if <head> is not present', () => {74+ const template = (75+ <html>76+ <body>77+ <link rel='stylesheet' href='style1.css' precedence='default' />78+ <link rel='stylesheet' href='style2.css' precedence='high' />79+ <h1>World</h1>80+ </body>81+ </html>82+ )83+ expect(template.toString()).toBe(84+ '<html><body><link rel="stylesheet" href="style1.css" data-precedence="default"/><link rel="stylesheet" href="style2.css" data-precedence="high"/><h1>World</h1></body></html>'85+ )86+ })87+88+ it('should not do special behavior if disabled is present', () => {89+ const template = (90+ <html>91+ <head></head>92+ <body>93+ <link rel='stylesheet' href='style1.css' precedence='default' />94+ <link rel='stylesheet' href='style2.css' precedence='default' disabled />95+ <h1>World</h1>96+ </body>97+ </html>98+ )99+ expect(template.toString()).toBe(100+ '<html><head><link rel="stylesheet" href="style1.css" data-precedence="default"/></head><body><link rel="stylesheet" href="style2.css" precedence="default" disabled=""/><h1>World</h1></body></html>'101+ )102+ })103+104+ it('should not be hoisted if has no precedence attribute', () => {105+ const template = (106+ <html>107+ <head></head>108+ <body>109+ <link rel='stylesheet' href='style1.css' />110+ <h1>World</h1>111+ </body>112+ </html>113+ )114+ expect(template.toString()).toBe(115+ '<html><head></head><body><link rel="stylesheet" href="style1.css"/><h1>World</h1></body></html>'116+ )117+ })118+ })119+120+ describe('meta element', () => {121+ it('should be hoisted meta tag', async () => {122+ const template = (123+ <html>124+ <head></head>125+ <body>126+ <meta name='description' content='Hello' />127+ <h1>World</h1>128+ </body>129+ </html>130+ )131+ expect(template.toString()).toBe(132+ '<html><head><meta name="description" content="Hello"/></head><body><h1>World</h1></body></html>'133+ )134+ })135+136+ it('should be de-duped by name', () => {137+ const template = (138+ <html>139+ <head></head>140+ <body>141+ <meta name='description' content='Hello' />142+ <meta name='description' content='World' />143+ <h1>World</h1>144+ </body>145+ </html>146+ )147+ expect(template.toString()).toBe(148+ '<html><head><meta name="description" content="Hello"/></head><body><h1>World</h1></body></html>'149+ )150+ })151+152+ it('should not do special behavior if itemProp is present', () => {153+ const template = (154+ <html>155+ <head></head>156+ <body>157+ <meta name='description' content='Hello' itemProp='test' />158+ <h1>World</h1>159+ </body>160+ </html>161+ )162+ expect(template.toString()).toBe(163+ '<html><head></head><body><meta name="description" content="Hello" itemprop="test"/><h1>World</h1></body></html>'164+ )165+ })166+ })167+168+ describe('script element', () => {169+ it('should be hoisted script tag', async () => {170+ const template = (171+ <html>172+ <head></head>173+ <body>174+ <script src='script.js' async={true} />175+ <h1>World</h1>176+ </body>177+ </html>178+ )179+ expect(template.toString()).toBe(180+ '<html><head><script src="script.js" async=""></script></head><body><h1>World</h1></body></html>'181+ )182+ })183+184+ it('should be de-duped by href with async={true}', () => {185+ const template = (186+ <html>187+ <head></head>188+ <body>189+ <script src='script.js' async />190+ <script src='script.js' async />191+ <h1>World</h1>192+ </body>193+ </html>194+ )195+ expect(template.toString()).toBe(196+ '<html><head><script src="script.js" async=""></script></head><body><h1>World</h1></body></html>'197+ )198+ })199+200+ it('should be omitted "blocking", "onLoad" and "onError" props', () => {201+ const template = (202+ <html>203+ <head></head>204+ <body>205+ <script206+ src='script.js'207+ async={true}208+ onLoad={() => {}}209+ onError={() => {}}210+ blocking='render'211+ />212+ <h1>World</h1>213+ </body>214+ </html>215+ )216+ expect(template.toString()).toBe(217+ '<html><head><script src="script.js" async=""></script></head><body><h1>World</h1></body></html>'218+ )219+ })220+221+ it('should not do special behavior if async is not present', () => {222+ const template = (223+ <html>224+ <head></head>225+ <body>226+ <script src='script.js' />227+ <h1>World</h1>228+ </body>229+ </html>230+ )231+ expect(template.toString()).toBe(232+ '<html><head></head><body><script src="script.js"></script><h1>World</h1></body></html>'233+ )234+ })235+ })236+237+ describe('style element', () => {238+ it('should be hoisted style tag', async () => {239+ const template = (240+ <html>241+ <head></head>242+ <body>243+ <style href='red' precedence='default'>244+ {'body { color: red; }'}245+ </style>246+ <h1>World</h1>247+ </body>248+ </html>249+ )250+ expect(template.toString()).toBe(251+ '<html><head><style data-href="red" data-precedence="default">body { color: red; }</style></head><body><h1>World</h1></body></html>'252+ )253+ })254+255+ it('should be sorted by precedence attribute', async () => {256+ const template = (257+ <html>258+ <head></head>259+ <body>260+ <style href='red' precedence='default'>261+ {'body { color: red; }'}262+ </style>263+ <style href='green' precedence='high'>264+ {'body { color: green; }'}265+ </style>266+ <style href='blue' precedence='default'>267+ {'body { color: blue; }'}268+ </style>269+ <h1>World</h1>270+ </body>271+ </html>272+ )273+ expect(template.toString()).toBe(274+ '<html><head><style data-href="red" data-precedence="default">body { color: red; }</style><style data-href="blue" data-precedence="default">body { color: blue; }</style><style data-href="green" data-precedence="high">body { color: green; }</style></head><body><h1>World</h1></body></html>'275+ )276+ })277+278+ it('should not be hoisted if href is not present', () => {279+ const template = (280+ <html>281+ <head></head>282+ <body>283+ <style>{'body { color: red; }'}</style>284+ <h1>World</h1>285+ </body>286+ </html>287+ )288+ expect(template.toString()).toBe(289+ '<html><head></head><body><style>body { color: red; }</style><h1>World</h1></body></html>'290+ )291+ })292+ })293+ })294+295+ describe('form element', () => {296+ it('should be omitted "action" prop if it is a function', () => {297+ const template = (298+ <html>299+ <head></head>300+ <body>301+ <form action={() => {}} method='get'>302+ <input type='text' />303+ </form>304+ </body>305+ </html>306+ )307+ expect(template.toString()).toBe(308+ '<html><head></head><body><form method="get"><input type="text"/></form></body></html>'309+ )310+ })311+312+ it('should be rendered permalink', () => {313+ const [, action] = useActionState(() => {}, {}, 'permalink')314+ const template = (315+ <html>316+ <head></head>317+ <body>318+ <form action={action} method='get'>319+ <input type='text' />320+ </form>321+ </body>322+ </html>323+ )324+ expect(template.toString()).toBe(325+ '<html><head></head><body><form action="permalink" method="get"><input type="text"/></form></body></html>'326+ )327+ })328+329+ it('should not do special behavior if action is a string', () => {330+ const template = (331+ <html>332+ <head></head>333+ <body>334+ <form action='/entries' method='get'>335+ <input type='text' />336+ </form>337+ </body>338+ </html>339+ )340+ expect(template.toString()).toBe(341+ '<html><head></head><body><form action="/entries" method="get"><input type="text"/></form></body></html>'342+ )343+ })344+345+ it('should not do special behavior if no action prop', () => {346+ const template = (347+ <html>348+ <head></head>349+ <body>350+ <form>351+ <input type='text' />352+ </form>353+ </body>354+ </html>355+ )356+ expect(template.toString()).toBe(357+ '<html><head></head><body><form><input type="text"/></form></body></html>'358+ )359+ })360+361+ describe('input element', () => {362+ it('should be rendered as is', () => {363+ const template = <input type='text' />364+ expect(template.toString()).toBe('<input type="text"/>')365+ })366+367+ it('should be omitted "formAction" prop if it is a function', () => {368+ const template = (369+ <html>370+ <head></head>371+ <body>372+ <input type='text' formAction={() => {}} />373+ </body>374+ </html>375+ )376+ expect(template.toString()).toBe(377+ '<html><head></head><body><input type="text"/></body></html>'378+ )379+ })380+381+ it('should be rendered permalink', () => {382+ const [, formAction] = useActionState(() => {}, {}, 'permalink')383+ const template = (384+ <html>385+ <head></head>386+ <body>387+ <input type='text' formAction={formAction} />388+ </body>389+ </html>390+ )391+ expect(template.toString()).toBe(392+ '<html><head></head><body><input type="text" formaction="permalink"/></body></html>'393+ )394+ })395+ })396+ })397+})398+399+export {}added:src/jsx/intrinsic-element/components.ts+175 added
1+import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'2+import { JSXNode } from '../base'3+import type { Child, Props } from '../base'4+import type { FC, PropsWithChildren } from '../types'5+import { raw } from '../../helper/html'6+import { dataPrecedenceAttr, deDupeKeyMap } from './common'7+import { PERMALINK } from '../constants'8+import { toArray } from '../children'9+import type { IntrinsicElements } from '../intrinsic-elements'10+11+const metaTagMap: WeakMap<12+ object,13+ Record<string, [string, Props, string | undefined][]>14+> = new WeakMap()15+const insertIntoHead: (16+ tagName: string,17+ tag: string,18+ props: Props,19+ precedence: string | undefined20+) => HtmlEscapedCallback =21+ (tagName, tag, props, precedence) =>22+ ({ buffer, context }): undefined => {23+ if (!buffer) {24+ return25+ }26+ const map = metaTagMap.get(context) || {}27+ metaTagMap.set(context, map)28+ const tags = (map[tagName] ||= [])29+30+ let duped = false31+ const deDupeKeys = deDupeKeyMap[tagName]32+ if (deDupeKeys.length > 0) {33+ LOOP: for (const [, tagProps] of tags) {34+ for (const key of deDupeKeys) {35+ if ((tagProps?.[key] ?? null) === props?.[key]) {36+ duped = true37+ break LOOP38+ }39+ }40+ }41+ }42+43+ if (duped) {44+ buffer[0] = buffer[0].replaceAll(tag, '')45+ } else if (deDupeKeys.length > 0) {46+ tags.push([tag, props, precedence])47+ } else {48+ tags.unshift([tag, props, precedence])49+ }50+51+ if (buffer[0].indexOf('</head>') !== -1) {52+ let insertTags53+ if (precedence === undefined) {54+ insertTags = tags.map(([tag]) => tag)55+ } else {56+ const precedences: string[] = []57+ insertTags = tags58+ .map(([tag, , precedence]) => {59+ let order = precedences.indexOf(precedence as string)60+ if (order === -1) {61+ precedences.push(precedence as string)62+ order = precedences.length - 163+ }64+ return [tag, order] as [string, number]65+ })66+ .sort((a, b) => a[1] - b[1])67+ .map(([tag]) => tag)68+ }69+70+ insertTags.forEach((tag) => {71+ buffer[0] = buffer[0].replaceAll(tag, '')72+ })73+ buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join(''))74+ }75+ }76+77+const returnWithoutSpecialBehavior = (tag: string, children: Child, props: Props) =>78+ raw(new JSXNode(tag, props, toArray(children ?? [])).toString())79+80+const documentMetadataTag = (tag: string, children: Child, props: Props, sort: boolean) => {81+ if ('itemProp' in props) {82+ return returnWithoutSpecialBehavior(tag, children, props)83+ }84+85+ // eslint-disable-next-line @typescript-eslint/no-unused-vars86+ let { precedence, blocking, ...restProps } = props87+ precedence = sort ? precedence ?? '' : undefined88+ if (sort) {89+ restProps[dataPrecedenceAttr] = precedence90+ }91+92+ const string = new JSXNode(tag, restProps, toArray(children || [])).toString()93+94+ if (string instanceof Promise) {95+ return string.then((resString) =>96+ raw(string, [97+ ...((resString as HtmlEscapedString).callbacks || []),98+ insertIntoHead(tag, resString, restProps, precedence),99+ ])100+ )101+ } else {102+ return raw(string, [insertIntoHead(tag, string, restProps, precedence)])103+ }104+}105+106+export const title: FC<PropsWithChildren> = ({ children, ...props }) => {107+ return documentMetadataTag('title', children, props, false)108+}109+export const script: FC<PropsWithChildren<IntrinsicElements['script']>> = ({110+ children,111+ ...props112+}) => {113+ if (['src', 'async'].some((k) => !props[k])) {114+ return returnWithoutSpecialBehavior('script', children, props)115+ }116+117+ return documentMetadataTag('script', children, props, false)118+}119+120+export const style: FC<PropsWithChildren<IntrinsicElements['style']>> = ({121+ children,122+ ...props123+}) => {124+ if (!['href', 'precedence'].every((k) => k in props)) {125+ return returnWithoutSpecialBehavior('style', children, props)126+ }127+ props['data-href'] = props.href128+ delete props.href129+ return documentMetadataTag('style', children, props, true)130+}131+export const link: FC<PropsWithChildren<IntrinsicElements['link']>> = ({ children, ...props }) => {132+ if (133+ ['onLoad', 'onError'].some((k) => k in props) ||134+ (props.rel === 'stylesheet' && (!('precedence' in props) || 'disabled' in props))135+ ) {136+ return returnWithoutSpecialBehavior('link', children, props)137+ }138+ return documentMetadataTag('link', children, props, 'precedence' in props)139+}140+export const meta: FC<PropsWithChildren> = ({ children, ...props }) => {141+ return documentMetadataTag('meta', children, props, false)142+}143+144+const newJSXNode = (tag: string, { children, ...props }: PropsWithChildren<unknown>) =>145+ // eslint-disable-next-line @typescript-eslint/no-explicit-any146+ new JSXNode(tag, props, toArray(children ?? []) as Child[]) as any147+export const form: FC<148+ PropsWithChildren<{149+ action?: Function | string150+ method?: 'get' | 'post'151+ }>152+> = (props) => {153+ if (typeof props.action === 'function') {154+ props.action = PERMALINK in props.action ? (props.action[PERMALINK] as string) : undefined155+ }156+ return newJSXNode('form', props)157+}158+159+const formActionableElement = (160+ tag: string,161+ props: PropsWithChildren<{162+ formAction?: Function | string163+ }>164+) => {165+ if (typeof props.formAction === 'function') {166+ props.formAction =167+ PERMALINK in props.formAction ? (props.formAction[PERMALINK] as string) : undefined168+ }169+ return newJSXNode(tag, props)170+}171+172+export const input: (props: PropsWithChildren) => unknown = (props) =>173+ formActionableElement('input', props)174+export const button: (props: PropsWithChildren) => unknown = (props) =>175+ formActionableElement('button', props)modified:src/jsx/base.ts+36 added-9 removed
1 import { raw } from '../helper/html'2-import { escapeToBuffer, stringBufferToString } from '../utils/html'3-import type { HtmlEscaped, HtmlEscapedString, StringBuffer } from '../utils/html'2+import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'3+import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'4 import type { Context } from './context'5 import { globalContexts } from './context'6+import { DOM_RENDERER } from './constants'7 import type {8 JSX as HonoJSX,9 IntrinsicElements as IntrinsicElementsDefined,10 } from './intrinsic-elements'11 import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'12+import * as intrinsicElementTags from './intrinsic-element/components'13+import { domRenderers } from './intrinsic-element/common'14 15 // eslint-disable-next-line @typescript-eslint/no-explicit-any16 export type Props = Record<string, any>17 export type FC<P = Props> = {59 unmodified lines77 'reversed',78 'selected',79 ]80 78-const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {81+const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {82 for (let i = 0, len = children.length; i < len; i++) {83 const child = children[i]84 if (typeof child === 'string') {85 escapeToBuffer(child, buffer)48 unmodified lines134 return this.props.ref || null135 }136 137 toString(): string | Promise<string> {135- const buffer: StringBuffer = ['']138+ const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks139 this.localContexts?.forEach(([context, value]) => {140 context.values.push(value)141 })142 try {2 unmodified lines145 this.localContexts?.forEach(([context]) => {146 context.values.pop()147 })148 }146- return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)149+ return buffer.length === 1150+ ? 'callbacks' in buffer151+ ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()152+ : buffer[0]153+ : stringBufferToString(buffer, buffer.callbacks)154 }155 149- toStringToBuffer(buffer: StringBuffer): void {156+ toStringToBuffer(buffer: StringBufferWithCallbacks): void {157 const tag = this.tag as string158 const props = this.props159 let { children } = this160 60 unmodified lines221 }222 }223 224 class JSXFunctionNode extends JSXNode {218- toStringToBuffer(buffer: StringBuffer): void {225+ toStringToBuffer(buffer: StringBufferWithCallbacks): void {226 const { children } = this227 228 const res = (this.tag as Function).call(null, {229 ...this.props,19 unmodified lines249 } else if (res instanceof JSXNode) {250 res.toStringToBuffer(buffer)251 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {252 buffer[0] += res253+ if (res.callbacks) {254+ buffer.callbacks ||= []255+ buffer.callbacks.push(...res.callbacks)256+ }257 } else {258 escapeToBuffer(res, buffer)259 }260 }261 }262 263 export class JSXFragmentNode extends JSXNode {253- toStringToBuffer(buffer: StringBuffer): void {264+ toStringToBuffer(buffer: StringBufferWithCallbacks): void {265 childrenToStringToBuffer(this.children, buffer)266 }267 }268 14 unmodified lines283 node.key = key284 return node285 }286 287+let initDomRenderer = false288 export const jsxFn = (289 tag: string | Function,290 props: Props,291 children: (string | number | HtmlEscapedString)[]292 ): JSXNode => {293+ if (!initDomRenderer) {294+ for (const k in domRenderers) {295+ // eslint-disable-next-line @typescript-eslint/no-explicit-any296+ ;(intrinsicElementTags[k as keyof typeof intrinsicElementTags] as any)[DOM_RENDERER] =297+ domRenderers[k]298+ }299+ initDomRenderer = true300+ }301+302 if (typeof tag === 'function') {303 return new JSXFunctionNode(tag, props, children)304+ } else if (intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) {305+ return new JSXFunctionNode(306+ intrinsicElementTags[tag as keyof typeof intrinsicElementTags],307+ props,308+ children309+ )310 } else {311 return new JSXNode(tag, props, children)312 }313 }70 unmodified lines384 ...(children as (string | number | HtmlEscapedString)[])385 ) as T386 }387 361-export const reactAPICompatVersion = '18.0.0-hono-jsx'388+export const reactAPICompatVersion = '19.0.0-hono-jsx'modified:src/jsx/constants.ts+1 added
1 export const DOM_RENDERER = Symbol('RENDERER')2 export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3 export const DOM_STASH = Symbol('STASH')4 export const DOM_INTERNAL_TAG = Symbol('INTERNAL')5+export const PERMALINK = Symbol('PERMALINK')modified:src/jsx/context.ts+24 added-26 removed
3 unmodified lines4 import { DOM_RENDERER } from './constants'5 import { createContextProviderFunction } from './dom/context'6 import type { FC, PropsWithChildren } from './'7 8-export interface Context<T> {8+export interface Context<T> extends FC<PropsWithChildren<{ value: T }>> {9 values: T[]10 Provider: FC<PropsWithChildren<{ value: T }>>11 }12 13 export const globalContexts: Context<unknown>[] = []14 15 export const createContext = <T>(defaultValue: T): Context<T> => {16 const values = [defaultValue]17- const context: Context<T> = {18- values,19- Provider(props): HtmlEscapedString | Promise<HtmlEscapedString> {20- values.push(props.value)21- let string22- try {23- string = props.children24- ? (Array.isArray(props.children)25- ? new JSXFragmentNode('', {}, props.children)26- : props.children27- ).toString()28- : ''29- } finally {30- values.pop()31- }17+ const context: Context<T> = ((props): HtmlEscapedString | Promise<HtmlEscapedString> => {18+ values.push(props.value)19+ let string20+ try {21+ string = props.children22+ ? (Array.isArray(props.children)23+ ? new JSXFragmentNode('', {}, props.children)24+ : props.children25+ ).toString()26+ : ''27+ } finally {28+ values.pop()29+ }30 33- if (string instanceof Promise) {34- return string.then((resString) =>35- raw(resString, (resString as HtmlEscapedString).callbacks)36- )37- } else {38- return raw(string)39- }40- },41- }31+ if (string instanceof Promise) {32+ return string.then((resString) => raw(resString, (resString as HtmlEscapedString).callbacks))33+ } else {34+ return raw(string)35+ }36+ }) as Context<T>37+ context.values = values38+ context.Provider = context39+40 // eslint-disable-next-line @typescript-eslint/no-explicit-any43- ;(context.Provider as any)[DOM_RENDERER] = createContextProviderFunction(values)41+ ;(context as any)[DOM_RENDERER] = createContextProviderFunction(values)42 43 globalContexts.push(context as Context<unknown>)44 45 return context5 unmodified linesmodified:src/jsx/index.test.tsx+27 added-1 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 import { html } from '../helper/html'4 import { Hono } from '../hono'5 import { Suspense, renderToReadableStream } from './streaming'6-import DefaultExport, { Fragment, createContext, memo, useContext, version } from '.'6+import DefaultExport, { Fragment, StrictMode, createContext, memo, useContext, version } from '.'7 import type { Context, FC, PropsWithChildren } from '.'8 9 interface SiteData {10 title: string542 unmodified lines553 expect(template.toString()).toBe('')554 })555 })556 557+describe('StrictMode', () => {558+ it('Should render children', () => {559+ const template = (560+ <StrictMode>561+ <p>1</p>562+ <p>2</p>563+ </StrictMode>564+ )565+ expect(template.toString()).toBe('<p>1</p><p>2</p>')566+ })567+})568+569 describe('Context', () => {570 let ThemeContext: Context<string>571 let Consumer: FC572 let ErrorConsumer: FC66 unmodified lines639 expect(nextRequest.toString()).toBe('<span>light</span>')640 })641 })642 643+ describe('<Context> as a provider ', () => {644+ it('has a child', () => {645+ const template = (646+ <ThemeContext value='dark'>647+ <Consumer />648+ </ThemeContext>649+ )650+ expect(template.toString()).toBe('<span>dark</span>')651+ })652+ })653+654 it('default value', () => {655 const template = <Consumer />656 expect(template.toString()).toBe('<span>light</span>')657 })151 unmodified lines809 'useViewTransition',810 'useMemo',811 'useLayoutEffect',812 'useInsertionEffect',813+ 'useActionState',814+ 'useOptimistic',815 'Suspense',816+ 'StrictMode',817 ].forEach((key) => {818 it(key, () => {819 // eslint-disable-next-line @typescript-eslint/no-explicit-any820 expect((DefaultExport as any)[key]).toBeDefined()3 unmodified linesmodified:src/jsx/index.ts+7 added
28 unmodified lines29 useSyncExternalStore,30 useTransition,31 useViewTransition,32 } from './hooks'33+import { useActionState, useOptimistic } from './dom/hooks'34 import { Suspense } from './streaming'35 36 export {37 reactAPICompatVersion as version,38 jsx,39 memo,40 Fragment,41+ Fragment as StrictMode,42 isValidElement,43 jsx as createElement,44 cloneElement,45 ErrorBoundary,18 unmodified lines64 createRef,65 forwardRef,66 useImperativeHandle,67 useSyncExternalStore,68+ useActionState,69+ useOptimistic,70 Suspense,71 Children,72 DOMAttributes,73 }1 unmodified line75 export default {76 version: reactAPICompatVersion,77 memo,78 Fragment,79+ StrictMode: Fragment,80 isValidElement,81 createElement: jsx,82 cloneElement,83 ErrorBoundary,18 unmodified lines102 createRef,103 forwardRef,104 useImperativeHandle,105 useSyncExternalStore,106+ useActionState,107+ useOptimistic,108 Suspense,109 Children,110 }111 3 unmodified linesmodified:src/jsx/intrinsic-elements.ts+58 added-1 removed
144 unmodified lines145 }146 147 export interface HTMLAttributes extends JSXAttributes, EventAttributes, AnyAttributes {148 accesskey?: string | undefined149+ autocapitalize?: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters' | undefined150 autofocus?: boolean | undefined151 class?: string | Promise<string> | undefined152 contenteditable?: boolean | 'inherit' | undefined153 contextmenu?: string | undefined154 dir?: string | undefined155 draggable?: boolean | undefined156+ enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send' | undefined157 hidden?: boolean | undefined158 id?: string | undefined159+ inert?: boolean | undefined160+ inputmode?:161+ | 'none'162+ | 'text'163+ | 'tel'164+ | 'url'165+ | 'email'166+ | 'numeric'167+ | 'decimal'168+ | 'search'169+ | undefined170+ is?: string | undefined171+ itemid?: string | undefined172+ itemprop?: string | undefined173+ itemref?: string | undefined174+ itemscope?: boolean | undefined175+ itemtype?: string | undefined176 lang?: string | undefined177 nonce?: string | undefined178 placeholder?: string | undefined179+ popover?: string | undefined180 slot?: string | undefined181 spellcheck?: boolean | undefined182 style?: CSSProperties | undefined183 tabindex?: number | undefined184 title?: string | undefined185 translate?: 'yes' | 'no' | undefined186+ itemProp?: string | undefined187 }188 189 type HTMLAttributeReferrerPolicy =190 | ''51 unmodified lines242 formtarget?: string | undefined243 name?: string | undefined244 type?: 'submit' | 'reset' | 'button' | undefined245 value?: string | ReadonlyArray<string> | number | undefined246+247+ // React 19 compatibility248+ formAction?: string | Function | undefined249 }250 251 interface CanvasHTMLAttributes extends HTMLAttributes {252 height?: number | string | undefined46 unmodified lines299 method?: string | undefined300 name?: string | undefined301 novalidate?: boolean | undefined302 target?: string | undefined303+304+ // React 19 compatibility305+ action?: string | Function | undefined306 }307 308 interface HtmlHTMLAttributes extends HTMLAttributes {309 manifest?: string | undefined63 unmodified lines373 autocomplete?: string | undefined374 capture?: boolean | 'user' | 'environment' | undefined // https://www.w3.org/TR/html-media-capture/#the-capture-attribute375 checked?: boolean | undefined376 disabled?: boolean | undefined350- enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send' | undefined377 form?: string | undefined378 formenctype?: string | undefined379 formmethod?: string | undefined380 formnovalidate?: boolean | undefined15 unmodified lines396 step?: number | string | undefined397 type?: HTMLInputTypeAttribute | undefined398 value?: string | ReadonlyArray<string> | number | undefined399 width?: number | string | undefined400+401+ // React 19 compatibility402+ formAction?: string | Function | undefined403 }404 405 interface KeygenHTMLAttributes extends HTMLAttributes {406 challenge?: string | undefined24 unmodified lines431 referrerpolicy?: HTMLAttributeReferrerPolicy | undefined432 sizes?: string | undefined433 type?: string | undefined434 charSet?: string | undefined435+436+ // React 19 compatibility437+ rel?: string | undefined438+ precedence?: string | undefined439+ title?: string | undefined440+ disabled?: boolean | undefined441+ onError?: ((event: Event) => void) | undefined442+ onLoad?: ((event: Event) => void) | undefined443+ blocking?: 'render' | undefined444 }445 446 interface MapHTMLAttributes extends HTMLAttributes {447 name?: string | undefined21 unmodified lines469 'http-equiv'?: string | undefined470 name?: string | undefined471 media?: string | undefined472 content?: string | undefined473+474+ // React 19 compatibility475+ httpEquiv?: string | undefined476 }477 478 interface MeterHTMLAttributes extends HTMLAttributes {479 form?: string | undefined65 unmodified lines545 nomodule?: boolean | undefined546 referrerpolicy?: HTMLAttributeReferrerPolicy | undefined547 src?: string | undefined548 type?: string | undefined549+550+ // React 19 compatibility551+ crossOrigin?: CrossOrigin552+ fetchPriority?: string | undefined553+ noModule?: boolean | undefined554+ referrer?: HTMLAttributeReferrerPolicy | undefined555+ onError?: ((event: Event) => void) | undefined556+ onLoad?: ((event: Event) => void) | undefined557+ blocking?: 'render' | undefined558 }559 560 interface SelectHTMLAttributes extends HTMLAttributes {561 autocomplete?: string | undefined19 unmodified lines581 interface StyleHTMLAttributes extends HTMLAttributes {582 media?: string | undefined583 scoped?: boolean | undefined584 type?: string | undefined585+586+ // React 19 compatibility587+ href?: string | undefined588+ precedence?: string | undefined589+ title?: string | undefined590+ disabled?: boolean | undefined591+ blocking?: 'render' | undefined592 }593 594 interface TableHTMLAttributes extends HTMLAttributes {595 align?: 'left' | 'center' | 'right' | undefined191 unmodified linesmodified:src/jsx/streaming.test.tsx+2 added-2 removed
743 unmodified lines744 })745 746 describe('use()', async () => {747 it('render to string', async () => {748+ const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))749 const Content = () => {749- const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))750 const message = use(promise)751 return <h1>{message}</h1>752 }753 10 unmodified lines764 expect(str).toEqual('<h1>Hello from use()</h1>')765 })766 767 it('render to stream', async () => {768+ const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))769 const Content = () => {769- const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))770 const message = use(promise)771 return <h1>{message}</h1>772 }773 31 unmodified linesmodified:src/jsx/streaming.ts+1 added-1 removed
120 unmodified lines121 * The API might be changed.122 */123 export const renderToReadableStream = (124 str: HtmlEscapedString | Promise<HtmlEscapedString>,125- onError: (e: unknown) => void = console.trace125+ onError: (e: unknown) => string | void = console.trace126 ): ReadableStream<Uint8Array> => {127 const reader = new ReadableStream<Uint8Array>({128 async start(controller) {129 try {55 unmodified linesmodified:src/jsx/utils.test.ts+10 added-4 removed
1 import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'2 3 describe('normalizeIntrinsicElementKey', () => {4 test.each`5- key | expected6- ${'className'} | ${'class'}7- ${'htmlFor'} | ${'for'}8- ${'href'} | ${'href'}5+ key | expected6+ ${'className'} | ${'class'}7+ ${'htmlFor'} | ${'for'}8+ ${'crossOrigin'} | ${'crossorigin'}9+ ${'httpEquiv'} | ${'http-equiv'}10+ ${'itemProp'} | ${'itemprop'}11+ ${'fetchPriority'} | ${'fetchpriority'}12+ ${'noModule'} | ${'nomodule'}13+ ${'formAction'} | ${'formaction'}14+ ${'href'} | ${'href'}15 `('should convert $key to $expected', ({ key, expected }) => {16 expect(normalizeIntrinsicElementKey(key)).toBe(expected)17 })18 })90 unmodified linesmodified:src/jsx/utils.ts+6 added
1 const normalizeElementKeyMap: Map<string, string> = new Map([2 ['className', 'class'],3 ['htmlFor', 'for'],4+ ['crossOrigin', 'crossorigin'],5+ ['httpEquiv', 'http-equiv'],6+ ['itemProp', 'itemprop'],7+ ['fetchPriority', 'fetchpriority'],8+ ['noModule', 'nomodule'],9+ ['formAction', 'formaction'],10 ])11 export const normalizeIntrinsicElementKey = (key: string): string =>12 normalizeElementKeyMap.get(key) || key13 23 unmodified linesadded:src/middleware/combine/index.test.ts+264 added
1+import { Hono } from '../../hono'2+import { every, except, some } from '.'3+import type { MiddlewareHandler } from '../../types'4+5+const nextMiddleware: MiddlewareHandler = async (_, next) => await next()6+7+describe('some', () => {8+ let app: Hono9+10+ beforeEach(() => {11+ app = new Hono()12+ })13+14+ it('Should call only the first middleware', async () => {15+ const middleware1 = vi.fn(nextMiddleware)16+ const middleware2 = vi.fn(nextMiddleware)17+18+ app.use('/', some(middleware1, middleware2))19+ app.get('/', (c) => {20+ return c.text('Hello World')21+ })22+ const res = await app.request('http://localhost/')23+24+ expect(middleware1).toBeCalled()25+ expect(middleware2).not.toBeCalled()26+ expect(await res.text()).toBe('Hello World')27+ })28+29+ it('Should try to call the second middleware if the first one throws an error', async () => {30+ const middleware1 = () => {31+ throw new Error('Error')32+ }33+ const middleware2 = vi.fn(nextMiddleware)34+35+ app.use('/', some(middleware1, middleware2))36+ app.get('/', (c) => {37+ return c.text('Hello World')38+ })39+ const res = await app.request('http://localhost/')40+41+ expect(middleware2).toBeCalled()42+ expect(await res.text()).toBe('Hello World')43+ })44+45+ it('Should try to call the second middleware if the first one returns false', async () => {46+ const middleware1 = () => false47+ const middleware2 = vi.fn(nextMiddleware)48+49+ app.use('/', some(middleware1, middleware2))50+ app.get('/', (c) => {51+ return c.text('Hello World')52+ })53+ const res = await app.request('http://localhost/')54+55+ expect(middleware2).toBeCalled()56+ expect(await res.text()).toBe('Hello World')57+ })58+59+ it('Should throw last error if all middleware throw an error', async () => {60+ const middleware1 = () => {61+ throw new Error('Error1')62+ }63+ const middleware2 = () => {64+ throw new Error('Error2')65+ }66+67+ app.use('/', some(middleware1, middleware2))68+ app.get('/', (c) => {69+ return c.text('Hello World')70+ })71+ app.onError((error, c) => {72+ return c.text(error.message)73+ })74+ const res = await app.request('http://localhost/')75+76+ expect(await res.text()).toBe('Error2')77+ })78+79+ it('Should throw error if all middleware return false', async () => {80+ const middleware1 = () => false81+ const middleware2 = () => false82+83+ app.use('/', some(middleware1, middleware2))84+ app.get('/', (c) => {85+ return c.text('Hello World')86+ })87+ app.onError((_, c) => {88+ return c.text('oops')89+ })90+ const res = await app.request('http://localhost/')91+92+ expect(await res.text()).toBe('oops')93+ })94+})95+96+describe('every', () => {97+ let app: Hono98+99+ beforeEach(() => {100+ app = new Hono()101+ })102+103+ it('Should call all middleware', async () => {104+ const middleware1 = vi.fn(nextMiddleware)105+ const middleware2 = vi.fn(nextMiddleware)106+107+ app.use('/', every(middleware1, middleware2))108+ app.get('/', (c) => {109+ return c.text('Hello World')110+ })111+ const res = await app.request('http://localhost/')112+113+ expect(middleware1).toBeCalled()114+ expect(middleware2).toBeCalled()115+ expect(await res.text()).toBe('Hello World')116+ })117+118+ it('Should throw error if any middleware throws an error', async () => {119+ const middleware1 = () => {120+ throw new Error('Error1')121+ }122+ const middleware2 = vi.fn(nextMiddleware)123+124+ app.use('/', every(middleware1, middleware2))125+ app.get('/', (c) => {126+ return c.text('Hello World')127+ })128+ app.onError((error, c) => {129+ return c.text(error.message)130+ })131+ const res = await app.request('http://localhost/')132+133+ expect(await res.text()).toBe('Error1')134+ expect(middleware2).not.toBeCalled()135+ })136+137+ it('Should throw error if any middleware returns false', async () => {138+ const middleware1 = () => false139+ const middleware2 = vi.fn(nextMiddleware)140+141+ app.use('/', every(middleware1, middleware2))142+ app.get('/', (c) => {143+ return c.text('Hello World')144+ })145+ app.onError((_, c) => {146+ return c.text('oops')147+ })148+ const res = await app.request('http://localhost/')149+150+ expect(await res.text()).toBe('oops')151+ expect(middleware2).not.toBeCalled()152+ })153+})154+155+describe('except', () => {156+ let app: Hono157+158+ beforeEach(() => {159+ app = new Hono()160+ })161+162+ it('Should call all middleware, except the one that matches the condition', async () => {163+ const middleware1 = vi.fn(nextMiddleware)164+ const middleware2 = vi.fn(nextMiddleware)165+166+ app.use('*', except('/maintenance', middleware1, middleware2))167+ app.get('/maintenance', (c) => {168+ return c.text('Hello Maintenance')169+ })170+ app.get('*', (c) => {171+ return c.redirect('/maintenance')172+ })173+ let res = await app.request('http://localhost/')174+175+ expect(middleware1).toBeCalled()176+ expect(middleware2).toBeCalled()177+ expect(res.headers.get('location')).toBe('/maintenance')178+179+ middleware1.mockClear()180+ middleware2.mockClear()181+ res = await app.request('http://localhost/maintenance')182+183+ expect(middleware1).not.toBeCalled()184+ expect(middleware2).not.toBeCalled()185+ expect(await res.text()).toBe('Hello Maintenance')186+ })187+188+ it('Should call all middleware, except the one that matches some of the conditions', async () => {189+ const middleware1 = vi.fn(nextMiddleware)190+ const middleware2 = vi.fn(nextMiddleware)191+192+ app.use('*', except(['/maintenance', '/public/users/:id'], middleware1, middleware2))193+ app.get('/maintenance', (c) => {194+ return c.text('Hello Maintenance')195+ })196+ app.get('/public/users/:id', (c) => {197+ return c.text(`Hello Public User ${c.req.param('id')}`)198+ })199+ app.get('/secret', (c) => {200+ return c.text('Hello Secret')201+ })202+ let res = await app.request('http://localhost/secret')203+204+ expect(middleware1).toBeCalled()205+ expect(middleware2).toBeCalled()206+ expect(await res.text()).toBe('Hello Secret')207+208+ middleware1.mockClear()209+ middleware2.mockClear()210+ res = await app.request('http://localhost/maintenance')211+212+ expect(middleware1).not.toBeCalled()213+ expect(middleware2).not.toBeCalled()214+ expect(await res.text()).toBe('Hello Maintenance')215+216+ middleware1.mockClear()217+ middleware2.mockClear()218+ res = await app.request('http://localhost/public/users/123')219+220+ expect(middleware1).not.toBeCalled()221+ expect(middleware2).not.toBeCalled()222+ expect(await res.text()).toBe('Hello Public User 123')223+ })224+225+ it('Should call all middleware, except the one that matches some of the condition function', async () => {226+ const middleware1 = vi.fn(nextMiddleware)227+ const middleware2 = vi.fn(nextMiddleware)228+229+ app.use(230+ '*',231+ except(['/maintenance', (c) => !!c.req.path.match(/public/)], middleware1, middleware2)232+ )233+ app.get('/maintenance', (c) => {234+ return c.text('Hello Maintenance')235+ })236+ app.get('/public/users/:id', (c) => {237+ return c.text(`Hello Public User ${c.req.param('id')}`)238+ })239+ app.get('/secret', (c) => {240+ return c.text('Hello Secret')241+ })242+ let res = await app.request('http://localhost/secret')243+244+ expect(middleware1).toBeCalled()245+ expect(middleware2).toBeCalled()246+ expect(await res.text()).toBe('Hello Secret')247+248+ middleware1.mockClear()249+ middleware2.mockClear()250+ res = await app.request('http://localhost/maintenance')251+252+ expect(middleware1).not.toBeCalled()253+ expect(middleware2).not.toBeCalled()254+ expect(await res.text()).toBe('Hello Maintenance')255+256+ middleware1.mockClear()257+ middleware2.mockClear()258+ res = await app.request('http://localhost/public/users/123')259+260+ expect(middleware1).not.toBeCalled()261+ expect(middleware2).not.toBeCalled()262+ expect(await res.text()).toBe('Hello Public User 123')263+ })264+})added:src/middleware/combine/index.ts+153 added
1+/**2+ * @module3+ * Combine Middleware for Hono.4+ */5+6+import type { Context } from '../../context'7+import type { MiddlewareHandler, Next } from '../../types'8+import { TrieRouter } from '../../router/trie-router'9+import { METHOD_NAME_ALL } from '../../router'10+import { compose } from '../../compose'11+12+type Condition = (c: Context) => boolean13+14+/**15+ * Create a composed middleware that runs the first middleware that returns true.16+ *17+ * @param middleware - An array of MiddlewareHandler or Condition functions.18+ * Middleware is applied in the order it is passed, and if any middleware exits without returning19+ * an exception first, subsequent middleware will not be executed.20+ * You can also pass a condition function that returns a boolean value. If returns true21+ * the evaluation will be halted, and rest of the middleware will not be executed.22+ * @returns A composed middleware.23+ *24+ * @example25+ * ```ts26+ * import { some } from 'hono/combine'27+ * import { bearerAuth } from 'hono/bearer-auth'28+ * import { myRateLimit } from '@/rate-limit'29+ *30+ * // If client has a valid token, then skip rate limiting.31+ * // Otherwise, apply rate limiting.32+ * app.use('/api/*', some(33+ * bearerAuth({ token }),34+ * myRateLimit({ limit: 100 }),35+ * ));36+ * ```37+ */38+export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {39+ return async function some(c, next) {40+ let lastError: unknown41+ for (const handler of middleware) {42+ try {43+ const result = await handler(c, next)44+ if (result === true && !c.finalized) {45+ await next()46+ } else if (result === false) {47+ lastError = new Error('No successful middleware found')48+ continue49+ }50+ lastError = undefined51+ break52+ } catch (error) {53+ lastError = error54+ continue55+ }56+ }57+ if (lastError) {58+ throw lastError59+ }60+ }61+}62+63+/**64+ * Create a composed middleware that runs all middleware and throws an error if any of them fail.65+ *66+ * @param middleware - An array of MiddlewareHandler or Condition functions.67+ * Middleware is applied in the order it is passed, and if any middleware throws an error,68+ * subsequent middleware will not be executed.69+ * You can also pass a condition function that returns a boolean value. If returns false70+ * the evaluation will be halted, and rest of the middleware will not be executed.71+ * @returns A composed middleware.72+ *73+ * @example74+ * ```ts75+ * import { some, every } from 'hono/combine'76+ * import { bearerAuth } from 'hono/bearer-auth'77+ * import { myCheckLocalNetwork } from '@/check-local-network'78+ * import { myRateLimit } from '@/rate-limit'79+ *80+ * // If client is in local network, then skip authentication and rate limiting.81+ * // Otherwise, apply authentication and rate limiting.82+ * app.use('/api/*', some(83+ * myCheckLocalNetwork(),84+ * every(85+ * bearerAuth({ token }),86+ * myRateLimit({ limit: 100 }),87+ * ),88+ * ));89+ * ```90+ */91+export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {92+ const wrappedMiddleware = middleware.map((m) => async (c: Context, next: Next) => {93+ const res = await m(c, next)94+ if (res === false) {95+ throw new Error('Unmet condition')96+ }97+ })98+99+ const handler = async (c: Context, next: Next) =>100+ compose<Context>(wrappedMiddleware.map((m) => [[m, undefined], c.req.param()]))(c, next)101+102+ return async function every(c, next) {103+ await handler(c, next)104+ }105+}106+107+/**108+ * Create a composed middleware that runs all middleware except when the condition is met.109+ *110+ * @param condition - A string or Condition function.111+ * If there are multiple targets to match any of them, they can be passed as an array.112+ * If a string is passed, it will be treated as a path pattern to match.113+ * If a Condition function is passed, it will be evaluated against the request context.114+ * @param middleware - A composed middleware115+ *116+ * @example117+ * ```ts118+ * import { except } from 'hono/combine'119+ * import { bearerAuth } from 'hono/bearer-auth120+ *121+ * // If client is accessing public API, then skip authentication.122+ * // Otherwise, require a valid token.123+ * app.use('/api/*', except(124+ * '/api/public/*',125+ * bearerAuth({ token }),126+ * ));127+ * ```128+ */129+export const except = (130+ condition: string | Condition | (string | Condition)[],131+ ...middleware: MiddlewareHandler[]132+): MiddlewareHandler => {133+ let router: TrieRouter<true> | undefined = undefined134+ const conditions = (Array.isArray(condition) ? condition : [condition])135+ .map((condition) => {136+ if (typeof condition === 'string') {137+ router ||= new TrieRouter()138+ router.add(METHOD_NAME_ALL, condition, true)139+ } else {140+ return condition141+ }142+ })143+ .filter(Boolean) as Condition[]144+145+ if (router) {146+ conditions.unshift((c: Context) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0])147+ }148+149+ const handler = some((c: Context) => conditions.some((cond) => cond(c)), every(...middleware))150+ return async function except(c, next) {151+ await handler(c, next)152+ }153+}added:src/middleware/ip-restriction/index.test.ts+114 added
1+import { Hono } from '../../hono'2+import { Context } from '../../context'3+import type { AddressType, GetConnInfo } from '../../helper/conninfo'4+import { ipRestriction } from '.'5+import type { IPRestrictionRule } from '.'6+7+describe('ipRestriction middleware', () => {8+ it('Should restrict', async () => {9+ const getConnInfo: GetConnInfo = (c) => {10+ return {11+ remote: {12+ address: c.env.ip,13+ },14+ }15+ }16+ const app = new Hono<{17+ Bindings: {18+ ip: string19+ }20+ }>()21+ app.use(22+ '/basic',23+ ipRestriction(getConnInfo, {24+ allowList: ['192.168.1.0', '192.168.2.0/24'],25+ denyList: ['192.168.2.10'],26+ })27+ )28+ app.get('/basic', (c) => c.text('Hello World!'))29+30+ app.use(31+ '/allow-empty',32+ ipRestriction(getConnInfo, {33+ denyList: ['192.168.1.0'],34+ })35+ )36+ app.get('/allow-empty', (c) => c.text('Hello World!'))37+38+ expect((await app.request('/basic', {}, { ip: '0.0.0.0' })).status).toBe(403)39+40+ expect((await app.request('/basic', {}, { ip: '192.168.1.0' })).status).toBe(200)41+42+ expect((await app.request('/basic', {}, { ip: '192.168.2.5' })).status).toBe(200)43+ expect((await app.request('/basic', {}, { ip: '192.168.2.10' })).status).toBe(403)44+45+ expect((await app.request('/allow-empty', {}, { ip: '0.0.0.0' })).status).toBe(200)46+47+ expect((await app.request('/allow-empty', {}, { ip: '192.168.1.0' })).status).toBe(403)48+49+ expect((await app.request('/allow-empty', {}, { ip: '192.168.2.5' })).status).toBe(200)50+ expect((await app.request('/allow-empty', {}, { ip: '192.168.2.10' })).status).toBe(200)51+ })52+ it('Custom onerror', async () => {53+ const res = await ipRestriction(54+ () => '0.0.0.0',55+ { denyList: ['0.0.0.0'] },56+ () => new Response('error')57+ )(new Context(new Request('http://localhost/')), async () => void 0)58+ expect(res).toBeTruthy()59+ if (res) {60+ expect(await res.text()).toBe('error')61+ }62+ })63+})64+65+describe('isMatchForRule', () => {66+ const isMatch = async (info: { addr: string; type: AddressType }, rule: IPRestrictionRule) => {67+ const middleware = ipRestriction(68+ () => ({69+ remote: {70+ address: info.addr,71+ addressType: info.type,72+ },73+ }),74+ {75+ allowList: [rule],76+ }77+ )78+ try {79+ // eslint-disable-next-line @typescript-eslint/no-explicit-any80+ await middleware(undefined as any, () => Promise.resolve())81+ } catch (e) {82+ return false83+ }84+ return true85+ }86+87+ it('star', async () => {88+ expect(await isMatch({ addr: '192.168.2.0', type: 'IPv4' }, '*')).toBeTruthy()89+ expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '*')).toBeTruthy()90+ expect(await isMatch({ addr: '::0', type: 'IPv6' }, '*')).toBeTruthy()91+ })92+ it('CIDR Notation', async () => {93+ expect(await isMatch({ addr: '192.168.2.0', type: 'IPv4' }, '192.168.2.0/24')).toBeTruthy()94+ expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '192.168.2.0/24')).toBeTruthy()95+ expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '192.168.2.1/32')).toBeTruthy()96+ expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '192.168.2.2/32')).toBeFalsy()97+98+ expect(await isMatch({ addr: '::0', type: 'IPv6' }, '::0/1')).toBeTruthy()99+ })100+ it('Static Rules', async () => {101+ expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '192.168.2.1')).toBeTruthy()102+ expect(await isMatch({ addr: '1234::5678', type: 'IPv6' }, '1234::5678')).toBeTruthy()103+ })104+ it('Function Rules', async () => {105+ expect(await isMatch({ addr: '0.0.0.0', type: 'IPv4' }, () => true)).toBeTruthy()106+ expect(await isMatch({ addr: '0.0.0.0', type: 'IPv4' }, () => false)).toBeFalsy()107+108+ const ipaddr = '93.184.216.34'109+ await isMatch({ addr: ipaddr, type: 'IPv4' }, (ip) => {110+ expect(ipaddr).toBe(ip.addr)111+ return false112+ })113+ })114+})added:src/middleware/ip-restriction/index.ts+178 added
1+/**2+ * IP Restriction Middleware for Hono3+ * @module4+ */5+6+import type { Context, MiddlewareHandler } from '../..'7+import type { AddressType, GetConnInfo } from '../../helper/conninfo'8+import { HTTPException } from '../../http-exception'9+import {10+ convertIPv4ToBinary,11+ convertIPv6BinaryToString,12+ convertIPv6ToBinary,13+ distinctRemoteAddr,14+} from '../../utils/ipaddr'15+16+/**17+ * Function to get IP Address18+ */19+type GetIPAddr = GetConnInfo | ((c: Context) => string)20+21+/**22+ * ### IPv4 and IPv623+ * - `*` match all24+ *25+ * ### IPv426+ * - `192.168.2.0` static27+ * - `192.168.2.0/24` CIDR Notation28+ *29+ * ### IPv630+ * - `::1` static31+ * - `::1/10` CIDR Notation32+ */33+type IPRestrictionRuleFunction = (addr: { addr: string; type: AddressType }) => boolean34+export type IPRestrictionRule = string | ((addr: { addr: string; type: AddressType }) => boolean)35+36+const IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/37+const buildMatcher = (38+ rules: IPRestrictionRule[]39+): ((addr: { addr: string; type: AddressType; isIPv4: boolean }) => boolean) => {40+ const functionRules: IPRestrictionRuleFunction[] = []41+ const staticRules: Set<string> = new Set()42+ const cidrRules: [boolean, bigint, bigint][] = []43+44+ for (let rule of rules) {45+ if (rule === '*') {46+ return () => true47+ } else if (typeof rule === 'function') {48+ functionRules.push(rule)49+ } else {50+ if (IS_CIDR_NOTATION_REGEX.test(rule)) {51+ const splittedRule = rule.split('/')52+53+ const addrStr = splittedRule[0]54+ const type = distinctRemoteAddr(addrStr)55+ if (type === undefined) {56+ throw new TypeError(`Invalid rule: ${rule}`)57+ }58+59+ const isIPv4 = type === 'IPv4'60+ const prefix = parseInt(splittedRule[1])61+62+ if (isIPv4 ? prefix === 32 : prefix === 128) {63+ // this rule is a static rule64+ rule = addrStr65+ } else {66+ const addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr)67+ const mask = ((1n << BigInt(prefix)) - 1n) << BigInt((isIPv4 ? 32 : 128) - prefix)68+69+ cidrRules.push([isIPv4, addr & mask, mask] as [boolean, bigint, bigint])70+ continue71+ }72+ }73+74+ const type = distinctRemoteAddr(rule)75+ if (type === undefined) {76+ throw new TypeError(`Invalid rule: ${rule}`)77+ }78+ staticRules.add(79+ type === 'IPv4'80+ ? rule // IPv4 address is already normalized, so it is registered as is.81+ : convertIPv6BinaryToString(convertIPv6ToBinary(rule)) // normalize IPv6 address (e.g. 0000:0000:0000:0000:0000:0000:0000:0001 => ::1)82+ )83+ }84+ }85+86+ return (remote: {87+ addr: string88+ type: AddressType89+ isIPv4: boolean90+ binaryAddr?: bigint91+ }): boolean => {92+ if (staticRules.has(remote.addr)) {93+ return true94+ }95+ for (const [isIPv4, addr, mask] of cidrRules) {96+ if (isIPv4 !== remote.isIPv4) {97+ continue98+ }99+ const remoteAddr = (remote.binaryAddr ||= (100+ isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary101+ )(remote.addr))102+ if ((remoteAddr & mask) === addr) {103+ return true104+ }105+ }106+ for (const rule of functionRules) {107+ if (rule({ addr: remote.addr, type: remote.type })) {108+ return true109+ }110+ }111+ return false112+ }113+}114+115+/**116+ * Rules for IP Restriction Middleware117+ */118+export interface IPRestrictionRules {119+ denyList?: IPRestrictionRule[]120+ allowList?: IPRestrictionRule[]121+}122+123+/**124+ * IP Restriction Middleware125+ *126+ * @param getIP function to get IP Address127+ */128+export const ipRestriction = (129+ getIP: GetIPAddr,130+ { denyList = [], allowList = [] }: IPRestrictionRules,131+ onError?: (132+ remote: { addr: string; type: AddressType },133+ c: Context134+ ) => Response | Promise<Response>135+): MiddlewareHandler => {136+ const allowLength = allowList.length137+138+ const denyMatcher = buildMatcher(denyList)139+ const allowMatcher = buildMatcher(allowList)140+141+ const blockError = (c: Context): HTTPException =>142+ new HTTPException(403, {143+ res: c.text('Forbidden', {144+ status: 403,145+ }),146+ })147+148+ return async function ipRestriction(c, next) {149+ const connInfo = getIP(c)150+ const addr = typeof connInfo === 'string' ? connInfo : connInfo.remote.address151+ if (!addr) {152+ throw blockError(c)153+ }154+ const type =155+ (typeof connInfo !== 'string' && connInfo.remote.addressType) || distinctRemoteAddr(addr)156+157+ const remoteData = { addr, type, isIPv4: type === 'IPv4' }158+159+ if (denyMatcher(remoteData)) {160+ if (onError) {161+ return onError({ addr, type }, c)162+ }163+ throw blockError(c)164+ }165+ if (allowMatcher(remoteData)) {166+ return await next()167+ }168+169+ if (allowLength === 0) {170+ return await next()171+ } else {172+ if (onError) {173+ return await onError({ addr, type }, c)174+ }175+ throw blockError(c)176+ }177+ }178+}modified:src/middleware/jwt/index.test.ts+204 added
239 unmodified lines240 message: `invalid JWT token: ${credential}`,241 })242 })243 })244+245+ describe('Credentials in signed cookie with prefix Options', () => {246+ let handlerExecuted: boolean247+248+ beforeEach(() => {249+ handlerExecuted = false250+ })251+252+ const app = new Hono()253+254+ app.use(255+ '/auth/*',256+ jwt({257+ secret: 'a-secret',258+ cookie: {259+ key: 'cookie_name',260+ secret: 'cookie_secret',261+ prefixOptions: 'host',262+ },263+ })264+ )265+266+ app.get('/auth/*', async (c) => {267+ handlerExecuted = true268+ const payload = c.get('jwtPayload')269+ return c.json(payload)270+ })271+272+ it('Should not authorize', async () => {273+ const req = new Request('http://localhost/auth/a')274+ const res = await app.request(req)275+ expect(res).not.toBeNull()276+ expect(res.status).toBe(401)277+ expect(await res.text()).toBe('Unauthorized')278+ expect(handlerExecuted).toBeFalsy()279+ })280+281+ it('Should authorize', async () => {282+ const url = 'http://localhost/auth/a'283+ const req = new Request(url, {284+ headers: new Headers({285+ Cookie:286+ '__Host-cookie_name=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE.i2NSvtJOXOPS9NDL1u8dqTYmMrzcD4mNSws6P6qmeV0%3D; Path=/',287+ }),288+ })289+ const res = await app.request(req)290+ expect(res).not.toBeNull()291+ expect(res.status).toBe(200)292+ expect(await res.json()).toEqual({ message: 'hello world' })293+ expect(handlerExecuted).toBeTruthy()294+ })295+ })296+297+ describe('Credentials in signed cookie without prefix Options', () => {298+ let handlerExecuted: boolean299+300+ beforeEach(() => {301+ handlerExecuted = false302+ })303+304+ const app = new Hono()305+306+ app.use(307+ '/auth/*',308+ jwt({309+ secret: 'a-secret',310+ cookie: {311+ key: 'cookie_name',312+ secret: 'cookie_secret',313+ },314+ })315+ )316+317+ app.get('/auth/*', async (c) => {318+ handlerExecuted = true319+ const payload = c.get('jwtPayload')320+ return c.json(payload)321+ })322+323+ it('Should not authorize', async () => {324+ const req = new Request('http://localhost/auth/a')325+ const res = await app.request(req)326+ expect(res).not.toBeNull()327+ expect(res.status).toBe(401)328+ expect(await res.text()).toBe('Unauthorized')329+ expect(handlerExecuted).toBeFalsy()330+ })331+332+ it('Should authorize', async () => {333+ const url = 'http://localhost/auth/a'334+ const req = new Request(url, {335+ headers: new Headers({336+ Cookie:337+ 'cookie_name=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE.i2NSvtJOXOPS9NDL1u8dqTYmMrzcD4mNSws6P6qmeV0%3D; Path=/',338+ }),339+ })340+ const res = await app.request(req)341+ expect(res).not.toBeNull()342+ expect(res.status).toBe(200)343+ expect(await res.json()).toEqual({ message: 'hello world' })344+ expect(handlerExecuted).toBeTruthy()345+ })346+ })347+348+ describe('Credentials in cookie object with prefix Options', () => {349+ let handlerExecuted: boolean350+351+ beforeEach(() => {352+ handlerExecuted = false353+ })354+355+ const app = new Hono()356+357+ app.use(358+ '/auth/*',359+ jwt({360+ secret: 'a-secret',361+ cookie: {362+ key: 'cookie_name',363+ prefixOptions: 'host',364+ },365+ })366+ )367+368+ app.get('/auth/*', async (c) => {369+ handlerExecuted = true370+ const payload = c.get('jwtPayload')371+ return c.json(payload)372+ })373+374+ it('Should not authorize', async () => {375+ const req = new Request('http://localhost/auth/a')376+ const res = await app.request(req)377+ expect(res).not.toBeNull()378+ expect(res.status).toBe(401)379+ expect(await res.text()).toBe('Unauthorized')380+ expect(handlerExecuted).toBeFalsy()381+ })382+383+ it('Should authorize', async () => {384+ const url = 'http://localhost/auth/a'385+ const req = new Request(url, {386+ headers: new Headers({387+ Cookie:388+ '__Host-cookie_name=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE',389+ }),390+ })391+ const res = await app.request(req)392+ expect(res).not.toBeNull()393+ expect(res.status).toBe(200)394+ expect(await res.json()).toEqual({ message: 'hello world' })395+ expect(handlerExecuted).toBeTruthy()396+ })397+ })398+399+ describe('Credentials in cookie object without prefix Options', () => {400+ let handlerExecuted: boolean401+402+ beforeEach(() => {403+ handlerExecuted = false404+ })405+406+ const app = new Hono()407+408+ app.use(409+ '/auth/*',410+ jwt({411+ secret: 'a-secret',412+ cookie: {413+ key: 'cookie_name',414+ },415+ })416+ )417+418+ app.get('/auth/*', async (c) => {419+ handlerExecuted = true420+ const payload = c.get('jwtPayload')421+ return c.json(payload)422+ })423+424+ it('Should not authorize', async () => {425+ const req = new Request('http://localhost/auth/a')426+ const res = await app.request(req)427+ expect(res).not.toBeNull()428+ expect(res.status).toBe(401)429+ expect(await res.text()).toBe('Unauthorized')430+ expect(handlerExecuted).toBeFalsy()431+ })432+433+ it('Should authorize', async () => {434+ const url = 'http://localhost/auth/a'435+ const req = new Request(url, {436+ headers: new Headers({437+ Cookie:438+ 'cookie_name=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE',439+ }),440+ })441+ const res = await app.request(req)442+ expect(res).not.toBeNull()443+ expect(res.status).toBe(200)444+ expect(await res.json()).toEqual({ message: 'hello world' })445+ expect(handlerExecuted).toBeTruthy()446+ })447+ })448 })modified:src/middleware/jwt/jwt.ts+25 added-3 removed
2 unmodified lines3 * JWT Auth Middleware for Hono.4 */5 6 import type { Context } from '../../context'7-import { getCookie } from '../../helper/cookie'7+import { getCookie, getSignedCookie } from '../../helper/cookie'8 import { HTTPException } from '../../http-exception'9 import type { MiddlewareHandler } from '../../types'10+import type { CookiePrefixOptions } from '../../utils/cookie'11 import { Jwt } from '../../utils/jwt'12 import '../../context'13 import type { SignatureAlgorithm } from '../../utils/jwt/jwa'14 30 unmodified lines45 * ```46 */47 export const jwt = (options: {48 secret: string48- cookie?: string49+ cookie?:50+ | string51+ | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }52 alg?: SignatureAlgorithm53 }): MiddlewareHandler => {54 if (!options || !options.secret) {55 throw new Error('JWT auth middleware requires options for "secret"')21 unmodified lines77 } else {78 token = parts[1]79 }80 } else if (options.cookie) {81+ if (typeof options.cookie == 'string') {78- token = getCookie(ctx)[options.cookie]82+ token = getCookie(ctx, options.cookie)83+ } else if (options.cookie.secret) {84+ if (options.cookie.prefixOptions) {85+ token = await getSignedCookie(86+ ctx,87+ options.cookie.secret,88+ options.cookie.key,89+ options.cookie.prefixOptions90+ )91+ } else {92+ token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key)93+ }94+ } else {95+ if (options.cookie.prefixOptions) {96+ token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions)97+ } else {98+ token = getCookie(ctx, options.cookie.key)99+ }100+ }101 }102 103 if (!token) {104 const errDescription = 'no authorization included in request'54 unmodified linesadded:src/middleware/request-id/index.test.ts+155 added
1+import type { Context } from '../../context'2+import { Hono } from '../../hono'3+import { requestId } from '.'4+5+const regexUUIDv4 = /([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/6+7+describe('Request ID Middleware', () => {8+ const app = new Hono()9+ app.use('*', requestId())10+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))11+12+ it('Should return random request id', async () => {13+ const res = await app.request('http://localhost/requestId')14+ expect(res).not.toBeNull()15+ expect(res.status).toBe(200)16+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)17+ expect(await res.text()).match(regexUUIDv4)18+ })19+20+ it('Should return custom request id', async () => {21+ const res = await app.request('http://localhost/requestId', {22+ headers: {23+ 'X-Request-Id': 'hono-is-cool',24+ },25+ })26+ expect(res).not.toBeNull()27+ expect(res.status).toBe(200)28+ expect(res.headers.get('X-Request-Id')).toBe('hono-is-cool')29+ expect(await res.text()).toBe('hono-is-cool')30+ })31+32+ it('Should return random request id without using request header', async () => {33+ const res = await app.request('http://localhost/requestId', {34+ headers: {35+ 'X-Request-Id': 'Hello!12345-@*^',36+ },37+ })38+ expect(res).not.toBeNull()39+ expect(res.status).toBe(200)40+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)41+ expect(await res.text()).toMatch(regexUUIDv4)42+ })43+})44+45+describe('Request ID Middleware with custom generator', () => {46+ function generateWord() {47+ return 'HonoIsWebFramework'48+ }49+ function generateDoubleRequestId(c: Context) {50+ const honoId = c.req.header('Hono-Request-Id')51+ const ohnoId = c.req.header('Ohno-Request-Id')52+ if (honoId && ohnoId) {53+ return honoId + ohnoId54+ }55+ return crypto.randomUUID()56+ }57+ const app = new Hono()58+ app.use('/word', requestId({ generator: generateWord }))59+ app.use('/doubleRequestId', requestId({ generator: generateDoubleRequestId }))60+ app.get('/word', (c) => c.text(c.get('requestId') ?? 'No Request ID'))61+ app.get('/doubleRequestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))62+ it('Should return custom request id', async () => {63+ const res = await app.request('http://localhost/word')64+ expect(res).not.toBeNull()65+ expect(res.status).toBe(200)66+ expect(res.headers.get('X-Request-Id')).toBe('HonoIsWebFramework')67+ expect(await res.text()).toBe('HonoIsWebFramework')68+ })69+70+ it('Should return complex request id', async () => {71+ const res = await app.request('http://localhost/doubleRequestId', {72+ headers: {73+ 'Hono-Request-Id': 'Hello',74+ 'Ohno-Request-Id': 'World',75+ },76+ })77+ expect(res).not.toBeNull()78+ expect(res.status).toBe(200)79+ expect(res.headers.get('X-Request-Id')).toBe('HelloWorld')80+ expect(await res.text()).toBe('HelloWorld')81+ })82+})83+84+describe('Request ID Middleware with limit length', () => {85+ const charactersOf255 = 'h'.repeat(255)86+ const charactersOf256 = 'h'.repeat(256)87+88+ const app = new Hono()89+ app.use('/requestId', requestId())90+ app.use('/limit256', requestId({ limitLength: 256 }))91+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))92+ app.get('/limit256', (c) => c.text(c.get('requestId') ?? 'No Request ID'))93+94+ it('Should return custom request id', async () => {95+ const res = await app.request('http://localhost/requestId', {96+ headers: {97+ 'X-Request-Id': charactersOf255,98+ },99+ })100+ expect(res).not.toBeNull()101+ expect(res.status).toBe(200)102+ expect(res.headers.get('X-Request-Id')).toBe(charactersOf255)103+ expect(await res.text()).toBe(charactersOf255)104+ })105+ it('Should return random request id without using request header', async () => {106+ const res = await app.request('http://localhost/requestId', {107+ headers: {108+ 'X-Request-Id': charactersOf256,109+ },110+ })111+ expect(res).not.toBeNull()112+ expect(res.status).toBe(200)113+ expect(res.headers.get('X-Request-Id')).toMatch(regexUUIDv4)114+ expect(await res.text()).toMatch(regexUUIDv4)115+ })116+ it('Should return custom request id with 256 characters', async () => {117+ const res = await app.request('http://localhost/limit256', {118+ headers: {119+ 'X-Request-Id': charactersOf256,120+ },121+ })122+ expect(res).not.toBeNull()123+ expect(res.status).toBe(200)124+ expect(res.headers.get('X-Request-Id')).toBe(charactersOf256)125+ expect(await res.text()).toBe(charactersOf256)126+ })127+})128+129+describe('Request ID Middleware with custom header', () => {130+ const app = new Hono()131+ app.use('/requestId', requestId({ headerName: 'Hono-Request-Id' }))132+ app.get('/emptyId', requestId({ headerName: '' }))133+ app.get('/requestId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))134+ app.get('/emptyId', (c) => c.text(c.get('requestId') ?? 'No Request ID'))135+136+ it('Should return custom request id', async () => {137+ const res = await app.request('http://localhost/requestId', {138+ headers: {139+ 'Hono-Request-Id': 'hono-is-cool',140+ },141+ })142+ expect(res).not.toBeNull()143+ expect(res.status).toBe(200)144+ expect(res.headers.get('Hono-Request-Id')).toBe('hono-is-cool')145+ expect(await res.text()).toBe('hono-is-cool')146+ })147+148+ it('Should not return request id', async () => {149+ const res = await app.request('http://localhost/emptyId')150+ expect(res).not.toBeNull()151+ expect(res.status).toBe(200)152+ expect(res.headers.get('X-Request-Id')).toBeNull()153+ expect(await res.text()).toMatch(regexUUIDv4)154+ })155+})added:src/middleware/request-id/index.ts+8 added
1+import type { RequestIdVariables } from './request-id'2+export type { RequestIdVariables }3+export { requestId } from './request-id'4+import type {} from '../..'5+6+declare module '../..' {7+ interface ContextVariableMap extends RequestIdVariables {}8+}added:src/middleware/request-id/request-id.ts+59 added
1+/**2+ * @module3+ * Request ID Middleware for Hono.4+ */5+6+import type { Context } from '../../context'7+import type { MiddlewareHandler } from '../../types'8+9+export type RequestIdVariables = {10+ requestId: string11+}12+13+export type RequestIdOptions = {14+ limitLength?: number15+ headerName?: string16+ generator?: (c: Context) => string17+}18+19+/**20+ * Request ID Middleware for Hono.21+ *22+ * @param {object} options - Options for Request ID middleware.23+ * @param {number} [options.limitLength=255] - The maximum length of request id.24+ * @param {string} [options.headerName=X-Request-Id] - The header name used in request id.25+ * @param {generator} [options.generator=() => crypto.randomUUID()] - The request id generation function.26+ *27+ * @returns {MiddlewareHandler} The middleware handler function.28+ *29+ * @example30+ * ```ts31+ * type Variables = RequestIdVariables32+ * const app = new Hono<{Variables: Variables}>()33+ *34+ * app.use(requestId())35+ * app.get('/', (c) => {36+ * console.log(c.get('requestId')) // Debug37+ * return c.text('Hello World!')38+ * })39+ * ```40+ */41+export const requestId = ({42+ limitLength = 255,43+ headerName = 'X-Request-Id',44+ generator = () => crypto.randomUUID(),45+}: RequestIdOptions = {}): MiddlewareHandler => {46+ return async function requestId(c, next) {47+ // If `headerName` is empty string, req.header will return the object48+ let reqId = headerName ? c.req.header(headerName) : undefined49+ if (!reqId || reqId.length > limitLength || /[^\w\-]/.test(reqId)) {50+ reqId = generator(c)51+ }52+53+ c.set('requestId', reqId)54+ if (headerName) {55+ c.header(headerName, reqId)56+ }57+ await next()58+ }59+}modified:src/preset/quick.test.ts+33 added
5 unmodified lines6 const app = new Hono()7 expect(getRouterName(app)).toBe('SmartRouter + LinearRouter')8 })9 })10+11+describe('Generics for Bindings and Variables', () => {12+ interface CloudflareBindings {13+ MY_VARIABLE: string14+ }15+16+ it('Should not throw type errors', () => {17+ // @ts-expect-error Bindings should extend object18+ new Hono<{19+ Bindings: number20+ }>()21+22+ const appWithInterface = new Hono<{23+ Bindings: CloudflareBindings24+ }>()25+26+ appWithInterface.get('/', (c) => {27+ expectTypeOf(c.env.MY_VARIABLE).toMatchTypeOf<string>()28+ return c.text('/')29+ })30+31+ const appWithType = new Hono<{32+ Bindings: {33+ foo: string34+ }35+ }>()36+37+ appWithType.get('/', (c) => {38+ expectTypeOf(c.env.foo).toMatchTypeOf<string>()39+ return c.text('Hello Hono!')40+ })41+ })42+})modified:src/preset/tiny.test.ts+33 added
5 unmodified lines6 const app = new Hono()7 expect(getRouterName(app)).toBe('PatternRouter')8 })9 })10+11+describe('Generics for Bindings and Variables', () => {12+ interface CloudflareBindings {13+ MY_VARIABLE: string14+ }15+16+ it('Should not throw type errors', () => {17+ // @ts-expect-error Bindings should extend object18+ new Hono<{19+ Bindings: number20+ }>()21+22+ const appWithInterface = new Hono<{23+ Bindings: CloudflareBindings24+ }>()25+26+ appWithInterface.get('/', (c) => {27+ expectTypeOf(c.env.MY_VARIABLE).toMatchTypeOf<string>()28+ return c.text('/')29+ })30+31+ const appWithType = new Hono<{32+ Bindings: {33+ foo: string34+ }35+ }>()36+37+ appWithType.get('/', (c) => {38+ expectTypeOf(c.env.foo).toMatchTypeOf<string>()39+ return c.text('Hello Hono!')40+ })41+ })42+})modified:src/utils/html.ts+19 added-2 removed
33 unmodified lines34 * 'Hono',35 * ]36 */37 export type StringBuffer = (string | Promise<string>)[]38+export type StringBufferWithCallbacks = StringBuffer & { callbacks: HtmlEscapedCallback[] }39 40 export const raw = (value: unknown, callbacks?: HtmlEscapedCallback[]): HtmlEscapedString => {41 const escapedString = new String(value) as HtmlEscapedString42 escapedString.isEscaped = true6 unmodified lines49 // https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/server/escapeTextForBrowser.js50 51 const escapeRe = /[&<>'"]/52 52-export const stringBufferToString = async (buffer: StringBuffer): Promise<HtmlEscapedString> => {53+export const stringBufferToString = async (54+ buffer: StringBuffer,55+ callbacks: HtmlEscapedCallback[] | undefined56+): Promise<HtmlEscapedString> => {57 let str = ''54- const callbacks: HtmlEscapedCallback[] = []58+ callbacks ||= []59 for (let i = buffer.length - 1; ; i--) {60 str += buffer[i]61 i--62 if (i < 0) {61 unmodified lines124 125 buffer[0] += str.substring(lastIndex, index)126 }127 128+export const resolveCallbackSync = (str: string | HtmlEscapedString): string => {129+ const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]130+ if (!callbacks?.length) {131+ return str132+ }133+ const buffer: [string] = [str]134+ const context = {}135+136+ callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }))137+138+ return buffer[0]139+}140+141 export const resolveCallback = async (142 str: string | HtmlEscapedString,143 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],144 preserveCallbacks: boolean,28 unmodified linesadded:src/utils/ipaddr.test.ts+61 added
1+import {2+ convertIPv4ToBinary,3+ convertIPv6BinaryToString,4+ convertIPv6ToBinary,5+ distinctRemoteAddr,6+ expandIPv6,7+} from './ipaddr'8+9+describe('expandIPv6', () => {10+ it('Should result be valid', () => {11+ expect(expandIPv6('1::1')).toBe('0001:0000:0000:0000:0000:0000:0000:0001')12+ expect(expandIPv6('::1')).toBe('0000:0000:0000:0000:0000:0000:0000:0001')13+ expect(expandIPv6('2001:2::')).toBe('2001:0002:0000:0000:0000:0000:0000:0000')14+ expect(expandIPv6('2001:2::')).toBe('2001:0002:0000:0000:0000:0000:0000:0000')15+ expect(expandIPv6('2001:0:0:db8::1')).toBe('2001:0000:0000:0db8:0000:0000:0000:0001')16+ })17+})18+describe('distinctRemoteAddr', () => {19+ it('Should result be valud', () => {20+ expect(distinctRemoteAddr('1::1')).toBe('IPv6')21+ expect(distinctRemoteAddr('::1')).toBe('IPv6')22+23+ expect(distinctRemoteAddr('192.168.2.0')).toBe('IPv4')24+ expect(distinctRemoteAddr('192.168.2.0')).toBe('IPv4')25+26+ expect(distinctRemoteAddr('example.com')).toBeUndefined()27+ })28+})29+30+describe('convertIPv4ToBinary', () => {31+ it('Should result is valid', () => {32+ expect(convertIPv4ToBinary('0.0.0.0')).toBe(0n)33+ expect(convertIPv4ToBinary('0.0.0.1')).toBe(1n)34+35+ expect(convertIPv4ToBinary('0.0.1.0')).toBe(1n << 8n)36+ })37+})38+describe('convertIPv6ToBinary', () => {39+ it('Should result is valid', () => {40+ expect(convertIPv6ToBinary('::0')).toBe(0n)41+ expect(convertIPv6ToBinary('::1')).toBe(1n)42+43+ expect(convertIPv6ToBinary('::f')).toBe(15n)44+ expect(convertIPv6ToBinary('1234:::5678')).toBe(24196103360772296748952112894165669496n)45+ })46+})47+48+describe('convertIPv6ToString', () => {49+ // add tons of test cases here50+ test.each`51+ input | expected52+ ${'::1'} | ${'::1'}53+ ${'1::'} | ${'1::'}54+ ${'1234:::5678'} | ${'1234::5678'}55+ ${'2001:2::'} | ${'2001:2::'}56+ ${'2001::db8:0:0:0:0:1'} | ${'2001:0:db8::1'}57+ ${'1234:5678:9abc:def0:1234:5678:9abc:def0'} | ${'1234:5678:9abc:def0:1234:5678:9abc:def0'}58+ `('convertIPv6ToString($input) === $expected', ({ input, expected }) => {59+ expect(convertIPv6BinaryToString(convertIPv6ToBinary(input))).toBe(expected)60+ })61+})added:src/utils/ipaddr.ts+113 added
1+/**2+ * Utils for IP Addresses3+ * @module4+ */5+6+import type { AddressType } from '../helper/conninfo'7+8+/**9+ * Expand IPv6 Address10+ * @param ipV6 Shorten IPv6 Address11+ * @return expanded IPv6 Address12+ */13+export const expandIPv6 = (ipV6: string): string => {14+ const sections = ipV6.split(':')15+ for (let i = 0; i < sections.length; i++) {16+ const node = sections[i]17+ if (node !== '') {18+ sections[i] = node.padStart(4, '0')19+ } else {20+ sections[i + 1] === '' && sections.splice(i + 1, 1)21+ sections[i] = new Array(8 - sections.length + 1).fill('0000').join(':')22+ }23+ }24+ return sections.join(':')25+}26+27+const IPV4_REGEX = /^[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}$/28+29+/**30+ * Distinct Remote Addr31+ * @param remoteAddr Remote Addr32+ */33+export const distinctRemoteAddr = (remoteAddr: string): AddressType => {34+ if (IPV4_REGEX.test(remoteAddr)) {35+ return 'IPv4'36+ }37+ if (remoteAddr.includes(':')) {38+ // Domain can't include `:`39+ return 'IPv6'40+ }41+}42+43+/**44+ * Convert IPv4 to Uint8Array45+ * @param ipv4 IPv4 Address46+ * @returns BigInt47+ */48+export const convertIPv4ToBinary = (ipv4: string): bigint => {49+ const parts = ipv4.split('.')50+ let result = 0n51+ for (let i = 0; i < 4; i++) {52+ result <<= 8n53+ result += BigInt(parts[i])54+ }55+ return result56+}57+58+/**59+ * Convert IPv6 to Uint8Array60+ * @param ipv6 IPv6 Address61+ * @returns BigInt62+ */63+export const convertIPv6ToBinary = (ipv6: string): bigint => {64+ const sections = expandIPv6(ipv6).split(':')65+ let result = 0n66+ for (let i = 0; i < 8; i++) {67+ result <<= 16n68+ result += BigInt(parseInt(sections[i], 16))69+ }70+ return result71+}72+73+/**74+ * Convert a binary representation of an IPv6 address to a string.75+ * @param ipV6 binary IPv6 Address76+ * @return normalized IPv6 Address in string77+ */78+export const convertIPv6BinaryToString = (ipV6: bigint): string => {79+ const sections = []80+ for (let i = 0; i < 8; i++) {81+ sections.push(((ipV6 >> BigInt(16 * (7 - i))) & 0xffffn).toString(16))82+ }83+84+ let currentZeroStart = -185+ let maxZeroStart = -186+ let maxZeroEnd = -187+ for (let i = 0; i < 8; i++) {88+ if (sections[i] === '0') {89+ if (currentZeroStart === -1) {90+ currentZeroStart = i91+ }92+ } else {93+ if (currentZeroStart > -1) {94+ if (i - currentZeroStart > maxZeroEnd - maxZeroStart) {95+ maxZeroStart = currentZeroStart96+ maxZeroEnd = i97+ }98+ currentZeroStart = -199+ }100+ }101+ }102+ if (currentZeroStart > -1) {103+ if (8 - currentZeroStart > maxZeroEnd - maxZeroStart) {104+ maxZeroStart = currentZeroStart105+ maxZeroEnd = 8106+ }107+ }108+ if (maxZeroStart !== -1) {109+ sections.splice(maxZeroStart, maxZeroEnd - maxZeroStart, ':')110+ }111+112+ return sections.join(':').replace(/:{2,}/g, '::')113+}modified:src/compose.ts+2 added-2 removed
32 unmodified lines33 export const compose = <C extends ComposeContext, E extends Env = Env>(34 middleware: [[Function, unknown], ParamIndexMap | Params][],35 onError?: ErrorHandler<E>,36 onNotFound?: NotFoundHandler<E>37-) => {38- return (context: C, next?: Function) => {37+): ((context: C, next?: Function) => Promise<C>) => {38+ return (context, next) => {39 let index = -140 return dispatch(0)41 42 /**52 unmodified linesmodified:src/context.test.ts+7 added
86 unmodified lines87 expect(c.get('foo')).toBe('bar')88 expect(c.get('foo2')).toBe(undefined)89 })90 91+ it('c.var', async () => {92+ expect(c.var.foo).toBe(undefined)93+ c.set('foo', 'bar')94+ expect(c.var.foo).toBe('bar')95+ expect(c.var.foo2).toBe(undefined)96+ })97+98 it('c.notFound()', async () => {99 const res = c.notFound()100 expect(res).instanceOf(Response)101 })364 unmodified linesmodified:src/context.ts+25 added-8 removed
263 unmodified lines264 * })265 * ```266 */267 env: E['Bindings'] = {}268- #var: E['Variables'] | undefined268+ #var: Map<unknown, unknown> | undefined269 finalized: boolean = false270 /**271 * `.error` can get the error object from the middleware if the Handler throws an error.272 *245 unmodified lines518 * c.set('message', 'Hono is cool!!')519 * await next()520 * })521 * ```522-```522 */524- set: Set<E> = (key: string, value: unknown) => {525- this.#var ??= {}526- this.#var[key as string] = value523+ set: Set<524+ IsAny<E> extends true525+ ? {526+ // eslint-disable-next-line @typescript-eslint/no-explicit-any527+ Variables: ContextVariableMap & Record<string, any>528+ }529+ : E530+ > = (key: string, value: unknown) => {531+ this.#var ??= new Map()532+ this.#var.set(key, value)533 }534 535 /**536 * `.get()` can use the value specified by the key.7 unmodified lines544 * return c.text(`The message is "${message}"`)545 * })546 * ```547 */548+ get: Get<549+ IsAny<E> extends true550+ ? {551+ // eslint-disable-next-line @typescript-eslint/no-explicit-any552+ Variables: ContextVariableMap & Record<string, any>553+ }554+ : E542- get: Get<E> = (key: string) => {543- return this.#var ? this.#var[key] : undefined555+ > = (key: string) => {556+ return this.#var ? this.#var.get(key) : undefined557 }558 559 /**560 * `.var` can access the value of a variable.9 unmodified lines570 get var(): Readonly<571 // eslint-disable-next-line @typescript-eslint/no-explicit-any572 ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])573 > {561- return { ...this.#var } as never574+ if (!this.#var) {575+ // eslint-disable-next-line @typescript-eslint/no-explicit-any576+ return {} as any577+ }578+ return Object.fromEntries(this.#var)579 }580 581 newResponse: NewResponse = (582 data: Data | null,226 unmodified linesmodified:src/hono.test.ts+33 added
3583 unmodified lines3584 const res = await a.request('/sub/foo')3585 expect(res.status).toBe(200)3586 })3587 })3588+3589+describe('Generics for Bindings and Variables', () => {3590+ interface CloudflareBindings {3591+ MY_VARIABLE: string3592+ }3593+3594+ it('Should not throw type errors', () => {3595+ // @ts-expect-error Bindings should extend object3596+ new Hono<{3597+ Bindings: number3598+ }>()3599+3600+ const appWithInterface = new Hono<{3601+ Bindings: CloudflareBindings3602+ }>()3603+3604+ appWithInterface.get('/', (c) => {3605+ expectTypeOf(c.env.MY_VARIABLE).toMatchTypeOf<string>()3606+ return c.text('/')3607+ })3608+3609+ const appWithType = new Hono<{3610+ Bindings: {3611+ foo: string3612+ }3613+ }>()3614+3615+ appWithType.get('/', (c) => {3616+ expectTypeOf(c.env.foo).toMatchTypeOf<string>()3617+ return c.text('Hello Hono!')3618+ })3619+ })3620+})modified:src/types.test.ts+9 added-1 removed
1 /* eslint-disable @typescript-eslint/ban-types */2 /* eslint-disable @typescript-eslint/no-unused-vars */3 import { expectTypeOf } from 'vitest'4-import type { Context } from './context'4+import { Context } from './context'5 import { createMiddleware } from './helper/factory'6 import { Hono } from './hono'7 import { poweredBy } from './middleware/powered-by'8 import type {1738 unmodified lines1747 expectTypeOf(c.get('payload')).toEqualTypeOf<number>()1748 return c.json(0)1749 })1750 })1751+1752+ it('Should use ContextVariableMap when c is Context<any>', () => {1753+ const c = new Context(new Request('http://localhost'))1754+ expectTypeOf(c.get('payload')).toEqualTypeOf<string>()1755+ expectTypeOf(c.var.payload).toEqualTypeOf<string>()1756+ // @ts-expect-error the value of payload should be string1757+ expectTypeOf(c.set('payload', 123))1758+ })1759 })1760 1761 /**1762 * It's challenge to test all cases. This is a minimal pattern.488 unmodified linesmodified:src/types.ts+2 added-2 removed
22 unmodified lines23 ////// Values //////24 ////// //////25 ////////////////////////////////////////26 27-export type Bindings = Record<string, unknown>28-export type Variables = Record<string, unknown>27+export type Bindings = object28+export type Variables = object29 30 export type BlankEnv = {}31 export type Env = {32 Bindings?: Bindings1977 unmodified linesmodified:jsr.json+7 added-1 removed
19 unmodified lines20 "./http-exception": "./src/http-exception.ts",21 "./basic-auth": "./src/middleware/basic-auth/index.ts",22 "./bearer-auth": "./src/middleware/bearer-auth/index.ts",23 "./body-limit": "./src/middleware/body-limit/index.ts",24+ "./ip-restriction": "./src/middleware/ip-restriction/index.ts",25 "./cache": "./src/middleware/cache/index.ts",26 "./cookie": "./src/helper/cookie/index.ts",27 "./accepts": "./src/helper/accepts/index.ts",28 "./compress": "./src/middleware/compress/index.ts",12 unmodified lines41 "./jsx/dom/jsx-dev-runtime": "./src/jsx/dom/jsx-dev-runtime.ts",42 "./jsx/dom/jsx-runtime": "./src/jsx/dom/jsx-runtime.ts",43 "./jsx/dom/client": "./src/jsx/dom/client.ts",44 "./jsx/dom/css": "./src/jsx/dom/css.ts",45+ "./jsx/dom/server": "./src/jsx/dom/server.ts",46 "./jwt": "./src/middleware/jwt/jwt.ts",47 "./timing": "./src/middleware/timing/timing.ts",48 "./logger": "./src/middleware/logger/index.ts",49 "./method-override": "./src/middleware/method-override/index.ts",50 "./powered-by": "./src/middleware/powered-by/index.ts",51 "./pretty-json": "./src/middleware/pretty-json/index.ts",52+ "./request-id": "./src/middleware/request-id/request-id.ts",53 "./secure-headers": "./src/middleware/secure-headers/secure-headers.ts",54+ "./combine": "./src/middleware/combine/index.ts",55 "./ssg": "./src/helper/ssg/index.ts",56 "./streaming": "./src/helper/streaming/index.ts",57 "./validator": "./src/validator/index.ts",58 "./router": "./src/router.ts",13 unmodified lines72 "./aws-lambda": "./src/adapter/aws-lambda/index.ts",73 "./vercel": "./src/adapter/vercel/index.ts",74 "./netlify": "./src/adapter/netlify/index.ts",75 "./lambda-edge": "./src/adapter/lambda-edge/index.ts",76+ "./service-worker": "./src/adapter/service-worker/index.ts",77 "./testing": "./src/helper/testing/index.ts",78 "./dev": "./src/helper/dev/index.ts",79 "./ws": "./src/helper/websocket/index.ts",80 "./utils/body": "./src/utils/body.ts",15 unmodified lines96 "./utils/jwt/utf8": "./src/utils/jwt/utf8.ts",97 "./utils/mime": "./src/utils/mime.ts",98 "./utils/stream": "./src/utils/stream.ts",99 "./utils/types": "./src/utils/types.ts",95- "./utils/url": "./src/utils/url.ts"100+ "./utils/url": "./src/utils/url.ts",101+ "./utils/ipaddr": "./src/utils/ipaddr.ts"102 },103 "publish": {104 "include": [105 "jsr.json",13 unmodified linesmodified:package.json+42 added-2 removed
1 {2 "name": "hono",3- "version": "4.4.13",3+ "version": "4.5.0-rc.2",4 "description": "Web framework built on Web Standards",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",69 unmodified lines77 "types": "./dist/types/middleware/body-limit/index.d.ts",78 "import": "./dist/middleware/body-limit/index.js",79 "require": "./dist/cjs/middleware/body-limit/index.js"80 },81+ "./ip-restriction": {82+ "types": "./dist/types/middleware/ip-restriction/index.d.ts",83+ "import": "./dist/middleware/ip-restriction/index.js",84+ "require": "./dist/cjs/middleware/ip-restriction/index.js"85+ },86 "./cache": {87 "types": "./dist/types/middleware/cache/index.d.ts",88 "import": "./dist/middleware/cache/index.js",89 "require": "./dist/cjs/middleware/cache/index.js"92 unmodified lines182 "types": "./dist/types/jsx/dom/css.d.ts",183 "import": "./dist/jsx/dom/css.js",184 "require": "./dist/cjs/jsx/dom/css.js"185 },186+ "./jsx/dom/server": {187+ "types": "./dist/types/jsx/dom/server.d.ts",188+ "import": "./dist/jsx/dom/server.js",189+ "require": "./dist/cjs/jsx/dom/server.js"190+ },191 "./jwt": {192 "types": "./dist/types/middleware/jwt/index.d.ts",193 "import": "./dist/middleware/jwt/index.js",194 "require": "./dist/cjs/middleware/jwt/index.js"27 unmodified lines222 "types": "./dist/types/middleware/pretty-json/index.d.ts",223 "import": "./dist/middleware/pretty-json/index.js",224 "require": "./dist/cjs/middleware/pretty-json/index.js"225 },226+ "./request-id": {227+ "types": "./dist/types/middleware/request-id/index.d.ts",228+ "import": "./dist/middleware/request-id/index.js",229+ "require": "./dist/cjs/middleware/request-id/index.js"230+ },231 "./secure-headers": {232 "types": "./dist/types/middleware/secure-headers/index.d.ts",233 "import": "./dist/middleware/secure-headers/index.js",234 "require": "./dist/cjs/middleware/secure-headers/index.js"235 },236+ "./combine": {237+ "types": "./dist/types/middleware/combine/index.d.ts",238+ "import": "./dist/middleware/combine/index.js",239+ "require": "./dist/cjs/middleware/combine/index.js"240+ },241 "./ssg": {242 "types": "./dist/types/helper/ssg/index.d.ts",243 "import": "./dist/helper/ssg/index.js",244 "require": "./dist/cjs/helper/ssg/index.js"107 unmodified lines352 "types": "./dist/types/adapter/lambda-edge/index.d.ts",353 "import": "./dist/adapter/lambda-edge/index.js",354 "require": "./dist/cjs/adapter/lambda-edge/index.js"355 },356+ "./service-worker": {357+ "types": "./dist/types/adapter/service-worker/index.d.ts",358+ "import": "./dist/adapter/service-worker/index.js",359+ "require": "./dist/cjs/adapter/service-worker/index.js"360+ },361 "./testing": {362 "types": "./dist/types/helper/testing/index.d.ts",363 "import": "./dist/helper/testing/index.js",364 "require": "./dist/cjs/helper/testing/index.js"39 unmodified lines404 ],405 "body-limit": [406 "./dist/types/middleware/body-limit"407 ],408+ "ip-restriction": [409+ "./dist/types/middleware/ip-restriction"410+ ],411 "cache": [412 "./dist/types/middleware/cache"413 ],414 "cookie": [46 unmodified lines461 ],462 "jsx/dom/css": [463 "./dist/types/jsx/dom/css.d.ts"464 ],465+ "jsx/dom/server": [466+ "./dist/types/jsx/dom/server.d.ts"467+ ],468 "jwt": [469 "./dist/types/middleware/jwt"470 ],471 "timeout": [13 unmodified lines485 ],486 "pretty-json": [487 "./dist/types/middleware/pretty-json"488 ],489+ "request-id": [490+ "./dist/types/middleware/request-id"491+ ],492 "streaming": [493 "./dist/types/helper/streaming"494 ],495 "ssg": [1 unmodified line497 ],498 "secure-headers": [499 "./dist/types/middleware/secure-headers"500 ],501+ "combine": [502+ "./dist/types/middleware/combine"503+ ],504 "validator": [505 "./dist/types/validator/index.d.ts"506 ],507 "router": [55 unmodified lines563 ],564 "lambda-edge": [565 "./dist/types/adapter/lambda-edge"566 ],567+ "service-worker": [568+ "./dist/types/adapter/service-worker"569+ ],570 "testing": [571 "./dist/types/helper/testing"572 ],573 "dev": [64 unmodified lines638 },639 "engines": {640 "node": ">=16.0.0"641 }602-}642+}