Skip to content
Myr

feat(compress): improve compress middleware (#3317)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* improve compression middleware * run lint & format * improve test * refactor * fix setting headers * fix ctx.res setter add tests * revert change * minor * remove workaround and simplify * remove diff * update test * improvements

authored by nitedani · committed by GitHub · parent f9349ec · Browse files · 2 files+195 added−67 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+195 added−67 removed

  • tests:+160 added−65 removed
  • other:+35 added−2 removed

2 files+195 added−67 removed

modified:src/middleware/compress/index.test.ts+160 added-65 removed
modified:src/middleware/compress/index.ts+35 added-2 removed
4 unmodified lines
56import type { MiddlewareHandler } from '../../types'78const ENCODING_TYPES = ['gzip', 'deflate'] as const9const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i10const compressibleContentTypeRegExp =11 /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i1213interface CompressionOptions {14 encoding?: (typeof ENCODING_TYPES)[number]15 threshold?: number16}1718/**19 * Compress Middleware for Hono.
1 unmodified line
21 * @see {@link https://hono.dev/docs/middleware/builtin/compress}22 *23 * @param {CompressionOptions} [options] - The options for the compress middleware.24 * @param {'gzip' | 'deflate'} [options.encoding] - The compression scheme to allow for response compression. Either 'gzip' or 'deflate'. If not defined, both are allowed and will be used based on the Accept-Encoding header. 'gzip' is prioritized if this option is not provided and the client provides both in the Accept-Encoding header.25 * @param {number} [options.threshold=1024] - The minimum size in bytes to compress. Defaults to 1024 bytes.26 * @returns {MiddlewareHandler} The middleware handler function.27 *28 * @example29 * ```ts
2 unmodified lines
32 * app.use(compress())33 * ```34 */35export const compress = (options?: CompressionOptions): MiddlewareHandler => {36 const threshold = options?.threshold ?? 10243738 return async function compress(ctx, next) {39 await next()4041 const contentLength = ctx.res.headers.get('Content-Length')4243 // Check if response should be compressed44 if (45 ctx.res.headers.has('Content-Encoding') || // already encoded46 ctx.req.method === 'HEAD' || // HEAD request47 (contentLength && Number(contentLength) < threshold) || // content-length below threshold48 !shouldCompress(ctx.res) || // not compressible type49 !shouldTransform(ctx.res) // cache-control: no-transform50 ) {51 return52 }5354 const accepted = ctx.req.header('Accept-Encoding')55 const encoding =56 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))57 if (!encoding || !ctx.res.body) {58 return59 }39 // eslint-disable-next-line @typescript-eslint/ban-ts-comment40 // @ts-ignore6061 // Compress the response62 const stream = new CompressionStream(encoding)63 ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)64 ctx.res.headers.delete('Content-Length')65 ctx.res.headers.set('Content-Encoding', encoding)66 }67}6869const shouldCompress = (res: Response) => {70 const type = res.headers.get('Content-Type')71 return type && compressibleContentTypeRegExp.test(type)72}7374const shouldTransform = (res: Response) => {75 const cacheControl = res.headers.get('Cache-Control')76 // Don't compress for Cache-Control: no-transform77 // https://tools.ietf.org/html/rfc7234#section-5.2.2.478 return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl)79}