Skip to content
Myr

handler.ts

This file

Path

src/adapter/lambda-edge/handler.ts

263 lines · 7.5 KiB · TypeScript

Last changed by

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

History of this file

Take it

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

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–39why, one step back
1import crypto from 'node:crypto'
2import type { Hono } from '../../hono'3import { decodeBase64, encodeBase64 } from '../../utils/encode'45// eslint-disable-next-line @typescript-eslint/ban-ts-comment6// @ts-ignore7globalThis.crypto ??= crypto89interface CloudFrontHeader {10 key: string11 value: string12}1314interface CloudFrontHeaders {15 [name: string]: CloudFrontHeader[]16}1718interface CloudFrontCustomOrigin {19 customHeaders: CloudFrontHeaders20 domainName: string21 keepaliveTimeout: number22 path: string23 port: number24 protocol: string25 readTimeout: number26 sslProtocols: string[]27}28// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html29interface CloudFrontS3Origin {30 authMethod: 'origin-access-identity' | 'none'31 customHeaders: CloudFrontHeaders32 domainName: string33 path: string34 region: string35}36type CloudFrontOrigin =37 | { s3: CloudFrontS3Origin; custom?: never }38 | { custom: CloudFrontCustomOrigin; s3?: never }39

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 40–42why, one step back
40/**
41 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.42 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 43–57why, one step back
43export interface CloudFrontRequest {
44 clientIp: string45 headers: CloudFrontHeaders46 method: string47 querystring: string48 uri: string49 body?: {50 inputTruncated: boolean51 action: string52 encoding: string53 data: string54 }55 origin?: CloudFrontOrigin56}57

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 58–60why, one step back
58/**
59 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.60 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 61–66why, one step back
61export interface CloudFrontResponse {
62 headers: CloudFrontHeaders63 status: string64 statusDescription?: string65}66

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 67–69why, one step back
67/**
68 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.69 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 70–84why, one step back
70export interface CloudFrontConfig {
71 distributionDomainName: string72 distributionId: string73 eventType: string74 requestId: string75}7677interface CloudFrontEvent {78 cf: {79 config: CloudFrontConfig80 request: CloudFrontRequest81 response?: CloudFrontResponse82 }83}84

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 85–87why, one step back
85/**
86 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.87 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 88–93why, one step back
88export interface CloudFrontEdgeEvent {
89 Records: CloudFrontEvent[]90}9192type CloudFrontContext = {}93

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 94–96why, one step back
94/**
95 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.96 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 97–129why, one step back
97export interface Callback {
98 (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void99}100101// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-model102interface CloudFrontResult {103 status: string104 statusDescription?: string105 headers?: {106 [header: string]: {107 key: string108 value: string109 }[]110 }111 body?: string112 bodyEncoding?: 'text' | 'base64'113}114115/**116 * Accepts events from 'Lambda@Edge' event117 * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html118 */119const convertHeaders = (headers: Headers): CloudFrontHeaders => {120 const cfHeaders: CloudFrontHeaders = {}121 headers.forEach((value, key) => {122 cfHeaders[key.toLowerCase()] = [123 ...(cfHeaders[key.toLowerCase()] || []),124 { key: key.toLowerCase(), value },125 ]126 })127 return cfHeaders128}129

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 130–132why, one step back
130/**
131 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.132 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 133–139why, one step back
133export const handle = (
134 // eslint-disable-next-line @typescript-eslint/no-explicit-any135 app: Hono<any>136): ((137 event: CloudFrontEdgeEvent,138 context?: CloudFrontContext,139 callback?: Callback

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

line 140why, one step back
140) => Promise<CloudFrontResult | CloudFrontRequest>) => {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 141–142why, one step back
141 return async (event, ...args: [context?: CloudFrontContext, callback?: Callback]) => {
142 const [context, callback] = args

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 143–144why, one step back
143 let callbackError: Error | null = null
144 let callbackResult: CloudFrontResult | CloudFrontRequest | undefined

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 145–146why, one step back
145 const cf = getCloudFrontRecord(event)
146 const res = await app.fetch(createRequest(cf), {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 147–149why, one step back
147 event,
148 context,149 callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 150–153why, one step back
150 if (!callbackError && !callbackResult) {
151 callbackError = err152 callbackResult = result153 }

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 154–155why, one step back
154 callback?.(err, result)
155 },

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 156–158why, one step back
156 config: cf.config,
157 request: cf.request,158 response: cf.response,

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 159why, one step back
159 })

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 160–163why, one step back
160 if (callbackError) {
161 throw callbackError162 }163 return callbackResult ?? createResult(res)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 164–167why, one step back
164 }
165}166167const createResult = async (res: Response): Promise<CloudFrontResult> => {

fix(lambda-edge): base64 encode content-encoded response bodies (#5099)Yusuke Wadabefore adoption6217f4b

lines 168–171why, one step back
168 const contentEncoding = res.headers.get('content-encoding')
169 const isBase64Encoded =170 isContentTypeBinary(res.headers.get('content-type') || '') ||171 (!!contentEncoding && !/^identity$/i.test(contentEncoding))

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 172–181why, one step back
172 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
173174 return {175 status: res.status.toString(),176 headers: convertHeaders(res.headers),177 body,178 ...(isBase64Encoded && { bodyEncoding: 'base64' }),179 }180}181

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 182–204why, one step back
182/**
183 * Reads the CloudFront record out of a Lambda@Edge event.184 *185 * The event is supplied by the runtime, so a malformed one means the function186 * was invoked with something other than a Lambda@Edge event. Fail with a187 * message naming the adapter and the missing field, rather than letting an188 * unattributable property access error escape.189 */190const getCloudFrontRecord = (event: CloudFrontEdgeEvent): CloudFrontEvent['cf'] => {191 const cf = event?.Records?.[0]?.cf192 if (!cf?.request) {193 throw new TypeError(194 'Unable to map the CloudFront event to a Request: expected `Records[0].cf.request` in the Lambda@Edge event.'195 )196 }197 return cf198}199200const createRequest = (cf: CloudFrontEvent['cf']): Request => {201 const request = cf.request202 const queryString = request.querystring203 const host = request.headers?.host?.[0]?.value || cf.config?.distributionDomainName204 const urlPath = `https://${host}${request.uri}`

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 205–207why, one step back
205 const url = queryString ? `${urlPath}?${queryString}` : urlPath
206207 const headers = new Headers()

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

line 208why, one step back
208 Object.entries(request.headers ?? {}).forEach(([k, v]) => {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 209–211why, one step back
209 v.forEach((header) => headers.append(k, header.value))
210 })211

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 212–213why, one step back
212 const requestBody = request.body
213 const method = request.method

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 214–217why, one step back
214 const rawBody = createBody(method, requestBody)
215216 let body: string | Uint8Array<ArrayBuffer> | undefined = rawBody217 if (rawBody !== undefined) {

fix(lambda-edge): satisfy Deno lib types for Content-Length body encoding (#5013)Yusuke Wadabefore adoptione50df01

lines 218–221why, one step back
218 const bytes =
219 typeof rawBody === 'string'220 ? (new TextEncoder().encode(rawBody) as Uint8Array<ArrayBuffer>)221 : rawBody

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 222–232why, one step back
222 body = bytes
223 headers.set('content-length', bytes.length.toString())224 }225226 return new Request(url, {227 headers,228 method,229 body,230 })231}232

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 233–235why, one step back
233/**
234 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.235 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 236–251why, one step back
236export const createBody = (
237 method: string,238 requestBody: CloudFrontRequest['body']239): string | Uint8Array<ArrayBuffer> | undefined => {240 if (!requestBody || !requestBody.data) {241 return undefined242 }243 if (method === 'GET' || method === 'HEAD') {244 return undefined245 }246 if (requestBody.encoding === 'base64') {247 return decodeBase64(requestBody.data)248 }249 return requestBody.data250}251

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 252–254why, one step back
252/**
253 * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.254 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 255why, one step back
255export const isContentTypeBinary = (contentType: string): boolean => {

fix(lambda-edge): sync content type detection with aws-lambda (#5426)sarybefore adoptionde310ac

lines 256–260why, one step back
256 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {
257 return true258 }259260 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 261–263why, one step back
261 contentType
262 )263}