Skip to content
Myr

index.test.ts

This file

Path

src/middleware/compress/index.test.ts

535 lines 路 19.1 KiB 路 TypeScript

Last changed by

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

History of this file

Take it

1import { compress } from '.'2import { stream, streamSSE } from '../../helper/streaming'3import { Hono } from '../../hono'45describe('Compress Middleware', () => {6  const app = new Hono()78  // Apply compress middleware to all routes9  app.use('*', compress())1011  // Test routes12  app.get('/small', (c) => {13    c.header('Content-Type', 'text/plain')14    c.header('Content-Length', '5')15    return c.text('small')16  })17  app.get('/large', (c) => {18    c.header('Content-Type', 'text/plain')19    c.header('Content-Length', '1024')20    return c.text('a'.repeat(1024))21  })22  app.get('/small-json', (c) => {23    c.header('Content-Type', 'application/json')24    c.header('Content-Length', '26')25    return c.json({ message: 'Hello, World!' })26  })27  app.get('/large-json', (c) => {28    c.header('Content-Type', 'application/json')29    c.header('Content-Length', '1024')30    return c.json({ data: 'a'.repeat(1024), message: 'Large JSON' })31  })32  app.get('/no-transform', (c) => {33    c.header('Content-Type', 'text/plain')34    c.header('Content-Length', '1024')35    c.header('Cache-Control', 'no-transform')36    return c.text('a'.repeat(1024))37  })38  app.get('/jpeg-image', (c) => {39    c.header('Content-Type', 'image/jpeg')40    c.header('Content-Length', '1024')41    return c.body(new Uint8Array(1024)) // Simulated JPEG data42  })43  app.get('/already-compressed', (c) => {44    c.header('Content-Type', 'application/octet-stream')45    c.header('Content-Encoding', 'br')46    c.header('Content-Length', '1024')47    return c.body(new Uint8Array(1024)) // Simulated compressed data48  })49  app.get('/transfer-encoding-deflate', (c) => {50    c.header('Content-Type', 'application/octet-stream')51    c.header('Transfer-Encoding', 'deflate')52    c.header('Content-Length', '1024')53    return c.body(new Uint8Array(1024)) // Simulated deflate data54  })55  app.get('/chunked', (c) => {56    c.header('Content-Type', 'application/octet-stream')57    c.header('Transfer-Encoding', 'chunked')58    c.header('Content-Length', '1024')59    return c.body(new Uint8Array(1024)) // Simulated chunked data60  })61  app.get('/partial', (c) => {62    c.header('Content-Type', 'text/plain')63    c.header('Content-Length', '1024')64    c.header('Content-Range', 'bytes 0-1023/2048')65    return c.body('a'.repeat(1024), 206)66  })67  app.get('/stream', (c) =>68    stream(c, async (stream) => {69      c.header('Content-Type', 'text/plain')70      // 60000 bytes71      for (let i = 0; i < 10000; i++) {72        await stream.write('chunk ')73      }74    })75  )76  app.get('/already-compressed-stream', (c) =>77    stream(c, async (stream) => {78      c.header('Content-Type', 'text/plain')79      c.header('Content-Encoding', 'br')80      // 60000 bytes81      for (let i = 0; i < 10000; i++) {82        await stream.write(new Uint8Array([0, 1, 2, 3, 4, 5])) // Simulated compressed data83      }84    })85  )86  app.get('/sse', (c) =>87    streamSSE(c, async (stream) => {88      for (let i = 0; i < 1000; i++) {89        await stream.writeSSE({ data: 'chunk' })90      }91    })92  )93  app.notFound((c) => c.text('Custom NotFound', 404))9495  const testCompression = async (96    path: string,97    acceptEncoding: string,98    expectedEncoding: string | null99  ) => {100    const req = new Request(`http://localhost${path}`, {101      method: 'GET',102      headers: new Headers({ 'Accept-Encoding': acceptEncoding }),103    })104    const res = await app.request(req)105    expect(res.headers.get('Content-Encoding')).toBe(expectedEncoding)106    return res107  }108109  describe('Compression Behavior', () => {110    it('should compress large responses with gzip', async () => {111      const res = await testCompression('/large', 'gzip', 'gzip')112      expect(res.headers.get('Content-Length')).toBeNull()113      expect((await res.arrayBuffer()).byteLength).toBeLessThan(1024)114    })115116    it('should compress large responses with deflate', async () => {117      const res = await testCompression('/large', 'deflate', 'deflate')118      expect((await res.arrayBuffer()).byteLength).toBeLessThan(1024)119    })120121    it('should prioritize gzip over deflate when both are accepted', async () => {122      await testCompression('/large', 'gzip, deflate', 'gzip')123    })124125    it('should not compress small responses', async () => {126      const res = await testCompression('/small', 'gzip, deflate', null)127      expect(res.headers.get('Content-Length')).toBe('5')128    })129130    it('should not compress when no Accept-Encoding is provided', async () => {131      await testCompression('/large', '', null)132    })133134    it('should not compress images', async () => {135      const res = await testCompression('/jpeg-image', 'gzip', null)136      expect(res.headers.get('Content-Type')).toBe('image/jpeg')137      expect(res.headers.get('Content-Length')).toBe('1024')138    })139140    it('should not compress already compressed responses', async () => {141      const res = await testCompression('/already-compressed', 'gzip', 'br')142      expect(res.headers.get('Content-Length')).toBe('1024')143    })144145    it('should remove Content-Length when compressing', async () => {146      const res = await testCompression('/large', 'gzip', 'gzip')147      expect(res.headers.get('Content-Length')).toBeNull()148    })149150    it('should not remove Content-Length when not compressing', async () => {151      const res = await testCompression('/jpeg-image', 'gzip', null)152      expect(res.headers.get('Content-Length')).toBeDefined()153    })154155    it('should not compress transfer-encoding: deflate', async () => {156      const res = await testCompression('/transfer-encoding-deflate', 'gzip', null)157      expect(res.headers.get('Content-Length')).toBe('1024')158      expect(res.headers.get('Transfer-Encoding')).toBe('deflate')159    })160161    it('should not compress transfer-encoding: chunked', async () => {162      const res = await testCompression('/chunked', 'gzip', null)163      expect(res.headers.get('Content-Length')).toBe('1024')164      expect(res.headers.get('Transfer-Encoding')).toBe('chunked')165    })166167    it('should not compress 206 Partial Content responses', async () => {168      const res = await testCompression('/partial', 'gzip', null)169      expect(res.status).toBe(206)170      expect(res.headers.get('Content-Length')).toBe('1024')171      expect(res.headers.get('Content-Range')).toBe('bytes 0-1023/2048')172      expect(await res.text()).toBe('a'.repeat(1024))173    })174  })175176  describe('JSON Handling', () => {177    it('should not compress small JSON responses', async () => {178      const res = await testCompression('/small-json', 'gzip', null)179      expect(res.headers.get('Content-Length')).toBe('26')180    })181182    it('should compress large JSON responses', async () => {183      const res = await testCompression('/large-json', 'gzip', 'gzip')184      expect(res.headers.get('Content-Length')).toBeNull()185      const decompressed = await decompressResponse(res)186      const json = JSON.parse(decompressed)187      expect(json.data.length).toBe(1024)188      expect(json.message).toBe('Large JSON')189    })190  })191192  describe('Streaming Responses', () => {193    it('should compress streaming responses written in multiple chunks', async () => {194      const res = await testCompression('/stream', 'gzip', 'gzip')195      const decompressed = await decompressResponse(res)196      expect(decompressed.length).toBe(60000)197    })198199    it('should not compress already compressed streaming responses', async () => {200      const res = await testCompression('/already-compressed-stream', 'gzip', 'br')201      expect((await res.arrayBuffer()).byteLength).toBe(60000)202    })203204    it('should not compress server-sent events', async () => {205      const res = await testCompression('/sse', 'gzip', null)206      expect((await res.arrayBuffer()).byteLength).toBe(13000)207    })208  })209210  describe('ETag Handling', () => {211    const app = new Hono()212    app.use('*', compress())213    app.get('/strong-etag', (c) => {214      c.header('Content-Type', 'text/plain')215      c.header('Content-Length', '1024')216      c.header('ETag', '"strong-etag"')217      return c.text('a'.repeat(1024))218    })219    app.get('/weak-etag', (c) => {220      c.header('Content-Type', 'text/plain')221      c.header('Content-Length', '1024')222      c.header('ETag', 'W/"weak-etag"')223      return c.text('a'.repeat(1024))224    })225    app.get('/no-etag', (c) => {226      c.header('Content-Type', 'text/plain')227      c.header('Content-Length', '1024')228      return c.text('a'.repeat(1024))229    })230231    it('should convert strong ETag to weak ETag when compressing', async () => {232      const res = await app.request('/strong-etag', {233        headers: { 'Accept-Encoding': 'gzip' },234      })235      expect(res.headers.get('Content-Encoding')).toBe('gzip')236      expect(res.headers.get('ETag')).toBe('W/"strong-etag"')237    })238239    it('should keep strong ETag when not compressing', async () => {240      const res = await app.request('/strong-etag')241      expect(res.headers.get('Content-Encoding')).toBeNull()242      expect(res.headers.get('ETag')).toBe('"strong-etag"')243    })244245    it('should not modify weak ETag when compressing', async () => {246      const res = await app.request('/weak-etag', {247        headers: { 'Accept-Encoding': 'gzip' },248      })249      expect(res.headers.get('Content-Encoding')).toBe('gzip')250      expect(res.headers.get('ETag')).toBe('W/"weak-etag"')251    })252253    it('should not add ETag when none exists', async () => {254      const res = await app.request('/no-etag', {255        headers: { 'Accept-Encoding': 'gzip' },256      })257      expect(res.headers.get('Content-Encoding')).toBe('gzip')258      expect(res.headers.get('ETag')).toBeNull()259    })260  })261262  describe('Vary Header', () => {263    const app = new Hono()264    app.use('*', compress())265    app.get('/no-vary', (c) => {266      c.header('Content-Type', 'text/plain')267      c.header('Content-Length', '1024')268      return c.text('a'.repeat(1024))269    })270    app.get('/existing-vary', (c) => {271      c.header('Content-Type', 'text/plain')272      c.header('Content-Length', '1024')273      c.header('Vary', 'Cookie')274      return c.text('a'.repeat(1024))275    })276    app.get('/already-accept-encoding', (c) => {277      c.header('Content-Type', 'text/plain')278      c.header('Content-Length', '1024')279      c.header('Vary', 'Accept-Encoding')280      return c.text('a'.repeat(1024))281    })282    app.get('/wildcard-vary', (c) => {283      c.header('Content-Type', 'text/plain')284      c.header('Content-Length', '1024')285      c.header('Vary', '*')286      return c.text('a'.repeat(1024))287    })288    app.get('/not-compressible', (c) => {289      c.header('Content-Type', 'image/png')290      c.header('Content-Length', '1024')291      return c.body('a'.repeat(1024))292    })293294    it('should set Vary: Accept-Encoding when compressing', async () => {295      const res = await app.request('/no-vary', {296        headers: { 'Accept-Encoding': 'gzip' },297      })298      expect(res.headers.get('Content-Encoding')).toBe('gzip')299      expect(res.headers.get('Vary')).toBe('Accept-Encoding')300    })301302    it('should append Accept-Encoding to an existing Vary header', async () => {303      const res = await app.request('/existing-vary', {304        headers: { 'Accept-Encoding': 'gzip' },305      })306      expect(res.headers.get('Content-Encoding')).toBe('gzip')307      expect(res.headers.get('Vary')).toBe('Cookie, Accept-Encoding')308    })309310    it('should not duplicate Accept-Encoding when Vary already lists it', async () => {311      const res = await app.request('/already-accept-encoding', {312        headers: { 'Accept-Encoding': 'gzip' },313      })314      expect(res.headers.get('Content-Encoding')).toBe('gzip')315      expect(res.headers.get('Vary')).toBe('Accept-Encoding')316    })317318    it('should leave Vary: * unchanged', async () => {319      const res = await app.request('/wildcard-vary', {320        headers: { 'Accept-Encoding': 'gzip' },321      })322      expect(res.headers.get('Content-Encoding')).toBe('gzip')323      expect(res.headers.get('Vary')).toBe('*')324    })325326    it('should set Vary on an identity response when Accept-Encoding is absent', async () => {327      const res = await app.request('/no-vary')328      expect(res.headers.get('Content-Encoding')).toBeNull()329      expect(res.headers.get('Vary')).toBe('Accept-Encoding')330    })331332    it('should set Vary on an identity response when no offered encoding is accepted', async () => {333      const res = await app.request('/no-vary', {334        headers: { 'Accept-Encoding': 'br' },335      })336      expect(res.headers.get('Content-Encoding')).toBeNull()337      expect(res.headers.get('Vary')).toBe('Accept-Encoding')338    })339340    it('should not add a Vary header when the response is not eligible for compression', async () => {341      const res = await app.request('/not-compressible', {342        headers: { 'Accept-Encoding': 'gzip' },343      })344      expect(res.headers.get('Content-Encoding')).toBeNull()345      expect(res.headers.get('Vary')).toBeNull()346    })347  })348349  describe('contentTypeFilter', () => {350    describe('RegExp', () => {351      const app = new Hono()352      app.use('*', compress({ contentTypeFilter: /^application\/json/, threshold: 0 }))353      app.get('/json', (c) => c.json({ data: 'a'.repeat(1024) }))354      app.get('/text', (c) => c.text('a'.repeat(1024)))355356      it('should compress when Content-Type matches', async () => {357        const res = await app.request('/json', {358          headers: { 'Accept-Encoding': 'gzip' },359        })360        expect(res.headers.get('Content-Encoding')).toBe('gzip')361      })362363      it('should not compress when Content-Type does not match', async () => {364        const res = await app.request('/text', {365          headers: { 'Accept-Encoding': 'gzip' },366        })367        expect(res.headers.get('Content-Encoding')).toBeNull()368      })369    })370371    describe('function', () => {372      const app = new Hono()373      app.use('*', compress({ contentTypeFilter: (type) => type.includes('json'), threshold: 0 }))374      app.get('/json', (c) => c.json({ data: 'a'.repeat(1024) }))375      app.get('/text', (c) => c.text('a'.repeat(1024)))376377      it('should compress when Content-Type matches', async () => {378        const res = await app.request('/json', {379          headers: { 'Accept-Encoding': 'gzip' },380        })381        expect(res.headers.get('Content-Encoding')).toBe('gzip')382      })383384      it('should not compress when Content-Type does not match', async () => {385        const res = await app.request('/text', {386          headers: { 'Accept-Encoding': 'gzip' },387        })388        expect(res.headers.get('Content-Encoding')).toBeNull()389      })390    })391  })392393  describe('Edge Cases', () => {394    it('should not compress responses with Cache-Control: no-transform', async () => {395      await testCompression('/no-transform', 'gzip', null)396    })397398    it('should handle HEAD requests without compression', async () => {399      const req = new Request('http://localhost/large', {400        method: 'HEAD',401        headers: new Headers({ 'Accept-Encoding': 'gzip' }),402      })403      const res = await app.request(req)404      expect(res.headers.get('Content-Encoding')).toBeNull()405    })406407    it('should compress custom 404 Not Found responses', async () => {408      const res = await testCompression('/not-found', 'gzip', 'gzip')409      expect(res.status).toBe(404)410      const decompressed = await decompressResponse(res)411      expect(decompressed).toBe('Custom NotFound')412    })413  })414415  describe('Encoding Option', () => {416    const buildApp = (encoding: 'gzip' | 'deflate') => {417      const app = new Hono()418      app.use('*', compress({ encoding }))419      app.get('/large', (c) => {420        c.header('Content-Type', 'text/plain')421        c.header('Content-Length', '1024')422        return c.text('a'.repeat(1024))423      })424      return app425    }426427    it('should compress when configured encoding is accepted by the client', async () => {428      const app = buildApp('gzip')429      const res = await app.request('/large', {430        headers: { 'Accept-Encoding': 'gzip' },431      })432      expect(res.headers.get('Content-Encoding')).toBe('gzip')433    })434435    it('should not compress when configured encoding is not in Accept-Encoding', async () => {436      const app = buildApp('gzip')437      const res = await app.request('/large', {438        headers: { 'Accept-Encoding': 'deflate' },439      })440      expect(res.headers.get('Content-Encoding')).toBeNull()441    })442443    it('should not compress when Accept-Encoding header is absent', async () => {444      const app = buildApp('gzip')445      const res = await app.request('/large')446      expect(res.headers.get('Content-Encoding')).toBeNull()447    })448  })449450  describe('Accept-Encoding parsing', () => {451    const buildAppDefault = () => {452      const app = new Hono()453      app.use('*', compress())454      app.get('/large', (c) => {455        c.header('Content-Type', 'text/plain')456        c.header('Content-Length', '1024')457        return c.text('a'.repeat(1024))458      })459      return app460    }461462    const buildAppWithEncoding = (encoding: 'gzip' | 'deflate') => {463      const app = new Hono()464      app.use('*', compress({ encoding }))465      app.get('/large', (c) => {466        c.header('Content-Type', 'text/plain')467        c.header('Content-Length', '1024')468        return c.text('a'.repeat(1024))469      })470      return app471    }472473    it('should not compress when configured encoding has q=0', async () => {474      const app = buildAppWithEncoding('gzip')475      const res = await app.request('/large', {476        headers: { 'Accept-Encoding': 'gzip;q=0' },477      })478      expect(res.headers.get('Content-Encoding')).toBeNull()479    })480481    it('should fall back to another encoding when the preferred one has q=0', async () => {482      const app = buildAppDefault()483      const res = await app.request('/large', {484        headers: { 'Accept-Encoding': 'gzip;q=0, deflate' },485      })486      expect(res.headers.get('Content-Encoding')).toBe('deflate')487    })488489    it('should compress when Accept-Encoding is the wildcard *', async () => {490      const app = buildAppWithEncoding('gzip')491      const res = await app.request('/large', {492        headers: { 'Accept-Encoding': '*' },493      })494      expect(res.headers.get('Content-Encoding')).toBe('gzip')495    })496497    it('should compress when Accept-Encoding token differs only in case', async () => {498      const app = buildAppWithEncoding('gzip')499      const res = await app.request('/large', {500        headers: { 'Accept-Encoding': 'GZIP' },501      })502      expect(res.headers.get('Content-Encoding')).toBe('gzip')503    })504505    it('should not treat x-gzip as gzip', async () => {506      const app = buildAppWithEncoding('gzip')507      const res = await app.request('/large', {508        headers: { 'Accept-Encoding': 'x-gzip' },509      })510      expect(res.headers.get('Content-Encoding')).toBeNull()511    })512513    it('should pick the encoding with the highest q value', async () => {514      const app = buildAppDefault()515      const res = await app.request('/large', {516        headers: { 'Accept-Encoding': 'gzip;q=0.5, deflate;q=0.9' },517      })518      expect(res.headers.get('Content-Encoding')).toBe('deflate')519    })520521    it('should prefer gzip over deflate when q values are equal', async () => {522      const app = buildAppDefault()523      const res = await app.request('/large', {524        headers: { 'Accept-Encoding': 'gzip;q=0.5, deflate;q=0.5' },525      })526      expect(res.headers.get('Content-Encoding')).toBe('gzip')527    })528  })529})530531async function decompressResponse(res: Response): Promise<string> {532  const decompressedStream = res.body!.pipeThrough(new DecompressionStream('gzip'))533  const decompressedResponse = new Response(decompressedStream)534  return await decompressedResponse.text()535}