Skip to content
Myr

test: move adapter runtime tests into `adapters/*` (#5466)

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

authored by Yusuke Wada · committed by GitHub · parent 1c6e060 · Browse files · 69 files+2885 added−2980 removed
This commit

State

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

Diff stats

69 files+2885 added−2980 removed

  • tests:+2848 added−2781 removed
  • other:+37 added−199 removed

69 files+2885 added−2980 removed

modified:.github/workflows/ci-adapters.yml+4 added
modified:.github/workflows/ci.yml-36 removed
201 unmodified lines
202 node-version-file: '.tool-versions'203 - run: pnpm run build204 - run: pnpm run test:workerd205206 lambda:207 name: 'AWS Lambda'208 runs-on: ubuntu-latest209 steps:210 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6211 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2212 with:213 bun-version-file: '.tool-versions'214 - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0215 with:216 cache: true217 run_install: true218 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6219 with:220 node-version-file: '.tool-versions'221 - run: pnpm run build222 - run: pnpm run test:lambda223224 lambda-edge:225 name: 'Lambda@Edge'226 runs-on: ubuntu-latest227 steps:228 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6229 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2230 with:231 bun-version-file: '.tool-versions'232 - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0233 with:234 cache: true235 run_install: true236 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6237 with:238 node-version-file: '.tool-versions'239 - run: pnpm run build240 - run: pnpm run test:lambda-edge241206 perf-measures-check-on-pr:207 name: 'Type & Bundle size Check on PR'208 runs-on: ubuntu-latest209 if: github.event_name == 'pull_request'
89 unmodified lines
added:adapters/aws-lambda/test/index.test.ts+1087 added
1import { Readable } from 'stream'2import { Hono } from 'hono'3import { basicAuth } from 'hono/basic-auth'4import { getCookie, setCookie } from 'hono/cookie'5import { streamSSE, streamText } from 'hono/streaming'6import {7 ALBProcessor,8 EventV1Processor,9 EventV2Processor,10 getProcessor,11 handle,12 streamHandle,13} from '../src/handler'14import type {15 ALBProxyEvent,16 APIGatewayProxyEventV2,17 LatticeProxyEventV2,18 LambdaEvent,19} from '../src/handler'20import type {21 ApiGatewayRequestContext,22 ApiGatewayRequestContextV2,23 LatticeRequestContextV2,24 LambdaContext,25} from '../src/types'26import './mock'2728type Bindings = {29 event: LambdaEvent30 lambdaContext: LambdaContext31 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV232}3334const testApiGatewayRequestContextV2 = {35 accountId: '123456789012',36 apiId: 'urlid',37 authentication: null,38 authorizer: {39 iam: {40 accessKey: 'AKIA...',41 accountId: '111122223333',42 callerId: 'AIDA...',43 cognitoIdentity: null,44 principalOrgId: null,45 userArn: 'arn:aws:iam::111122223333:user/example-user',46 userId: 'AIDA...',47 },48 },49 domainName: 'example.com',50 domainPrefix: '<url-id>',51 http: {52 method: 'POST',53 path: '/my/path',54 protocol: 'HTTP/1.1',55 sourceIp: '123.123.123.123',56 userAgent: 'agent',57 },58 requestId: 'id',59 routeKey: '$default',60 stage: '$default',61 time: '12/Mar/2020:19:03:58 +0000',62 timeEpoch: 1583348638390,63 customProperty: 'customValue',64}6566const testLatticeRequestContext: LatticeRequestContextV2 = {67 serviceNetworkArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:servicenetwork/sn-a1b2c3',68 serviceArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:service/svc-a1b2c3',69 targetGroupArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:targetgroup/tg-a1b2c3',70 region: 'us-east-1',71 timeEpoch: '1759915938150314',72 identity: {73 sourceVpcArn: 'arn:aws:ec2:us-east-1:111122223333:vpc/vpc-a1b2c3',74 },75}7677describe('AWS Lambda Adapter for Hono', () => {78 const app = new Hono<{ Bindings: Bindings }>()7980 app.get('/', (c) => {81 return c.text('Hello Lambda!')82 })8384 app.get('/binary', (c) => {85 return c.body('Fake Image', 200, {86 'Content-Type': 'image/png',87 })88 })8990 app.post('/post', async (c) => {91 const body = (await c.req.parseBody()) as { message: string }92 return c.text(body.message)93 })9495 app.post('/post/binary', async (c) => {96 const body = await c.req.blob()97 return c.text(`${body.size} bytes`)98 })99100 const username = 'hono-user-a'101 const password = 'hono-password-a'102 app.use('/auth/*', basicAuth({ username, password }))103 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))104105 app.get('/lambda-event', (c) => {106 const event = c.env.event107 return c.json(event)108 })109110 app.get('/lambda-context', (c) => {111 const fnctx = c.env.lambdaContext112 return c.json(fnctx)113 })114115 app.get('/custom-context/v1/apigw', (c) => {116 const lambdaContext = c.env.requestContext117 return c.json(lambdaContext)118 })119120 app.get('/custom-context/apigw', (c) => {121 const lambdaContext = c.env.event.requestContext122 return c.json(lambdaContext)123 })124125 app.get('/custom-context/v1/lambda', (c) => {126 const lambdaContext = c.env.requestContext127 return c.json(lambdaContext)128 })129130 app.get('/custom-context/lambda', (c) => {131 const lambdaContext = c.env.event.requestContext132 return c.json(lambdaContext)133 })134135 app.get('/query-params', (c) => {136 const queryParams = c.req.query()137 return c.json(queryParams)138 })139140 app.get('/multi-query-params', (c) => {141 const multiQueryParams = c.req.queries()142 return c.json(multiQueryParams)143 })144145 const testCookie1 = {146 key: 'id',147 value: crypto.randomUUID(),148 get serialized() {149 return `${this.key}=${this.value}; Path=/`150 },151 }152 const testCookie2 = {153 key: 'secret',154 value: crypto.randomUUID(),155 get serialized() {156 return `${this.key}=${this.value}; Path=/`157 },158 }159160 app.post('/cookie', (c) => {161 setCookie(c, testCookie1.key, testCookie1.value)162 setCookie(c, testCookie2.key, testCookie2.value)163 return c.text('Cookies Set')164 })165166 app.get('/cookie', (c) => {167 const validCookies =168 getCookie(c, testCookie1.key) === testCookie1.value &&169 getCookie(c, testCookie2.key) === testCookie2.value170 if (!validCookies) {171 return c.text('Invalid Cookies')172 }173 return c.text('Valid Cookies')174 })175176 app.post('/headers', (c) => {177 if (c.req.header('foo')?.includes('bar')) {178 return c.json({ message: 'ok' })179 }180 return c.json({ message: 'fail' }, 400)181 })182183 const handler = handle(app)184185 const testApiGatewayRequestContext = {186 accountId: '123456789012',187 apiId: 'id',188 authorizer: {189 claims: null,190 scopes: null,191 },192 domainName: 'example.com',193 domainPrefix: 'id',194 extendedRequestId: 'request-id',195 httpMethod: 'GET',196 identity: {197 sourceIp: 'IP',198 userAgent: 'user-agent',199 },200 path: '/my/path',201 protocol: 'HTTP/1.1',202 requestId: 'id=',203 requestTime: '04/Mar/2020:19:15:17 +0000',204 requestTimeEpoch: 1583349317135,205 resourcePath: '/',206 stage: '$default',207 customProperty: 'customValue',208 }209210 const testALBRequestContext = {211 elb: {212 targetGroupArn:213 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',214 },215 }216217 it('Should handle a GET request and return a 200 response', async () => {218 const event = {219 version: '1.0',220 resource: '/',221 httpMethod: 'GET',222 headers: { 'content-type': 'text/plain' },223 path: '/',224 body: null,225 isBase64Encoded: false,226 requestContext: testApiGatewayRequestContext,227 }228229 const response = await handler(event)230 expect(response.statusCode).toBe(200)231 expect(response.body).toBe('Hello Lambda!')232 expect(response.headers['content-type']).toMatch(/^text\/plain/)233 expect(response.multiValueHeaders).toBeUndefined()234 expect(response.isBase64Encoded).toBe(false)235 })236237 it('Should handle a GET request and return a 200 response with binary', async () => {238 const event = {239 version: '1.0',240 resource: '/binary',241 httpMethod: 'GET',242 headers: {},243 path: '/binary',244 body: null,245 isBase64Encoded: false,246 requestContext: testApiGatewayRequestContext,247 }248249 const response = await handler(event)250 expect(response.statusCode).toBe(200)251 expect(response.body).toBe('RmFrZSBJbWFnZQ==')252 expect(response.headers['content-type']).toMatch(/^image\/png/)253 expect(response.multiValueHeaders).toBeUndefined()254 expect(response.isBase64Encoded).toBe(true)255 })256257 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {258 const event = {259 version: '2.0',260 routeKey: '$default',261 headers: { 'content-type': 'text/plain' },262 rawPath: '/',263 rawQueryString: '',264 body: null,265 isBase64Encoded: false,266 requestContext: testApiGatewayRequestContextV2,267 }268269 testApiGatewayRequestContextV2.http.method = 'GET'270271 const response = await handler(event)272 expect(response.statusCode).toBe(200)273 expect(response.body).toBe('Hello Lambda!')274 expect(response.headers['content-type']).toMatch(/^text\/plain/)275 expect(response.multiValueHeaders).toBeUndefined()276 expect(response.isBase64Encoded).toBe(false)277 })278279 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {280 const event = {281 headers: { 'content-type': 'text/plain' },282 httpMethod: 'GET',283 path: '/',284 queryStringParameters: {285 query: '1234ABCD',286 },287 body: null,288 isBase64Encoded: false,289 requestContext: testALBRequestContext,290 }291292 const response = await handler(event)293 expect(response.statusCode).toBe(200)294 expect(response.body).toBe('Hello Lambda!')295 expect(response.headers['content-type']).toMatch(/^text\/plain/)296 expect(response.multiValueHeaders).toBeUndefined()297 expect(response.isBase64Encoded).toBe(false)298 })299300 it('Should handle a GET request and return a 200 response (LatticeProxyEvent)', async () => {301 const event: LatticeProxyEventV2 = {302 version: '2.0',303 path: '/?query=1234ABCD',304 method: 'GET',305 headers: { 'content-type': ['text/plain'] },306 queryStringParameters: {},307 body: null,308 isBase64Encoded: false,309 requestContext: testLatticeRequestContext,310 }311312 const response = await handler(event)313 expect(response.statusCode).toBe(200)314 expect(response.body).toBe('Hello Lambda!')315 expect(response.headers['content-type']).toMatch(/^text\/plain/)316 expect(response.multiValueHeaders).toBeUndefined()317 expect(response.isBase64Encoded).toBe(false)318 })319320 it('Should handle a GET request and return a 404 response', async () => {321 const event = {322 version: '1.0',323 resource: '/nothing',324 httpMethod: 'GET',325 headers: { 'content-type': 'text/plain' },326 path: '/nothing',327 body: null,328 isBase64Encoded: false,329 requestContext: testApiGatewayRequestContext,330 }331332 const response = await handler(event)333 expect(response.statusCode).toBe(404)334 })335336 it('Should handle a POST request and return a 200 response', async () => {337 const searchParam = new URLSearchParams()338 searchParam.append('message', 'Good Morning Lambda!')339 const event = {340 version: '1.0',341 resource: '/post',342 httpMethod: 'POST',343 headers: {344 'Content-Type': 'application/x-www-form-urlencoded',345 },346 path: '/post',347 body: Buffer.from(searchParam.toString()).toString('base64'),348 isBase64Encoded: true,349 requestContext: testApiGatewayRequestContext,350 }351352 const response = await handler(event)353 expect(response.statusCode).toBe(200)354 expect(response.body).toBe('Good Morning Lambda!')355 })356357 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {358 const searchParam = new URLSearchParams()359 searchParam.append('message', 'Good Morning Lambda!')360 const event = {361 version: '2.0',362 routeKey: '$default',363 headers: {364 'Content-Type': 'application/x-www-form-urlencoded',365 },366 rawPath: '/post',367 rawQueryString: '',368 body: Buffer.from(searchParam.toString()).toString('base64'),369 isBase64Encoded: true,370 requestContext: testApiGatewayRequestContextV2,371 }372373 testApiGatewayRequestContextV2.http.method = 'POST'374375 const response = await handler(event)376 expect(response.statusCode).toBe(200)377 expect(response.body).toBe('Good Morning Lambda!')378 })379380 it('Should handle a POST request with binary and return a 200 response', async () => {381 const array = new Uint8Array([0xc0, 0xff, 0xee])382 const buffer = Buffer.from(array)383 const event = {384 version: '1.0',385 resource: '/post/binary',386 httpMethod: 'POST',387 headers: {388 'Content-Type': 'application/x-www-form-urlencoded',389 },390 path: '/post/binary',391 body: buffer.toString('base64'),392 isBase64Encoded: true,393 requestContext: testApiGatewayRequestContext,394 }395396 const response = await handler(event)397 expect(response.statusCode).toBe(200)398 expect(response.body).toBe('3 bytes')399 })400401 it('Should handle a request and return a 401 response with Basic auth', async () => {402 const event = {403 version: '1.0',404 resource: '/auth/abc',405 httpMethod: 'GET',406 headers: {407 'Content-Type': 'plain/text',408 },409 path: '/auth/abc',410 body: null,411 isBase64Encoded: true,412 requestContext: testApiGatewayRequestContext,413 }414415 const response = await handler(event)416 expect(response.statusCode).toBe(401)417 })418419 it('Should handle a request and return a 200 response with Basic auth', async () => {420 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'421 const event = {422 version: '1.0',423 resource: '/auth/abc',424 httpMethod: 'GET',425 headers: {426 'Content-Type': 'plain/text',427 Authorization: `Basic ${credential}`,428 },429 path: '/auth/abc',430 body: null,431 isBase64Encoded: true,432 requestContext: testApiGatewayRequestContext,433 }434435 const response = await handler(event)436 expect(response.statusCode).toBe(200)437 expect(response.body).toBe('Good Night Lambda!')438 })439440 it('Should handle a GET request and return custom context', async () => {441 const event = {442 version: '1.0',443 resource: '/custom-context/apigw',444 httpMethod: 'GET',445 headers: { 'content-type': 'application/json' },446 path: '/custom-context/apigw',447 body: null,448 isBase64Encoded: false,449 requestContext: testApiGatewayRequestContext,450 }451452 const response = await handler(event)453 expect(response.statusCode).toBe(200)454 expect(JSON.parse(response.body).customProperty).toEqual('customValue')455 })456457 it('Should handle a GET request and context', async () => {458 const event = {459 version: '1.0',460 resource: '/lambda-context',461 httpMethod: 'GET',462 headers: { 'content-type': 'application/json' },463 path: '/lambda-context',464 body: null,465 isBase64Encoded: false,466 requestContext: testApiGatewayRequestContext,467 }468 const context: LambdaContext = {469 callbackWaitsForEmptyEventLoop: false,470 functionName: 'myLambdaFunction',471 functionVersion: '1.0.0',472 invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',473 memoryLimitInMB: '128',474 awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',475 logGroupName: '/aws/lambda/myLambdaFunction',476 logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',477 getRemainingTimeInMillis: () => {478 return 60000 // 60 seconds479 },480 }481 const response = await handler(event, context)482 expect(response.statusCode).toBe(200)483 expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)484 })485486 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {487 const apiGatewayEvent = {488 version: '1.0',489 resource: '/cookie',490 httpMethod: 'POST',491 headers: { 'content-type': 'text/plain' },492 path: '/cookie',493 body: null,494 isBase64Encoded: false,495 requestContext: testApiGatewayRequestContext,496 }497498 const apiGatewayResponse = await handler(apiGatewayEvent)499500 expect(apiGatewayResponse.statusCode).toBe(200)501 expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [502 testCookie1.serialized,503 testCookie2.serialized,504 ])505506 const apiGatewayEventV2 = {507 version: '2.0',508 routeKey: '$default',509 httpMethod: 'POST',510 headers: { 'content-type': 'text/plain' },511 rawPath: '/cookie',512 rawQueryString: '',513 body: null,514 isBase64Encoded: false,515 requestContext: testApiGatewayRequestContextV2,516 }517518 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)519520 expect(apiGatewayResponseV2.statusCode).toBe(200)521 expect(apiGatewayResponseV2).toHaveProperty('cookies', [522 testCookie1.serialized,523 testCookie2.serialized,524 ])525 })526527 it('Should handle a POST request and return a 200 response with cookies set (LatticeProxyEvent V2)', async () => {528 const latticeProxyEvent: LatticeProxyEventV2 = {529 version: '2.0',530 path: '/cookie',531 method: 'POST',532 headers: { 'content-type': ['text/plain'] },533 queryStringParameters: {},534 body: null,535 isBase64Encoded: false,536 requestContext: testLatticeRequestContext,537 }538539 const latticeResponse = await handler(latticeProxyEvent)540541 expect(latticeResponse.statusCode).toBe(200)542 expect(latticeResponse.headers).toHaveProperty('set-cookie', [543 testCookie1.serialized,544 testCookie2.serialized,545 ])546 })547548 describe('headers', () => {549 describe('single-value headers', () => {550 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551 const event = {552 body: '{}',553 httpMethod: 'POST',554 isBase64Encoded: false,555 path: '/headers',556 headers: {557 host: 'localhost',558 foo: 'bar',559 },560 requestContext: testALBRequestContext,561 }562 const albResponse = await handler(event)563 expect(albResponse.statusCode).toBe(200)564 expect(albResponse.headers).toEqual(565 expect.objectContaining({566 'content-type': 'application/json',567 })568 )569 expect(albResponse.multiValueHeaders).toBeUndefined()570 })571572 it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {573 const apigatewayProxyEvent = {574 version: '1.0',575 resource: '/headers',576 httpMethod: 'POST',577 headers: {578 host: 'localhost',579 foo: 'bar',580 },581 path: '/headers',582 body: null,583 isBase64Encoded: false,584 requestContext: testApiGatewayRequestContext,585 }586 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)587 expect(apiGatewayResponseV2.statusCode).toBe(200)588 })589590 it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {591 const apigatewayProxyV2Event = {592 version: '2.0',593 routeKey: '$default',594 headers: {595 host: 'localhost',596 foo: 'bar',597 },598 rawPath: '/headers',599 rawQueryString: '',600 requestContext: testApiGatewayRequestContextV2,601 resource: '/headers',602 body: null,603 isBase64Encoded: false,604 }605 const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)606 expect(apiGatewayResponseV2.statusCode).toBe(200)607 })608 })609610 describe('multi-value headers', () => {611 it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {612 const event = {613 body: '{}',614 httpMethod: 'POST',615 isBase64Encoded: false,616 path: '/headers',617 multiValueHeaders: {618 host: ['localhost'],619 foo: ['bar'],620 },621 requestContext: testALBRequestContext,622 }623 const albResponse = await handler(event)624 expect(albResponse.statusCode).toBe(200)625 expect(albResponse.multiValueHeaders).toBeDefined()626 expect(albResponse.multiValueHeaders).toEqual(627 expect.objectContaining({628 'content-type': ['application/json'],629 })630 )631 })632633 it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {634 const apigatewayProxyEvent = {635 version: '1.0',636 resource: '/headers',637 httpMethod: 'POST',638 headers: {},639 multiValueHeaders: {640 host: ['localhost'],641 foo: ['bar'],642 },643 path: '/headers',644 body: null,645 isBase64Encoded: false,646 requestContext: testApiGatewayRequestContext,647 }648 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649 expect(apiGatewayResponseV2.statusCode).toBe(200)650 })651652 it('Should extract multi-value headers and return 200 (LatticeProxyEvent)', async () => {653 const event: LatticeProxyEventV2 = {654 version: '2.0',655 path: '/headers',656 method: 'POST',657 headers: {658 host: ['localhost'],659 foo: ['bar'],660 },661 queryStringParameters: {},662 body: null,663 isBase64Encoded: false,664 requestContext: testLatticeRequestContext,665 }666667 const response = await handler(event)668669 expect(response.statusCode).toBe(200)670 })671 })672 })673674 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {675 const apiGatewayEvent = {676 version: '1.0',677 resource: '/cookie',678 httpMethod: 'GET',679 headers: {680 'content-type': 'text/plain',681 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),682 },683 path: '/cookie',684 body: null,685 isBase64Encoded: false,686 requestContext: testApiGatewayRequestContext,687 }688689 const apiGatewayResponse = await handler(apiGatewayEvent)690691 expect(apiGatewayResponse.statusCode).toBe(200)692 expect(apiGatewayResponse.body).toBe('Valid Cookies')693 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)694 expect(apiGatewayResponse.isBase64Encoded).toBe(false)695696 const apiGatewayEventV2 = {697 version: '2.0',698 routeKey: '$default',699 headers: { 'content-type': 'text/plain' },700 rawPath: '/cookie',701 cookies: [testCookie1.serialized, testCookie2.serialized],702 rawQueryString: '',703 body: null,704 isBase64Encoded: false,705 requestContext: testApiGatewayRequestContextV2,706 }707 testApiGatewayRequestContextV2.http.method = 'GET'708709 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)710711 expect(apiGatewayResponseV2.statusCode).toBe(200)712 expect(apiGatewayResponseV2.body).toBe('Valid Cookies')713 expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)714 expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)715 })716717 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {718 const albEventDefaultHeaders = {719 version: '1.0',720 resource: '/cookie',721 httpMethod: 'GET',722 headers: {723 'content-type': 'text/plain',724 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),725 },726 path: '/cookie',727 body: null,728 isBase64Encoded: false,729 requestContext: testALBRequestContext,730 }731732 const albResponse = await handler(albEventDefaultHeaders)733734 expect(albResponse.statusCode).toBe(200)735 expect(albResponse.body).toBe('Valid Cookies')736 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)737 expect(albResponse.multiValueHeaders).toBeUndefined()738 expect(albResponse.isBase64Encoded).toBe(false)739 })740741 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {742 const albEventMultiValueHeaders = {743 version: '1.0',744 resource: '/cookie',745 httpMethod: 'GET',746 multiValueHeaders: {747 'content-type': ['text/plain'],748 cookie: [testCookie1.serialized, testCookie2.serialized],749 },750 path: '/cookie',751 body: null,752 isBase64Encoded: false,753 requestContext: testALBRequestContext,754 }755756 const albResponse = await handler(albEventMultiValueHeaders)757758 expect(albResponse.statusCode).toBe(200)759 expect(albResponse.body).toBe('Valid Cookies')760 expect(albResponse.headers).toBeUndefined()761 expect(albResponse.multiValueHeaders['content-type']).toEqual([762 expect.stringMatching(/^text\/plain/),763 ])764 expect(albResponse.isBase64Encoded).toBe(false)765 })766767 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {768 const albEventDefaultHeaders = {769 version: '1.0',770 resource: '/cookie',771 httpMethod: 'POST',772 headers: {773 'content-type': 'text/plain',774 cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),775 },776 path: '/cookie',777 body: null,778 isBase64Encoded: false,779 requestContext: testALBRequestContext,780 }781782 const albResponse = await handler(albEventDefaultHeaders)783784 expect(albResponse.statusCode).toBe(200)785 expect(albResponse.body).toBe('Cookies Set')786 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)787 expect(albResponse.multiValueHeaders).toBeUndefined()788 expect(albResponse.headers['set-cookie']).toEqual(testCookie1.serialized)789 expect(albResponse.isBase64Encoded).toBe(false)790 })791792 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {793 const albEventDefaultHeaders = {794 version: '1.0',795 resource: '/cookie',796 httpMethod: 'POST',797 multiValueHeaders: {798 'content-type': ['text/plain'],799 cookie: [testCookie1.serialized, testCookie2.serialized],800 },801 path: '/cookie',802 body: null,803 isBase64Encoded: false,804 requestContext: testALBRequestContext,805 }806807 const albResponse = await handler(albEventDefaultHeaders)808809 expect(albResponse.statusCode).toBe(200)810 expect(albResponse.body).toBe('Cookies Set')811 expect(albResponse.headers).toBeUndefined()812 expect(albResponse.multiValueHeaders['set-cookie']).toEqual(813 expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])814 )815 expect(albResponse.isBase64Encoded).toBe(false)816 })817818 it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {819 const albEventDefaultHeaders = {820 resource: '/query-params',821 httpMethod: 'GET',822 headers: {823 'content-type': 'application/json',824 },825 queryStringParameters: {826 key1: 'value1',827 key2: 'value2',828 },829 path: '/query-params',830 body: null,831 isBase64Encoded: false,832 requestContext: testALBRequestContext,833 }834835 const albResponse = await handler(albEventDefaultHeaders)836837 expect(albResponse.statusCode).toBe(200)838 expect(albResponse.body).toContain(839 JSON.stringify({840 key1: 'value1',841 key2: 'value2',842 })843 )844 expect(albResponse.headers['content-type']).toMatch(/^application\/json/)845 expect(albResponse.multiValueHeaders).toBeUndefined()846 expect(albResponse.isBase64Encoded).toBe(false)847 })848849 it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {850 const albEventDefaultHeaders = {851 resource: '/query-params',852 httpMethod: 'GET',853 multiValueHeaders: {854 'content-type': ['application/json'],855 },856 multiValueQueryStringParameters: {857 key1: ['value1'],858 key2: ['value2'],859 },860 path: '/query-params',861 body: null,862 isBase64Encoded: false,863 requestContext: testALBRequestContext,864 }865866 const albResponse = await handler(albEventDefaultHeaders)867868 expect(albResponse.statusCode).toBe(200)869 expect(albResponse.body).toContain(870 JSON.stringify({871 key1: 'value1',872 key2: 'value2',873 })874 )875 expect(albResponse.headers).toBeUndefined()876 expect(albResponse.multiValueHeaders['content-type']).toEqual([877 expect.stringMatching(/^application\/json/),878 ])879 expect(albResponse.isBase64Encoded).toBe(false)880 })881882 it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {883 const albEventDefaultHeaders = {884 resource: '/query-params',885 httpMethod: 'GET',886 multiValueHeaders: {887 'content-type': ['application/json'],888 },889 multiValueQueryStringParameters: {890 key1: ['value1'],891 key2: ['value2', 'otherValue2'],892 },893 path: '/multi-query-params',894 body: null,895 isBase64Encoded: false,896 requestContext: testALBRequestContext,897 }898899 const albResponse = await handler(albEventDefaultHeaders)900901 expect(albResponse.statusCode).toBe(200)902 expect(albResponse.body).toContain(903 JSON.stringify({904 key1: ['value1'],905 key2: ['value2', 'otherValue2'],906 })907 )908 expect(albResponse.headers).toBeUndefined()909 expect(albResponse.multiValueHeaders['content-type']).toEqual([910 expect.stringMatching(/^application\/json/),911 ])912 expect(albResponse.isBase64Encoded).toBe(false)913 })914})915916describe('streamHandle function', () => {917 const app = new Hono<{ Bindings: Bindings }>()918919 app.get('/', (c) => {920 return c.text('Hello Lambda!')921 })922923 app.get('/stream/text', async (c) => {924 return streamText(c, async (stream) => {925 for (let i = 0; i < 3; i++) {926 await stream.writeln(`${i}`)927 await stream.sleep(1)928 }929 })930 })931932 app.get('/sse', async (c) => {933 return streamSSE(c, async (stream) => {934 let id = 0935 const maxIterations = 2936937 while (id < maxIterations) {938 const message = `Message\nIt is ${id}`939 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })940 await stream.sleep(10)941 }942 })943 })944945 const handler = streamHandle(app)946947 it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {948 const event = {949 headers: { 'content-type': ' binary/octet-stream' },950 rawPath: '/stream/text',951 rawQueryString: '',952 body: null,953 isBase64Encoded: false,954 requestContext: testApiGatewayRequestContextV2,955 }956957 testApiGatewayRequestContextV2.http.method = 'GET'958959 const mockReadableStream = new Readable({960 // eslint-disable-next-line @typescript-eslint/no-empty-function961 read() {},962 })963964 mockReadableStream.push('0\n')965 mockReadableStream.push('1\n')966 mockReadableStream.push('2\n')967 mockReadableStream.push('3\n')968 mockReadableStream.push(null) // EOF969970 // @ts-expect-error should this be a ReadbleStream?971 await handler(event, mockReadableStream, vi.fn())972973 const chunks = []974 for await (const chunk of mockReadableStream) {975 chunks.push(chunk)976 }977 expect(chunks.join('')).toContain('0\n1\n2\n3\n')978 })979980 it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {981 const event = {982 headers: { 'content-type': 'text/event-stream' },983 rawPath: '/sse',984 rawQueryString: '',985 body: null,986 isBase64Encoded: false,987 requestContext: testApiGatewayRequestContextV2,988 }989990 testApiGatewayRequestContextV2.http.method = 'GET'991992 const mockReadableStream = new Readable({993 // eslint-disable-next-line @typescript-eslint/no-empty-function994 read() {},995 })996997 const initContentType = {998 'Content-Type': 'application/vnd.awslambda.http-integration-response',999 }1000 mockReadableStream.push(JSON.stringify(initContentType))10011002 // Send JSON formatted response headers, followed by 8 NULL characters as a separator1003 const httpResponseMetadata = {1004 statusCode: 200,1005 headers: { 'Custom-Header': 'value' },1006 cookies: ['session=abcd1234'],1007 }1008 const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()1009 mockReadableStream.push(jsonResponsePrelude)10101011 mockReadableStream.push('data: Message\ndata: It is 0\n\n')1012 mockReadableStream.push('data: Message\ndata: It is 1\n\n')1013 mockReadableStream.push(null) // EOF10141015 // @ts-expect-error should this be a ReadbleStream?1016 await handler(event, mockReadableStream, vi.fn())10171018 const chunks = []1019 for await (const chunk of mockReadableStream) {1020 chunks.push(chunk)1021 }10221023 // If you have chunks, you might want to convert them to strings before checking1024 const output = Buffer.concat(chunks).toString()1025 expect(output).toContain('data: Message\ndata: It is 0\n\n')1026 expect(output).toContain('data: Message\ndata: It is 1\n\n')10271028 // Assertions for the newly added header and prelude1029 expect(output).toContain('application/vnd.awslambda.http-integration-response')1030 expect(output).toContain('Custom-Header')1031 expect(output).toContain('session=abcd1234')10321033 // Check for JSON prelude and NULL sequence1034 const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'1035 expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))1036 })1037})10381039describe('getProcessor function', () => {1040 it('Should return ALBProcessor for an ALBProxyEvent event', () => {1041 const event: ALBProxyEvent = {1042 httpMethod: 'GET',1043 path: '/',1044 body: null,1045 isBase64Encoded: false,1046 requestContext: {1047 elb: {1048 targetGroupArn:1049 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',1050 },1051 },1052 }10531054 const processor = getProcessor(event)1055 expect(processor).toBeInstanceOf(ALBProcessor)1056 })10571058 it('Should return EventV1Processor for an event without requestContext', () => {1059 const event = {1060 httpMethod: 'GET',1061 path: '/',1062 body: null,1063 isBase64Encoded: false,1064 }10651066 // while LambdaEvent RequestContext property is mandatory, it can be absent when testing through invoke-api or AWS Console1067 // in such cases, a V1 processor should be returned1068 const processor = getProcessor(event as unknown as LambdaEvent)1069 expect(processor).toBeInstanceOf(EventV1Processor)1070 })10711072 it('Should return EventV2Processor for an APIGatewayProxyEventV2 event', () => {1073 const event: APIGatewayProxyEventV2 = {1074 version: '2.0',1075 routeKey: '$default',1076 headers: { 'content-type': 'text/plain' },1077 rawPath: '/',1078 rawQueryString: '',1079 body: null,1080 isBase64Encoded: false,1081 requestContext: testApiGatewayRequestContextV2,1082 }10831084 const processor = getProcessor(event)1085 expect(processor).toBeInstanceOf(EventV2Processor)1086 })1087})
added:adapters/aws-lambda/test/mock.ts+38 added
added:adapters/aws-lambda/test/stream-backpressure.test.ts+107 added
1import { Writable } from 'node:stream'2import { Hono } from 'hono'3import { streamHandle } from '../src/handler'4import type { LambdaContext } from '../src/types'56const awslambda = {7 streamifyResponse: <T>(handlerFunc: T): T => handlerFunc,8 HttpResponseStream: {9 from: (stream: Writable): Writable => stream,10 },11}1213vi.stubGlobal('awslambda', awslambda)1415type StreamingHandler = (16 event: unknown,17 responseStream: Writable,18 context: LambdaContext19) => Promise<void>2021const CHUNK_SIZE = 16 * 102422const CHUNK_COUNT = 1282324const event = {25 headers: {},26 rawPath: '/',27 rawQueryString: '',28 body: null,29 isBase64Encoded: false,30 requestContext: { http: { method: 'GET' } },31}3233describe('streamHandle backpressure', () => {34 it('should pace reads against the destination and resolve only once it has finished', async () => {35 let emittedChunks = 036 let writtenBytes = 037 let maxChunksAhead = 03839 const app = new Hono()40 app.get(41 '/',42 () =>43 new Response(44 new ReadableStream({45 pull(controller) {46 if (emittedChunks < CHUNK_COUNT) {47 emittedChunks++48 controller.enqueue(new Uint8Array(CHUNK_SIZE))49 } else {50 controller.close()51 }52 },53 })54 )55 )5657 const responseStream = new Writable({58 highWaterMark: CHUNK_SIZE,59 write(buffer: Buffer, _encoding, callback) {60 maxChunksAhead = Math.max(maxChunksAhead, emittedChunks - writtenBytes / CHUNK_SIZE)61 setImmediate(() => {62 writtenBytes += buffer.length63 callback()64 })65 },66 })6768 const handler = streamHandle(app) as unknown as StreamingHandler69 await handler(event, responseStream, {} as LambdaContext)7071 expect(writtenBytes).toBe(CHUNK_SIZE * CHUNK_COUNT)72 expect(responseStream.writableFinished).toBe(true)73 expect(maxChunksAhead).toBeLessThan(CHUNK_COUNT / 2)74 })7576 it('should report a body that errors mid-stream without rejecting', async () => {77 const app = new Hono()78 app.get(79 '/',80 () =>81 new Response(82 new ReadableStream({83 pull(controller) {84 controller.enqueue(new Uint8Array(CHUNK_SIZE))85 controller.error(new Error('body failed'))86 },87 })88 )89 )9091 const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})92 const responseStream = new Writable({93 write(_buffer, _encoding, callback) {94 setImmediate(callback)95 },96 })9798 const handler = streamHandle(app) as unknown as StreamingHandler99 await expect(handler(event, responseStream, {} as LambdaContext)).resolves.toBeUndefined()100101 expect(consoleError).toHaveBeenCalledWith(102 'Error processing request:',103 expect.objectContaining({ message: 'body failed' })104 )105 consoleError.mockRestore()106 })107})
added:adapters/aws-lambda/test/stream-mock.ts+41 added
added:adapters/aws-lambda/test/stream.test.ts+75 added
modified:adapters/aws-lambda/tsconfig.json+2 added-2 removed
added:adapters/bun/test/.static/plain.txt+1 added
1Bun!!
added:adapters/bun/test/static/hello.world/index.html+1 added
added:adapters/bun/test/static/helloworld/index.html+1 added
1Hi
added:adapters/bun/test/static/download+1 added
1download
added:adapters/bun/test/static/plain.txt+1 added
1Bun!
added:adapters/bun/test/static-absolute-root/plain.txt+1 added
1Bun!
added:adapters/bun/test/favicon.icobinary

A binary file, added.

added:adapters/bun/test/index.test.ts+150 added
1import { afterAll, beforeEach, describe, expect, it, mock } from 'bun:test'2import fs from 'node:fs/promises'3import path from 'node:path'4import { Hono } from 'hono'5import type { WSMessageReceive } from 'hono/ws'6import { createBunWebSocket, serveStatic, toSSG } from '../src/index'7import type { BunWebSocketData } from '../src/index'89describe('serveStatic', () => {10 const app = new Hono()11 const onNotFound = mock(() => {})12 app.all('/favicon.ico', serveStatic({ path: './test/favicon.ico' }))13 app.all('/favicon-notfound.ico', serveStatic({ path: './test/favicon-notfound.ico', onNotFound }))14 app.use('/favicon-notfound.ico', async (c, next) => {15 await next()16 c.header('X-Custom', 'Bun')17 })18 app.get(19 '/static/*',20 serveStatic({21 root: './test/',22 onNotFound,23 })24 )25 app.get(26 '/dot-static/*',27 serveStatic({28 root: './test/',29 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),30 })31 )32 app.all('/static-absolute-root/*', serveStatic({ root: path.dirname(__filename) }))3334 beforeEach(() => onNotFound.mockClear())3536 it('Should return static file correctly', async () => {37 const res = await app.request(new Request('http://localhost/favicon.ico'))38 await res.arrayBuffer()39 expect(res.status).toBe(200)40 expect(res.headers.get('Content-Type')).toBe('image/x-icon')41 })4243 it('Should return 404 response', async () => {44 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))45 expect(res.status).toBe(404)46 expect(res.headers.get('X-Custom')).toBe('Bun')47 expect(onNotFound).toHaveBeenCalledWith(48 process.platform === 'win32' ? 'test\\favicon-notfound.ico' : 'test/favicon-notfound.ico',49 expect.anything()50 )51 })5253 it('Should return 200 response - /static/plain.txt', async () => {54 const res = await app.request(new Request('http://localhost/static/plain.txt'))55 expect(res.status).toBe(200)56 expect(await res.text()).toMatch(/^Bun!(\r?\n)?$/)57 expect(onNotFound).not.toHaveBeenCalled()58 })5960 it('Should return 200 response - /static/download', async () => {61 const res = await app.request(new Request('http://localhost/static/download'))62 expect(res.status).toBe(200)63 expect(await res.text()).toMatch(/^download(\r?\n)?$/)64 expect(onNotFound).not.toHaveBeenCalled()65 })6667 it('Should return 200 response - /dot-static/plain.txt', async () => {68 const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))69 expect(res.status).toBe(200)70 expect(await res.text()).toMatch(/^Bun!!(\r?\n)?$/)71 })7273 it('Should return 200 response - /static/helloworld', async () => {74 const res = await app.request('http://localhost/static/helloworld')75 expect(res.status).toBe(200)76 expect(await res.text()).toMatch(/Hi\r?\n/)77 })7879 it('Should return 200 response - /static/hello.world', async () => {80 const res = await app.request('http://localhost/static/hello.world')81 expect(res.status).toBe(200)82 expect(await res.text()).toMatch(/Hi\r?\n/)83 })8485 it('Should return 200 response - /static-absolute-root/plain.txt', async () => {86 const res = await app.request('http://localhost/static-absolute-root/plain.txt')87 expect(res.status).toBe(200)88 expect(await res.text()).toMatch(/^Bun!(\r?\n)?$/)89 expect(onNotFound).not.toHaveBeenCalled()90 })91})9293describe('toSSG', () => {94 const dir = './test/.ssg-output'9596 afterAll(async () => {97 await fs.rm(dir, { recursive: true, force: true })98 })99100 it('Should generate static files for the routes', async () => {101 const app = new Hono()102 app.get('/', (c) => c.text('Hello, World!'))103 app.get('/about', (c) => c.text('About Page'))104 app.get('/about/some', (c) => c.text('About Page 2tier'))105 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))106 app.get('/bravo', (c) => c.html('Bravo Page'))107108 const result = await toSSG(app, { dir })109 expect(result.success).toBeTruthy()110 expect(result.error).toBeUndefined()111 expect(result.files).toBeDefined()112 expect(await fs.readFile(path.join(dir, 'index.txt'), 'utf8')).toBe('Hello, World!')113 })114})115116describe('createBunWebSocket', () => {117 const app = new Hono()118 const { websocket, upgradeWebSocket } = createBunWebSocket()119120 it('Should deliver messages to the handler', async () => {121 const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>122 app.get(123 '/ws',124 upgradeWebSocket(() => ({125 onMessage(evt) {126 resolve(evt.data)127 },128 }))129 )130 )131 const upgradedData = await new Promise<BunWebSocketData>((resolve) =>132 app.fetch(new Request('http://localhost/ws'), {133 upgrade: (_req: Request, data: { data: BunWebSocketData }) => {134 resolve(data.data)135 },136 })137 )138 const message = Math.random().toString()139 websocket.message(140 {141 close: () => undefined,142 readyState: 3,143 data: upgradedData,144 send: () => undefined,145 },146 message147 )148 expect(await receivedMessagePromise).toBe(message)149 })150})
modified:adapters/bun/tsconfig.json+7 added-3 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "module": "ES2020",5 "rootDir": "./src/",5 "outDir": "./dist/",7 "types": ["bun-types"],6 "types": [7 "bun-types"8 ],9 "noEmit": true10 },10 "include": ["src/**/*.ts"]11 "include": [12 "src/**/*.ts",13 "test/**/*.ts"14 ]15}
added:adapters/cloudflare-workers/test/websocket.test.ts+38 added
1import { unstable_dev } from 'wrangler'2import { WebSocket } from 'ws'34describe('upgradeWebSocket on workerd', () => {5 // worker.fetch does not support WebSocket:6 // https://github.com/cloudflare/workers-sdk/issues/4573#issuecomment-18504209737 it('Should echo a message over the WebSocket connection', async () => {8 const worker = await unstable_dev('./test/worker.ts', {9 compatibilityDate: '2026-07-01',10 experimental: { disableExperimentalWarning: true },11 })12 const ws = new WebSocket(`ws://${worker.address}:${worker.port}/ws`)1314 const openHandler = vi.fn()15 const messageHandler = vi.fn()16 const closeHandler = vi.fn()1718 await new Promise<void>((resolve) => {19 ws.addEventListener('open', () => {20 openHandler()21 ws.send('Hello')22 })23 ws.addEventListener('message', (event) => {24 messageHandler(event.data)25 ws.close()26 })27 ws.addEventListener('close', () => {28 closeHandler()29 resolve()30 })31 })32 await worker.stop()3334 expect(openHandler).toHaveBeenCalled()35 expect(messageHandler).toHaveBeenCalledWith('Hello')36 expect(closeHandler).toHaveBeenCalled()37 })38})
added:adapters/cloudflare-workers/test/worker.ts+15 added
1import { Hono } from 'hono'2import { upgradeWebSocket } from '../src/index'34const app = new Hono()56app.get(7 '/ws',8 upgradeWebSocket(() => ({9 onMessage(event, ws) {10 ws.send(event.data as string)11 },12 }))13)1415export default app
modified:adapters/cloudflare-workers/package.json+4 added-1 removed
30 unmodified lines
31 "engines": {32 "node": ">=16.9.0"33 },34 "devDependencies": {35 "hono": "workspace:*"35 "hono": "workspace:*",36 "wrangler": "4.107.0",37 "ws": "^8.21.0",38 "@types/ws": "^8.18.1"39 }40}
modified:adapters/cloudflare-workers/tsconfig.json+2 added-2 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "module": "ES2020",5 "rootDir": "./src/",5 "outDir": "./dist/",6 "types": [7 "node",8 "vitest/globals"9 ],10 "noEmit": true11 },12 "include": [14 "src/**/*.ts"13 "src/**/*.ts",14 "test/**/*.ts"15 ]16}
added:adapters/deno/test/.static/plain.txt+1 added
1Deno!!
added:adapters/deno/test/static/hello.world/index.html+1 added
1Hi
added:adapters/deno/test/static/helloworld/index.html+1 added
1Hi
added:adapters/deno/test/static/download+1 added
1download
added:adapters/deno/test/static/plain.txt+1 added
1Deno!
added:adapters/deno/test/static-absolute-root/plain.txt+1 added
1Deno!
added:adapters/deno/test/assert.ts+11 added
1export const assertEquals = (actual: unknown, expected: unknown): void => {2 if (actual !== expected) {3 throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`)4 }5}67export const assertMatch = (actual: string, expected: RegExp): void => {8 if (!expected.test(actual)) {9 throw new Error(`Expected ${JSON.stringify(actual)} to match ${expected}`)10 }11}
added:adapters/deno/test/deno.json+21 added
1{2 "compilerOptions": {3 "lib": [4 "deno.ns",5 "dom",6 "dom.iterable"7 ]8 },9 "unstable": [10 "sloppy-imports"11 ],12 "imports": {13 "hono": "../../../src/index.ts",14 "hono/types": "../../../src/types.ts",15 "hono/conninfo": "../../../src/helper/conninfo/index.ts",16 "hono/serve-static": "../../../src/middleware/serve-static/index.ts",17 "hono/ssg": "../../../src/helper/ssg/index.ts",18 "hono/ws": "../../../src/helper/websocket/index.ts"19 },20 "lock": false21}
added:adapters/deno/test/favicon.icobinary

A binary file, added.

added:adapters/deno/test/serve-static.test.ts+94 added
1import { Hono } from 'hono'2import { serveStatic } from '../src/index.ts'3import { assertEquals, assertMatch } from './assert.ts'45Deno.test('Serve Static middleware', async () => {6 const app = new Hono()7 let notFoundCalls = 08 const onNotFound = () => {9 notFoundCalls++10 }11 app.all('/favicon.ico', serveStatic({ path: './test/favicon.ico' }))12 app.all('/favicon-notfound.ico', serveStatic({ path: './test/favicon-notfound.ico', onNotFound }))13 app.use('/favicon-notfound.ico', async (c, next) => {14 await next()15 c.header('X-Custom', 'Deno')16 })1718 app.get(19 '/static/*',20 serveStatic({21 root: './test',22 onNotFound,23 })24 )2526 app.get(27 '/dot-static/*',28 serveStatic({29 root: './test',30 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),31 })32 )3334 app.get('/static-absolute-root/*', serveStatic({ root: new URL('.', import.meta.url).pathname }))3536 let res = await app.request('http://localhost/favicon.ico')37 assertEquals(res.status, 200)38 assertEquals(res.headers.get('Content-Type'), 'image/x-icon')39 await res.body?.cancel()4041 res = await app.request('http://localhost/favicon-notfound.ico')42 assertEquals(res.status, 404)43 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)44 assertEquals(res.headers.get('X-Custom'), 'Deno')45 assertEquals(notFoundCalls, 1)4647 res = await app.request('http://localhost/static/plain.txt')48 assertEquals(res.status, 200)49 assertMatch(await res.text(), /^Deno!(\r?\n)?$/)5051 res = await app.request('http://localhost/static/download')52 assertEquals(res.status, 200)53 assertMatch(await res.text(), /^download(\r?\n)?$/)5455 res = await app.request('http://localhost/dot-static/plain.txt')56 assertEquals(res.status, 200)57 assertMatch(await res.text(), /^Deno!!(\r?\n)?$/)58 assertEquals(notFoundCalls, 1)5960 res = await app.fetch({61 method: 'GET',62 url: 'http://localhost/static/%2e%2e/static/plain.txt',63 } as Request)64 assertEquals(res.status, 404)65 assertEquals(await res.text(), '404 Not Found')6667 res = await app.request('http://localhost/static/helloworld')68 assertEquals(res.status, 200)69 assertEquals(await res.text(), 'Hi\n')7071 res = await app.request('http://localhost/static/hello.world')72 assertEquals(res.status, 200)73 assertEquals(await res.text(), 'Hi\n')7475 res = await app.request('http://localhost/static-absolute-root/plain.txt')76 assertEquals(res.status, 200)77 assertMatch(await res.text(), /^Deno!(\r?\n)?$/)7879 res = await app.request('http://localhost/static')80 assertEquals(res.status, 404)81 assertEquals(await res.text(), '404 Not Found')8283 res = await app.request('http://localhost/static/dir')84 assertEquals(res.status, 404)85 assertEquals(await res.text(), '404 Not Found')8687 res = await app.request('http://localhost/static/helloworld/nested')88 assertEquals(res.status, 404)89 assertEquals(await res.text(), '404 Not Found')9091 res = await app.request('http://localhost/static/helloworld/../')92 assertEquals(res.status, 404)93 assertEquals(await res.text(), '404 Not Found')94})
added:adapters/deno/test/ssg.test.ts+23 added
1import { Hono } from 'hono'2import { toSSG } from '../src/index.ts'3import { assertEquals } from './assert.ts'45Deno.test('toSSG', async () => {6 const dir = './test/.ssg-output'7 const app = new Hono()8 app.get('/', (c) => c.text('Hello, World!'))9 app.get('/about', (c) => c.text('About Page'))10 app.get('/about/some', (c) => c.text('About Page 2tier'))11 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))12 app.get('/bravo', (c) => c.html('Bravo Page'))1314 try {15 const result = await toSSG(app, { dir })16 assertEquals(result.success, true)17 assertEquals(result.error, undefined)18 assertEquals(result.files !== undefined, true)19 assertEquals(await Deno.readTextFile(`${dir}/index.txt`), 'Hello, World!')20 } finally {21 await Deno.remove(dir, { recursive: true })22 }23})
modified:adapters/deno/package.json+2 added-1 removed
13 unmodified lines
14 }15 },16 "scripts": {17 "build": "rm -rf dist && vp pack && publint",18 "test": "tsc -p tsconfig.json && vp test --run"18 "test": "tsc -p tsconfig.json && vp test --run",19 "test:deno": "deno test --allow-read --allow-env --allow-write --allow-net -c test/deno.json test"20 },21 "license": "MIT",22 "repository": {23 "type": "git",
16 unmodified lines
modified:adapters/deno/vite.config.ts+2 added
9 unmodified lines
10 outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11 },12 test: {13 globals: true,14 // test/ holds Deno tests, run with `pnpm run test:deno`15 include: ['src/**/*.test.ts'],16 },17})
added:adapters/lambda-edge/test/index.test.ts+1134 added
1import { Hono } from 'hono'2import { basicAuth } from 'hono/basic-auth'3import type {4 Callback,5 CloudFrontConfig,6 CloudFrontRequest,7 CloudFrontResponse,8} from '../src/handler'9import { handle } from '../src/handler'1011type Bindings = {12 callback: Callback13 config: CloudFrontConfig14 request: CloudFrontRequest15 response: CloudFrontResponse16}1718describe('Lambda@Edge Adapter for Hono', () => {19 const app = new Hono<{ Bindings: Bindings }>()2021 app.get('/', (c) => {22 return c.text('Hello Lambda!')23 })2425 app.get('/binary', (c) => {26 return c.body('Fake Image', 200, {27 'Content-Type': 'image/png',28 })29 })3031 app.post('/post', async (c) => {32 const body = (await c.req.parseBody()) as { message: string }33 return c.text(body.message)34 })3536 app.get('/callback/request', async (c, next) => {37 await next()38 c.env.callback(null, c.env.request)39 })4041 app.get('/config/eventCheck', async (c, next) => {42 await next()43 if (c.env.config.eventType in ['viewer-request', 'origin-request']) {44 c.env.callback(null, c.env.request)45 } else {46 c.env.callback(null, c.env.response)47 }48 })4950 app.get('/callback/response', async (c, next) => {51 await next()52 c.env.callback(null, c.env.response)53 })5455 app.post('/post/binary', async (c) => {56 const body = await c.req.blob()57 return c.text(`${body.size} bytes`)58 })5960 const username = 'hono-user-a'61 const password = 'hono-password-a'62 app.use('/auth/*', basicAuth({ username, password }))63 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))6465 app.get('/header/add', async (c, next) => {66 c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [67 {68 key: 'Strict-Transport-Security',69 value: 'max-age=63072000; includeSubdomains; preload',70 },71 ]72 c.env.response.headers['X-Custom'.toLowerCase()] = [73 {74 key: 'X-Custom',75 value: 'Foo',76 },77 ]78 await next()79 c.env.callback(null, c.env.response)80 })8182 const handler = handle(app)8384 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {85 const event = {86 Records: [87 {88 cf: {89 config: {90 distributionDomainName: 'd111111abcdef8.cloudfront.net',91 distributionId: 'EDFDVBD6EXAMPLE',92 eventType: 'viewer-request',93 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',94 },95 request: {96 clientIp: '203.0.113.178',97 headers: {98 host: [99 {100 key: 'Host',101 value: 'd111111abcdef8.cloudfront.net',102 },103 ],104 'user-agent': [105 {106 key: 'User-Agent',107 value: 'curl/7.66.0',108 },109 ],110 accept: [111 {112 key: 'accept',113 value: '*/*',114 },115 ],116 },117 method: 'GET',118 querystring: '',119 uri: '/',120 },121 },122 },123 ],124 }125 const response = await handler(event)126 expect(response).toMatchObject({ status: '200' })127 expect(response.body).toBe('Hello Lambda!')128 if (response.headers && response.headers['content-type']) {129 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)130 } else {131 throw new Error("'content-type' header is missing in the response")132 }133 })134135 it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {136 const event = {137 Records: [138 {139 cf: {140 config: {141 distributionDomainName: 'd111111abcdef8.cloudfront.net',142 distributionId: 'EDFDVBD6EXAMPLE',143 eventType: 'origin-request',144 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',145 },146 request: {147 clientIp: '203.0.113.178',148 headers: {149 'x-forwarded-for': [150 {151 key: 'X-Forwarded-For',152 value: '203.0.113.178',153 },154 ],155 'user-agent': [156 {157 key: 'User-Agent',158 value: 'Amazon CloudFront',159 },160 ],161 via: [162 {163 key: 'Via',164 value: '2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)',165 },166 ],167 host: [168 {169 key: 'Host',170 value: 'example.org',171 },172 ],173 'cache-control': [174 {175 key: 'Cache-Control',176 value: 'no-cache',177 },178 ],179 },180 method: 'GET',181 origin: {182 custom: {183 customHeaders: {},184 domainName: 'example.org',185 keepaliveTimeout: 5,186 path: '',187 port: 443,188 protocol: 'https',189 readTimeout: 30,190 sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],191 },192 },193 querystring: '',194 uri: '/',195 },196 },197 },198 ],199 }200 const response = await handler(event)201 expect(response).toMatchObject({ status: '200' })202 expect(response.body).toBe('Hello Lambda!')203 if (response.headers && response.headers['content-type']) {204 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)205 } else {206 throw new Error("'content-type' header is missing in the response")207 }208 })209210 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {211 const event = {212 Records: [213 {214 cf: {215 config: {216 distributionDomainName: 'd111111abcdef8.cloudfront.net',217 distributionId: 'EDFDVBD6EXAMPLE',218 eventType: 'viewer-response',219 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',220 },221 request: {222 clientIp: '203.0.113.178',223 headers: {224 host: [225 {226 key: 'Host',227 value: 'd111111abcdef8.cloudfront.net',228 },229 ],230 'user-agent': [231 {232 key: 'User-Agent',233 value: 'curl/7.66.0',234 },235 ],236 accept: [237 {238 key: 'accept',239 value: '*/*',240 },241 ],242 },243 method: 'GET',244 querystring: '',245 uri: '/',246 },247 response: {248 headers: {249 'access-control-allow-credentials': [250 {251 key: 'Access-Control-Allow-Credentials',252 value: 'true',253 },254 ],255 'access-control-allow-origin': [256 {257 key: 'Access-Control-Allow-Origin',258 value: '*',259 },260 ],261 date: [262 {263 key: 'Date',264 value: 'Mon, 13 Jan 2020 20:14:56 GMT',265 },266 ],267 'referrer-policy': [268 {269 key: 'Referrer-Policy',270 value: 'no-referrer-when-downgrade',271 },272 ],273 server: [274 {275 key: 'Server',276 value: 'ExampleCustomOriginServer',277 },278 ],279 'x-content-type-options': [280 {281 key: 'X-Content-Type-Options',282 value: 'nosniff',283 },284 ],285 'x-frame-options': [286 {287 key: 'X-Frame-Options',288 value: 'DENY',289 },290 ],291 'x-xss-protection': [292 {293 key: 'X-XSS-Protection',294 value: '1; mode=block',295 },296 ],297 age: [298 {299 key: 'Age',300 value: '2402',301 },302 ],303 'content-type': [304 {305 key: 'Content-Type',306 value: 'text/html; charset=utf-8',307 },308 ],309 'content-length': [310 {311 key: 'Content-Length',312 value: '9593',313 },314 ],315 },316 status: '200',317 statusDescription: 'OK',318 },319 },320 },321 ],322 }323 const response = await handler(event)324 expect(response).toMatchObject({ status: '200' })325 expect(response.body).toBe('Hello Lambda!')326 if (response.headers && response.headers['content-type']) {327 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)328 } else {329 throw new Error("'content-type' header is missing in the response")330 }331 })332333 it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {334 const event = {335 Records: [336 {337 cf: {338 config: {339 distributionDomainName: 'd111111abcdef8.cloudfront.net',340 distributionId: 'EDFDVBD6EXAMPLE',341 eventType: 'origin-response',342 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',343 },344 request: {345 clientIp: '203.0.113.178',346 headers: {347 'x-forwarded-for': [348 {349 key: 'X-Forwarded-For',350 value: '203.0.113.178',351 },352 ],353 'user-agent': [354 {355 key: 'User-Agent',356 value: 'Amazon CloudFront',357 },358 ],359 via: [360 {361 key: 'Via',362 value: '2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)',363 },364 ],365 host: [366 {367 key: 'Host',368 value: 'example.org',369 },370 ],371 'cache-control': [372 {373 key: 'Cache-Control',374 value: 'no-cache',375 },376 ],377 },378 method: 'GET',379 origin: {380 custom: {381 customHeaders: {},382 domainName: 'example.org',383 keepaliveTimeout: 5,384 path: '',385 port: 443,386 protocol: 'https',387 readTimeout: 30,388 sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],389 },390 },391 querystring: '',392 uri: '/',393 },394 response: {395 headers: {396 'access-control-allow-credentials': [397 {398 key: 'Access-Control-Allow-Credentials',399 value: 'true',400 },401 ],402 'access-control-allow-origin': [403 {404 key: 'Access-Control-Allow-Origin',405 value: '*',406 },407 ],408 date: [409 {410 key: 'Date',411 value: 'Mon, 13 Jan 2020 20:12:38 GMT',412 },413 ],414 'referrer-policy': [415 {416 key: 'Referrer-Policy',417 value: 'no-referrer-when-downgrade',418 },419 ],420 server: [421 {422 key: 'Server',423 value: 'ExampleCustomOriginServer',424 },425 ],426 'x-content-type-options': [427 {428 key: 'X-Content-Type-Options',429 value: 'nosniff',430 },431 ],432 'x-frame-options': [433 {434 key: 'X-Frame-Options',435 value: 'DENY',436 },437 ],438 'x-xss-protection': [439 {440 key: 'X-XSS-Protection',441 value: '1; mode=block',442 },443 ],444 'content-type': [445 {446 key: 'Content-Type',447 value: 'text/html; charset=utf-8',448 },449 ],450 'content-length': [451 {452 key: 'Content-Length',453 value: '9593',454 },455 ],456 },457 status: '200',458 statusDescription: 'OK',459 },460 },461 },462 ],463 }464 const response = await handler(event)465 expect(response).toMatchObject({ status: '200' })466 expect(response.body).toBe('Hello Lambda!')467 if (response.headers && response.headers['content-type']) {468 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)469 } else {470 throw new Error("'content-type' header is missing in the response")471 }472 })473474 it('Should handle a GET request and return a 200 response with binary', async () => {475 const event = {476 Records: [477 {478 cf: {479 config: {480 distributionDomainName: 'example.com',481 distributionId: 'EXAMPLE123',482 eventType: 'viewer-request',483 requestId: 'exampleRequestId',484 },485 request: {486 clientIp: '123.123.123.123',487 headers: {488 host: [489 {490 key: 'Host',491 value: 'example.com',492 },493 ],494 },495 method: 'GET',496 querystring: '',497 uri: '/binary',498 },499 },500 },501 ],502 }503504 const response = await handler(event)505506 expect(response).toMatchObject({ status: '200' })507 expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded fake image508 if (response.headers && response.headers['content-type']) {509 expect(response.headers['content-type'][0].value).toMatch(/^image\/png/)510 } else {511 throw new Error("'content-type' header is missing in the response")512 }513 })514515 it('Should handle a GET request and return a 404 response', async () => {516 const event = {517 Records: [518 {519 cf: {520 config: {521 distributionDomainName: 'example.com',522 distributionId: 'EXAMPLE123',523 eventType: 'viewer-request',524 requestId: 'exampleRequestId',525 },526 request: {527 clientIp: '123.123.123.123',528 headers: {529 host: [530 {531 key: 'Host',532 value: 'example.com',533 },534 ],535 },536 method: 'GET',537 querystring: '',538 uri: '/nothing',539 },540 },541 },542 ],543 }544545 const response = await handler(event)546547 expect(response).toMatchObject({ status: '404' })548 })549550 it('Should handle a POST request and return a 200 response', async () => {551 const searchParam = new URLSearchParams()552 searchParam.append('message', 'Good Morning Lambda!')553554 const event = {555 Records: [556 {557 cf: {558 config: {559 distributionDomainName: 'example.com',560 distributionId: 'EXAMPLE123',561 eventType: 'viewer-request',562 requestId: 'exampleRequestId',563 },564 request: {565 clientIp: '123.123.123.123',566 headers: {567 host: [568 {569 key: 'Host',570 value: 'example.com',571 },572 ],573 'content-type': [574 {575 key: 'Content-Type',576 value: 'application/x-www-form-urlencoded',577 },578 ],579 },580 method: 'POST',581 querystring: '',582 uri: '/post',583 body: {584 inputTruncated: false,585 action: 'read-only',586 encoding: 'base64',587 data: Buffer.from(searchParam.toString()).toString('base64'),588 },589 },590 },591 },592 ],593 }594595 const response = await handler(event)596597 expect(response).toMatchObject({ status: '200' })598 expect(response.body).toBe('Good Morning Lambda!')599 })600601 it('Should handle a POST request with binary and return a 200 response', async () => {602 const array = new Uint8Array([0xc0, 0xff, 0xee])603 const buffer = Buffer.from(array)604 const event = {605 Records: [606 {607 cf: {608 config: {609 distributionDomainName: 'example.com',610 distributionId: 'EXAMPLE123',611 eventType: 'viewer-request',612 requestId: 'exampleRequestId',613 },614 request: {615 clientIp: '123.123.123.123',616 headers: {617 host: [618 {619 key: 'Host',620 value: 'example.com',621 },622 ],623 'content-type': [624 {625 key: 'Content-Type',626 value: 'application/x-www-form-urlencoded',627 },628 ],629 },630 method: 'POST',631 querystring: '',632 uri: '/post/binary',633 body: {634 inputTruncated: false,635 action: 'read-only',636 encoding: 'base64',637 data: buffer.toString('base64'),638 },639 },640 },641 },642 ],643 }644645 const response = await handler(event)646 expect(response).toMatchObject({ status: '200' })647 expect(response.body).toBe('3 bytes')648 })649650 it('Should handle a request and return a 401 response with Basic auth', async () => {651 const event = {652 Records: [653 {654 cf: {655 config: {656 distributionDomainName: 'example.com',657 distributionId: 'EXAMPLE123',658 eventType: 'viewer-request',659 requestId: 'exampleRequestId',660 },661 request: {662 clientIp: '123.123.123.123',663 headers: {664 host: [665 {666 key: 'Host',667 value: 'example.com',668 },669 ],670 'content-type': [671 {672 key: 'Content-Type',673 value: 'plain/text',674 },675 ],676 },677 method: 'GET',678 querystring: '',679 uri: '/auth/abc',680 },681 },682 },683 ],684 }685686 const response = await handler(event)687688 expect(response).toMatchObject({ status: '401' })689 })690691 it('Should handle a request and return a 401 response with Basic auth', async () => {692 const event = {693 Records: [694 {695 cf: {696 config: {697 distributionDomainName: 'example.com',698 distributionId: 'EXAMPLE123',699 eventType: 'viewer-request',700 requestId: 'exampleRequestId',701 },702 request: {703 clientIp: '123.123.123.123',704 headers: {705 host: [706 {707 key: 'Host',708 value: 'example.com',709 },710 ],711 'content-type': [712 {713 key: 'Content-Type',714 value: 'plain/text',715 },716 ],717 },718 method: 'GET',719 querystring: '',720 uri: '/auth/abc',721 },722 },723 },724 ],725 }726727 const response = await handler(event)728729 expect(response).toMatchObject({ status: '401' })730 })731732 it('Should call a callback to continue processing the request', async () => {733 const event = {734 Records: [735 {736 cf: {737 config: {738 distributionDomainName: 'example.com',739 distributionId: 'EXAMPLE123',740 eventType: 'viewer-request',741 requestId: 'exampleRequestId',742 },743 request: {744 clientIp: '123.123.123.123',745 headers: {},746 method: 'GET',747 querystring: '',748 uri: '/callback/request',749 },750 },751 },752 ],753 }754755 let called = false756 let requestClientIp = ''757758 await handler(event, {}, (_err, result) => {759 if (result && 'clientIp' in result) {760 requestClientIp = result.clientIp761 }762 called = true763 })764765 expect(called).toBe(true)766 expect(requestClientIp).toBe('123.123.123.123')767 })768769 it('Should call a callback to continue processing the response', async () => {770 const event = {771 Records: [772 {773 cf: {774 config: {775 distributionDomainName: 'example.com',776 distributionId: 'EDFDVBD6EXAMPLE',777 eventType: 'viewer-response',778 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',779 },780 request: {781 clientIp: '203.0.113.178',782 headers: {783 host: [784 {785 key: 'Host',786 value: 'example.com',787 },788 ],789 'user-agent': [790 {791 key: 'User-Agent',792 value: 'curl/7.66.0',793 },794 ],795 accept: [796 {797 key: 'accept',798 value: '*/*',799 },800 ],801 },802 method: 'GET',803 querystring: '',804 uri: '/callback/response',805 },806 response: {807 headers: {808 'access-control-allow-credentials': [809 {810 key: 'Access-Control-Allow-Credentials',811 value: 'true',812 },813 ],814 'access-control-allow-origin': [815 {816 key: 'Access-Control-Allow-Origin',817 value: '*',818 },819 ],820 date: [821 {822 key: 'Date',823 value: 'Mon, 13 Jan 2020 20:14:56 GMT',824 },825 ],826 'referrer-policy': [827 {828 key: 'Referrer-Policy',829 value: 'no-referrer-when-downgrade',830 },831 ],832 server: [833 {834 key: 'Server',835 value: 'ExampleCustomOriginServer',836 },837 ],838 'x-content-type-options': [839 {840 key: 'X-Content-Type-Options',841 value: 'nosniff',842 },843 ],844 'x-frame-options': [845 {846 key: 'X-Frame-Options',847 value: 'DENY',848 },849 ],850 'x-xss-protection': [851 {852 key: 'X-XSS-Protection',853 value: '1; mode=block',854 },855 ],856 age: [857 {858 key: 'Age',859 value: '2402',860 },861 ],862 'content-type': [863 {864 key: 'Content-Type',865 value: 'text/html; charset=utf-8',866 },867 ],868 'content-length': [869 {870 key: 'Content-Length',871 value: '9593',872 },873 ],874 },875 status: '200',876 statusDescription: 'OK',877 },878 },879 },880 ],881 }882883 interface CloudFrontHeaders {884 [name: string]: [885 {886 key: string887 value: string888 },889 ]890 }891 let called = false892 let headers: CloudFrontHeaders = {}893 await handler(event, {}, (_err, result) => {894 if (result && result.headers) {895 headers = result.headers as CloudFrontHeaders896 }897 called = true898 })899900 expect(called).toBe(true)901 expect(headers['access-control-allow-credentials']).toEqual([902 {903 key: 'Access-Control-Allow-Credentials',904 value: 'true',905 },906 ])907 expect(headers['access-control-allow-origin']).toEqual([908 {909 key: 'Access-Control-Allow-Origin',910 value: '*',911 },912 ])913 })914915 it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {916 const event = {917 Records: [918 {919 cf: {920 config: {921 distributionDomainName: 'example.com',922 distributionId: 'EDFDVBD6EXAMPLE',923 eventType: 'viewer-response',924 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',925 },926 request: {927 clientIp: '203.0.113.178',928 headers: {929 host: [930 {931 key: 'Host',932 value: 'example.com',933 },934 ],935 'user-agent': [936 {937 key: 'User-Agent',938 value: 'curl/7.66.0',939 },940 ],941 accept: [942 {943 key: 'accept',944 value: '*/*',945 },946 ],947 },948 method: 'GET',949 querystring: '',950 uri: '/header/add',951 },952 response: {953 headers: {954 'access-control-allow-credentials': [955 {956 key: 'Access-Control-Allow-Credentials',957 value: 'true',958 },959 ],960 'access-control-allow-origin': [961 {962 key: 'Access-Control-Allow-Origin',963 value: '*',964 },965 ],966 date: [967 {968 key: 'Date',969 value: 'Mon, 13 Jan 2020 20:14:56 GMT',970 },971 ],972 'referrer-policy': [973 {974 key: 'Referrer-Policy',975 value: 'no-referrer-when-downgrade',976 },977 ],978 server: [979 {980 key: 'Server',981 value: 'ExampleCustomOriginServer',982 },983 ],984 'x-content-type-options': [985 {986 key: 'X-Content-Type-Options',987 value: 'nosniff',988 },989 ],990 'x-frame-options': [991 {992 key: 'X-Frame-Options',993 value: 'DENY',994 },995 ],996 'x-xss-protection': [997 {998 key: 'X-XSS-Protection',999 value: '1; mode=block',1000 },1001 ],1002 age: [1003 {1004 key: 'Age',1005 value: '2402',1006 },1007 ],1008 'content-type': [1009 {1010 key: 'Content-Type',1011 value: 'text/html; charset=utf-8',1012 },1013 ],1014 'content-length': [1015 {1016 key: 'Content-Length',1017 value: '9593',1018 },1019 ],1020 },1021 status: '200',1022 statusDescription: 'OK',1023 },1024 },1025 },1026 ],1027 }10281029 interface CloudFrontHeaders {1030 [name: string]: [1031 {1032 key: string1033 value: string1034 },1035 ]1036 }1037 let called = false1038 let headers: CloudFrontHeaders = {}1039 await handler(event, {}, (_err, result) => {1040 if (result && result.headers) {1041 headers = result.headers as CloudFrontHeaders1042 }1043 called = true1044 })10451046 expect(called).toBe(true)1047 expect(headers['strict-transport-security']).toEqual([1048 {1049 key: 'Strict-Transport-Security',1050 value: 'max-age=63072000; includeSubdomains; preload',1051 },1052 ])1053 expect(headers['x-custom']).toEqual([1054 {1055 key: 'X-Custom',1056 value: 'Foo',1057 },1058 ])1059 })10601061 it('Callback Event (Lambda@Edge response)', async () => {1062 const event = {1063 Records: [1064 {1065 cf: {1066 config: {1067 distributionDomainName: 'example.com',1068 distributionId: 'EDFDVBD6EXAMPLE',1069 eventType: 'viewer-response',1070 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',1071 },1072 request: {1073 clientIp: '203.0.113.178',1074 headers: {1075 host: [1076 {1077 key: 'Host',1078 value: 'example.com',1079 },1080 ],1081 },1082 method: 'GET',1083 querystring: '',1084 uri: '/config/eventCheck',1085 },1086 },1087 },1088 ],1089 }10901091 let called = false1092 await handler(event, {}, () => {1093 called = true1094 })10951096 expect(called).toBe(true)1097 })10981099 it('Should return a response where bodyEncoding is "base64" with binary', async () => {1100 const event = {1101 Records: [1102 {1103 cf: {1104 config: {1105 distributionDomainName: 'example.com',1106 distributionId: 'EXAMPLE123',1107 eventType: 'viewer-request',1108 requestId: 'exampleRequestId',1109 },1110 request: {1111 clientIp: '123.123.123.123',1112 headers: {1113 host: [1114 {1115 key: 'Host',1116 value: 'example.com',1117 },1118 ],1119 },1120 method: 'GET',1121 querystring: '',1122 uri: '/binary',1123 },1124 },1125 },1126 ],1127 }11281129 const response = await handler(event)11301131 expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded "Fake Image"1132 expect(response).toMatchObject({ bodyEncoding: 'base64' })1133 })1134})
modified:adapters/lambda-edge/tsconfig.json+2 added-2 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "module": "ES2020",5 "rootDir": "./src/",5 "outDir": "./dist/",6 "types": [7 "node",8 "vitest/globals"9 ],10 "noEmit": true11 },12 "include": [14 "src/**/*.ts"13 "src/**/*.ts",14 "test/**/*.ts"15 ]16}
modified:docs/MAINTAINING.md+3 added
50 unmodified lines
51The `release.yml` workflow runs `deno publish --set-version <version from the tag>` when the tagged adapter has a `deno.json`.52Before the first release, create the package on jsr.io under the `@hono` scope and link the `honojs/hono`53repository so the workflow can publish with OIDC. `deno publish --dry-run --set-version 0.0.1` in `adapters/deno` checks the package locally.5455Tests under `adapters/deno/test` run on Deno (`pnpm --filter @hono/deno run test:deno`) with `test/deno.json`,56which maps `hono` to the working tree instead.5758### Adding a new adapter59601. Copy `adapters/bun` as `adapters/<name>` and adjust `package.json` (`name`, `description`) and the sources.612. The workspace picks it up automatically (`pnpm-workspace.yaml` has `adapters/*`).
12 unmodified lines
deleted:runtime-tests/bun/.static/plain.txt-1 removed
1Bun!!
deleted:runtime-tests/bun/static/hello.world/index.html-1 removed
1Hi
deleted:runtime-tests/bun/static/helloworld/index.html-1 removed
1Hi
deleted:runtime-tests/bun/static/download-1 removed
1download
deleted:runtime-tests/bun/static/plain.txt-1 removed
1Bun!
deleted:runtime-tests/bun/static-absolute-root/plain.txt-1 removed
1Bun!
deleted:runtime-tests/bun/favicon.icobinary

A binary file, deleted.

modified:runtime-tests/bun/index.test.tsx+1 added-192 removed
1import fs from 'fs/promises'2import path from 'path'3import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'1import { afterEach, beforeEach, describe, expect, it } from 'vitest'2import { stream, streamSSE } from '../..//src/helper/streaming'5import { serveStatic, toSSG } from '../../src/adapter/bun'6import { createBunWebSocket } from '../../src/adapter/bun/websocket'7import type { BunWebSocketData } from '../../src/adapter/bun/websocket'3import { Context } from '../../src/context'4import { env, getRuntimeKey } from '../../src/helper/adapter'10import type { WSMessageReceive } from '../../src/helper/websocket'5import { Hono } from '../../src/index'6import type { PropsWithChildren } from '../../src/jsx'7import { basicAuth } from '../../src/middleware/basic-auth'8import { jwt } from '../../src/middleware/jwt'
70 unmodified lines
79 expect(await res.text()).toBe('auth')80 })81})8289describe('Serve Static Middleware', () => {90 const app = new Hono()91 const onNotFound = vi.fn(() => {})92 app.all('/favicon.ico', serveStatic({ path: './runtime-tests/bun/favicon.ico' }))93 app.all(94 '/favicon-notfound.ico',95 serveStatic({ path: './runtime-tests/bun/favicon-notfound.ico', onNotFound })96 )97 app.use('/favicon-notfound.ico', async (c, next) => {98 await next()99 c.header('X-Custom', 'Bun')100 })101 app.get(102 '/static/*',103 serveStatic({104 root: './runtime-tests/bun/',105 onNotFound,106 })107 )108 app.get(109 '/dot-static/*',110 serveStatic({111 root: './runtime-tests/bun/',112 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),113 })114 )115116 app.all('/static-absolute-root/*', serveStatic({ root: path.dirname(__filename) }))117118 beforeEach(() => onNotFound.mockClear())119120 it('Should return static file correctly', async () => {121 const res = await app.request(new Request('http://localhost/favicon.ico'))122 await res.arrayBuffer()123 expect(res.status).toBe(200)124 expect(res.headers.get('Content-Type')).toBe('image/x-icon')125 })126127 it('Should return 404 response', async () => {128 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))129 expect(res.status).toBe(404)130 expect(res.headers.get('X-Custom')).toBe('Bun')131 expect(onNotFound).toHaveBeenCalledWith(132 process.platform === 'win32'133 ? 'runtime-tests\\bun\\favicon-notfound.ico'134 : 'runtime-tests/bun/favicon-notfound.ico',135 expect.anything()136 )137 })138139 it('Should return 200 response - /static/plain.txt', async () => {140 const res = await app.request(new Request('http://localhost/static/plain.txt'))141 expect(res.status).toBe(200)142 expect(await res.text()).toMatch(/^Bun!(\r?\n)?$/)143 expect(onNotFound).not.toHaveBeenCalled()144 })145146 it('Should return 200 response - /static/download', async () => {147 const res = await app.request(new Request('http://localhost/static/download'))148 expect(res.status).toBe(200)149 expect(await res.text()).toMatch(/^download(\r?\n)?$/)150 expect(onNotFound).not.toHaveBeenCalled()151 })152153 it('Should return 200 response - /dot-static/plain.txt', async () => {154 const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))155 expect(res.status).toBe(200)156 expect(await res.text()).toMatch(/^Bun!!(\r?\n)?$/)157 })158159 it('Should return 200 response - /static/helloworld', async () => {160 const res = await app.request('http://localhost/static/helloworld')161 expect(res.status).toBe(200)162 expect(await res.text()).toMatch(/Hi\r?\n/)163 })164165 it('Should return 200 response - /static/hello.world', async () => {166 const res = await app.request('http://localhost/static/hello.world')167 expect(res.status).toBe(200)168 expect(await res.text()).toMatch(/Hi\r?\n/)169 })170171 it('Should return 200 response - /static-absolute-root/plain.txt', async () => {172 const res = await app.request('http://localhost/static-absolute-root/plain.txt')173 expect(res.status).toBe(200)174 expect(await res.text()).toMatch(/^Bun!(\r?\n)?$/)175 expect(onNotFound).not.toHaveBeenCalled()176 })177})17883// Bun support WebCrypto since v0.2.284// So, JWT middleware works well.85describe('JWT Auth Middleware', () => {86 const app = new Hono()
66 unmodified lines
153 expect(await res.text()).toBe('<html><p>hello</p></html>')154 })155})156253describe('toSSG function', () => {254 let app: Hono255256 beforeEach(() => {257 app = new Hono()258 app.get('/', (c) => c.text('Hello, World!'))259 app.get('/about', (c) => c.text('About Page'))260 app.get('/about/some', (c) => c.text('About Page 2tier'))261 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))262 app.get('/bravo', (c) => c.html('Bravo Page'))263 app.get('/Charlie', async (c, next) => {264 c.setRenderer((content, head) => {265 return c.html(266 <html>267 <head>268 <title>{head.title || ''}</title>269 </head>270 <body>271 <p>{content}</p>272 </body>273 </html>274 )275 })276 await next()277 })278 app.get('/Charlie', (c) => {279 return c.render('Hello!', { title: 'Charlies Page' })280 })281 })282283 it('Should correctly generate static HTML files for Hono routes', async () => {284 const result = await toSSG(app, { dir: './static' })285 expect(result.success).toBeTruthy()286 expect(result.error).toBeUndefined()287 expect(result.files).toBeDefined()288 afterAll(async () => {289 await deleteDirectory('./static')290 })291 })292})293294describe('WebSockets Helper', () => {295 const app = new Hono()296 const { websocket, upgradeWebSocket } = createBunWebSocket()297298 it('Should websockets is working', async () => {299 const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>300 app.get(301 '/ws',302 upgradeWebSocket(() => ({303 onMessage(evt) {304 resolve(evt.data)305 },306 }))307 )308 )309 const upgradedData = await new Promise<BunWebSocketData>((resolve) =>310 app.fetch(new Request('http://localhost/ws'), {311 upgrade: (_req: Request, data: { data: BunWebSocketData }) => {312 resolve(data.data)313 },314 })315 )316 const message = Math.random().toString()317 websocket.message(318 {319 close: () => undefined,320 readyState: 3,321 data: upgradedData,322 send: () => undefined,323 },324 message325 )326 const receivedMessage = await receivedMessagePromise327 expect(receivedMessage).toBe(message)328 })329})330331async function deleteDirectory(dirPath: string) {332 if (333 await fs334 .stat(dirPath)335 .then((stat) => stat.isDirectory())336 .catch(() => false)337 ) {338 for (const entry of await fs.readdir(dirPath)) {339 const entryPath = path.join(dirPath, entry)340 await deleteDirectory(entryPath)341 }342 await fs.rmdir(dirPath)343 } else {344 await fs.unlink(dirPath)345 }346}347157describe('streaming', () => {158 const app = new Hono()159 let server: ReturnType<typeof Bun.serve>160 let aborted = false
108 unmodified lines
deleted:runtime-tests/deno/.static/plain.txt-1 removed
1Deno!!
deleted:runtime-tests/deno/static/hello.world/index.html-1 removed
1Hi
deleted:runtime-tests/deno/static/helloworld/index.html-1 removed
1Hi
deleted:runtime-tests/deno/static/download-1 removed
1download
deleted:runtime-tests/deno/static/plain.txt-1 removed
1Deno!
deleted:runtime-tests/deno/static-absolute-root/plain.txt-1 removed
1Deno!
deleted:runtime-tests/deno/favicon.icobinary

A binary file, deleted.

modified:runtime-tests/deno/middleware.test.tsx+1 added-95 removed
1import { assertEquals, assertMatch } from '@std/assert'2import { dirname, fromFileUrl } from '@std/path'3import { assertSpyCall, assertSpyCalls, spy } from '@std/testing/mock'4import { serveStatic } from '../../src/adapter/deno/index.ts'1import { assertEquals } from '@std/assert'2import { Hono } from '../../src/hono.ts'3import { basicAuth } from '../../src/middleware/basic-auth/index.ts'4import { jwt } from '../../src/middleware/jwt/index.ts'5
56 unmodified lines
62 )63 assertEquals(template.toString(), '<p>1</p><p>2</p>')64})6569Deno.test('Serve Static middleware', async () => {70 const app = new Hono()71 const onNotFound = spy(() => {})72 app.all('/favicon.ico', serveStatic({ path: './runtime-tests/deno/favicon.ico' }))73 app.all(74 '/favicon-notfound.ico',75 serveStatic({ path: './runtime-tests/deno/favicon-notfound.ico', onNotFound })76 )77 app.use('/favicon-notfound.ico', async (c, next) => {78 await next()79 c.header('X-Custom', 'Deno')80 })8182 app.get(83 '/static/*',84 serveStatic({85 root: './runtime-tests/deno',86 onNotFound,87 })88 )8990 app.get(91 '/dot-static/*',92 serveStatic({93 root: './runtime-tests/deno',94 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),95 })96 )9798 app.get('/static-absolute-root/*', serveStatic({ root: dirname(fromFileUrl(import.meta.url)) }))99100 let res = await app.request('http://localhost/favicon.ico')101 assertEquals(res.status, 200)102 assertEquals(res.headers.get('Content-Type'), 'image/x-icon')103 await res.body?.cancel()104105 res = await app.request('http://localhost/favicon-notfound.ico')106 assertEquals(res.status, 404)107 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)108 assertEquals(res.headers.get('X-Custom'), 'Deno')109 assertSpyCall(onNotFound, 0)110111 res = await app.request('http://localhost/static/plain.txt')112 assertEquals(res.status, 200)113 assertMatch(await res.text(), /^Deno!(\r?\n)?$/)114115 res = await app.request('http://localhost/static/download')116 assertEquals(res.status, 200)117 assertMatch(await res.text(), /^download(\r?\n)?$/)118119 res = await app.request('http://localhost/dot-static/plain.txt')120 assertEquals(res.status, 200)121 assertMatch(await res.text(), /^Deno!!(\r?\n)?$/)122 assertSpyCalls(onNotFound, 1)123124 res = await app.fetch({125 method: 'GET',126 url: 'http://localhost/static/%2e%2e/static/plain.txt',127 } as Request)128 assertEquals(res.status, 404)129 assertEquals(await res.text(), '404 Not Found')130131 res = await app.request('http://localhost/static/helloworld')132 assertEquals(res.status, 200)133 assertEquals(await res.text(), 'Hi\n')134135 res = await app.request('http://localhost/static/hello.world')136 assertEquals(res.status, 200)137 assertEquals(await res.text(), 'Hi\n')138139 res = await app.request('http://localhost/static-absolute-root/plain.txt')140 assertEquals(res.status, 200)141 assertMatch(await res.text(), /^Deno!(\r?\n)?$/)142143 res = await app.request('http://localhost/static')144 assertEquals(res.status, 404)145 assertEquals(await res.text(), '404 Not Found')146147 res = await app.request('http://localhost/static/dir')148 assertEquals(res.status, 404)149 assertEquals(await res.text(), '404 Not Found')150151 res = await app.request('http://localhost/static/helloworld/nested')152 assertEquals(res.status, 404)153 assertEquals(await res.text(), '404 Not Found')154155 res = await app.request('http://localhost/static/helloworld/../')156 assertEquals(res.status, 404)157 assertEquals(await res.text(), '404 Not Found')158})15966Deno.test('JWT Authentication middleware', async () => {67 const app = new Hono<{ Variables: { 'x-foo': string } }>()68 app.use('/*', async (c, next) => {69 await next()
23 unmodified lines
deleted:runtime-tests/deno/ssg.test.tsx-52 removed
1import { assertEquals } from '@std/assert'2import { toSSG } from '../../src/adapter/deno/ssg.ts'3import { Hono } from '../../src/hono.ts'45Deno.test('toSSG function', async () => {6 const app = new Hono()7 app.get('/', (c) => c.text('Hello, World!'))8 app.get('/about', (c) => c.text('About Page'))9 app.get('/about/some', (c) => c.text('About Page 2tier'))10 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))11 app.get('/bravo', (c) => c.html('Bravo Page'))12 app.get('/Charlie', async (c, next) => {13 c.setRenderer((content) => {14 return c.html(15 <html>16 <body>17 <p>{content}</p>18 </body>19 </html>20 )21 })22 await next()23 })24 app.get('/Charlie', (c) => {25 return c.render('Hello!')26 })2728 const result = await toSSG(app, { dir: './ssg-static' })29 assertEquals(result.success, true)30 assertEquals(result.error, undefined)31 assertEquals(result.files !== undefined, true)3233 await deleteDirectory('./ssg-static')34})3536async function deleteDirectory(dirPath: string): Promise<void> {37 try {38 const stat = await Deno.stat(dirPath)3940 if (stat.isDirectory) {41 for await (const dirEntry of Deno.readDir(dirPath)) {42 const entryPath = `${dirPath}/${dirEntry.name}`43 await deleteDirectory(entryPath)44 }45 await Deno.remove(dirPath)46 } else {47 await Deno.remove(dirPath)48 }49 } catch (error) {50 console.error(`Error deleting directory: ${error}`)51 }52}
deleted:runtime-tests/lambda/index.test.ts-1087 removed
1import { Readable } from 'stream'2import {3 ALBProcessor,4 EventV1Processor,5 EventV2Processor,6 getProcessor,7 handle,8 streamHandle,9} from '../../src/adapter/aws-lambda/handler'10import type {11 ALBProxyEvent,12 APIGatewayProxyEventV2,13 LatticeProxyEventV2,14 LambdaEvent,15} from '../../src/adapter/aws-lambda/handler'16import type {17 ApiGatewayRequestContext,18 ApiGatewayRequestContextV2,19 LatticeRequestContextV2,20 LambdaContext,21} from '../../src/adapter/aws-lambda/types'22import { getCookie, setCookie } from '../../src/helper/cookie'23import { streamSSE, streamText } from '../../src/helper/streaming'24import { Hono } from '../../src/hono'25import { basicAuth } from '../../src/middleware/basic-auth'26import './mock'2728type Bindings = {29 event: LambdaEvent30 lambdaContext: LambdaContext31 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV232}3334const testApiGatewayRequestContextV2 = {35 accountId: '123456789012',36 apiId: 'urlid',37 authentication: null,38 authorizer: {39 iam: {40 accessKey: 'AKIA...',41 accountId: '111122223333',42 callerId: 'AIDA...',43 cognitoIdentity: null,44 principalOrgId: null,45 userArn: 'arn:aws:iam::111122223333:user/example-user',46 userId: 'AIDA...',47 },48 },49 domainName: 'example.com',50 domainPrefix: '<url-id>',51 http: {52 method: 'POST',53 path: '/my/path',54 protocol: 'HTTP/1.1',55 sourceIp: '123.123.123.123',56 userAgent: 'agent',57 },58 requestId: 'id',59 routeKey: '$default',60 stage: '$default',61 time: '12/Mar/2020:19:03:58 +0000',62 timeEpoch: 1583348638390,63 customProperty: 'customValue',64}6566const testLatticeRequestContext: LatticeRequestContextV2 = {67 serviceNetworkArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:servicenetwork/sn-a1b2c3',68 serviceArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:service/svc-a1b2c3',69 targetGroupArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:targetgroup/tg-a1b2c3',70 region: 'us-east-1',71 timeEpoch: '1759915938150314',72 identity: {73 sourceVpcArn: 'arn:aws:ec2:us-east-1:111122223333:vpc/vpc-a1b2c3',74 },75}7677describe('AWS Lambda Adapter for Hono', () => {78 const app = new Hono<{ Bindings: Bindings }>()7980 app.get('/', (c) => {81 return c.text('Hello Lambda!')82 })8384 app.get('/binary', (c) => {85 return c.body('Fake Image', 200, {86 'Content-Type': 'image/png',87 })88 })8990 app.post('/post', async (c) => {91 const body = (await c.req.parseBody()) as { message: string }92 return c.text(body.message)93 })9495 app.post('/post/binary', async (c) => {96 const body = await c.req.blob()97 return c.text(`${body.size} bytes`)98 })99100 const username = 'hono-user-a'101 const password = 'hono-password-a'102 app.use('/auth/*', basicAuth({ username, password }))103 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))104105 app.get('/lambda-event', (c) => {106 const event = c.env.event107 return c.json(event)108 })109110 app.get('/lambda-context', (c) => {111 const fnctx = c.env.lambdaContext112 return c.json(fnctx)113 })114115 app.get('/custom-context/v1/apigw', (c) => {116 const lambdaContext = c.env.requestContext117 return c.json(lambdaContext)118 })119120 app.get('/custom-context/apigw', (c) => {121 const lambdaContext = c.env.event.requestContext122 return c.json(lambdaContext)123 })124125 app.get('/custom-context/v1/lambda', (c) => {126 const lambdaContext = c.env.requestContext127 return c.json(lambdaContext)128 })129130 app.get('/custom-context/lambda', (c) => {131 const lambdaContext = c.env.event.requestContext132 return c.json(lambdaContext)133 })134135 app.get('/query-params', (c) => {136 const queryParams = c.req.query()137 return c.json(queryParams)138 })139140 app.get('/multi-query-params', (c) => {141 const multiQueryParams = c.req.queries()142 return c.json(multiQueryParams)143 })144145 const testCookie1 = {146 key: 'id',147 value: crypto.randomUUID(),148 get serialized() {149 return `${this.key}=${this.value}; Path=/`150 },151 }152 const testCookie2 = {153 key: 'secret',154 value: crypto.randomUUID(),155 get serialized() {156 return `${this.key}=${this.value}; Path=/`157 },158 }159160 app.post('/cookie', (c) => {161 setCookie(c, testCookie1.key, testCookie1.value)162 setCookie(c, testCookie2.key, testCookie2.value)163 return c.text('Cookies Set')164 })165166 app.get('/cookie', (c) => {167 const validCookies =168 getCookie(c, testCookie1.key) === testCookie1.value &&169 getCookie(c, testCookie2.key) === testCookie2.value170 if (!validCookies) {171 return c.text('Invalid Cookies')172 }173 return c.text('Valid Cookies')174 })175176 app.post('/headers', (c) => {177 if (c.req.header('foo')?.includes('bar')) {178 return c.json({ message: 'ok' })179 }180 return c.json({ message: 'fail' }, 400)181 })182183 const handler = handle(app)184185 const testApiGatewayRequestContext = {186 accountId: '123456789012',187 apiId: 'id',188 authorizer: {189 claims: null,190 scopes: null,191 },192 domainName: 'example.com',193 domainPrefix: 'id',194 extendedRequestId: 'request-id',195 httpMethod: 'GET',196 identity: {197 sourceIp: 'IP',198 userAgent: 'user-agent',199 },200 path: '/my/path',201 protocol: 'HTTP/1.1',202 requestId: 'id=',203 requestTime: '04/Mar/2020:19:15:17 +0000',204 requestTimeEpoch: 1583349317135,205 resourcePath: '/',206 stage: '$default',207 customProperty: 'customValue',208 }209210 const testALBRequestContext = {211 elb: {212 targetGroupArn:213 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',214 },215 }216217 it('Should handle a GET request and return a 200 response', async () => {218 const event = {219 version: '1.0',220 resource: '/',221 httpMethod: 'GET',222 headers: { 'content-type': 'text/plain' },223 path: '/',224 body: null,225 isBase64Encoded: false,226 requestContext: testApiGatewayRequestContext,227 }228229 const response = await handler(event)230 expect(response.statusCode).toBe(200)231 expect(response.body).toBe('Hello Lambda!')232 expect(response.headers['content-type']).toMatch(/^text\/plain/)233 expect(response.multiValueHeaders).toBeUndefined()234 expect(response.isBase64Encoded).toBe(false)235 })236237 it('Should handle a GET request and return a 200 response with binary', async () => {238 const event = {239 version: '1.0',240 resource: '/binary',241 httpMethod: 'GET',242 headers: {},243 path: '/binary',244 body: null,245 isBase64Encoded: false,246 requestContext: testApiGatewayRequestContext,247 }248249 const response = await handler(event)250 expect(response.statusCode).toBe(200)251 expect(response.body).toBe('RmFrZSBJbWFnZQ==')252 expect(response.headers['content-type']).toMatch(/^image\/png/)253 expect(response.multiValueHeaders).toBeUndefined()254 expect(response.isBase64Encoded).toBe(true)255 })256257 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {258 const event = {259 version: '2.0',260 routeKey: '$default',261 headers: { 'content-type': 'text/plain' },262 rawPath: '/',263 rawQueryString: '',264 body: null,265 isBase64Encoded: false,266 requestContext: testApiGatewayRequestContextV2,267 }268269 testApiGatewayRequestContextV2.http.method = 'GET'270271 const response = await handler(event)272 expect(response.statusCode).toBe(200)273 expect(response.body).toBe('Hello Lambda!')274 expect(response.headers['content-type']).toMatch(/^text\/plain/)275 expect(response.multiValueHeaders).toBeUndefined()276 expect(response.isBase64Encoded).toBe(false)277 })278279 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {280 const event = {281 headers: { 'content-type': 'text/plain' },282 httpMethod: 'GET',283 path: '/',284 queryStringParameters: {285 query: '1234ABCD',286 },287 body: null,288 isBase64Encoded: false,289 requestContext: testALBRequestContext,290 }291292 const response = await handler(event)293 expect(response.statusCode).toBe(200)294 expect(response.body).toBe('Hello Lambda!')295 expect(response.headers['content-type']).toMatch(/^text\/plain/)296 expect(response.multiValueHeaders).toBeUndefined()297 expect(response.isBase64Encoded).toBe(false)298 })299300 it('Should handle a GET request and return a 200 response (LatticeProxyEvent)', async () => {301 const event: LatticeProxyEventV2 = {302 version: '2.0',303 path: '/?query=1234ABCD',304 method: 'GET',305 headers: { 'content-type': ['text/plain'] },306 queryStringParameters: {},307 body: null,308 isBase64Encoded: false,309 requestContext: testLatticeRequestContext,310 }311312 const response = await handler(event)313 expect(response.statusCode).toBe(200)314 expect(response.body).toBe('Hello Lambda!')315 expect(response.headers['content-type']).toMatch(/^text\/plain/)316 expect(response.multiValueHeaders).toBeUndefined()317 expect(response.isBase64Encoded).toBe(false)318 })319320 it('Should handle a GET request and return a 404 response', async () => {321 const event = {322 version: '1.0',323 resource: '/nothing',324 httpMethod: 'GET',325 headers: { 'content-type': 'text/plain' },326 path: '/nothing',327 body: null,328 isBase64Encoded: false,329 requestContext: testApiGatewayRequestContext,330 }331332 const response = await handler(event)333 expect(response.statusCode).toBe(404)334 })335336 it('Should handle a POST request and return a 200 response', async () => {337 const searchParam = new URLSearchParams()338 searchParam.append('message', 'Good Morning Lambda!')339 const event = {340 version: '1.0',341 resource: '/post',342 httpMethod: 'POST',343 headers: {344 'Content-Type': 'application/x-www-form-urlencoded',345 },346 path: '/post',347 body: Buffer.from(searchParam.toString()).toString('base64'),348 isBase64Encoded: true,349 requestContext: testApiGatewayRequestContext,350 }351352 const response = await handler(event)353 expect(response.statusCode).toBe(200)354 expect(response.body).toBe('Good Morning Lambda!')355 })356357 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {358 const searchParam = new URLSearchParams()359 searchParam.append('message', 'Good Morning Lambda!')360 const event = {361 version: '2.0',362 routeKey: '$default',363 headers: {364 'Content-Type': 'application/x-www-form-urlencoded',365 },366 rawPath: '/post',367 rawQueryString: '',368 body: Buffer.from(searchParam.toString()).toString('base64'),369 isBase64Encoded: true,370 requestContext: testApiGatewayRequestContextV2,371 }372373 testApiGatewayRequestContextV2.http.method = 'POST'374375 const response = await handler(event)376 expect(response.statusCode).toBe(200)377 expect(response.body).toBe('Good Morning Lambda!')378 })379380 it('Should handle a POST request with binary and return a 200 response', async () => {381 const array = new Uint8Array([0xc0, 0xff, 0xee])382 const buffer = Buffer.from(array)383 const event = {384 version: '1.0',385 resource: '/post/binary',386 httpMethod: 'POST',387 headers: {388 'Content-Type': 'application/x-www-form-urlencoded',389 },390 path: '/post/binary',391 body: buffer.toString('base64'),392 isBase64Encoded: true,393 requestContext: testApiGatewayRequestContext,394 }395396 const response = await handler(event)397 expect(response.statusCode).toBe(200)398 expect(response.body).toBe('3 bytes')399 })400401 it('Should handle a request and return a 401 response with Basic auth', async () => {402 const event = {403 version: '1.0',404 resource: '/auth/abc',405 httpMethod: 'GET',406 headers: {407 'Content-Type': 'plain/text',408 },409 path: '/auth/abc',410 body: null,411 isBase64Encoded: true,412 requestContext: testApiGatewayRequestContext,413 }414415 const response = await handler(event)416 expect(response.statusCode).toBe(401)417 })418419 it('Should handle a request and return a 200 response with Basic auth', async () => {420 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'421 const event = {422 version: '1.0',423 resource: '/auth/abc',424 httpMethod: 'GET',425 headers: {426 'Content-Type': 'plain/text',427 Authorization: `Basic ${credential}`,428 },429 path: '/auth/abc',430 body: null,431 isBase64Encoded: true,432 requestContext: testApiGatewayRequestContext,433 }434435 const response = await handler(event)436 expect(response.statusCode).toBe(200)437 expect(response.body).toBe('Good Night Lambda!')438 })439440 it('Should handle a GET request and return custom context', async () => {441 const event = {442 version: '1.0',443 resource: '/custom-context/apigw',444 httpMethod: 'GET',445 headers: { 'content-type': 'application/json' },446 path: '/custom-context/apigw',447 body: null,448 isBase64Encoded: false,449 requestContext: testApiGatewayRequestContext,450 }451452 const response = await handler(event)453 expect(response.statusCode).toBe(200)454 expect(JSON.parse(response.body).customProperty).toEqual('customValue')455 })456457 it('Should handle a GET request and context', async () => {458 const event = {459 version: '1.0',460 resource: '/lambda-context',461 httpMethod: 'GET',462 headers: { 'content-type': 'application/json' },463 path: '/lambda-context',464 body: null,465 isBase64Encoded: false,466 requestContext: testApiGatewayRequestContext,467 }468 const context: LambdaContext = {469 callbackWaitsForEmptyEventLoop: false,470 functionName: 'myLambdaFunction',471 functionVersion: '1.0.0',472 invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',473 memoryLimitInMB: '128',474 awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',475 logGroupName: '/aws/lambda/myLambdaFunction',476 logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',477 getRemainingTimeInMillis: () => {478 return 60000 // 60 seconds479 },480 }481 const response = await handler(event, context)482 expect(response.statusCode).toBe(200)483 expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)484 })485486 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {487 const apiGatewayEvent = {488 version: '1.0',489 resource: '/cookie',490 httpMethod: 'POST',491 headers: { 'content-type': 'text/plain' },492 path: '/cookie',493 body: null,494 isBase64Encoded: false,495 requestContext: testApiGatewayRequestContext,496 }497498 const apiGatewayResponse = await handler(apiGatewayEvent)499500 expect(apiGatewayResponse.statusCode).toBe(200)501 expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [502 testCookie1.serialized,503 testCookie2.serialized,504 ])505506 const apiGatewayEventV2 = {507 version: '2.0',508 routeKey: '$default',509 httpMethod: 'POST',510 headers: { 'content-type': 'text/plain' },511 rawPath: '/cookie',512 rawQueryString: '',513 body: null,514 isBase64Encoded: false,515 requestContext: testApiGatewayRequestContextV2,516 }517518 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)519520 expect(apiGatewayResponseV2.statusCode).toBe(200)521 expect(apiGatewayResponseV2).toHaveProperty('cookies', [522 testCookie1.serialized,523 testCookie2.serialized,524 ])525 })526527 it('Should handle a POST request and return a 200 response with cookies set (LatticeProxyEvent V2)', async () => {528 const latticeProxyEvent: LatticeProxyEventV2 = {529 version: '2.0',530 path: '/cookie',531 method: 'POST',532 headers: { 'content-type': ['text/plain'] },533 queryStringParameters: {},534 body: null,535 isBase64Encoded: false,536 requestContext: testLatticeRequestContext,537 }538539 const latticeResponse = await handler(latticeProxyEvent)540541 expect(latticeResponse.statusCode).toBe(200)542 expect(latticeResponse.headers).toHaveProperty('set-cookie', [543 testCookie1.serialized,544 testCookie2.serialized,545 ])546 })547548 describe('headers', () => {549 describe('single-value headers', () => {550 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551 const event = {552 body: '{}',553 httpMethod: 'POST',554 isBase64Encoded: false,555 path: '/headers',556 headers: {557 host: 'localhost',558 foo: 'bar',559 },560 requestContext: testALBRequestContext,561 }562 const albResponse = await handler(event)563 expect(albResponse.statusCode).toBe(200)564 expect(albResponse.headers).toEqual(565 expect.objectContaining({566 'content-type': 'application/json',567 })568 )569 expect(albResponse.multiValueHeaders).toBeUndefined()570 })571572 it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {573 const apigatewayProxyEvent = {574 version: '1.0',575 resource: '/headers',576 httpMethod: 'POST',577 headers: {578 host: 'localhost',579 foo: 'bar',580 },581 path: '/headers',582 body: null,583 isBase64Encoded: false,584 requestContext: testApiGatewayRequestContext,585 }586 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)587 expect(apiGatewayResponseV2.statusCode).toBe(200)588 })589590 it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {591 const apigatewayProxyV2Event = {592 version: '2.0',593 routeKey: '$default',594 headers: {595 host: 'localhost',596 foo: 'bar',597 },598 rawPath: '/headers',599 rawQueryString: '',600 requestContext: testApiGatewayRequestContextV2,601 resource: '/headers',602 body: null,603 isBase64Encoded: false,604 }605 const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)606 expect(apiGatewayResponseV2.statusCode).toBe(200)607 })608 })609610 describe('multi-value headers', () => {611 it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {612 const event = {613 body: '{}',614 httpMethod: 'POST',615 isBase64Encoded: false,616 path: '/headers',617 multiValueHeaders: {618 host: ['localhost'],619 foo: ['bar'],620 },621 requestContext: testALBRequestContext,622 }623 const albResponse = await handler(event)624 expect(albResponse.statusCode).toBe(200)625 expect(albResponse.multiValueHeaders).toBeDefined()626 expect(albResponse.multiValueHeaders).toEqual(627 expect.objectContaining({628 'content-type': ['application/json'],629 })630 )631 })632633 it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {634 const apigatewayProxyEvent = {635 version: '1.0',636 resource: '/headers',637 httpMethod: 'POST',638 headers: {},639 multiValueHeaders: {640 host: ['localhost'],641 foo: ['bar'],642 },643 path: '/headers',644 body: null,645 isBase64Encoded: false,646 requestContext: testApiGatewayRequestContext,647 }648 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649 expect(apiGatewayResponseV2.statusCode).toBe(200)650 })651652 it('Should extract multi-value headers and return 200 (LatticeProxyEvent)', async () => {653 const event: LatticeProxyEventV2 = {654 version: '2.0',655 path: '/headers',656 method: 'POST',657 headers: {658 host: ['localhost'],659 foo: ['bar'],660 },661 queryStringParameters: {},662 body: null,663 isBase64Encoded: false,664 requestContext: testLatticeRequestContext,665 }666667 const response = await handler(event)668669 expect(response.statusCode).toBe(200)670 })671 })672 })673674 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {675 const apiGatewayEvent = {676 version: '1.0',677 resource: '/cookie',678 httpMethod: 'GET',679 headers: {680 'content-type': 'text/plain',681 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),682 },683 path: '/cookie',684 body: null,685 isBase64Encoded: false,686 requestContext: testApiGatewayRequestContext,687 }688689 const apiGatewayResponse = await handler(apiGatewayEvent)690691 expect(apiGatewayResponse.statusCode).toBe(200)692 expect(apiGatewayResponse.body).toBe('Valid Cookies')693 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)694 expect(apiGatewayResponse.isBase64Encoded).toBe(false)695696 const apiGatewayEventV2 = {697 version: '2.0',698 routeKey: '$default',699 headers: { 'content-type': 'text/plain' },700 rawPath: '/cookie',701 cookies: [testCookie1.serialized, testCookie2.serialized],702 rawQueryString: '',703 body: null,704 isBase64Encoded: false,705 requestContext: testApiGatewayRequestContextV2,706 }707 testApiGatewayRequestContextV2.http.method = 'GET'708709 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)710711 expect(apiGatewayResponseV2.statusCode).toBe(200)712 expect(apiGatewayResponseV2.body).toBe('Valid Cookies')713 expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)714 expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)715 })716717 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {718 const albEventDefaultHeaders = {719 version: '1.0',720 resource: '/cookie',721 httpMethod: 'GET',722 headers: {723 'content-type': 'text/plain',724 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),725 },726 path: '/cookie',727 body: null,728 isBase64Encoded: false,729 requestContext: testALBRequestContext,730 }731732 const albResponse = await handler(albEventDefaultHeaders)733734 expect(albResponse.statusCode).toBe(200)735 expect(albResponse.body).toBe('Valid Cookies')736 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)737 expect(albResponse.multiValueHeaders).toBeUndefined()738 expect(albResponse.isBase64Encoded).toBe(false)739 })740741 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {742 const albEventMultiValueHeaders = {743 version: '1.0',744 resource: '/cookie',745 httpMethod: 'GET',746 multiValueHeaders: {747 'content-type': ['text/plain'],748 cookie: [testCookie1.serialized, testCookie2.serialized],749 },750 path: '/cookie',751 body: null,752 isBase64Encoded: false,753 requestContext: testALBRequestContext,754 }755756 const albResponse = await handler(albEventMultiValueHeaders)757758 expect(albResponse.statusCode).toBe(200)759 expect(albResponse.body).toBe('Valid Cookies')760 expect(albResponse.headers).toBeUndefined()761 expect(albResponse.multiValueHeaders['content-type']).toEqual([762 expect.stringMatching(/^text\/plain/),763 ])764 expect(albResponse.isBase64Encoded).toBe(false)765 })766767 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {768 const albEventDefaultHeaders = {769 version: '1.0',770 resource: '/cookie',771 httpMethod: 'POST',772 headers: {773 'content-type': 'text/plain',774 cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),775 },776 path: '/cookie',777 body: null,778 isBase64Encoded: false,779 requestContext: testALBRequestContext,780 }781782 const albResponse = await handler(albEventDefaultHeaders)783784 expect(albResponse.statusCode).toBe(200)785 expect(albResponse.body).toBe('Cookies Set')786 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)787 expect(albResponse.multiValueHeaders).toBeUndefined()788 expect(albResponse.headers['set-cookie']).toEqual(testCookie1.serialized)789 expect(albResponse.isBase64Encoded).toBe(false)790 })791792 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {793 const albEventDefaultHeaders = {794 version: '1.0',795 resource: '/cookie',796 httpMethod: 'POST',797 multiValueHeaders: {798 'content-type': ['text/plain'],799 cookie: [testCookie1.serialized, testCookie2.serialized],800 },801 path: '/cookie',802 body: null,803 isBase64Encoded: false,804 requestContext: testALBRequestContext,805 }806807 const albResponse = await handler(albEventDefaultHeaders)808809 expect(albResponse.statusCode).toBe(200)810 expect(albResponse.body).toBe('Cookies Set')811 expect(albResponse.headers).toBeUndefined()812 expect(albResponse.multiValueHeaders['set-cookie']).toEqual(813 expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])814 )815 expect(albResponse.isBase64Encoded).toBe(false)816 })817818 it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {819 const albEventDefaultHeaders = {820 resource: '/query-params',821 httpMethod: 'GET',822 headers: {823 'content-type': 'application/json',824 },825 queryStringParameters: {826 key1: 'value1',827 key2: 'value2',828 },829 path: '/query-params',830 body: null,831 isBase64Encoded: false,832 requestContext: testALBRequestContext,833 }834835 const albResponse = await handler(albEventDefaultHeaders)836837 expect(albResponse.statusCode).toBe(200)838 expect(albResponse.body).toContain(839 JSON.stringify({840 key1: 'value1',841 key2: 'value2',842 })843 )844 expect(albResponse.headers['content-type']).toMatch(/^application\/json/)845 expect(albResponse.multiValueHeaders).toBeUndefined()846 expect(albResponse.isBase64Encoded).toBe(false)847 })848849 it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {850 const albEventDefaultHeaders = {851 resource: '/query-params',852 httpMethod: 'GET',853 multiValueHeaders: {854 'content-type': ['application/json'],855 },856 multiValueQueryStringParameters: {857 key1: ['value1'],858 key2: ['value2'],859 },860 path: '/query-params',861 body: null,862 isBase64Encoded: false,863 requestContext: testALBRequestContext,864 }865866 const albResponse = await handler(albEventDefaultHeaders)867868 expect(albResponse.statusCode).toBe(200)869 expect(albResponse.body).toContain(870 JSON.stringify({871 key1: 'value1',872 key2: 'value2',873 })874 )875 expect(albResponse.headers).toBeUndefined()876 expect(albResponse.multiValueHeaders['content-type']).toEqual([877 expect.stringMatching(/^application\/json/),878 ])879 expect(albResponse.isBase64Encoded).toBe(false)880 })881882 it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {883 const albEventDefaultHeaders = {884 resource: '/query-params',885 httpMethod: 'GET',886 multiValueHeaders: {887 'content-type': ['application/json'],888 },889 multiValueQueryStringParameters: {890 key1: ['value1'],891 key2: ['value2', 'otherValue2'],892 },893 path: '/multi-query-params',894 body: null,895 isBase64Encoded: false,896 requestContext: testALBRequestContext,897 }898899 const albResponse = await handler(albEventDefaultHeaders)900901 expect(albResponse.statusCode).toBe(200)902 expect(albResponse.body).toContain(903 JSON.stringify({904 key1: ['value1'],905 key2: ['value2', 'otherValue2'],906 })907 )908 expect(albResponse.headers).toBeUndefined()909 expect(albResponse.multiValueHeaders['content-type']).toEqual([910 expect.stringMatching(/^application\/json/),911 ])912 expect(albResponse.isBase64Encoded).toBe(false)913 })914})915916describe('streamHandle function', () => {917 const app = new Hono<{ Bindings: Bindings }>()918919 app.get('/', (c) => {920 return c.text('Hello Lambda!')921 })922923 app.get('/stream/text', async (c) => {924 return streamText(c, async (stream) => {925 for (let i = 0; i < 3; i++) {926 await stream.writeln(`${i}`)927 await stream.sleep(1)928 }929 })930 })931932 app.get('/sse', async (c) => {933 return streamSSE(c, async (stream) => {934 let id = 0935 const maxIterations = 2936937 while (id < maxIterations) {938 const message = `Message\nIt is ${id}`939 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })940 await stream.sleep(10)941 }942 })943 })944945 const handler = streamHandle(app)946947 it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {948 const event = {949 headers: { 'content-type': ' binary/octet-stream' },950 rawPath: '/stream/text',951 rawQueryString: '',952 body: null,953 isBase64Encoded: false,954 requestContext: testApiGatewayRequestContextV2,955 }956957 testApiGatewayRequestContextV2.http.method = 'GET'958959 const mockReadableStream = new Readable({960 // eslint-disable-next-line @typescript-eslint/no-empty-function961 read() {},962 })963964 mockReadableStream.push('0\n')965 mockReadableStream.push('1\n')966 mockReadableStream.push('2\n')967 mockReadableStream.push('3\n')968 mockReadableStream.push(null) // EOF969970 // @ts-expect-error should this be a ReadbleStream?971 await handler(event, mockReadableStream, vi.fn())972973 const chunks = []974 for await (const chunk of mockReadableStream) {975 chunks.push(chunk)976 }977 expect(chunks.join('')).toContain('0\n1\n2\n3\n')978 })979980 it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {981 const event = {982 headers: { 'content-type': 'text/event-stream' },983 rawPath: '/sse',984 rawQueryString: '',985 body: null,986 isBase64Encoded: false,987 requestContext: testApiGatewayRequestContextV2,988 }989990 testApiGatewayRequestContextV2.http.method = 'GET'991992 const mockReadableStream = new Readable({993 // eslint-disable-next-line @typescript-eslint/no-empty-function994 read() {},995 })996997 const initContentType = {998 'Content-Type': 'application/vnd.awslambda.http-integration-response',999 }1000 mockReadableStream.push(JSON.stringify(initContentType))10011002 // Send JSON formatted response headers, followed by 8 NULL characters as a separator1003 const httpResponseMetadata = {1004 statusCode: 200,1005 headers: { 'Custom-Header': 'value' },1006 cookies: ['session=abcd1234'],1007 }1008 const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()1009 mockReadableStream.push(jsonResponsePrelude)10101011 mockReadableStream.push('data: Message\ndata: It is 0\n\n')1012 mockReadableStream.push('data: Message\ndata: It is 1\n\n')1013 mockReadableStream.push(null) // EOF10141015 // @ts-expect-error should this be a ReadbleStream?1016 await handler(event, mockReadableStream, vi.fn())10171018 const chunks = []1019 for await (const chunk of mockReadableStream) {1020 chunks.push(chunk)1021 }10221023 // If you have chunks, you might want to convert them to strings before checking1024 const output = Buffer.concat(chunks).toString()1025 expect(output).toContain('data: Message\ndata: It is 0\n\n')1026 expect(output).toContain('data: Message\ndata: It is 1\n\n')10271028 // Assertions for the newly added header and prelude1029 expect(output).toContain('application/vnd.awslambda.http-integration-response')1030 expect(output).toContain('Custom-Header')1031 expect(output).toContain('session=abcd1234')10321033 // Check for JSON prelude and NULL sequence1034 const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'1035 expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))1036 })1037})10381039describe('getProcessor function', () => {1040 it('Should return ALBProcessor for an ALBProxyEvent event', () => {1041 const event: ALBProxyEvent = {1042 httpMethod: 'GET',1043 path: '/',1044 body: null,1045 isBase64Encoded: false,1046 requestContext: {1047 elb: {1048 targetGroupArn:1049 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',1050 },1051 },1052 }10531054 const processor = getProcessor(event)1055 expect(processor).toBeInstanceOf(ALBProcessor)1056 })10571058 it('Should return EventV1Processor for an event without requestContext', () => {1059 const event = {1060 httpMethod: 'GET',1061 path: '/',1062 body: null,1063 isBase64Encoded: false,1064 }10651066 // while LambdaEvent RequestContext property is mandatory, it can be absent when testing through invoke-api or AWS Console1067 // in such cases, a V1 processor should be returned1068 const processor = getProcessor(event as unknown as LambdaEvent)1069 expect(processor).toBeInstanceOf(EventV1Processor)1070 })10711072 it('Should return EventV2Processor for an APIGatewayProxyEventV2 event', () => {1073 const event: APIGatewayProxyEventV2 = {1074 version: '2.0',1075 routeKey: '$default',1076 headers: { 'content-type': 'text/plain' },1077 rawPath: '/',1078 rawQueryString: '',1079 body: null,1080 isBase64Encoded: false,1081 requestContext: testApiGatewayRequestContextV2,1082 }10831084 const processor = getProcessor(event)1085 expect(processor).toBeInstanceOf(EventV2Processor)1086 })1087})
deleted:runtime-tests/lambda/mock.ts-38 removed
1import { vi } from 'vitest'2import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'3import type { LambdaContext } from '../../src/adapter/aws-lambda/types'45type StreamifyResponseHandler = (6 handlerFunc: (7 event: LambdaEvent,8 responseStream: NodeJS.WritableStream,9 context: LambdaContext10 ) => Promise<void>11) => (event: LambdaEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>1213const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {14 return async (event, context) => {15 const mockWritableStream: NodeJS.WritableStream = new (require('stream').Writable)({16 write(chunk: Buffer, _encoding: string, callback: () => void) {17 console.log('Writing chunk:', chunk.toString())18 callback()19 },20 final(callback: () => void) {21 console.log('Finalizing stream.')22 callback()23 },24 })25 mockWritableStream.on('finish', () => {26 console.log('Stream has finished')27 })28 await handlerFunc(event, mockWritableStream, context)29 mockWritableStream.end()30 return mockWritableStream31 }32}3334const awslambda = {35 streamifyResponse: mockStreamifyResponse,36}3738vi.stubGlobal('awslambda', awslambda)
deleted:runtime-tests/lambda/stream-backpressure.test.ts-107 removed
1import { Writable } from 'node:stream'2import { streamHandle } from '../../src/adapter/aws-lambda/handler'3import type { LambdaContext } from '../../src/adapter/aws-lambda/types'4import { Hono } from '../../src/hono'56const awslambda = {7 streamifyResponse: <T>(handlerFunc: T): T => handlerFunc,8 HttpResponseStream: {9 from: (stream: Writable): Writable => stream,10 },11}1213vi.stubGlobal('awslambda', awslambda)1415type StreamingHandler = (16 event: unknown,17 responseStream: Writable,18 context: LambdaContext19) => Promise<void>2021const CHUNK_SIZE = 16 * 102422const CHUNK_COUNT = 1282324const event = {25 headers: {},26 rawPath: '/',27 rawQueryString: '',28 body: null,29 isBase64Encoded: false,30 requestContext: { http: { method: 'GET' } },31}3233describe('streamHandle backpressure', () => {34 it('should pace reads against the destination and resolve only once it has finished', async () => {35 let emittedChunks = 036 let writtenBytes = 037 let maxChunksAhead = 03839 const app = new Hono()40 app.get(41 '/',42 () =>43 new Response(44 new ReadableStream({45 pull(controller) {46 if (emittedChunks < CHUNK_COUNT) {47 emittedChunks++48 controller.enqueue(new Uint8Array(CHUNK_SIZE))49 } else {50 controller.close()51 }52 },53 })54 )55 )5657 const responseStream = new Writable({58 highWaterMark: CHUNK_SIZE,59 write(buffer: Buffer, _encoding, callback) {60 maxChunksAhead = Math.max(maxChunksAhead, emittedChunks - writtenBytes / CHUNK_SIZE)61 setImmediate(() => {62 writtenBytes += buffer.length63 callback()64 })65 },66 })6768 const handler = streamHandle(app) as unknown as StreamingHandler69 await handler(event, responseStream, {} as LambdaContext)7071 expect(writtenBytes).toBe(CHUNK_SIZE * CHUNK_COUNT)72 expect(responseStream.writableFinished).toBe(true)73 expect(maxChunksAhead).toBeLessThan(CHUNK_COUNT / 2)74 })7576 it('should report a body that errors mid-stream without rejecting', async () => {77 const app = new Hono()78 app.get(79 '/',80 () =>81 new Response(82 new ReadableStream({83 pull(controller) {84 controller.enqueue(new Uint8Array(CHUNK_SIZE))85 controller.error(new Error('body failed'))86 },87 })88 )89 )9091 const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})92 const responseStream = new Writable({93 write(_buffer, _encoding, callback) {94 setImmediate(callback)95 },96 })9798 const handler = streamHandle(app) as unknown as StreamingHandler99 await expect(handler(event, responseStream, {} as LambdaContext)).resolves.toBeUndefined()100101 expect(consoleError).toHaveBeenCalledWith(102 'Error processing request:',103 expect.objectContaining({ message: 'body failed' })104 )105 consoleError.mockRestore()106 })107})
deleted:runtime-tests/lambda/stream-mock.ts-44 removed
1import { Writable } from 'node:stream'2import { vi } from 'vitest'3import type {4 APIGatewayProxyEvent,5 APIGatewayProxyEventV2,6} from '../../src/adapter/aws-lambda/handler'7import type { LambdaContext } from '../../src/adapter/aws-lambda/types'89type StreamifyResponseHandler = (10 handlerFunc: (11 event: APIGatewayProxyEvent | APIGatewayProxyEventV2,12 responseStream: Writable,13 context: LambdaContext14 ) => Promise<void>15) => (event: APIGatewayProxyEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>1617const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {18 return async (event, context) => {19 const chunks: unknown[] = []20 const mockWritableStream = new Writable({21 write(chunk, _encoding, callback) {22 chunks.push(chunk)23 callback()24 },25 })26 // @ts-expect-error chunks property for testing27 mockWritableStream.chunks = chunks28 await handlerFunc(event, mockWritableStream, context)29 mockWritableStream.end()30 return mockWritableStream31 }32}3334const awslambda = {35 streamifyResponse: mockStreamifyResponse,36 HttpResponseStream: {37 from: (stream: Writable, httpResponseMetadata: unknown): Writable => {38 stream.write(Buffer.from(JSON.stringify(httpResponseMetadata)))39 return stream40 },41 },42}4344vi.stubGlobal('awslambda', awslambda)
deleted:runtime-tests/lambda/stream.test.ts-75 removed
1import { streamHandle } from '../../src/adapter/aws-lambda/handler'2import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'3import type {4 ApiGatewayRequestContext,5 ApiGatewayRequestContextV2,6 LambdaContext,7} from '../../src/adapter/aws-lambda/types'8import { Hono } from '../../src/hono'9import './stream-mock'1011type Bindings = {12 event: LambdaEvent13 lambdaContext: LambdaContext14 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV215}1617const testApiGatewayRequestContextV2 = {18 accountId: '123456789012',19 apiId: 'urlid',20 authentication: null,21 authorizer: {22 iam: {23 accessKey: 'AKIA...',24 accountId: '111122223333',25 callerId: 'AIDA...',26 cognitoIdentity: null,27 principalOrgId: null,28 userArn: 'arn:aws:iam::111122223333:user/example-user',29 userId: 'AIDA...',30 },31 },32 domainName: 'example.com',33 domainPrefix: '<url-id>',34 http: {35 method: 'GET',36 path: '/my/path',37 protocol: 'HTTP/1.1',38 sourceIp: '123.123.123.123',39 userAgent: 'agent',40 },41 requestId: 'id',42 routeKey: '$default',43 stage: '$default',44 time: '12/Mar/2020:19:03:58 +0000',45 timeEpoch: 1583348638390,46 customProperty: 'customValue',47}4849describe('streamHandle function', () => {50 const app = new Hono<{ Bindings: Bindings }>()5152 app.get('/cookies', async (c) => {53 c.res.headers.append('Set-Cookie', 'cookie1=value1')54 c.res.headers.append('Set-Cookie', 'cookie2=value2')55 return c.text('Cookies Set')56 })5758 const handler = streamHandle(app)5960 it('to write multiple cookies into the headers', async () => {61 const event = {62 headers: { 'content-type': 'text/plain' },63 rawPath: '/cookies',64 rawQueryString: '',65 body: null,66 isBase64Encoded: false,67 requestContext: testApiGatewayRequestContextV2,68 }6970 const stream = await handler(event, {} as LambdaContext, vi.fn())7172 const metadata = JSON.parse(stream.chunks[0].toString())73 expect(metadata.cookies).toEqual(['cookie1=value1', 'cookie2=value2'])74 })75})
deleted:runtime-tests/lambda/tsconfig.json-10 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "noEmit": true,5 "types": ["vitest/globals"]6 },7 "references": [8 { "path": "../../tsconfig.build.json" }9 ]10}
deleted:runtime-tests/lambda/vitest.config.ts-11 removed
1import { defineProject } from 'vitest/config'23export default defineProject({4 test: {5 env: {6 NAME: 'Node',7 },8 globals: true,9 name: 'lambda',10 },11})
deleted:runtime-tests/lambda-edge/index.test.ts-1134 removed
1import type {2 Callback,3 CloudFrontConfig,4 CloudFrontRequest,5 CloudFrontResponse,6} from '../../src/adapter/lambda-edge/handler'7import { handle } from '../../src/adapter/lambda-edge/handler'8import { Hono } from '../../src/hono'9import { basicAuth } from '../../src/middleware/basic-auth'1011type Bindings = {12 callback: Callback13 config: CloudFrontConfig14 request: CloudFrontRequest15 response: CloudFrontResponse16}1718describe('Lambda@Edge Adapter for Hono', () => {19 const app = new Hono<{ Bindings: Bindings }>()2021 app.get('/', (c) => {22 return c.text('Hello Lambda!')23 })2425 app.get('/binary', (c) => {26 return c.body('Fake Image', 200, {27 'Content-Type': 'image/png',28 })29 })3031 app.post('/post', async (c) => {32 const body = (await c.req.parseBody()) as { message: string }33 return c.text(body.message)34 })3536 app.get('/callback/request', async (c, next) => {37 await next()38 c.env.callback(null, c.env.request)39 })4041 app.get('/config/eventCheck', async (c, next) => {42 await next()43 if (c.env.config.eventType in ['viewer-request', 'origin-request']) {44 c.env.callback(null, c.env.request)45 } else {46 c.env.callback(null, c.env.response)47 }48 })4950 app.get('/callback/response', async (c, next) => {51 await next()52 c.env.callback(null, c.env.response)53 })5455 app.post('/post/binary', async (c) => {56 const body = await c.req.blob()57 return c.text(`${body.size} bytes`)58 })5960 const username = 'hono-user-a'61 const password = 'hono-password-a'62 app.use('/auth/*', basicAuth({ username, password }))63 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))6465 app.get('/header/add', async (c, next) => {66 c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [67 {68 key: 'Strict-Transport-Security',69 value: 'max-age=63072000; includeSubdomains; preload',70 },71 ]72 c.env.response.headers['X-Custom'.toLowerCase()] = [73 {74 key: 'X-Custom',75 value: 'Foo',76 },77 ]78 await next()79 c.env.callback(null, c.env.response)80 })8182 const handler = handle(app)8384 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {85 const event = {86 Records: [87 {88 cf: {89 config: {90 distributionDomainName: 'd111111abcdef8.cloudfront.net',91 distributionId: 'EDFDVBD6EXAMPLE',92 eventType: 'viewer-request',93 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',94 },95 request: {96 clientIp: '203.0.113.178',97 headers: {98 host: [99 {100 key: 'Host',101 value: 'd111111abcdef8.cloudfront.net',102 },103 ],104 'user-agent': [105 {106 key: 'User-Agent',107 value: 'curl/7.66.0',108 },109 ],110 accept: [111 {112 key: 'accept',113 value: '*/*',114 },115 ],116 },117 method: 'GET',118 querystring: '',119 uri: '/',120 },121 },122 },123 ],124 }125 const response = await handler(event)126 expect(response).toMatchObject({ status: '200' })127 expect(response.body).toBe('Hello Lambda!')128 if (response.headers && response.headers['content-type']) {129 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)130 } else {131 throw new Error("'content-type' header is missing in the response")132 }133 })134135 it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {136 const event = {137 Records: [138 {139 cf: {140 config: {141 distributionDomainName: 'd111111abcdef8.cloudfront.net',142 distributionId: 'EDFDVBD6EXAMPLE',143 eventType: 'origin-request',144 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',145 },146 request: {147 clientIp: '203.0.113.178',148 headers: {149 'x-forwarded-for': [150 {151 key: 'X-Forwarded-For',152 value: '203.0.113.178',153 },154 ],155 'user-agent': [156 {157 key: 'User-Agent',158 value: 'Amazon CloudFront',159 },160 ],161 via: [162 {163 key: 'Via',164 value: '2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)',165 },166 ],167 host: [168 {169 key: 'Host',170 value: 'example.org',171 },172 ],173 'cache-control': [174 {175 key: 'Cache-Control',176 value: 'no-cache',177 },178 ],179 },180 method: 'GET',181 origin: {182 custom: {183 customHeaders: {},184 domainName: 'example.org',185 keepaliveTimeout: 5,186 path: '',187 port: 443,188 protocol: 'https',189 readTimeout: 30,190 sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],191 },192 },193 querystring: '',194 uri: '/',195 },196 },197 },198 ],199 }200 const response = await handler(event)201 expect(response).toMatchObject({ status: '200' })202 expect(response.body).toBe('Hello Lambda!')203 if (response.headers && response.headers['content-type']) {204 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)205 } else {206 throw new Error("'content-type' header is missing in the response")207 }208 })209210 it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {211 const event = {212 Records: [213 {214 cf: {215 config: {216 distributionDomainName: 'd111111abcdef8.cloudfront.net',217 distributionId: 'EDFDVBD6EXAMPLE',218 eventType: 'viewer-response',219 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',220 },221 request: {222 clientIp: '203.0.113.178',223 headers: {224 host: [225 {226 key: 'Host',227 value: 'd111111abcdef8.cloudfront.net',228 },229 ],230 'user-agent': [231 {232 key: 'User-Agent',233 value: 'curl/7.66.0',234 },235 ],236 accept: [237 {238 key: 'accept',239 value: '*/*',240 },241 ],242 },243 method: 'GET',244 querystring: '',245 uri: '/',246 },247 response: {248 headers: {249 'access-control-allow-credentials': [250 {251 key: 'Access-Control-Allow-Credentials',252 value: 'true',253 },254 ],255 'access-control-allow-origin': [256 {257 key: 'Access-Control-Allow-Origin',258 value: '*',259 },260 ],261 date: [262 {263 key: 'Date',264 value: 'Mon, 13 Jan 2020 20:14:56 GMT',265 },266 ],267 'referrer-policy': [268 {269 key: 'Referrer-Policy',270 value: 'no-referrer-when-downgrade',271 },272 ],273 server: [274 {275 key: 'Server',276 value: 'ExampleCustomOriginServer',277 },278 ],279 'x-content-type-options': [280 {281 key: 'X-Content-Type-Options',282 value: 'nosniff',283 },284 ],285 'x-frame-options': [286 {287 key: 'X-Frame-Options',288 value: 'DENY',289 },290 ],291 'x-xss-protection': [292 {293 key: 'X-XSS-Protection',294 value: '1; mode=block',295 },296 ],297 age: [298 {299 key: 'Age',300 value: '2402',301 },302 ],303 'content-type': [304 {305 key: 'Content-Type',306 value: 'text/html; charset=utf-8',307 },308 ],309 'content-length': [310 {311 key: 'Content-Length',312 value: '9593',313 },314 ],315 },316 status: '200',317 statusDescription: 'OK',318 },319 },320 },321 ],322 }323 const response = await handler(event)324 expect(response).toMatchObject({ status: '200' })325 expect(response.body).toBe('Hello Lambda!')326 if (response.headers && response.headers['content-type']) {327 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)328 } else {329 throw new Error("'content-type' header is missing in the response")330 }331 })332333 it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {334 const event = {335 Records: [336 {337 cf: {338 config: {339 distributionDomainName: 'd111111abcdef8.cloudfront.net',340 distributionId: 'EDFDVBD6EXAMPLE',341 eventType: 'origin-response',342 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',343 },344 request: {345 clientIp: '203.0.113.178',346 headers: {347 'x-forwarded-for': [348 {349 key: 'X-Forwarded-For',350 value: '203.0.113.178',351 },352 ],353 'user-agent': [354 {355 key: 'User-Agent',356 value: 'Amazon CloudFront',357 },358 ],359 via: [360 {361 key: 'Via',362 value: '2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)',363 },364 ],365 host: [366 {367 key: 'Host',368 value: 'example.org',369 },370 ],371 'cache-control': [372 {373 key: 'Cache-Control',374 value: 'no-cache',375 },376 ],377 },378 method: 'GET',379 origin: {380 custom: {381 customHeaders: {},382 domainName: 'example.org',383 keepaliveTimeout: 5,384 path: '',385 port: 443,386 protocol: 'https',387 readTimeout: 30,388 sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],389 },390 },391 querystring: '',392 uri: '/',393 },394 response: {395 headers: {396 'access-control-allow-credentials': [397 {398 key: 'Access-Control-Allow-Credentials',399 value: 'true',400 },401 ],402 'access-control-allow-origin': [403 {404 key: 'Access-Control-Allow-Origin',405 value: '*',406 },407 ],408 date: [409 {410 key: 'Date',411 value: 'Mon, 13 Jan 2020 20:12:38 GMT',412 },413 ],414 'referrer-policy': [415 {416 key: 'Referrer-Policy',417 value: 'no-referrer-when-downgrade',418 },419 ],420 server: [421 {422 key: 'Server',423 value: 'ExampleCustomOriginServer',424 },425 ],426 'x-content-type-options': [427 {428 key: 'X-Content-Type-Options',429 value: 'nosniff',430 },431 ],432 'x-frame-options': [433 {434 key: 'X-Frame-Options',435 value: 'DENY',436 },437 ],438 'x-xss-protection': [439 {440 key: 'X-XSS-Protection',441 value: '1; mode=block',442 },443 ],444 'content-type': [445 {446 key: 'Content-Type',447 value: 'text/html; charset=utf-8',448 },449 ],450 'content-length': [451 {452 key: 'Content-Length',453 value: '9593',454 },455 ],456 },457 status: '200',458 statusDescription: 'OK',459 },460 },461 },462 ],463 }464 const response = await handler(event)465 expect(response).toMatchObject({ status: '200' })466 expect(response.body).toBe('Hello Lambda!')467 if (response.headers && response.headers['content-type']) {468 expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)469 } else {470 throw new Error("'content-type' header is missing in the response")471 }472 })473474 it('Should handle a GET request and return a 200 response with binary', async () => {475 const event = {476 Records: [477 {478 cf: {479 config: {480 distributionDomainName: 'example.com',481 distributionId: 'EXAMPLE123',482 eventType: 'viewer-request',483 requestId: 'exampleRequestId',484 },485 request: {486 clientIp: '123.123.123.123',487 headers: {488 host: [489 {490 key: 'Host',491 value: 'example.com',492 },493 ],494 },495 method: 'GET',496 querystring: '',497 uri: '/binary',498 },499 },500 },501 ],502 }503504 const response = await handler(event)505506 expect(response).toMatchObject({ status: '200' })507 expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded fake image508 if (response.headers && response.headers['content-type']) {509 expect(response.headers['content-type'][0].value).toMatch(/^image\/png/)510 } else {511 throw new Error("'content-type' header is missing in the response")512 }513 })514515 it('Should handle a GET request and return a 404 response', async () => {516 const event = {517 Records: [518 {519 cf: {520 config: {521 distributionDomainName: 'example.com',522 distributionId: 'EXAMPLE123',523 eventType: 'viewer-request',524 requestId: 'exampleRequestId',525 },526 request: {527 clientIp: '123.123.123.123',528 headers: {529 host: [530 {531 key: 'Host',532 value: 'example.com',533 },534 ],535 },536 method: 'GET',537 querystring: '',538 uri: '/nothing',539 },540 },541 },542 ],543 }544545 const response = await handler(event)546547 expect(response).toMatchObject({ status: '404' })548 })549550 it('Should handle a POST request and return a 200 response', async () => {551 const searchParam = new URLSearchParams()552 searchParam.append('message', 'Good Morning Lambda!')553554 const event = {555 Records: [556 {557 cf: {558 config: {559 distributionDomainName: 'example.com',560 distributionId: 'EXAMPLE123',561 eventType: 'viewer-request',562 requestId: 'exampleRequestId',563 },564 request: {565 clientIp: '123.123.123.123',566 headers: {567 host: [568 {569 key: 'Host',570 value: 'example.com',571 },572 ],573 'content-type': [574 {575 key: 'Content-Type',576 value: 'application/x-www-form-urlencoded',577 },578 ],579 },580 method: 'POST',581 querystring: '',582 uri: '/post',583 body: {584 inputTruncated: false,585 action: 'read-only',586 encoding: 'base64',587 data: Buffer.from(searchParam.toString()).toString('base64'),588 },589 },590 },591 },592 ],593 }594595 const response = await handler(event)596597 expect(response).toMatchObject({ status: '200' })598 expect(response.body).toBe('Good Morning Lambda!')599 })600601 it('Should handle a POST request with binary and return a 200 response', async () => {602 const array = new Uint8Array([0xc0, 0xff, 0xee])603 const buffer = Buffer.from(array)604 const event = {605 Records: [606 {607 cf: {608 config: {609 distributionDomainName: 'example.com',610 distributionId: 'EXAMPLE123',611 eventType: 'viewer-request',612 requestId: 'exampleRequestId',613 },614 request: {615 clientIp: '123.123.123.123',616 headers: {617 host: [618 {619 key: 'Host',620 value: 'example.com',621 },622 ],623 'content-type': [624 {625 key: 'Content-Type',626 value: 'application/x-www-form-urlencoded',627 },628 ],629 },630 method: 'POST',631 querystring: '',632 uri: '/post/binary',633 body: {634 inputTruncated: false,635 action: 'read-only',636 encoding: 'base64',637 data: buffer.toString('base64'),638 },639 },640 },641 },642 ],643 }644645 const response = await handler(event)646 expect(response).toMatchObject({ status: '200' })647 expect(response.body).toBe('3 bytes')648 })649650 it('Should handle a request and return a 401 response with Basic auth', async () => {651 const event = {652 Records: [653 {654 cf: {655 config: {656 distributionDomainName: 'example.com',657 distributionId: 'EXAMPLE123',658 eventType: 'viewer-request',659 requestId: 'exampleRequestId',660 },661 request: {662 clientIp: '123.123.123.123',663 headers: {664 host: [665 {666 key: 'Host',667 value: 'example.com',668 },669 ],670 'content-type': [671 {672 key: 'Content-Type',673 value: 'plain/text',674 },675 ],676 },677 method: 'GET',678 querystring: '',679 uri: '/auth/abc',680 },681 },682 },683 ],684 }685686 const response = await handler(event)687688 expect(response).toMatchObject({ status: '401' })689 })690691 it('Should handle a request and return a 401 response with Basic auth', async () => {692 const event = {693 Records: [694 {695 cf: {696 config: {697 distributionDomainName: 'example.com',698 distributionId: 'EXAMPLE123',699 eventType: 'viewer-request',700 requestId: 'exampleRequestId',701 },702 request: {703 clientIp: '123.123.123.123',704 headers: {705 host: [706 {707 key: 'Host',708 value: 'example.com',709 },710 ],711 'content-type': [712 {713 key: 'Content-Type',714 value: 'plain/text',715 },716 ],717 },718 method: 'GET',719 querystring: '',720 uri: '/auth/abc',721 },722 },723 },724 ],725 }726727 const response = await handler(event)728729 expect(response).toMatchObject({ status: '401' })730 })731732 it('Should call a callback to continue processing the request', async () => {733 const event = {734 Records: [735 {736 cf: {737 config: {738 distributionDomainName: 'example.com',739 distributionId: 'EXAMPLE123',740 eventType: 'viewer-request',741 requestId: 'exampleRequestId',742 },743 request: {744 clientIp: '123.123.123.123',745 headers: {},746 method: 'GET',747 querystring: '',748 uri: '/callback/request',749 },750 },751 },752 ],753 }754755 let called = false756 let requestClientIp = ''757758 await handler(event, {}, (_err, result) => {759 if (result && 'clientIp' in result) {760 requestClientIp = result.clientIp761 }762 called = true763 })764765 expect(called).toBe(true)766 expect(requestClientIp).toBe('123.123.123.123')767 })768769 it('Should call a callback to continue processing the response', async () => {770 const event = {771 Records: [772 {773 cf: {774 config: {775 distributionDomainName: 'example.com',776 distributionId: 'EDFDVBD6EXAMPLE',777 eventType: 'viewer-response',778 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',779 },780 request: {781 clientIp: '203.0.113.178',782 headers: {783 host: [784 {785 key: 'Host',786 value: 'example.com',787 },788 ],789 'user-agent': [790 {791 key: 'User-Agent',792 value: 'curl/7.66.0',793 },794 ],795 accept: [796 {797 key: 'accept',798 value: '*/*',799 },800 ],801 },802 method: 'GET',803 querystring: '',804 uri: '/callback/response',805 },806 response: {807 headers: {808 'access-control-allow-credentials': [809 {810 key: 'Access-Control-Allow-Credentials',811 value: 'true',812 },813 ],814 'access-control-allow-origin': [815 {816 key: 'Access-Control-Allow-Origin',817 value: '*',818 },819 ],820 date: [821 {822 key: 'Date',823 value: 'Mon, 13 Jan 2020 20:14:56 GMT',824 },825 ],826 'referrer-policy': [827 {828 key: 'Referrer-Policy',829 value: 'no-referrer-when-downgrade',830 },831 ],832 server: [833 {834 key: 'Server',835 value: 'ExampleCustomOriginServer',836 },837 ],838 'x-content-type-options': [839 {840 key: 'X-Content-Type-Options',841 value: 'nosniff',842 },843 ],844 'x-frame-options': [845 {846 key: 'X-Frame-Options',847 value: 'DENY',848 },849 ],850 'x-xss-protection': [851 {852 key: 'X-XSS-Protection',853 value: '1; mode=block',854 },855 ],856 age: [857 {858 key: 'Age',859 value: '2402',860 },861 ],862 'content-type': [863 {864 key: 'Content-Type',865 value: 'text/html; charset=utf-8',866 },867 ],868 'content-length': [869 {870 key: 'Content-Length',871 value: '9593',872 },873 ],874 },875 status: '200',876 statusDescription: 'OK',877 },878 },879 },880 ],881 }882883 interface CloudFrontHeaders {884 [name: string]: [885 {886 key: string887 value: string888 },889 ]890 }891 let called = false892 let headers: CloudFrontHeaders = {}893 await handler(event, {}, (_err, result) => {894 if (result && result.headers) {895 headers = result.headers as CloudFrontHeaders896 }897 called = true898 })899900 expect(called).toBe(true)901 expect(headers['access-control-allow-credentials']).toEqual([902 {903 key: 'Access-Control-Allow-Credentials',904 value: 'true',905 },906 ])907 expect(headers['access-control-allow-origin']).toEqual([908 {909 key: 'Access-Control-Allow-Origin',910 value: '*',911 },912 ])913 })914915 it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {916 const event = {917 Records: [918 {919 cf: {920 config: {921 distributionDomainName: 'example.com',922 distributionId: 'EDFDVBD6EXAMPLE',923 eventType: 'viewer-response',924 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',925 },926 request: {927 clientIp: '203.0.113.178',928 headers: {929 host: [930 {931 key: 'Host',932 value: 'example.com',933 },934 ],935 'user-agent': [936 {937 key: 'User-Agent',938 value: 'curl/7.66.0',939 },940 ],941 accept: [942 {943 key: 'accept',944 value: '*/*',945 },946 ],947 },948 method: 'GET',949 querystring: '',950 uri: '/header/add',951 },952 response: {953 headers: {954 'access-control-allow-credentials': [955 {956 key: 'Access-Control-Allow-Credentials',957 value: 'true',958 },959 ],960 'access-control-allow-origin': [961 {962 key: 'Access-Control-Allow-Origin',963 value: '*',964 },965 ],966 date: [967 {968 key: 'Date',969 value: 'Mon, 13 Jan 2020 20:14:56 GMT',970 },971 ],972 'referrer-policy': [973 {974 key: 'Referrer-Policy',975 value: 'no-referrer-when-downgrade',976 },977 ],978 server: [979 {980 key: 'Server',981 value: 'ExampleCustomOriginServer',982 },983 ],984 'x-content-type-options': [985 {986 key: 'X-Content-Type-Options',987 value: 'nosniff',988 },989 ],990 'x-frame-options': [991 {992 key: 'X-Frame-Options',993 value: 'DENY',994 },995 ],996 'x-xss-protection': [997 {998 key: 'X-XSS-Protection',999 value: '1; mode=block',1000 },1001 ],1002 age: [1003 {1004 key: 'Age',1005 value: '2402',1006 },1007 ],1008 'content-type': [1009 {1010 key: 'Content-Type',1011 value: 'text/html; charset=utf-8',1012 },1013 ],1014 'content-length': [1015 {1016 key: 'Content-Length',1017 value: '9593',1018 },1019 ],1020 },1021 status: '200',1022 statusDescription: 'OK',1023 },1024 },1025 },1026 ],1027 }10281029 interface CloudFrontHeaders {1030 [name: string]: [1031 {1032 key: string1033 value: string1034 },1035 ]1036 }1037 let called = false1038 let headers: CloudFrontHeaders = {}1039 await handler(event, {}, (_err, result) => {1040 if (result && result.headers) {1041 headers = result.headers as CloudFrontHeaders1042 }1043 called = true1044 })10451046 expect(called).toBe(true)1047 expect(headers['strict-transport-security']).toEqual([1048 {1049 key: 'Strict-Transport-Security',1050 value: 'max-age=63072000; includeSubdomains; preload',1051 },1052 ])1053 expect(headers['x-custom']).toEqual([1054 {1055 key: 'X-Custom',1056 value: 'Foo',1057 },1058 ])1059 })10601061 it('Callback Event (Lambda@Edge response)', async () => {1062 const event = {1063 Records: [1064 {1065 cf: {1066 config: {1067 distributionDomainName: 'example.com',1068 distributionId: 'EDFDVBD6EXAMPLE',1069 eventType: 'viewer-response',1070 requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',1071 },1072 request: {1073 clientIp: '203.0.113.178',1074 headers: {1075 host: [1076 {1077 key: 'Host',1078 value: 'example.com',1079 },1080 ],1081 },1082 method: 'GET',1083 querystring: '',1084 uri: '/config/eventCheck',1085 },1086 },1087 },1088 ],1089 }10901091 let called = false1092 await handler(event, {}, () => {1093 called = true1094 })10951096 expect(called).toBe(true)1097 })10981099 it('Should return a response where bodyEncoding is "base64" with binary', async () => {1100 const event = {1101 Records: [1102 {1103 cf: {1104 config: {1105 distributionDomainName: 'example.com',1106 distributionId: 'EXAMPLE123',1107 eventType: 'viewer-request',1108 requestId: 'exampleRequestId',1109 },1110 request: {1111 clientIp: '123.123.123.123',1112 headers: {1113 host: [1114 {1115 key: 'Host',1116 value: 'example.com',1117 },1118 ],1119 },1120 method: 'GET',1121 querystring: '',1122 uri: '/binary',1123 },1124 },1125 },1126 ],1127 }11281129 const response = await handler(event)11301131 expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded "Fake Image"1132 expect(response).toMatchObject({ bodyEncoding: 'base64' })1133 })1134})
deleted:runtime-tests/lambda-edge/tsconfig.json-10 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "noEmit": true,5 "types": ["vitest/globals"]6 },7 "references": [8 { "path": "../../tsconfig.build.json" }9 ]10}
deleted:runtime-tests/lambda-edge/vitest.config.ts-11 removed
1import { defineProject } from 'vitest/config'23export default defineProject({4 test: {5 env: {6 NAME: 'Node',7 },8 globals: true,9 name: 'lambda-edge',10 },11})
modified:runtime-tests/workerd/index.test.ts-39 removed
1import { unstable_dev } from 'wrangler'2import type { Unstable_DevWorker } from 'wrangler'3import { WebSocket } from 'ws'34describe('workerd', () => {5 let worker: Unstable_DevWorker6
29 unmodified lines
36 expect(await res.text()).toBe('True')37 })38})3941describe('workerd with WebSocket', () => {42 // worker.fetch does not support WebSocket:43 // https://github.com/cloudflare/workers-sdk/issues/4573#issuecomment-185042097344 it('Should handle the WebSocket connection correctly', async () => {45 const worker = await unstable_dev('./runtime-tests/workerd/index.ts', {46 compatibilityDate: '2026-07-01',47 experimental: { disableExperimentalWarning: true },48 })49 const ws = new WebSocket(`ws://${worker.address}:${worker.port}/ws`)5051 const openHandler = vi.fn()52 const messageHandler = vi.fn()53 const closeHandler = vi.fn()5455 const waitForOpen = new Promise((resolve) => {56 ws.addEventListener('open', () => {57 openHandler()58 ws.send('Hello')59 })60 ws.addEventListener('close', async () => {61 closeHandler()62 resolve(undefined)63 })64 ws.addEventListener('message', async (event) => {65 messageHandler(event.data)66 ws.close()67 })68 })6970 await waitForOpen71 await worker.stop()7273 expect(openHandler).toHaveBeenCalled()74 expect(messageHandler).toHaveBeenCalledWith('Hello')75 expect(closeHandler).toHaveBeenCalled()76 })77})7840describe('workerd with NO_COLOR', () => {41 let worker: Unstable_DevWorker4243 beforeAll(async () => {
19 unmodified lines
modified:runtime-tests/workerd/index.ts-12 removed
1import { upgradeWebSocket } from '../../src/adapter/cloudflare-workers'1import { env, getRuntimeKey } from '../../src/helper/adapter'2import { Hono } from '../../src/hono'3import { getColorEnabledAsync } from '../../src/utils/color'4
5 unmodified lines
10 const { NAME } = env<{ NAME: string }>(c)11 return c.text(NAME)12})1315app.get(16 '/ws',17 upgradeWebSocket(() => {18 return {19 onMessage(event, ws) {20 ws.send(event.data as string)21 },22 }23 })24)2514app.get('/color', async (c) => {15 return c.text((await getColorEnabledAsync()) ? 'True' : 'False')16})17
1 unmodified line
modified:package.json-2 removed
16 unmodified lines
17 "test:bun": "bun test --jsx-import-source ../../src/jsx runtime-tests/bun",18 "test:fastly": "vp test --run --project fastly",19 "test:node": "vp test --run --project node",20 "test:workerd": "vp test --run --project workerd",21 "test:lambda": "vp test --run --project lambda",22 "test:lambda-edge": "vp test --run --project lambda-edge",21 "test:all": "pnpm run test && pnpm run test:deno && pnpm run test:bun",22 "check": "vp check",23 "check:fix": "vp check --fix",24 "lint": "vp lint src runtime-tests build perf-measures benchmarks adapters",
682 unmodified lines
modified:pnpm-lock.yaml+9 added
245 unmodified lines
246 version: link:../..247248 adapters/cloudflare-workers:249 devDependencies:250 '@types/ws':251 specifier: ^8.18.1252 version: 8.18.1253 hono:254 specifier: workspace:*255 version: link:../..256 wrangler:257 specifier: 4.107.0258 version: 4.107.0259 ws:260 specifier: ^8.21.0261 version: 8.21.3262263 adapters/deno:264 devDependencies:265 '@types/node':
9798 unmodified lines
modified:tsconfig.json-2 removed
4 unmodified lines
5 { "path": "./tsconfig.spec.json" },6 { "path": "./perf-measures/type-check/scripts/tsconfig.json" },7 { "path": "./runtime-tests/bun/tsconfig.json" },8 { "path": "./runtime-tests/fastly/tsconfig.json" },9 { "path": "./runtime-tests/lambda/tsconfig.json" },10 { "path": "./runtime-tests/lambda-edge/tsconfig.json" },9 { "path": "./runtime-tests/node/tsconfig.json" },10 { "path": "./runtime-tests/workerd/tsconfig.json" }11 ]12}