Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 95 additions & 19 deletions src/helper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { promisify } from 'node:util'
import zlib from 'node:zlib'
import { Buffer } from 'node:buffer'
import { Duplex } from 'node:stream'
import { Duplex, Readable } from 'node:stream'
import process from 'node:process'
import type { H3Event } from 'h3'
import * as h3 from 'h3'
Expand Down Expand Up @@ -280,11 +280,21 @@ function createCompressor(method: Compression): (payload: Uint8Array) => Promise
return promisify(zlib[compressors[method]]) as (payload: Uint8Array) => Promise<Buffer>
}

function isReadableStream(value: unknown): boolean {
function isReadableStream(value: unknown): value is ReadableStream {
return typeof value === 'object' && value !== null
&& typeof (value as ReadableStream).getReader === 'function'
}

function isNodeStream(value: unknown): value is Readable {
return typeof value === 'object' && value !== null
&& typeof (value as Readable).pipe === 'function'
&& typeof (value as Readable).on === 'function'
}

function isBlob(value: unknown): value is Blob {
return typeof Blob !== 'undefined' && value instanceof Blob
}

/**
* Whether a hook response body carries no bytes at all. Empty bodies are never
* compressed — the encoding framing would only add bytes, and a
Expand All @@ -300,15 +310,47 @@ function isEmptyBody(body: unknown): boolean {
return false
}

/**
* Whether h3 would send a body as JSON: objects and arrays (e.g. returned from
* a `/server/api` route), numbers and booleans. Streams, `Blob`s, `Response`s
* and errors are not — serializing those would replace the payload with
* their internal state (`{"_events":…}`) or `{}`.
*/
function isJsonBody(body: unknown): boolean {
if (typeof body === 'number' || typeof body === 'boolean')
return true

if (typeof body !== 'object' || body === null || body instanceof Error)
return false

const value = body as Record<string, unknown>
return typeof value.getReader !== 'function'
&& typeof value.pipe !== 'function'
&& typeof value.arrayBuffer !== 'function'
}

/**
* Serializes a JSON body. `undefined` when it can't be (circular, or a value
* `JSON.stringify` drops).
*/
function serializeJson(body: unknown): string | undefined {
try {
return JSON.stringify(body)
}
catch {
return undefined
}
}

/**
* Turns a response body into a buffer that can be compressed. Strings, buffers
* and typed arrays are used as-is; plain JSON-serializable values (e.g. objects
* returned from a `/server/api` route) are serialized to JSON and flagged so
* the caller can set the content type. Returns `undefined` for bodies that
* can't / shouldn't be buffered (streams, empty).
* and typed arrays are used as-is; JSON bodies (see {@link isJsonBody}) are
* serialized and flagged so the caller can set the content type. Returns
* `undefined` for bodies that can't / shouldn't be buffered (streams, blobs,
* responses, empty).
*/
function toCompressibleBuffer(body: unknown): { payload: Buffer; json: boolean } | undefined {
if (isEmptyBody(body) || isReadableStream(body))
if (isEmptyBody(body))
return undefined

if (typeof body === 'string')
Expand All @@ -320,15 +362,41 @@ function toCompressibleBuffer(body: unknown): { payload: Buffer; json: boolean }
if (body instanceof ArrayBuffer)
return { payload: Buffer.from(body), json: false }

try {
const json = JSON.stringify(body)
if (json === undefined)
return undefined
return { payload: Buffer.from(json), json: true }
}
catch {
if (!isJsonBody(body))
return undefined
}

const json = serializeJson(body)
return json === undefined ? undefined : { payload: Buffer.from(json), json: true }
}

/**
* Prepares a response body for the stream path. Web and node streams, blobs,
* strings and bytes are streamed as they are; JSON bodies are serialized
* first (a plain `new Response(object)` would send `[object Object]`).
* Anything else — e.g. a `Response` returned on h3 v1 — is left alone.
*
* Streams are only opened once the body is actually compressed: `Readable.toWeb`
* starts consuming the node stream, so the "not compressed" path must not
* touch it.
*/
function toStreamSource(body: unknown): { open: () => ReadableStream; json: boolean } | undefined {
if (isEmptyBody(body))
return undefined

if (isReadableStream(body))
return { open: () => body, json: false }

if (isNodeStream(body))
return { open: () => Readable.toWeb(body) as unknown as ReadableStream, json: false }

if (typeof body === 'string' || body instanceof Uint8Array || body instanceof ArrayBuffer || isBlob(body))
return { open: () => new Response(body as BodyInit).body as ReadableStream, json: false }

if (!isJsonBody(body))
return undefined

const json = serializeJson(body)
return json === undefined ? undefined : { open: () => new Response(json).body as ReadableStream, json: true }
}

/**
Expand Down Expand Up @@ -509,7 +577,8 @@ export async function compress(
*
* Nothing happens for empty or already-encoded bodies. Otherwise
* `Vary: Accept-Encoding` is set, and the body is compressed if the client
* accepts the coding.
* accepts the coding. JSON bodies are serialized first, and web / node
* streams, blobs, strings and bytes are streamed as they are.
* @param { H3Event } event - A H3 event object.
* @param { Partial<RenderResponse> } response - A response object with body parameter.
* @param { StreamCompression } [method] - The coding to apply, if the client accepts it. Negotiated from `Accept-Encoding` when omitted.
Expand All @@ -522,7 +591,11 @@ export async function compressStream(
method?: StreamCompression,
options: StreamCompressionOptions = {},
): Promise<void> {
if (isEmptyBody(response.body) || isEncoded(event, response))
if (isEncoded(event, response))
return

const source = toStreamSource(response.body)
if (!source)
return

varyOnAcceptEncoding(event, response)
Expand All @@ -533,9 +606,12 @@ export async function compressStream(
if (!encoding)
return

const stream = new Response(response.body as string).body as ReadableStream
// Mirror h3, which serializes objects as JSON.
if (source.json)
setResponseHeader(event, 'Content-Type', 'application/json')

setEncoding(event, response, encoding)
response.body = stream.pipeThrough(createCompressionTransform(encoding))
response.body = source.open().pipeThrough(createCompressionTransform(encoding))
}

function ensureToResponse(): NonNullable<typeof toResponse> {
Expand Down
158 changes: 158 additions & 0 deletions test/body-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { Buffer } from 'node:buffer'
import { Readable } from 'node:stream'
import zlib from 'node:zlib'
import supertest from 'supertest'
import { describe, expect, it } from 'vitest'
import * as h3 from 'h3'
import { compress, compressStream, useCompression, useCompressionStream } from '../src'
import { applyCompression } from '../src/runtime/nitro-plugin'
import { isV1, isV2 } from './_version'

// The hook path hands over whatever the handler returned. Only JSON-like
// values may be serialized; streams, blobs and responses must either be
// streamed as they are or left alone — never replaced by `[object Object]`,
// `1,2` or `{"_events":…}`.

const { createApp, eventHandler, mockEvent, toNodeListener } = h3 as typeof import('h3')

const json = { message: 'hello world', items: [1, 2, 3] }
const text = 'Hello world! '.repeat(50)

async function readStream(stream: ReadableStream): Promise<Buffer> {
const chunks: Buffer[] = []
const reader = stream.getReader()
while (true) {
const { done, value } = await reader.read()
if (done)
break
chunks.push(Buffer.from(value))
}
return Buffer.concat(chunks)
}

function eventFor(encoding = 'gzip') {
return mockEvent('/', { headers: { 'accept-encoding': encoding } })
}

describe.runIf(isV2)('stream path body types', () => {
it.each([
['an object', json],
['an array', [1, 2, 3]],
['a number', 42],
])('serializes %s as JSON', async (_name, body) => {
const event = eventFor()
const response: { body: unknown } = { body }

await useCompressionStream(event, response)

expect(event.res.headers.get('content-encoding')).toEqual('gzip')
expect(event.res.headers.get('content-type')).toEqual('application/json')
expect(JSON.parse(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString())).toEqual(body)
})

it('streams a node stream', async () => {
const event = eventFor()
const response: { body: unknown } = { body: Readable.from([text.slice(0, 100), text.slice(100)]) }

await useCompressionStream(event, response)

expect(event.res.headers.get('content-encoding')).toEqual('gzip')
expect(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString()).toEqual(text)
})

it('streams a blob', async () => {
const event = eventFor()
const response: { body: unknown } = { body: new Blob([text]) }

await useCompressionStream(event, response)

expect(event.res.headers.get('content-encoding')).toEqual('gzip')
expect(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString()).toEqual(text)
})

it('does not touch a node stream it does not compress', async () => {
const event = eventFor('identity')
const stream = Readable.from([text])
const response: { body: unknown } = { body: stream }

await compressStream(event, response, 'gzip')

expect(response.body).toBe(stream)
expect(stream.readableFlowing).toBeNull()
expect(event.res.headers.get('content-encoding')).toBeNull()
})

it('leaves a Response body alone', async () => {
const event = eventFor()
const body = new Response(text)
const response: { body: unknown } = { body }

await useCompressionStream(event, response)

expect(response.body).toBe(body)
expect(event.res.headers.get('content-encoding')).toBeNull()
})
})

describe.runIf(isV2)('buffered path body types', () => {
it.each([
['a node stream', () => Readable.from([text])],
['a web stream', () => new Response(text).body],
['a blob', () => new Blob([text])],
['a Response', () => new Response(text)],
['an error', () => new Error('boom')],
])('leaves %s alone instead of serializing it', async (_name, create) => {
const event = eventFor()
const body = create()
const response: { body: unknown } = { body }

await useCompression(event, response)

expect(response.body).toBe(body)
expect(event.res.headers.get('content-encoding')).toBeNull()
expect(event.res.headers.get('vary')).toBeNull()
})

it('still serializes JSON bodies', async () => {
const event = eventFor()
const response: { body: unknown } = { body: json }

await compress(event, response)

expect(event.res.headers.get('content-type')).toEqual('application/json')
expect(JSON.parse(zlib.gunzipSync(response.body as Buffer).toString())).toEqual(json)
})
})

describe.runIf(isV1)('body types on the h3 v1 app hook', () => {
function appWith(hook: (event: any, response: any) => unknown) {
const app = createApp({ onBeforeResponse: hook })
app.use('/api', eventHandler(() => json))
app.use('/stream', eventHandler(() => Readable.from([text])))
return supertest(toNodeListener(app))
}

it('the nuxt plugin in stream mode compresses a JSON api route', async () => {
const result = await appWith((event, response) => applyCompression(event, response, { encoding: 'stream' }))
.get('/api')
.set('Accept-Encoding', 'gzip')

expect(result.headers['content-encoding']).toEqual('gzip')
expect(result.headers['content-type']).toContain('application/json')
expect(result.body).toEqual(json)
})

it('useCompression leaves a node stream intact', async () => {
const result = await appWith(useCompression).get('/stream').set('Accept-Encoding', 'gzip')

expect(result.headers['content-encoding']).toBeUndefined()
expect(result.text).toEqual(text)
})

it('useCompressionStream compresses a node stream', async () => {
const result = await appWith(useCompressionStream).get('/stream').set('Accept-Encoding', 'gzip')

expect(result.headers['content-encoding']).toEqual('gzip')
expect(result.text).toEqual(text)
})
})
Loading