Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

688 lines · 20.2 KiB · TypeScript

Last changed by

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

History of this file

Take it

The walk stopped after 200 commits: lines older than 3a550d2 point at it.

4.10.4Yusuke Wadabefore adoption3a550d2

lines 1–9why, one step back
1import type { Hono } from '../../hono'
2import type { Env, Schema } from '../../types'3import { decodeBase64, encodeBase64 } from '../../utils/encode'4import type {5 ALBRequestContext,6 ApiGatewayRequestContext,7 ApiGatewayRequestContextV2,8 Handler,9 LambdaContext,

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 10why, one step back
10 LatticeRequestContextV2,

4.10.4Yusuke Wadabefore adoption3a550d2

lines 11–22why, one step back
11} from './types'
1213function sanitizeHeaderValue(value: string): string {14 // Check if the value contains non-ASCII characters (char codes > 127)15 // eslint-disable-next-line no-control-regex16 const hasNonAscii = /[^\x00-\x7F]/.test(value)17 if (!hasNonAscii) {18 return value19 }20 return encodeURIComponent(value)21}22

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 23–27why, one step back
23export type LambdaEvent =
24 | APIGatewayProxyEvent25 | APIGatewayProxyEventV226 | ALBProxyEvent27 | LatticeProxyEventV2

4.10.4Yusuke Wadabefore adoption3a550d2

line 28why, one step back
28

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 29–39why, one step back
29export interface LatticeProxyEventV2 {
30 version: string31 path: string32 method: string33 headers: Record<string, string[] | undefined>34 queryStringParameters: Record<string, string[] | undefined>35 body: string | null36 isBase64Encoded: boolean37 requestContext: LatticeRequestContextV238}39

4.10.4Yusuke Wadabefore adoption3a550d2

lines 40–99why, one step back
40// When calling HTTP API or Lambda directly through function urls
41export interface APIGatewayProxyEventV2 {42 version: string43 routeKey: string44 headers: Record<string, string | undefined>45 multiValueHeaders?: undefined46 cookies?: string[]47 rawPath: string48 rawQueryString: string49 body: string | null50 isBase64Encoded: boolean51 requestContext: ApiGatewayRequestContextV252 queryStringParameters?: {53 [name: string]: string | undefined54 }55 pathParameters?: {56 [name: string]: string | undefined57 }58 stageVariables?: {59 [name: string]: string | undefined60 }61}6263// When calling Lambda through an API Gateway64export interface APIGatewayProxyEvent {65 version: string66 httpMethod: string67 headers: Record<string, string | undefined>68 multiValueHeaders?: {69 [headerKey: string]: string[]70 }71 path: string72 body: string | null73 isBase64Encoded: boolean74 queryStringParameters?: Record<string, string | undefined>75 requestContext: ApiGatewayRequestContext76 resource: string77 multiValueQueryStringParameters?: {78 [parameterKey: string]: string[]79 }80 pathParameters?: Record<string, string>81 stageVariables?: Record<string, string>82}8384// When calling Lambda through an Application Load Balancer85export interface ALBProxyEvent {86 httpMethod: string87 headers?: Record<string, string | undefined>88 multiValueHeaders?: Record<string, string[] | undefined>89 path: string90 body: string | null91 isBase64Encoded: boolean92 queryStringParameters?: Record<string, string | undefined>93 multiValueQueryStringParameters?: {94 [parameterKey: string]: string[]95 }96 requestContext: ALBRequestContext97}9899type WithHeaders = {

Merge commit from forkYusuke Wadabefore adoption7ae7cba

line 100why, one step back
100 headers: Record<string, string | string[]>

4.10.4Yusuke Wadabefore adoption3a550d2

lines 101–117why, one step back
101 multiValueHeaders?: undefined
102}103type WithMultiValueHeaders = {104 headers?: undefined105 multiValueHeaders: Record<string, string[]>106}107108export type APIGatewayProxyResult = {109 statusCode: number110 statusDescription?: string111 body: string112 cookies?: string[]113 isBase64Encoded: boolean114} & (WithHeaders | WithMultiValueHeaders)115116const getRequestContext = (117 event: LambdaEvent

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 118–122why, one step back
118):
119 | ApiGatewayRequestContext120 | ApiGatewayRequestContextV2121 | ALBRequestContext122 | LatticeRequestContextV2 => {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 123–140why, one step back
123 return event.requestContext
124}125126const streamToNodeStream = async (127 reader: ReadableStreamDefaultReader<Uint8Array>,128 writer: NodeJS.WritableStream129): Promise<void> => {130 let readResult = await reader.read()131 while (!readResult.done) {132 writer.write(readResult.value)133 readResult = await reader.read()134 }135 writer.end()136}137138export const streamHandle = <139 E extends Env = Env,140 S extends Schema = {},

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

