Skip to content
Myr

index.test.tsx

This file

Path

src/jsx/index.test.tsx

1,745 lines · 53.8 KiB · TypeScript

Last changed by

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

History of this file

Take it

1import DefaultExport, {2  ErrorBoundary,3  Fragment,4  StrictMode,5  createContext,6  createElement,7  jsx,8  memo,9  useContext,10  version,11} from '.'12import type { Context, FC, PropsWithChildren } from '.'13/** @jsxImportSource ./ */14/* eslint-disable @typescript-eslint/no-explicit-any */15import { html, raw } from '../helper/html'16import { Hono } from '../hono'17import { DOM_MEMO } from './constants'18import { captureRenderContext } from './context'19import { Suspense, renderToReadableStream } from './streaming'2021interface SiteData {22  title: string23  children?: any24}2526describe('JSX middleware', () => {27  let app: Hono2829  beforeEach(() => {30    app = new Hono()31  })3233  it('Should render HTML strings', async () => {34    app.get('/', (c) => {35      return c.html(<h1>Hello</h1>)36    })37    const res = await app.request('http://localhost/')38    expect(res.status).toBe(200)39    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')40    expect(await res.text()).toBe('<h1>Hello</h1>')41  })4243  it('Should be able to be used with html middleware', async () => {44    const Layout = (props: SiteData) =>45      html`<!DOCTYPE html>46        <html>47          <head>48            <title>${props.title}</title>49          </head>50          <body>51            ${props.children}52          </body>53        </html>`5455    const Content = (props: { siteData: SiteData; name: string }) => (56      <Layout {...props.siteData}>57        <h1>{props.name}</h1>58      </Layout>59    )6061    app.get('/', (c) => {62      const props = {63        name: 'JSX',64        siteData: {65          title: 'with html middleware',66        },67      }68      return c.html(<Content {...props} />)69    })70    const res = await app.request('http://localhost/')71    expect(res.status).toBe(200)72    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')73    expect(await res.text()).toBe(`<!DOCTYPE html>74        <html>75          <head>76            <title>with html middleware</title>77          </head>78          <body>79            <h1>JSX</h1>80          </body>81        </html>`)82  })8384  it('Should render async component', async () => {85    const ChildAsyncComponent = async () => {86      await new Promise((resolve) => setTimeout(resolve, 10))87      return <span>child async component</span>88    }8990    const AsyncComponent = async () => {91      await new Promise((resolve) => setTimeout(resolve, 10))92      return (93        <h1>94          Hello from async component95          <ChildAsyncComponent />96        </h1>97      )98    }99100    app.get('/', (c) => {101      return c.html(<AsyncComponent />)102    })103    const res = await app.request('http://localhost/')104    expect(res.status).toBe(200)105    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')106    expect(await res.text()).toBe(107      '<h1>Hello from async component<span>child async component</span></h1>'108    )109  })110111  it('Should render async component with "html" tagged template strings', async () => {112    const AsyncComponent = async () => {113      await new Promise((resolve) => setTimeout(resolve, 10))114      return <h1>Hello from async component</h1>115    }116117    app.get('/', (c) => {118      // prettier-ignore119      return c.html(120        html`<html><body>${(<AsyncComponent />)}</body></html>`121      )122    })123    const res = await app.request('http://localhost/')124    expect(res.status).toBe(200)125    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')126    expect(await res.text()).toBe('<html><body><h1>Hello from async component</h1></body></html>')127  })128129  it('Should handle async component error', async () => {130    const componentError = new Error('Error from async error component')131132    const AsyncComponent = async () => {133      await new Promise((resolve) => setTimeout(resolve, 10))134      return <h1>Hello from async component</h1>135    }136    const AsyncErrorComponent = async () => {137      await new Promise((resolve) => setTimeout(resolve, 0))138      throw componentError139    }140141    let raisedError: any142    app.onError((e, c) => {143      raisedError = e144      return c.html('<html><body><h1>Error from onError</h1></body></html>', 500)145    })146    app.get('/', (c) => {147      return c.html(148        <>149          <AsyncComponent />150          <AsyncErrorComponent />151        </>152      )153    })154155    const res = await app.request('http://localhost/')156    expect(res.status).toBe(500)157    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')158    expect(await res.text()).toBe('<html><body><h1>Error from onError</h1></body></html>')159    expect(raisedError).toBe(componentError)160  })161})162163describe('render to string', () => {164  it('Nested array', () => {165    const template = (166      <p>167        {[[['a']], [['b']]].map((item1) =>168          item1.map((item2) => item2.map((item3) => <span>{item3}</span>))169        )}170      </p>171    )172    expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')173  })174175  it('Component returning an array', () => {176    const Item = ({ x }: { x: number }) => <span>{x}</span>177    const Items = () => [0, 1].map((x) => <Item key={x} x={x} />)178    const template = <Items />179    expect(template.toString()).toBe('<span>0</span><span>1</span>')180  })181182  it('Component returning a nested array', () => {183    const Items = () => [['a', 'b'], [<span>c</span>], null]184    const template = <Items />185    expect(template.toString()).toBe('ab<span>c</span>')186  })187188  it('Component returning an array preserves escaped string callbacks', () => {189    const Items = () => [190      raw('a', [191        ({ buffer }) => {192          if (buffer) {193            buffer[0] += 'b'194          }195        },196      ]),197    ]198    expect((<Items />).toString()).toBe('ab')199  })200201  it('Component returning an array escapes strings', async () => {202    const SyncItems = () => ['<script>alert(1)</script>']203    const AsyncItems = async () => ['<script>alert(1)</script>']204    const expected = '&lt;script&gt;alert(1)&lt;/script&gt;'205206    expect((<SyncItems />).toString()).toBe(expected)207    expect((await (<AsyncItems />).toString()).toString()).toBe(expected)208  })209210  it('Component returning an array including async components', async () => {211    const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>212    const Items = () => [0, 1].map((x) => <AsyncItem key={x} x={x} />)213    const template = <Items />214    expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')215  })216217  it('Component typed as FC returning an array', () => {218    const Item: FC<{ x: number }> = ({ x }) => <span>{x}</span>219    const Items: FC = () => [0, 1].map((x) => <Item key={x} x={x} />)220    const template = <Items />221    expect(template.toString()).toBe('<span>0</span><span>1</span>')222  })223224  it('Async component returning an array', async () => {225    const AsyncItems = async () => [<span>a</span>, <span>b</span>]226    const template = <AsyncItems />227    expect((await template.toString()).toString()).toBe('<span>a</span><span>b</span>')228  })229230  it('Async component returning an array of async components', async () => {231    const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>232    const AsyncItems = async () => [<AsyncItem key={0} x={0} />, <AsyncItem key={1} x={1} />]233    const template = <AsyncItems />234    expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')235  })236237  it('Empty elements are rended without closing tag', () => {238    const template = <input />239    expect(template.toString()).toBe('<input/>')240  })241242  it('Empty elements with children are rended with children and closing tag', () => {243    const template = <link>https://example.com</link>244    expect(template.toString()).toBe('<link>https://example.com</link>')245  })246247  describe('programmatic tag names', () => {248    it('Should throw when jsx() receives a tag name that can break out of the HTML context', () => {249      const payloads = [250        '><script>alert(1)</script><x',251        'div onmouseover="alert(1)" x=',252        'div></div><img src=x onerror=alert(1)><div',253        '!--',254        '!DOCTYPE',255        '?xml',256      ]257258      for (const tag of payloads) {259        expect(() => jsx(tag, {}, 'hello')).toThrow(`Invalid JSX tag name: ${tag}`)260      }261    })262263    it('Should throw when createElement() receives a tag name that can break out of the HTML context', () => {264      expect(() => createElement('div onmouseover="alert(1)" x=', {}, 'hello')).toThrow(265        'Invalid JSX tag name: div onmouseover="alert(1)" x='266      )267    })268269    it('Should throw when jsx() receives an invalid non-primitive tag name', () => {270      expect(() => jsx(new String('div') as never, {}, 'hello')).toThrow(271        'Invalid JSX tag name: div'272      )273      expect(() =>274        jsx({ toString: () => 'div onmouseover="alert(1)" x=' } as never, {}, 'hello')275      ).toThrow('Invalid JSX tag name: div onmouseover="alert(1)" x=')276    })277278    it('Should allow compatible custom and namespaced tag names', () => {279      expect(jsx('custom-element', {}, 'hello').toString()).toBe(280        '<custom-element>hello</custom-element>'281      )282      expect(jsx('foo:bar', {}, 'hello').toString()).toBe('<foo:bar>hello</foo:bar>')283      expect(jsx('x.foo', {}, 'hello').toString()).toBe('<x.foo>hello</x.foo>')284      expect(jsx('x_bar', {}, 'hello').toString()).toBe('<x_bar>hello</x_bar>')285      expect(jsx('é', {}, 'hello').toString()).toBe('<é>hello</é>')286    })287  })288289  it('Props value is null', () => {290    const template = <span data-hello={null}>Hello</span>291    expect(template.toString()).toBe('<span>Hello</span>')292  })293294  it('Props value is undefined', () => {295    const template = <span data-hello={undefined}>Hello</span>296    expect(template.toString()).toBe('<span>Hello</span>')297  })298299  describe('dangerouslySetInnerHTML', () => {300    it('Should render dangerouslySetInnerHTML', () => {301      const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>302      expect(template.toString()).toBe('<span>" is allowed here</span>')303    })304305    it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {306      expect(() =>307        (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()308      ).toThrow(Error)309    })310  })311312  // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored313  describe('Booleans, Null, and Undefined Are Ignored', () => {314    it.each([true, false, undefined, null])('%s', (item) => {315      expect((<span>{item}</span>).toString()).toBe('<span></span>')316    })317318    it('falsy value', () => {319      const template = <span>{0}</span>320      expect(template.toString()).toBe('<span>0</span>')321    })322  })323324  // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true325  describe('Props Default to “True”', () => {326    it('default prop value', () => {327      const template = <span data-hello>Hello</span>328      expect(template.toString()).toBe('<span data-hello="true">Hello</span>')329    })330  })331332  // https://html.spec.whatwg.org/#attributes-3333  describe('Boolean attribute', () => {334    it('default prop value for checked', () => {335      const template = <input type='checkbox' checked />336      expect(template.toString()).toBe('<input type="checkbox" checked=""/>')337    })338339    it('default prop value for checked={true}', () => {340      const template = <input type='checkbox' checked={true} />341      expect(template.toString()).toBe('<input type="checkbox" checked=""/>')342    })343344    it('no prop for checked={false}', () => {345      const template = <input type='checkbox' checked={false} />346      expect(template.toString()).toBe('<input type="checkbox"/>')347    })348349    it('default prop value for disabled', () => {350      const template = <input type='checkbox' disabled />351      expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')352    })353354    it('default prop value for disabled={true}', () => {355      const template = <input type='checkbox' disabled={true} />356      expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')357    })358359    it('no prop for disabled={false}', () => {360      const template = <input type='checkbox' disabled={false} />361      expect(template.toString()).toBe('<input type="checkbox"/>')362    })363364    it('default prop value for readonly', () => {365      const template = <input type='checkbox' readonly />366      expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')367    })368369    it('default prop value for readonly={true}', () => {370      const template = <input type='checkbox' readonly={true} />371      expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')372    })373374    it('no prop for readonly={false}', () => {375      const template = <input type='checkbox' readonly={false} />376      expect(template.toString()).toBe('<input type="checkbox"/>')377    })378379    it('default prop value for selected', () => {380      const template = (381        <option value='test' selected>382          Test383        </option>384      )385      expect(template.toString()).toBe('<option value="test" selected="">Test</option>')386    })387388    it('default prop value for selected={true}', () => {389      const template = (390        <option value='test' selected={true}>391          Test392        </option>393      )394      expect(template.toString()).toBe('<option value="test" selected="">Test</option>')395    })396397    it('no prop for selected={false}', () => {398      const template = (399        <option value='test' selected={false}>400          Test401        </option>402      )403      expect(template.toString()).toBe('<option value="test">Test</option>')404    })405406    it('default prop value for multiple select', () => {407      const template = (408        <select multiple>409          <option>test</option>410        </select>411      )412      expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')413    })414415    it('default prop value for select multiple={true}', () => {416      const template = (417        <select multiple={true}>418          <option>test</option>419        </select>420      )421      expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')422    })423424    it('no prop for select multiple={false}', () => {425      const template = (426        <select multiple={false}>427          <option>test</option>428        </select>429      )430      expect(template.toString()).toBe('<select><option>test</option></select>')431    })432433    it('should render "false" value properly for other non-defined keys', () => {434      const template = <input type='checkbox' testkey={false} />435      expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')436    })437438    it('should support attributes for elements other than input', () => {439      const template = (440        <video controls autoplay>441          <source src='movie.mp4' type='video/mp4' />442        </video>443      )444      expect(template.toString()).toBe(445        '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'446      )447    })448  })449450  describe('download attribute', () => {451    it('<a download={true}></a> should be rendered as <a download=""></a>', () => {452      const template = <a download={true}></a>453      expect(template.toString()).toBe('<a download=""></a>')454    })455456    it('<a download={false}></a> should be rendered as <a></a>', () => {457      const template = <a download={false}></a>458      expect(template.toString()).toBe('<a></a>')459    })460461    it('<a download></a> should be rendered as <a download=""></a>', () => {462      const template = <a download></a>463      expect(template.toString()).toBe('<a download=""></a>')464    })465466    it('<a download="test"></a> should be rendered as <a download="test"></a>', () => {467      const template = <a download='test'></a>468      expect(template.toString()).toBe('<a download="test"></a>')469    })470  })471472  describe('Function', () => {473    it('should be ignored used in on* props', () => {474      const onClick = () => {}475      const template = <button onClick={onClick}>Click</button>476      expect(template.toString()).toBe('<button>Click</button>')477    })478479    it('should be ignored used in ref props', () => {480      const ref = () => {}481      const template = <div ref={ref}>Content</div>482      expect(template.toString()).toBe('<div>Content</div>')483    })484485    it('should raise an error if used in other props', () => {486      const onClick = () => {}487      const template = <button data-handler={onClick}>Click</button>488      expect(() => template.toString()).toThrow(Error)489    })490  })491492  // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children493  describe('Functions as Children', () => {494    it('Function', () => {495      function Repeat(props: any) {496        const items = []497        for (let i = 0; i < props.numTimes; i++) {498          items.push((props.children as Function)(i))499        }500        return <div>{items}</div>501      }502503      function ListOfTenThings() {504        return (505          <Repeat numTimes={10}>506            {(index: string) => <div key={index}>This is item {index} in the list</div>}507          </Repeat>508        )509      }510511      const template = <ListOfTenThings />512      expect(template.toString()).toBe(513        '<div><div>This is item 0 in the list</div><div>This is item 1 in the list</div><div>This is item 2 in the list</div><div>This is item 3 in the list</div><div>This is item 4 in the list</div><div>This is item 5 in the list</div><div>This is item 6 in the list</div><div>This is item 7 in the list</div><div>This is item 8 in the list</div><div>This is item 9 in the list</div></div>'514      )515    })516  })517518  describe('FC', () => {519    it('Should define the type correctly', () => {520      const Layout: FC<PropsWithChildren<{ title: string }>> = (props) => {521        return (522          <html>523            <head>524              <title>{props.title}</title>525            </head>526            <body>{props.children}</body>527          </html>528        )529      }530531      const Top = (532        <Layout title='Home page'>533          <h1>Hono</h1>534          <p>Hono is great</p>535        </Layout>536      )537538      expect(Top.toString()).toBe(539        '<html><head><title>Home page</title></head><body><h1>Hono</h1><p>Hono is great</p></body></html>'540      )541    })542543    describe('Booleans, Null, and Undefined Are Ignored', () => {544      it.each([true, false, undefined, null])('%s', (item) => {545        const Component: FC = (() => {546          return item547        }) as FC548        const template = <Component />549        expect(template.toString()).toBe('')550      })551552      it('falsy value', () => {553        const Component: FC = (() => {554          return 0555        }) as unknown as FC556        const template = <Component />557        expect(template.toString()).toBe('0')558      })559    })560  })561562  describe('style attribute', () => {563    it('should convert the object to strings', () => {564      const template = (565        <h1566          style={{567            color: 'red',568            fontSize: 'small',569            fontFamily: 'Menlo, Consolas, "DejaVu Sans Mono", monospace',570          }}571        >572          Hello573        </h1>574      )575      expect(template.toString()).toBe(576        '<h1 style="color:red;font-size:small;font-family:Menlo, Consolas, &quot;DejaVu Sans Mono&quot;, monospace">Hello</h1>'577      )578    })579    it('should not convert the strings', () => {580      const template = <h1 style='color:red;font-size:small'>Hello</h1>581      expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')582    })583    it('should render variable without any name conversion', () => {584      const template = <h1 style={{ '--myVar': 1 }}>Hello</h1>585      expect(template.toString()).toBe('<h1 style="--myVar:1px">Hello</h1>')586    })587588    describe('CSS injection prevention', () => {589      it('should drop style values containing ";" to prevent CSS injection', () => {590        const userInput =591          'transparent;background:url(https://attacker.example/a.png);position:fixed;top:0'592        const template = <div style={{ color: userInput }} />593        const out = template.toString() as string594        expect(out).not.toContain('background:url')595        expect(out).not.toContain('position:fixed')596        expect(out).not.toContain('color:')597        expect(out).toBe('<div style=""></div>')598      })599600      it('should drop only the unsafe property and keep other safe properties', () => {601        const template = <div style={{ color: 'red;background:blue', backgroundColor: 'white' }} />602        const out = template.toString() as string603        expect(out).toBe('<div style="background-color:white"></div>')604        expect(out).not.toContain('background:blue')605      })606607      it('should drop style values that try to hide declaration separators in CSS comments', () => {608        const template = (609          <div610            style={{611              color: 'red/*(*/;background:blue;position:fixed;top:0',612              backgroundColor: 'white',613            }}614          />615        )616        const out = template.toString() as string617        expect(out).toBe('<div style="background-color:white"></div>')618        expect(out).not.toContain('position:fixed')619      })620621      it('should drop style values that try to expose declarations through CSS curly blocks', () => {622        const template = (623          <div624            style={{625              color: 'red{;background:blue}',626              backgroundColor: 'white',627            }}628          />629        )630        const out = template.toString() as string631        expect(out).toBe('<div style="background-color:white"></div>')632        expect(out).not.toContain('background:blue')633      })634635      it('should drop unterminated style values that can swallow following declarations', () => {636        const template = <div style={{ color: 'red/*', display: 'none' }} />637        const out = template.toString() as string638        expect(out).toBe('<div style="display:none"></div>')639        expect(out).not.toContain('color:')640      })641642      it('should drop style property names that can inject declarations', () => {643        const template = (644          <div645            style={{646              'color;background-image': 'url(https://attacker.example/a.png)',647              backgroundColor: 'white',648            }}649          />650        )651        const out = template.toString() as string652        expect(out).toBe('<div style="background-color:white"></div>')653        expect(out).not.toContain('background-image')654      })655656      it('should still HTML-escape safe style values', () => {657        const template = <h1 style={{ fontFamily: '"DejaVu Sans Mono", monospace' }}>Hello</h1>658        expect(template.toString()).toBe(659          '<h1 style="font-family:&quot;DejaVu Sans Mono&quot;, monospace">Hello</h1>'660        )661      })662663      it('should keep semicolons inside quoted style values', () => {664        const template = <h1 style={{ fontFamily: '"a;b", sans-serif' }}>Hello</h1>665        expect(template.toString()).toBe(666          '<h1 style="font-family:&quot;a;b&quot;, sans-serif">Hello</h1>'667        )668      })669670      it('should drop quoted style values that use newlines to expose declaration separators', () => {671        const template = (672          <div673            style={{674              fontFamily: '"\n;background:url(https://attacker.example/a.png)',675              backgroundColor: 'white',676            }}677          />678        )679        expect(template.toString()).toBe('<div style="background-color:white"></div>')680      })681682      it('should keep numeric style values working', () => {683        const template = <div style={{ fontSize: 10, lineHeight: 1.5 }} />684        expect(template.toString()).toBe('<div style="font-size:10px;line-height:1.5"></div>')685      })686687      it('should not throw when style values contain ";"', () => {688        expect(() => (<div style={{ color: 'red;evil:1' }} />).toString()).not.toThrow()689      })690    })691  })692693  describe('HtmlEscaped in props', () => {694    it('should not be double-escaped', () => {695      const escapedString = html`${'<html-escaped-string>'}`696      const template = <span data-text={escapedString}>Hello</span>697      expect(template.toString()).toBe('<span data-text="&lt;html-escaped-string&gt;">Hello</span>')698    })699  })700701  describe('XSS prevention for attribute keys', () => {702    it('Should skip attribute keys containing double quotes', () => {703      const props: Record<string, string> = { ['" onfocus="alert(1)']: 'x' }704      const template = <div {...props}>Hello</div>705      expect(template.toString()).toBe('<div>Hello</div>')706    })707708    it('Should skip attribute keys containing >', () => {709      const props: Record<string, string> = { ['"><script>alert(1)</script><x x="']: 'x' }710      const template = <div {...props}>Hello</div>711      expect(template.toString()).toBe('<div>Hello</div>')712    })713714    it('Should skip attribute keys containing <', () => {715      const props: Record<string, string> = { ['foo<bar']: 'x' }716      const template = <div {...props}>Hello</div>717      expect(template.toString()).toBe('<div>Hello</div>')718    })719720    it('Should skip attribute keys containing backslashes', () => {721      const props: Record<string, string> = { ['foo\\bar']: 'x' }722      const template = <div {...props}>Hello</div>723      expect(template.toString()).toBe('<div>Hello</div>')724    })725726    it('Should skip attribute keys containing backticks', () => {727      const props: Record<string, string> = { ['foo`bar']: 'x' }728      const template = <div {...props}>Hello</div>729      expect(template.toString()).toBe('<div>Hello</div>')730    })731732    it('Should skip attribute keys containing spaces', () => {733      const props: Record<string, string> = { ['foo bar']: 'x' }734      const template = <div {...props}>Hello</div>735      expect(template.toString()).toBe('<div>Hello</div>')736    })737738    it('Should still render valid attributes alongside invalid ones', () => {739      const props: Record<string, string> = {740        id: 'safe',741        ['" onfocus="alert(1)']: 'x',742        class: 'test',743      }744      const template = <div {...props}>Hello</div>745      expect(template.toString()).toBe('<div id="safe" class="test">Hello</div>')746    })747748    it('Should skip invalid attribute keys before style serialization', () => {749      const template = <div {...{ ['" onfocus="alert(1)']: { fontSize: 10 } }}>Hello</div>750      expect(template.toString()).toBe('<div>Hello</div>')751    })752753    it('Should skip invalid attribute keys before function prop validation', () => {754      const template = <div {...{ ['" onfocus="alert(1)']: () => 'x' }}>Hello</div>755      expect(template.toString()).toBe('<div>Hello</div>')756    })757758    it('Should skip invalid attribute keys before dangerouslySetInnerHTML handling', () => {759      const template = (760        <div {...{ ['" onfocus="alert(1)']: { __html: '<strong>Injected</strong>' } }}>Hello</div>761      )762      expect(template.toString()).toBe('<div>Hello</div>')763    })764765    it('Should skip invalid attribute keys with Promise values', async () => {766      const template = <div {...{ ['" onfocus="alert(1)']: Promise.resolve('x') }}>Hello</div>767      expect(await template.toString()).toBe('<div>Hello</div>')768    })769  })770771  describe('head', () => {772    it('Simple head elements should be rendered as is', () => {773      const template = (774        <head>775          <title>Hono!</title>776          <meta name='description' content='A description' />777          <script src='script.js'></script>778        </head>779      )780      expect(template.toString()).toBe(781        '<head><title>Hono!</title><meta name="description" content="A description"/><script src="script.js"></script></head>'782      )783    })784  })785})786787describe('className', () => {788  it('should convert to class attribute for intrinsic elements', () => {789    const template = <h1 className='h1'>Hello</h1>790    expect(template.toString()).toBe('<h1 class="h1">Hello</h1>')791  })792793  it('should convert to class attribute for custom elements', () => {794    const template = <custom-element className='h1'>Hello</custom-element>795    expect(template.toString()).toBe('<custom-element class="h1">Hello</custom-element>')796  })797798  it('should not convert to class attribute for custom components', () => {799    const CustomComponent: FC<{ className: string }> = ({ className }) => (800      <div data-class-name={className}>Hello</div>801    )802    const template = <CustomComponent className='h1' />803    expect(template.toString()).toBe('<div data-class-name="h1">Hello</div>')804  })805})806807describe('memo', () => {808  it('does not reuse the result of a previous render', () => {809    let counter = 0810    const Header = memo(() => <title>Test Site {counter}</title>)811    const Body = () => <span>{counter}</span>812813    let template = (814      <html>815        <head>816          <Header />817        </head>818        <body>819          <Body />820        </body>821      </html>822    )823    expect(template.toString()).toBe(824      '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'825    )826827    counter++828    template = (829      <html>830        <head>831          <Header />832        </head>833        <body>834          <Body />835        </body>836      </html>837    )838    expect(template.toString()).toBe(839      '<html><head><title>Test Site 1</title></head><body><span>1</span></body></html>'840    )841  })842843  it('does not carry a context value into a later render', () => {844    const NameContext = createContext('anonymous')845    const Panel = memo(() => <p>{useContext(NameContext)}</p>)846    const render = (name: string) =>847      (848        <NameContext.Provider value={name}>849          <Panel />850        </NameContext.Provider>851      ).toString()852853    expect(render('alice')).toBe('<p>alice</p>')854    expect(render('bob')).toBe('<p>bob</p>')855  })856857  it('props are updated', () => {858    const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)859860    let template = <Body counter={0} />861    expect(template.toString()).toBe('<span>0</span>')862863    template = <Body counter={1} />864    expect(template.toString()).toBe('<span>1</span>')865  })866867  it('custom propsAreEqual is handed to the DOM renderer', () => {868    const propsAreEqual = (_: { counter: number }, nextProps: { counter: number }) =>869      nextProps.counter === 0870    const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>, propsAreEqual)871872    expect((Body as any)[DOM_MEMO]).toBe(propsAreEqual)873874    expect((<Body counter={0} />).toString()).toBe('<span>0</span>')875    expect((<Body counter={1} />).toString()).toBe('<span>1</span>')876  })877})878879describe('Fragment', () => {880  it('Should render children', () => {881    const template = (882      <>883        <p>1</p>884        <p>2</p>885      </>886    )887    expect(template.toString()).toBe('<p>1</p><p>2</p>')888  })889890  it('Should render children - with `Fragment`', () => {891    const template = (892      <Fragment>893        <p>1</p>894        <p>2</p>895      </Fragment>896    )897    expect(template.toString()).toBe('<p>1</p><p>2</p>')898  })899900  it('Should render a child', () => {901    const template = (902      <>903        <p>1</p>904      </>905    )906    expect(template.toString()).toBe('<p>1</p>')907  })908909  it('Should render a child - with `Fragment`', () => {910    const template = (911      <Fragment>912        <p>1</p>913      </Fragment>914    )915    expect(template.toString()).toBe('<p>1</p>')916  })917918  it('Should render nothing for empty Fragment', () => {919    const template = <></>920    expect(template.toString()).toBe('')921  })922923  it('Should render nothing for undefined', () => {924    const template = <>{undefined}</>925    expect(template.toString()).toBe('')926  })927})928929describe('StrictMode', () => {930  it('Should render children', () => {931    const template = (932      <StrictMode>933        <p>1</p>934        <p>2</p>935      </StrictMode>936    )937    expect(template.toString()).toBe('<p>1</p><p>2</p>')938  })939})940941describe('SVG', () => {942  it('simple', () => {943    const template = (944      <svg>945        <circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />946      </svg>947    )948    expect(template.toString()).toBe(949      '<svg><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></circle></svg>'950    )951  })952953  it('title element', () => {954    const template = (955      <>956        <head>957          <title>Document Title</title>958        </head>959        <svg>960          <title>SVG Title</title>961        </svg>962      </>963    )964    expect(template.toString()).toBe(965      '<head><title>Document Title</title></head><svg><title>SVG Title</title></svg>'966    )967  })968969  it('should skip invalid attribute keys in SVG while preserving valid ones', () => {970    const template = (971      <svg>972        <g {...{ ['" onload="alert(1)']: 'x', viewBox: '0 0 10 10' }} />973      </svg>974    )975    expect(template.toString()).toBe('<svg><g viewBox="0 0 10 10"></g></svg>')976  })977978  it('should normalize kebab-case attributes on the <svg> root element', () => {979    const template = <svg {...{ strokeWidth: '1.5', strokeLinecap: 'round' }} viewBox='0 0 16 16' />980    expect(template.toString()).toBe(981      '<svg stroke-width="1.5" stroke-linecap="round" viewBox="0 0 16 16"></svg>'982    )983  })984985  describe('attribute', () => {986    describe('camelCase', () => {987      test.each`988        key989        ${'attributeName'}990        ${'baseFrequency'}991        ${'calcMode'}992        ${'clipPathUnits'}993        ${'diffuseConstant'}994        ${'edgeMode'}995        ${'filterUnits'}996        ${'gradientTransform'}997        ${'gradientUnits'}998        ${'kernelMatrix'}999        ${'kernelUnitLength'}1000        ${'keyPoints'}1001        ${'keySplines'}1002        ${'keyTimes'}1003        ${'lengthAdjust'}1004        ${'limitingConeAngle'}1005        ${'markerHeight'}1006        ${'markerUnits'}1007        ${'markerWidth'}1008        ${'maskContentUnits'}1009        ${'maskUnits'}1010        ${'numOctaves'}1011        ${'pathLength'}1012        ${'patternContentUnits'}1013        ${'patternTransform'}1014        ${'patternUnits'}1015        ${'pointsAtX'}1016        ${'pointsAtY'}1017        ${'pointsAtZ'}1018        ${'preserveAlpha'}1019        ${'preserveAspectRatio'}1020        ${'primitiveUnits'}1021        ${'refX'}1022        ${'refY'}1023        ${'repeatCount'}1024        ${'repeatDur'}1025        ${'specularConstant'}1026        ${'specularExponent'}1027        ${'spreadMethod'}1028        ${'startOffset'}1029        ${'stdDeviation'}1030        ${'stitchTiles'}1031        ${'surfaceScale'}1032        ${'crossorigin'}1033        ${'systemLanguage'}1034        ${'tableValues'}1035        ${'targetX'}1036        ${'targetY'}1037        ${'textLength'}1038        ${'viewBox'}1039        ${'xChannelSelector'}1040        ${'yChannelSelector'}1041      `('$key', ({ key }) => {1042        const template = (1043          <svg>1044            <g {...{ [key]: 'test' }} />1045          </svg>1046        )1047        expect(template.toString()).toBe(`<svg><g ${key}="test"></g></svg>`)1048      })1049    })10501051    describe('kebab-case', () => {1052      test.each`1053        key1054        ${'alignmentBaseline'}1055        ${'baselineShift'}1056        ${'clipPath'}1057        ${'clipRule'}1058        ${'colorInterpolation'}1059        ${'colorInterpolationFilters'}1060        ${'dominantBaseline'}1061        ${'fillOpacity'}1062        ${'fillRule'}1063        ${'floodColor'}1064        ${'floodOpacity'}1065        ${'fontFamily'}1066        ${'fontSize'}1067        ${'fontSizeAdjust'}1068        ${'fontStretch'}1069        ${'fontStyle'}1070        ${'fontVariant'}1071        ${'fontWeight'}1072        ${'imageRendering'}1073        ${'letterSpacing'}1074        ${'lightingColor'}1075        ${'markerEnd'}1076        ${'markerMid'}1077        ${'markerStart'}1078        ${'overlinePosition'}1079        ${'overlineThickness'}1080        ${'paintOrder'}1081        ${'pointerEvents'}1082        ${'shapeRendering'}1083        ${'stopColor'}1084        ${'stopOpacity'}1085        ${'strikethroughPosition'}1086        ${'strikethroughThickness'}1087        ${'strokeDasharray'}1088        ${'strokeDashoffset'}1089        ${'strokeLinecap'}1090        ${'strokeLinejoin'}1091        ${'strokeMiterlimit'}1092        ${'strokeOpacity'}1093        ${'strokeWidth'}1094        ${'textAnchor'}1095        ${'textDecoration'}1096        ${'textRendering'}1097        ${'transformOrigin'}1098        ${'underlinePosition'}1099        ${'underlineThickness'}1100        ${'unicodeBidi'}1101        ${'vectorEffect'}1102        ${'wordSpacing'}1103        ${'writingMode'}1104      `('$key', ({ key }) => {1105        const template = (1106          <svg>1107            <g {...{ [key]: 'test' }} />1108          </svg>1109        )1110        expect(template.toString()).toBe(1111          `<svg><g ${key.replace(/([A-Z])/g, '-$1').toLowerCase()}="test"></g></svg>`1112        )1113      })1114    })11151116    describe('data-*', () => {1117      test.each`1118        key1119        ${'data-foo'}1120        ${'data-foo-bar'}1121        ${'data-fooBar'}1122      `('$key', ({ key }) => {1123        const template = (1124          <svg>1125            <g {...{ [key]: 'test' }} />1126          </svg>1127        )1128        expect(template.toString()).toBe(`<svg><g ${key}="test"></g></svg>`)1129      })1130    })1131  })1132})11331134describe('Context', () => {1135  let ThemeContext: Context<string>1136  let Consumer: FC1137  let ErrorConsumer: FC1138  let AsyncConsumer: FC1139  let AsyncErrorConsumer: FC1140  beforeAll(() => {1141    ThemeContext = createContext('light')1142    Consumer = () => {1143      const theme = useContext(ThemeContext)1144      return <span>{theme}</span>1145    }1146    ErrorConsumer = () => {1147      throw new Error('ErrorConsumer')1148    }1149    AsyncConsumer = async () => {1150      const theme = useContext(ThemeContext)1151      return <span>{theme}</span>1152    }1153    AsyncErrorConsumer = async () => {1154      throw new Error('AsyncErrorConsumer')1155    }1156  })11571158  describe('with .Provider', () => {1159    it('has a child', () => {1160      const template = (1161        <ThemeContext.Provider value='dark'>1162          <Consumer />1163        </ThemeContext.Provider>1164      )1165      expect(template.toString()).toBe('<span>dark</span>')1166    })11671168    it('has children', () => {1169      const template = (1170        <ThemeContext.Provider value='dark'>1171          <div>1172            <Consumer />!1173          </div>1174          <div>1175            <Consumer />!1176          </div>1177        </ThemeContext.Provider>1178      )1179      expect(template.toString()).toBe('<div><span>dark</span>!</div><div><span>dark</span>!</div>')1180    })11811182    it('escapes a single string child', async () => {1183      const template = (1184        <ThemeContext.Provider value='dark'>{'<img src=x onerror=alert(1)>'}</ThemeContext.Provider>1185      )11861187      expect(String(await template.toString())).toBe('&lt;img src=x onerror=alert(1)&gt;')1188    })11891190    it('escapes a string returned by an asynchronous child', async () => {1191      const Async = async () => '<img src=x onerror=alert(1)>' as any1192      const template = (1193        <ThemeContext.Provider value='dark'>1194          <Async />1195        </ThemeContext.Provider>1196      )11971198      expect(String(await template.toString())).toBe('&lt;img src=x onerror=alert(1)&gt;')1199    })12001201    it('preserves explicitly trusted content', async () => {1202      const template = (1203        <ThemeContext.Provider value='dark'>1204          {raw('<strong>trusted</strong>')}1205        </ThemeContext.Provider>1206      )12071208      expect(await template.toString()).toBe('<strong>trusted</strong>')1209    })12101211    it('escapes untrusted object stringification', async () => {1212      const object = { toString: () => '<img src=x onerror=alert(1)>' }1213      const asyncObject = { toString: async () => '<img src=x onerror=alert(1)>' }1214      const rawObject = { toString: () => raw('<img src=x onerror=alert(1)>') }12151216      for (const child of [object, asyncObject, rawObject]) {1217        const template = (1218          <ThemeContext.Provider value='dark'>{child as never}</ThemeContext.Provider>1219        )1220        expect(String(await template.toString())).toBe('&lt;img src=x onerror=alert(1)&gt;')1221      }1222    })12231224    it('continues to omit unsupported objects in child arrays', async () => {1225      const object = { toString: () => '<img src=x onerror=alert(1)>' }1226      const template = (1227        <ThemeContext.Provider value='dark'>{[object as never, 'safe']}</ThemeContext.Provider>1228      )12291230      expect(await template.toString()).toBe('safe')1231    })12321233    it('keeps a direct Promise child unchanged', async () => {1234      const template = (1235        <ThemeContext.Provider value='dark'>{Promise.resolve('resolved')}</ThemeContext.Provider>1236      )12371238      expect(await template.toString()).toBe('[object Promise]')1239    })12401241    it('nested', () => {1242      const template = (1243        <ThemeContext.Provider value='dark'>1244          <Consumer />1245          <ThemeContext.Provider value='black'>1246            <Consumer />1247          </ThemeContext.Provider>1248          <Consumer />1249        </ThemeContext.Provider>1250      )1251      expect(template.toString()).toBe('<span>dark</span><span>black</span><span>dark</span>')1252    })12531254    it('should reset context by error', () => {1255      const template = (1256        <ThemeContext.Provider value='dark'>1257          <ErrorConsumer />1258        </ThemeContext.Provider>1259      )1260      expect(() => template.toString()).toThrow()12611262      const nextRequest = <Consumer />1263      expect(nextRequest.toString()).toBe('<span>light</span>')1264    })1265  })12661267  describe('<Context> as a provider ', () => {1268    it('has a child', () => {1269      const template = (1270        <ThemeContext value='dark'>1271          <Consumer />1272        </ThemeContext>1273      )1274      expect(template.toString()).toBe('<span>dark</span>')1275    })1276  })12771278  it('default value', () => {1279    const template = <Consumer />1280    expect(template.toString()).toBe('<span>light</span>')1281  })12821283  describe('with Suspence', () => {1284    const RedTheme = () => (1285      <ThemeContext.Provider value='red'>1286        <Consumer />1287      </ThemeContext.Provider>1288    )12891290    it('Should preserve context in sync component', async () => {1291      const template = (1292        <ThemeContext.Provider value='dark'>1293          <Suspense fallback={<RedTheme />}>1294            <Consumer />1295            <ThemeContext.Provider value='black'>1296              <Consumer />1297            </ThemeContext.Provider>1298          </Suspense>1299        </ThemeContext.Provider>1300      )1301      const stream = renderToReadableStream(template)13021303      const chunks = []1304      const textDecoder = new TextDecoder()1305      for await (const chunk of stream as any) {1306        chunks.push(textDecoder.decode(chunk))1307      }13081309      expect(chunks).toEqual(['<span>dark</span><span>black</span>'])1310    })13111312    it('Should preserve context in async component', async () => {1313      const template = (1314        <ThemeContext.Provider value='dark'>1315          <Suspense fallback={<RedTheme />}>1316            <Consumer />1317            <ThemeContext.Provider value='black'>1318              <AsyncConsumer />1319            </ThemeContext.Provider>1320          </Suspense>1321        </ThemeContext.Provider>1322      )1323      const stream = renderToReadableStream(template)13241325      const chunks = []1326      const textDecoder = new TextDecoder()1327      for await (const chunk of stream as any) {1328        chunks.push(textDecoder.decode(chunk))1329      }13301331      expect(chunks).toEqual([1332        '<template id="H:0"></template><span>red</span><!--/$-->',1333        `<template data-hono-target="H:0"><span>dark</span><span>black</span></template><script>1334((d,c,n) => {1335c=d.currentScript.previousSibling1336d=d.getElementById('H:0')1337if(!d)return1338do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')1339d.replaceWith(c.content)1340})(document)1341</script>`,1342      ])1343    })1344  })13451346  describe('async component', () => {1347    const ParentAsyncConsumer = async () => {1348      const theme = useContext(ThemeContext)1349      return (1350        <div>1351          <span>{theme}</span>1352          <AsyncConsumer />1353        </div>1354      )1355    }13561357    const ParentAsyncErrorConsumer = async () => {1358      const theme = useContext(ThemeContext)1359      return (1360        <div>1361          <span>{theme}</span>1362          <AsyncErrorConsumer />1363        </div>1364      )1365    }13661367    it('simple', async () => {1368      const template = (1369        <ThemeContext.Provider value='dark'>1370          <AsyncConsumer />1371        </ThemeContext.Provider>1372      )1373      expect((await template.toString()).toString()).toBe('<span>dark</span>')1374    })13751376    it('returning an array', async () => {1377      const ArrayConsumer = async () => {1378        await new Promise((resolve) => setTimeout(resolve, 10))1379        return [<span>{useContext(ThemeContext)}</span>, <span>x</span>]1380      }1381      const template = (1382        <ThemeContext.Provider value='dark'>1383          <ArrayConsumer />1384        </ThemeContext.Provider>1385      )1386      expect((await template.toString()).toString()).toBe('<span>dark</span><span>x</span>')1387    })13881389    it('isolates a shared async result between providers', async () => {1390      const sharedResult = Promise.resolve(<Consumer />)1391      const SharedConsumer = () => sharedResult1392      const [dark, black] = await Promise.all([1393        (1394          <ThemeContext.Provider value='dark'>1395            <SharedConsumer />1396          </ThemeContext.Provider>1397        ).toString(),1398        (1399          <ThemeContext.Provider value='black'>1400            <SharedConsumer />1401          </ThemeContext.Provider>1402        ).toString(),1403      ])1404      expect(dark.toString()).toBe('<span>dark</span>')1405      expect(black.toString()).toBe('<span>black</span>')1406    })14071408    it('nested', async () => {1409      const template = (1410        <ThemeContext.Provider value='dark'>1411          <ParentAsyncConsumer />1412        </ThemeContext.Provider>1413      )1414      expect((await template.toString()).toString()).toBe(1415        '<div><span>dark</span><span>dark</span></div>'1416      )1417    })14181419    it('should reset context by error', async () => {1420      const template = (1421        <ThemeContext.Provider value='dark'>1422          <ParentAsyncErrorConsumer />1423        </ThemeContext.Provider>1424      )1425      await expect(async () => (await template.toString()).toString()).rejects.toThrow()14261427      const nextRequest = <Consumer />1428      expect(nextRequest.toString()).toBe('<span>light</span>')1429    })14301431    it('should keep captured context until a resumed async callback settles', async () => {1432      let resolveReader!: () => void1433      const readerWait = new Promise<void>((resolve) => {1434        resolveReader = resolve1435      })1436      let markReaderEntered!: () => void1437      const readerEntered = new Promise<void>((resolve) => {1438        markReaderEntered = resolve1439      })14401441      const ResumedReader = () => {1442        const resume = captureRenderContext()1443        return resume(async () => {1444          markReaderEntered()1445          await readerWait1446          return <>{useContext(ThemeContext)}</>1447        })1448      }14491450      const htmlPromise = (1451        <ThemeContext.Provider value='dark'>1452          <ResumedReader />1453        </ThemeContext.Provider>1454      ).toString()14551456      await readerEntered1457      resolveReader()14581459      expect(`${await htmlPromise}`).toBe('dark')1460    })14611462    it('should pop captured context when a resumed callback throws', async () => {1463      const ThrowThenRead = ({ resume }: { resume: ReturnType<typeof captureRenderContext> }) => {1464        try {1465          resume(() => {1466            throw new Error('boom')1467          })1468        } catch {}1469        return <>{useContext(ThemeContext)}</>1470      }1471      const CaptureOuter = () => {1472        const resume = captureRenderContext()1473        return (1474          <ThemeContext.Provider value='inner'>1475            <ThrowThenRead resume={resume} />1476          </ThemeContext.Provider>1477        )1478      }14791480      expect(1481        `${await (1482          <ThemeContext.Provider value='outer'>1483            <CaptureOuter />1484          </ThemeContext.Provider>1485        ).toString()}`1486      ).toBe('inner')1487    })14881489    it('should pop captured context when a resumed async callback rejects', async () => {1490      const RejectThenRead = async ({1491        resume,1492      }: {1493        resume: ReturnType<typeof captureRenderContext>1494      }) => {1495        try {1496          await resume(async () => {1497            await Promise.resolve()1498            throw new Error('boom')1499          })1500        } catch {}1501        return <>{useContext(ThemeContext)}</>1502      }1503      const CaptureOuter = () => {1504        const resume = captureRenderContext()1505        return (1506          <ThemeContext.Provider value='inner'>1507            <RejectThenRead resume={resume} />1508          </ThemeContext.Provider>1509        )1510      }15111512      expect(1513        `${await (1514          <ThemeContext.Provider value='outer'>1515            <CaptureOuter />1516          </ThemeContext.Provider>1517        ).toString()}`1518      ).toBe('inner')1519    })15201521    it('should isolate async component context between concurrent requests', async () => {1522      const app = new Hono()1523      const SessionContext = createContext({ username: 'guest', role: 'guest' })1524      const waits = new Map<string, Promise<void>>()1525      const entered = new Map<string, () => void>()15261527      const AdminDashboard = async ({ wait }: { wait: Promise<void> }) => {1528        entered.get(useContext(SessionContext).username)?.()1529        await wait1530        const session = useContext(SessionContext)15311532        if (session.role !== 'admin') {1533          return <div>Access Denied for {session.username}</div>1534        }15351536        return <div>Welcome Admin {session.username}. Secret Data: 42</div>1537      }15381539      app.get('/', (c) => {1540        const session = {1541          username: c.req.query('user') || 'guest',1542          role: c.req.query('role') || 'guest',1543        }1544        const wait = waits.get(session.username) || Promise.resolve()15451546        return c.html(1547          <SessionContext.Provider value={session}>1548            <AdminDashboard wait={wait} />1549          </SessionContext.Provider>1550        )1551      })15521553      let resolveAdmin!: () => void1554      let resolveAttacker!: () => void1555      waits.set(1556        'admin',1557        new Promise<void>((resolve) => {1558          resolveAdmin = resolve1559        })1560      )1561      waits.set(1562        'attacker',1563        new Promise<void>((resolve) => {1564          resolveAttacker = resolve1565        })1566      )1567      const adminEntered = new Promise<void>((resolve) => {1568        entered.set('admin', resolve)1569      })1570      const attackerEntered = new Promise<void>((resolve) => {1571        entered.set('attacker', resolve)1572      })15731574      const adminReq = app.fetch(new Request('http://localhost/?user=admin&role=admin'))1575      const attackerReq = app.fetch(new Request('http://localhost/?user=attacker&role=guest'))15761577      await Promise.all([adminEntered, attackerEntered])1578      resolveAttacker()1579      await Promise.resolve()1580      resolveAdmin()15811582      const [adminRes, attackerRes] = await Promise.all([adminReq, attackerReq])1583      const adminHtml = await adminRes.text()1584      const attackerHtml = await attackerRes.text()15851586      // Each request must render with exactly its own provided value: no1587      // cross-request leak, and no degradation to the context default.1588      expect(adminHtml).toBe('<div>Welcome Admin admin. Secret Data: 42</div>')1589      expect(attackerHtml).toBe('<div>Access Denied for attacker</div>')1590    })1591  })15921593  describe('async with html helper', () => {1594    it('should preserve context when using await before html helper', async () => {1595      // Regression test for https://github.com/honojs/hono/issues/45821596      // Context was being popped before async children resolved1597      const AsyncParentWithHtml = async (props: { children?: any }) => {1598        await new Promise((r) => setTimeout(r, 10))1599        return html`<div>${props.children}</div>`1600      }16011602      const template = (1603        <ThemeContext.Provider value='dark'>1604          <AsyncParentWithHtml>1605            <Consumer />1606          </AsyncParentWithHtml>1607        </ThemeContext.Provider>1608      )1609      expect((await template.toString()).toString()).toBe('<div><span>dark</span></div>')1610    })16111612    it('should preserve nested context when using await before html helper', async () => {1613      const AsyncParentWithHtml = async (props: { children?: any }) => {1614        await new Promise((r) => setTimeout(r, 10))1615        return html`<div>${props.children}</div>`1616      }16171618      const template = (1619        <ThemeContext.Provider value='dark'>1620          <AsyncParentWithHtml>1621            <ThemeContext.Provider value='black'>1622              <Consumer />1623            </ThemeContext.Provider>1624          </AsyncParentWithHtml>1625        </ThemeContext.Provider>1626      )1627      expect((await template.toString()).toString()).toBe('<div><span>black</span></div>')1628    })1629  })1630})16311632describe('ErrorBoundary', () => {1633  it('awaits thenable fallback values', async () => {1634    const Broken = () => {1635      throw new Error('boom')1636    }1637    const fallback = {1638      then(resolve: (value: unknown) => void) {1639        resolve(<span>Recovered</span>)1640      },1641    }16421643    expect(1644      `${await (1645        <ErrorBoundary fallback={fallback as any}>1646          <Broken />1647        </ErrorBoundary>1648      ).toString()}`1649    ).toBe('<span>Recovered</span>')1650  })16511652  it('prefers an empty fallback over fallbackRender', async () => {1653    const Broken = () => {1654      throw new Error('boom')1655    }1656    let fallbackRenderCalled = false16571658    expect(1659      `${await (1660        <ErrorBoundary1661          fallback=''1662          fallbackRender={() => {1663            fallbackRenderCalled = true1664            return <span>fallbackRender</span>1665          }}1666        >1667          <Broken />1668        </ErrorBoundary>1669      ).toString()}`1670    ).toBe('')1671    expect(fallbackRenderCalled).toBe(false)1672  })16731674  it('renders async rejection fallback with the captured context while streaming', async () => {1675    const ThemeContext = createContext('default')1676    const Fallback = () => <span>{useContext(ThemeContext)}</span>1677    const Broken = async () => {1678      await Promise.resolve()1679      throw new Error('boom')1680    }16811682    const stream = renderToReadableStream(1683      <ThemeContext.Provider value='outer'>1684        <ErrorBoundary fallbackRender={() => <Fallback />}>1685          <Broken />1686        </ErrorBoundary>1687      </ThemeContext.Provider>1688    )1689    const decoder = new TextDecoder()1690    let html = ''1691    for await (const chunk of stream) {1692      html += decoder.decode(chunk)1693    }16941695    expect(html).toContain('<span>outer</span>')1696    expect(html).not.toContain('<span>default</span>')1697  })1698})16991700describe('version', () => {1701  it('should be defined with semantic versioning format', () => {1702    expect(version).toMatch(/^\d+\.\d+\.\d+-hono-jsx$/)1703  })1704})17051706describe('default export', () => {1707  ;[1708    'version',1709    'memo',1710    'Fragment',1711    'isValidElement',1712    'createElement',1713    'cloneElement',1714    'ErrorBoundary',1715    'createContext',1716    'useContext',1717    'useState',1718    'useEffect',1719    'useRef',1720    'useCallback',1721    'useReducer',1722    'useDebugValue',1723    'createRef',1724    'forwardRef',1725    'useImperativeHandle',1726    'useSyncExternalStore',1727    'use',1728    'startTransition',1729    'useTransition',1730    'useDeferredValue',1731    'startViewTransition',1732    'useViewTransition',1733    'useMemo',1734    'useLayoutEffect',1735    'useInsertionEffect',1736    'useActionState',1737    'useOptimistic',1738    'Suspense',1739    'StrictMode',1740  ].forEach((key) => {1741    it(key, () => {1742      expect((DefaultExport as any)[key]).toBeDefined()1743    })1744  })1745})