line 141why, one step back
141 BasePath extends string = '/',

4.10.4Yusuke Wadabefore adoption3a550d2

lines 142–254why, one step back
142>(
143 app: Hono<E, S, BasePath>144): Handler => {145 // @ts-expect-error awslambda is not a standard API146 return awslambda.streamifyResponse(147 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {148 const processor = getProcessor(event)149 try {150 const req = processor.createRequest(event)151 const requestContext = getRequestContext(event)152153 const res = await app.fetch(req, {154 event,155 requestContext,156 context,157 })158159 const headers: Record<string, string> = {}160 const cookies: string[] = []161 res.headers.forEach((value, name) => {162 if (name === 'set-cookie') {163 cookies.push(value)164 } else {165 headers[name] = value166 }167 })168169 // Check content type170 const httpResponseMetadata = {171 statusCode: res.status,172 headers,173 cookies,174 }175176 // Update response stream177 // @ts-expect-error awslambda is not a standard API178 responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)179180 if (res.body) {181 await streamToNodeStream(res.body.getReader(), responseStream)182 } else {183 responseStream.write('')184 }185 } catch (error) {186 console.error('Error processing request:', error)187 responseStream.write('Internal Server Error')188 } finally {189 responseStream.end()190 }191 }192 )193}194195type HandleOptions = {196 isContentTypeBinary: ((contentType: string) => boolean) | undefined197}198199/**200 * Converts a Hono application to an AWS Lambda handler.201 *202 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),203 * and Lambda Function URLs.204 *205 * @param app - The Hono application instance206 * @param options - Optional configuration207 * @param options.isContentTypeBinary - A function to determine if the content type is binary.208 * If not provided, the default function will be used.209 * @returns Lambda handler function210 *211 * @example212 * ```js213 * import { Hono } from 'hono'214 * import { handle } from 'hono/aws-lambda'215 *216 * const app = new Hono()217 *218 * app.get('/', (c) => c.text('Hello from Lambda'))219 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))220 *221 * export const handler = handle(app)222 * ```223 *224 * @example225 * ```js226 * // With custom binary content type detection227 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'228 * export const handler = handle(app, {229 * isContentTypeBinary: (contentType) => {230 * if (defaultIsContentTypeBinary(contentType)) {231 * // default logic same as prior to v4.8.4232 * return true233 * }234 * return contentType.startsWith('image/') || contentType === 'application/pdf'235 * }236 * })237 * ```238 */239export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(240 app: Hono<E, S, BasePath>,241 { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }242): (<L extends LambdaEvent>(243 event: L,244 lambdaContext?: LambdaContext245) => Promise<246 APIGatewayProxyResult &247 (L extends { multiValueHeaders: Record<string, string[]> }248 ? WithMultiValueHeaders249 : WithHeaders)250>) => {251 // @ts-expect-error FIXME: Fix return typing252 return async (event, lambdaContext?) => {253 const processor = getProcessor(event)254

fix(aws-lambda): handle invalid header names in request processing (#4883)Yusuke Wadabefore adoptionfa2c74f

lines 255–266why, one step back
255 let req, requestContext
256 try {257 req = processor.createRequest(event)258 requestContext = getRequestContext(event)259 } catch (error) {260 console.error('Error processing request:', error)261 const errorResponse =262 error instanceof TypeError263 ? new Response('Invalid request', { status: 400 })264 : new Response('Internal Server Error', { status: 500 })265 return processor.createResult(event, errorResponse, { isContentTypeBinary })266 }

4.10.4Yusuke Wadabefore adoption3a550d2

lines 267–290why, one step back
267
268 const res = await app.fetch(req, {269 event,270 requestContext,271 lambdaContext,272 })273274 return processor.createResult(event, res, { isContentTypeBinary })275 }276}277278export abstract class EventProcessor<E extends LambdaEvent> {279 protected abstract getPath(event: E): string280281 protected abstract getMethod(event: E): string282283 protected abstract getQueryString(event: E): string284285 protected abstract getHeaders(event: E): Headers286287 protected abstract getCookies(event: E, headers: Headers): void288289 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void290

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 291–317why, one step back
291 protected getHeaderValue(headers: E['headers'], key: string): string | undefined {
292 const value = headers293 ? Array.isArray(headers[key])294 ? headers[key][0]295 : headers[key]296 : undefined297298 return value299 }300301 protected getDomainName(event: E): string | undefined {302 if (event.requestContext && 'domainName' in event.requestContext) {303 return event.requestContext.domainName304 }305306 const hostFromHeaders = this.getHeaderValue(event.headers, 'host')307308 if (hostFromHeaders) {309 return hostFromHeaders310 }311312 const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}313 const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')314315 return hostFromMultiValueHeaders316 }317

4.10.4Yusuke Wadabefore adoption3a550d2

lines 318–319why, one step back
318 createRequest(event: E): Request {
319 const queryString = this.getQueryString(event)

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 320why, one step back
320 const domainName = this.getDomainName(event)

4.10.4Yusuke Wadabefore adoption3a550d2

lines 321–333why, one step back
321 const path = this.getPath(event)
322 const urlPath = `https://${domainName}${path}`323 const url = queryString ? `${urlPath}?${queryString}` : urlPath324325 const headers = this.getHeaders(event)326327 const method = this.getMethod(event)328 const requestInit: RequestInit = {329 headers,330 method,331 }332333 if (event.body) {

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 334–338why, one step back
334 const body = event.isBase64Encoded
335 ? decodeBase64(event.body)336 : new TextEncoder().encode(event.body)337 requestInit.body = body338 headers.set('content-length', body.length.toString())

4.10.4Yusuke Wadabefore adoption3a550d2

lines 339–364why, one step back
339 }
340341 return new Request(url, requestInit)342 }343344 async createResult(345 event: E,346 res: Response,347 options: Pick<HandleOptions, 'isContentTypeBinary'>348 ): Promise<APIGatewayProxyResult> {349 // determine whether the response body should be base64 encoded350 const contentType = res.headers.get('content-type')351 const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided352 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false353354 if (!isBase64Encoded) {355 const contentEncoding = res.headers.get('content-encoding')356 isBase64Encoded = isContentEncodingBinary(contentEncoding)357 }358359 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()360361 const result: APIGatewayProxyResult = {362 body: body,363 statusCode: res.status,364 isBase64Encoded,

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 365why, one step back
365 ...('multiValueHeaders' in event && event.multiValueHeaders

4.10.4Yusuke Wadabefore adoption3a550d2

lines 366–387why, one step back
366 ? {
367 multiValueHeaders: {},368 }369 : {370 headers: {},371 }),372 }373374 this.setCookies(event, res, result)375 if (result.multiValueHeaders) {376 res.headers.forEach((value, key) => {377 result.multiValueHeaders[key] = [value]378 })379 } else {380 res.headers.forEach((value, key) => {381 result.headers[key] = value382 })383 }384385 return result386 }387

chore(eslint): upgrade `@hono/eslint-config` (#4781)Jonathan Hainesbefore adoption5d59ac7

line 388why, one step back
388 setCookies(_event: E, res: Response, result: APIGatewayProxyResult) {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 389–442why, one step back
389 if (res.headers.has('set-cookie')) {
390 const cookies = res.headers.getSetCookie391 ? res.headers.getSetCookie()392 : Array.from(res.headers.entries())393 .filter(([k]) => k === 'set-cookie')394 .map(([, v]) => v)395396 if (Array.isArray(cookies)) {397 this.setCookiesToResult(result, cookies)398 res.headers.delete('set-cookie')399 }400 }401 }402}403404export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {405 protected getPath(event: APIGatewayProxyEventV2): string {406 return event.rawPath407 }408409 protected getMethod(event: APIGatewayProxyEventV2): string {410 return event.requestContext.http.method411 }412413 protected getQueryString(event: APIGatewayProxyEventV2): string {414 return event.rawQueryString415 }416417 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {418 if (Array.isArray(event.cookies)) {419 headers.set('Cookie', event.cookies.join('; '))420 }421 }422423 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {424 result.cookies = cookies425 }426427 protected getHeaders(event: APIGatewayProxyEventV2): Headers {428 const headers = new Headers()429 this.getCookies(event, headers)430 if (event.headers) {431 for (const [k, v] of Object.entries(event.headers)) {432 if (v) {433 headers.set(k, v)434 }435 }436 }437 return headers438 }439}440441const v2Processor: EventV2Processor = new EventV2Processor()442

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 443–444why, one step back
443export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {
444 protected getPath(event: APIGatewayProxyEvent): string {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 445–447why, one step back
445 return event.path
446 }447

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 448why, one step back
448 protected getMethod(event: APIGatewayProxyEvent): string {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 449–451why, one step back
449 return event.httpMethod
450 }451

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

line 452why, one step back
452 protected getQueryString(event: APIGatewayProxyEvent): string {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 453–469why, one step back
453 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both
454 // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL455 if (event.multiValueQueryStringParameters) {456 return Object.entries(event.multiValueQueryStringParameters || {})457 .filter(([, value]) => value)458 .map(([key, values]) =>459 values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')460 )461 .join('&')462 } else {463 return Object.entries(event.queryStringParameters || {})464 .filter(([, value]) => value)465 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)466 .join('&')467 }468 }469

chore(builld): tsconfig project references (#4797)Jonathan Hainesbefore adoptiond69deb8

line 470why, one step back
470 protected getCookies(_event: APIGatewayProxyEvent, _headers: Headers): void {

4.10.4Yusuke Wadabefore adoption3a550d2

lines 471–583why, one step back
471 // nop
472 }473474 protected getHeaders(event: APIGatewayProxyEvent): Headers {475 const headers = new Headers()476 this.getCookies(event, headers)477 if (event.headers) {478 for (const [k, v] of Object.entries(event.headers)) {479 if (v) {480 headers.set(k, sanitizeHeaderValue(v))481 }482 }483 }484 if (event.multiValueHeaders) {485 for (const [k, values] of Object.entries(event.multiValueHeaders)) {486 if (values) {487 // avoid duplicating already set headers488 const foundK = headers.get(k)489 values.forEach((v) => {490 const sanitizedValue = sanitizeHeaderValue(v)491 return (492 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)493 )494 })495 }496 }497 }498 return headers499 }500501 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {502 result.multiValueHeaders = {503 'set-cookie': cookies,504 }505 }506}507508const v1Processor: EventV1Processor = new EventV1Processor()509510export class ALBProcessor extends EventProcessor<ALBProxyEvent> {511 protected getHeaders(event: ALBProxyEvent): Headers {512 const headers = new Headers()513 // if multiValueHeaders is present the ALB will use it instead of the headers field514 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers515 if (event.multiValueHeaders) {516 for (const [key, values] of Object.entries(event.multiValueHeaders)) {517 if (values && Array.isArray(values)) {518 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f519 const sanitizedValue = sanitizeHeaderValue(values.join('; '))520 headers.set(key, sanitizedValue)521 }522 }523 } else {524 for (const [key, value] of Object.entries(event.headers ?? {})) {525 if (value) {526 headers.set(key, sanitizeHeaderValue(value))527 }528 }529 }530 return headers531 }532533 protected getPath(event: ALBProxyEvent): string {534 return event.path535 }536537 protected getMethod(event: ALBProxyEvent): string {538 return event.httpMethod539 }540541 protected getQueryString(event: ALBProxyEvent): string {542 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both543 /*544 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:545 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency546 {547 ...548 queryStringParameters: { select: 'currency' },549 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },550 }551 The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.552 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.553 */554 if (event.multiValueQueryStringParameters) {555 return Object.entries(event.multiValueQueryStringParameters || {})556 .filter(([, value]) => value)557 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)558 .join('&')559 } else {560 return Object.entries(event.queryStringParameters || {})561 .filter(([, value]) => value)562 .map(([key, value]) => `${key}=${value}`)563 .join('&')564 }565 }566567 protected getCookies(event: ALBProxyEvent, headers: Headers): void {568 let cookie569 if (event.multiValueHeaders) {570 cookie = event.multiValueHeaders['cookie']?.join('; ')571 } else {572 cookie = event.headers ? event.headers['cookie'] : undefined573 }574 if (cookie) {575 headers.append('Cookie', cookie)576 }577 }578579 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {580 // when multi value headers is enabled581 if (result.multiValueHeaders) {582 result.multiValueHeaders['set-cookie'] = cookies583 } else {

Merge commit from forkYusuke Wadabefore adoption7ae7cba

line 584why, one step back
584 result.headers['set-cookie'] = cookies[0]

4.10.4Yusuke Wadabefore adoption3a550d2

lines 585–590why, one step back
585 }
586 }587}588589const albProcessor: ALBProcessor = new ALBProcessor()590

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 591–631why, one step back
591export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {
592 protected getPath(event: LatticeProxyEventV2): string {593 return event.path594 }595596 protected getMethod(event: LatticeProxyEventV2): string {597 return event.method598 }599600 protected getQueryString(): string {601 return ''602 }603604 protected getHeaders(event: LatticeProxyEventV2): Headers {605 const headers = new Headers()606607 if (event.headers) {608 for (const [k, values] of Object.entries(event.headers)) {609 if (values) {610 // avoid duplicating already set headers611 const foundK = headers.get(k)612 values.forEach((v) => {613 const sanitizedValue = sanitizeHeaderValue(v)614 return (615 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)616 )617 })618 }619 }620 }621622 return headers623 }624625 protected getCookies(): void {626 // nop627 }628629 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {630 result.headers = {631 ...result.headers,

Merge commit from forkYusuke Wadabefore adoption7ae7cba

line 632why, one step back
632 'set-cookie': cookies,

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 633–638why, one step back
633 }
634 }635}636637const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()638

4.10.4Yusuke Wadabefore adoption3a550d2

lines 639–645why, one step back
639export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {
640 if (isProxyEventALB(event)) {641 return albProcessor642 }643 if (isProxyEventV2(event)) {644 return v2Processor645 }

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 646–649why, one step back
646 if (isLatticeEventV2(event)) {
647 return latticeV2Processor648 }649

4.10.4Yusuke Wadabefore adoption3a550d2

lines 650–661why, one step back
650 return v1Processor
651}652653const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {654 if (event.requestContext) {655 return Object.hasOwn(event.requestContext, 'elb')656 }657 return false658}659660const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {661 return Object.hasOwn(event, 'rawPath')

feat(aws-lambda): handle AWS Lattice events (#4451)Andreas Hbefore adoptioncea3fb0

lines 662–668why, one step back
662}
663664const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {665 if (event.requestContext) {666 return Object.hasOwn(event.requestContext, 'serviceArn')667 }668 return false

4.10.4Yusuke Wadabefore adoption3a550d2

lines 669–688why, one step back
669}
670671/**672 * Check if the given content type is binary.673 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().674 * @param contentType The content type to check.675 * @returns True if the content type is binary, false otherwise.676 */677export const defaultIsContentTypeBinary = (contentType: string): boolean => {678 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/.test(679 contentType680 )681}682683export const isContentEncodingBinary = (contentEncoding: string | null) => {684 if (contentEncoding === null) {685 return false686 }687 return /^(gzip|deflate|compress|br)/.test(contentEncoding)688}