chore: rename `runtime_tests` to `runtime-tests` (#3419)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* chore: rename `runtime_tests` to `runtime-tests` * fixed GitHub workflow
authored by Yusuke Wada · committed by GitHub · parent b5c6285 · Browse files · 81 files·+3840 added−3840 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
81 files+3840 added−3840 removed
- tests:+3497 added−3497 removed
- other:+343 added−343 removed
Provenance
- Commit
dfbd717- Tree
609ad1f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
b5c6285
81 files changed+3840 added−3840 removed
modified:.github/workflows/ci.yml+3 added-3 removed
75 unmodified lines767778798081828081828384858693 unmodified lines75 unmodified lines - uses: actions/checkout@v4 - uses: denoland/setup-deno@v1 with: deno-version: v1.x - run: env NAME=Deno deno test --coverage=coverage/raw/deno-runtime --allow-read --allow-env --allow-write --allow-net -c runtime_tests/deno/deno.json runtime_tests/deno - run: deno test -c runtime_tests/deno-jsx/deno.precompile.json --coverage=coverage/raw/deno-precompile-jsx runtime_tests/deno-jsx - run: deno test -c runtime_tests/deno-jsx/deno.react-jsx.json --coverage=coverage/raw/deno-react-jsx runtime_tests/deno-jsx - run: env NAME=Deno deno test --coverage=coverage/raw/deno-runtime --allow-read --allow-env --allow-write --allow-net -c runtime-tests/deno/deno.json runtime-tests/deno - run: deno test -c runtime-tests/deno-jsx/deno.precompile.json --coverage=coverage/raw/deno-precompile-jsx runtime-tests/deno-jsx - run: deno test -c runtime-tests/deno-jsx/deno.react-jsx.json --coverage=coverage/raw/deno-react-jsx runtime-tests/deno-jsx - uses: actions/upload-artifact@v4 with: name: coverage-deno path: coverage/93 unmodified linesdeleted:runtime_tests/bun/.static/plain.txt-1 removed
1-Bun!!deleted:runtime_tests/bun/static/hello.world/index.html-1 removed
1Hideleted:runtime_tests/bun/static/helloworld/index.html-1 removed
1Hideleted:runtime_tests/bun/static/download-1 removed
1-downloaddeleted:runtime_tests/bun/static/plain.txt-1 removed
1-Bun!deleted:runtime_tests/bun/favicon.icobinary
A binary file, deleted.
deleted:runtime_tests/bun/index.test.tsx-432 removed
1-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2-import { stream, streamSSE } from '../..//src/helper/streaming'3-import { serveStatic, toSSG } from '../../src/adapter/bun'4-import { createBunWebSocket } from '../../src/adapter/bun/websocket'5-import type { BunWebSocketData } from '../../src/adapter/bun/websocket'6-import { Context } from '../../src/context'7-import { env, getRuntimeKey } from '../../src/helper/adapter'8-import type { WSMessageReceive } from '../../src/helper/websocket'9-import { Hono } from '../../src/index'10-// eslint-disable-next-line @typescript-eslint/no-unused-vars11-import { jsx } from '../../src/jsx'12-import { basicAuth } from '../../src/middleware/basic-auth'13-import { jwt } from '../../src/middleware/jwt'14-import { HonoRequest } from '../../src/request'15-16-// Test just only minimal patterns.17-// Because others are tested well in Cloudflare Workers environment already.18-19-Bun.env.NAME = 'Bun'20-21-describe('Basic', () => {22- const app = new Hono()23- app.get('/a/:foo', (c) => {24- c.header('x-param', c.req.param('foo'))25- c.header('x-query', c.req.query('q'))26- return c.text('Hello Bun!')27- })28-29- it('Should return 200 Response', async () => {30- const req = new Request('http://localhost/a/foo?q=bar')31- const res = await app.request(req)32- expect(res.status).toBe(200)33- expect(await res.text()).toBe('Hello Bun!')34- expect(res.headers.get('x-param')).toBe('foo')35- expect(res.headers.get('x-query')).toBe('bar')36- })37-38- it('returns current runtime (bun)', async () => {39- expect(getRuntimeKey()).toBe('bun')40- })41-})42-43-describe('Environment Variables', () => {44- it('Should return the environment variable', async () => {45- const c = new Context(new HonoRequest(new Request('http://localhost/')))46- const { NAME } = env<{ NAME: string }>(c)47- expect(NAME).toBe('Bun')48- })49-})50-51-describe('Basic Auth Middleware', () => {52- const app = new Hono()53-54- const username = 'hono-user-a'55- const password = 'hono-password-a'56- app.use(57- '/auth/*',58- basicAuth({59- username,60- password,61- })62- )63-64- app.get('/auth/*', () => new Response('auth'))65-66- it('Should not authorize, return 401 Response', async () => {67- const req = new Request('http://localhost/auth/a')68- const res = await app.request(req)69- expect(res.status).toBe(401)70- expect(await res.text()).toBe('Unauthorized')71- })72-73- it('Should authorize, return 200 Response', async () => {74- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'75- const req = new Request('http://localhost/auth/a')76- req.headers.set('Authorization', `Basic ${credential}`)77- const res = await app.request(req)78- expect(res.status).toBe(200)79- expect(await res.text()).toBe('auth')80- })81-})82-83-describe('Serve Static Middleware', () => {84- const app = new Hono()85- const onNotFound = vi.fn(() => {})86- app.all('/favicon.ico', serveStatic({ path: './runtime_tests/bun/favicon.ico' }))87- app.all(88- '/favicon-notfound.ico',89- serveStatic({ path: './runtime_tests/bun/favicon-notfound.ico', onNotFound })90- )91- app.use('/favicon-notfound.ico', async (c, next) => {92- await next()93- c.header('X-Custom', 'Bun')94- })95- app.get(96- '/static/*',97- serveStatic({98- root: './runtime_tests/bun/',99- onNotFound,100- })101- )102- app.get(103- '/dot-static/*',104- serveStatic({105- root: './runtime_tests/bun/',106- rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),107- })108- )109-110- beforeEach(() => onNotFound.mockClear())111-112- it('Should return static file correctly', async () => {113- const res = await app.request(new Request('http://localhost/favicon.ico'))114- await res.arrayBuffer()115- expect(res.status).toBe(200)116- expect(res.headers.get('Content-Type')).toBe('image/x-icon')117- })118-119- it('Should return 404 response', async () => {120- const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))121- expect(res.status).toBe(404)122- expect(res.headers.get('X-Custom')).toBe('Bun')123- expect(onNotFound).toHaveBeenCalledWith(124- './runtime_tests/bun/favicon-notfound.ico',125- expect.anything()126- )127- })128-129- it('Should return 200 response - /static/plain.txt', async () => {130- const res = await app.request(new Request('http://localhost/static/plain.txt'))131- expect(res.status).toBe(200)132- expect(await res.text()).toBe('Bun!')133- expect(onNotFound).not.toHaveBeenCalled()134- })135-136- it('Should return 200 response - /static/download', async () => {137- const res = await app.request(new Request('http://localhost/static/download'))138- expect(res.status).toBe(200)139- expect(await res.text()).toBe('download')140- expect(onNotFound).not.toHaveBeenCalled()141- })142-143- it('Should return 200 response - /dot-static/plain.txt', async () => {144- const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))145- expect(res.status).toBe(200)146- expect(await res.text()).toBe('Bun!!')147- })148-149- it('Should return 200 response - /static/helloworld', async () => {150- const res = await app.request('http://localhost/static/helloworld')151- expect(res.status).toBe(200)152- expect(await res.text()).toBe('Hi\n')153- })154-155- it('Should return 200 response - /static/hello.world', async () => {156- const res = await app.request('http://localhost/static/hello.world')157- expect(res.status).toBe(200)158- expect(await res.text()).toBe('Hi\n')159- })160-})161-162-// Bun support WebCrypto since v0.2.2163-// So, JWT middleware works well.164-describe('JWT Auth Middleware', () => {165- const app = new Hono()166- app.use('/jwt/*', jwt({ secret: 'a-secret' }))167- app.get('/jwt/a', (c) => c.text('auth'))168-169- it('Should not authorize, return 401 Response', async () => {170- const req = new Request('http://localhost/jwt/a')171- const res = await app.request(req)172- expect(res.status).toBe(401)173- expect(await res.text()).toBe('Unauthorized')174- })175-176- it('Should authorize, return 200 Response', async () => {177- const credential =178- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'179- const req = new Request('http://localhost/jwt/a')180- req.headers.set('Authorization', `Bearer ${credential}`)181- const res = await app.request(req)182- expect(res.status).toBe(200)183- expect(await res.text()).toBe('auth')184- })185-})186-187-// To enable JSX middleware,188-// set "jsxImportSource": "hono/jsx" in the tsconfig.json189-describe('JSX Middleware', () => {190- const app = new Hono()191-192- const Layout = (props: { children?: string }) => {193- return <html>{props.children}</html>194- }195-196- app.get('/', (c) => {197- return c.html(<h1>Hello</h1>)198- })199- app.get('/nest', (c) => {200- return c.html(201- <h1>202- <a href='/top'>Hello</a>203- </h1>204- )205- })206- app.get('/layout', (c) => {207- return c.html(208- <Layout>209- <p>hello</p>210- </Layout>211- )212- })213-214- it('Should return rendered HTML', async () => {215- const res = await app.request(new Request('http://localhost/'))216- expect(res.status).toBe(200)217- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')218- expect(await res.text()).toBe('<h1>Hello</h1>')219- })220-221- it('Should return rendered HTML with nest', async () => {222- const res = await app.request(new Request('http://localhost/nest'))223- expect(res.status).toBe(200)224- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')225- expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')226- })227-228- it('Should return rendered HTML with Layout', async () => {229- const res = await app.request(new Request('http://localhost/layout'))230- expect(res.status).toBe(200)231- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')232- expect(await res.text()).toBe('<html><p>hello</p></html>')233- })234-})235-236-describe('toSSG function', () => {237- let app: Hono238-239- beforeEach(() => {240- app = new Hono()241- app.get('/', (c) => c.text('Hello, World!'))242- app.get('/about', (c) => c.text('About Page'))243- app.get('/about/some', (c) => c.text('About Page 2tier'))244- app.post('/about/some/thing', (c) => c.text('About Page 3tier'))245- app.get('/bravo', (c) => c.html('Bravo Page'))246- app.get('/Charlie', async (c, next) => {247- c.setRenderer((content, head) => {248- return c.html(249- <html>250- <head>251- <title>{head.title || ''}</title>252- </head>253- <body>254- <p>{content}</p>255- </body>256- </html>257- )258- })259- await next()260- })261- app.get('/Charlie', (c) => {262- return c.render('Hello!', { title: 'Charlies Page' })263- })264- })265-266- it('Should correctly generate static HTML files for Hono routes', async () => {267- const result = await toSSG(app, { dir: './static' })268- expect(result.success).toBeTruly269- expect(result.error).toBeUndefined()270- expect(result.files).toBeDefined()271- afterAll(async () => {272- await deleteDirectory('./static')273- })274- })275-})276-277-describe('WebSockets Helper', () => {278- const app = new Hono()279- const { websocket, upgradeWebSocket } = createBunWebSocket()280-281- it('Should websockets is working', async () => {282- const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>283- app.get(284- '/ws',285- upgradeWebSocket(() => ({286- onMessage(evt) {287- resolve(evt.data)288- },289- }))290- )291- )292- const upgradedData = await new Promise<BunWebSocketData>((resolve) =>293- app.fetch(new Request('http://localhost/ws'), {294- upgrade: (_req: Request, data: { data: BunWebSocketData }) => {295- resolve(data.data)296- },297- })298- )299- const message = Math.random().toString()300- websocket.message(301- {302- close: () => undefined,303- readyState: 3,304- data: upgradedData,305- send: () => undefined,306- },307- message308- )309- const receivedMessage = await receivedMessagePromise310- expect(receivedMessage).toBe(message)311- })312-})313-const fs = require('fs').promises314-const path = require('path')315-316-async function deleteDirectory(dirPath) {317- if (318- await fs319- .stat(dirPath)320- .then((stat) => stat.isDirectory())321- .catch(() => false)322- ) {323- for (const entry of await fs.readdir(dirPath)) {324- const entryPath = path.join(dirPath, entry)325- await deleteDirectory(entryPath)326- }327- await fs.rmdir(dirPath)328- } else {329- await fs.unlink(dirPath)330- }331-}332-333-describe('streaming', () => {334- const app = new Hono()335- let server: ReturnType<typeof Bun.serve>336- let aborted = false337-338- app.get('/stream', (c) => {339- return stream(c, async (stream) => {340- stream.onAbort(() => {341- aborted = true342- })343- return new Promise<void>((resolve) => {344- stream.onAbort(resolve)345- })346- })347- })348- app.get('/streamHello', (c) => {349- return stream(c, async (stream) => {350- stream.onAbort(() => {351- aborted = true352- })353- await stream.write('Hello')354- })355- })356- app.get('/streamSSE', (c) => {357- return streamSSE(c, async (stream) => {358- stream.onAbort(() => {359- aborted = true360- })361- return new Promise<void>((resolve) => {362- stream.onAbort(resolve)363- })364- })365- })366- app.get('/streamSSEHello', (c) => {367- return streamSSE(c, async (stream) => {368- stream.onAbort(() => {369- aborted = true370- })371- await stream.write('Hello')372- })373- })374-375- beforeEach(() => {376- aborted = false377- server = Bun.serve({ port: 0, fetch: app.fetch })378- })379-380- afterEach(() => {381- server.stop()382- })383-384- describe('stream', () => {385- it('Should call onAbort', async () => {386- const ac = new AbortController()387- const req = new Request(`http://localhost:${server.port}/stream`, {388- signal: ac.signal,389- })390- expect(aborted).toBe(false)391- const res = fetch(req).catch(() => {})392- await new Promise((resolve) => setTimeout(resolve, 10))393- ac.abort()394- await res395- while (!aborted) {396- await new Promise((resolve) => setTimeout(resolve))397- }398- expect(aborted).toBe(true)399- })400-401- it('Should not be called onAbort if already closed', async () => {402- expect(aborted).toBe(false)403- const res = await fetch(`http://localhost:${server.port}/streamHello`)404- expect(await res.text()).toBe('Hello')405- expect(aborted).toBe(false)406- })407- })408-409- describe('streamSSE', () => {410- it('Should call onAbort', async () => {411- const ac = new AbortController()412- const req = new Request(`http://localhost:${server.port}/streamSSE`, {413- signal: ac.signal,414- })415- const res = fetch(req).catch(() => {})416- await new Promise((resolve) => setTimeout(resolve, 10))417- ac.abort()418- await res419- while (!aborted) {420- await new Promise((resolve) => setTimeout(resolve))421- }422- expect(aborted).toBe(true)423- })424-425- it('Should not be called onAbort if already closed', async () => {426- expect(aborted).toBe(false)427- const res = await fetch(`http://localhost:${server.port}/streamSSEHello`)428- expect(await res.text()).toBe('Hello')429- expect(aborted).toBe(false)430- })431- })432-})deleted:runtime_tests/bun/vitest.config.ts-14 removed
1234567891011121314/// <reference types="vitest" />import { defineConfig } from 'vitest/config'import config from '../../vitest.config'
export default defineConfig({ test: { globals: true, include: ['**/runtime_tests/bun/**/*.+(ts|tsx|js)'], coverage: { ...config.test?.coverage, reportsDirectory: './coverage/raw/runtime-bun', }, },})deleted:runtime_tests/deno/.static/plain.txt-1 removed
1-Deno!!deleted:runtime_tests/deno/.vscode/settings.json-7 removed
1-{2- "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],3- "editor.codeActionsOnSave": {4- "source.fixAll.eslint": true5- },6- "deno.enable": true7-}deleted:runtime_tests/deno/static/hello.world/index.html-1 removed
1-Hideleted:runtime_tests/deno/static/helloworld/index.html-1 removed
1-Hideleted:runtime_tests/deno/static/download-1 removed
1-downloaddeleted:runtime_tests/deno/static/plain.txt-1 removed
1-Deno!deleted:runtime_tests/deno/deno.json-19 removed
1-{2- "compilerOptions": {3- "jsx": "react-jsx",4- "jsxImportSource": "hono/jsx",5- "lib": [6- "deno.ns",7- "dom",8- "dom.iterable"9- ]10- },11- "unstable": [12- "sloppy-imports"13- ],14- "imports": {15- "@std/assert": "jsr:@std/assert@^1.0.3",16- "@std/testing": "jsr:@std/testing@^1.0.1",17- "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"18- }19-}deleted:runtime_tests/deno/deno.lock-34 removed
1-{2- "version": "3",3- "packages": {4- "specifiers": {5- "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.3",6- "jsr:@std/internal@^1.0.2": "jsr:@std/internal@1.0.2",7- "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.1"8- },9- "jsr": {10- "@std/assert@1.0.3": {11- "integrity": "b0d03ce1ced880df67132eea140623010d415848df66f6aa5df76507ca7c26d8",12- "dependencies": [13- "jsr:@std/internal@^1.0.2"14- ]15- },16- "@std/internal@1.0.2": {17- "integrity": "f4cabe2021352e8bfc24e6569700df87bf070914fc38d4b23eddd20108ac4495"18- },19- "@std/testing@1.0.1": {20- "integrity": "9c25841137ee818933e1722091bb9ed5fdc251c35e84c97979a52196bdb6c5c3",21- "dependencies": [22- "jsr:@std/assert@^1.0.3"23- ]24- }25- }26- },27- "remote": {},28- "workspace": {29- "dependencies": [30- "jsr:@std/assert@^1.0.3",31- "jsr:@std/testing@^1.0.1"32- ]33- }34-}deleted:runtime_tests/deno/favicon.icobinary
A binary file, deleted.
deleted:runtime_tests/deno/hono.test.ts-34 removed
1-import { assertEquals } from '@std/assert'2-import { Context } from '../../src/context.ts'3-import { env, getRuntimeKey } from '../../src/helper/adapter/index.ts'4-import { Hono } from '../../src/hono.ts'5-6-// Test just only minimal patterns.7-// Because others are tested well in Cloudflare Workers environment already.8-9-Deno.env.set('NAME', 'Deno')10-11-Deno.test('Hello World', async () => {12- const app = new Hono()13- app.get('/:foo', (c) => {14- c.header('x-param', c.req.param('foo'))15- c.header('x-query', c.req.query('q') || '')16- return c.text('Hello Deno!')17- })18-19- const res = await app.request('/foo?q=bar')20- assertEquals(res.status, 200)21- assertEquals(await res.text(), 'Hello Deno!')22- assertEquals(res.headers.get('x-param'), 'foo')23- assertEquals(res.headers.get('x-query'), 'bar')24-})25-26-Deno.test('runtime', () => {27- assertEquals(getRuntimeKey(), 'deno')28-})29-30-Deno.test('environment variables', () => {31- const c = new Context(new Request('http://localhost/'))32- const { NAME } = env<{ NAME: string }>(c)33- assertEquals(NAME, 'Deno')34-})deleted:runtime_tests/deno/middleware.test.tsx-163 removed
1-import { assertEquals, assertMatch } from '@std/assert'2-import { assertSpyCall, assertSpyCalls, spy } from '@std/testing/mock'3-import { serveStatic } from '../../src/adapter/deno/index.ts'4-import { Hono } from '../../src/hono.ts'5-import { basicAuth } from '../../src/middleware/basic-auth/index.ts'6-import { jwt } from '../../src/middleware/jwt/index.ts'7-8-// Test just only minimal patterns.9-// Because others are already tested well in Cloudflare Workers environment.10-11-Deno.test('Basic Auth Middleware', async () => {12- const app = new Hono()13-14- const username = 'hono'15- const password = 'acoolproject'16-17- app.use(18- '/auth/*',19- basicAuth({20- username,21- password,22- })23- )24-25- app.get('/auth/*', () => new Response('auth'))26-27- const res = await app.request('http://localhost/auth/a')28- assertEquals(res.status, 401)29- assertEquals(await res.text(), 'Unauthorized')30-31- const credential = 'aG9ubzphY29vbHByb2plY3Q='32-33- const req = new Request('http://localhost/auth/a')34- req.headers.set('Authorization', `Basic ${credential}`)35- const resOK = await app.request(req)36- assertEquals(resOK.status, 200)37- assertEquals(await resOK.text(), 'auth')38-39- const invalidCredential = 'G9ubzphY29vbHByb2plY3Q='40-41- const req2 = new Request('http://localhost/auth/a')42- req2.headers.set('Authorization', `Basic ${invalidCredential}`)43- const resNG = await app.request(req2)44- assertEquals(resNG.status, 401)45- assertEquals(await resNG.text(), 'Unauthorized')46-})47-48-Deno.test('JSX middleware', async () => {49- const app = new Hono()50- app.get('/', (c) => {51- return c.html(<h1>Hello</h1>)52- })53- const res = await app.request('http://localhost/')54- assertEquals(res.status, 200)55- assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')56- assertEquals(await res.text(), '<h1>Hello</h1>')57-58- // Fragment59- const template = (60- <>61- <p>1</p>62- <p>2</p>63- </>64- )65- assertEquals(template.toString(), '<p>1</p><p>2</p>')66-})67-68-Deno.test('Serve Static middleware', async () => {69- const app = new Hono()70- const onNotFound = spy(() => {})71- app.all('/favicon.ico', serveStatic({ path: './runtime_tests/deno/favicon.ico' }))72- app.all(73- '/favicon-notfound.ico',74- serveStatic({ path: './runtime_tests/deno/favicon-notfound.ico', onNotFound })75- )76- app.use('/favicon-notfound.ico', async (c, next) => {77- await next()78- c.header('X-Custom', 'Deno')79- })80-81- app.get(82- '/static/*',83- serveStatic({84- root: './runtime_tests/deno',85- onNotFound,86- })87- )88-89- app.get(90- '/dot-static/*',91- serveStatic({92- root: './runtime_tests/deno',93- rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),94- })95- )96-97- let res = await app.request('http://localhost/favicon.ico')98- assertEquals(res.status, 200)99- assertEquals(res.headers.get('Content-Type'), 'image/x-icon')100- await res.body?.cancel()101-102- res = await app.request('http://localhost/favicon-notfound.ico')103- assertEquals(res.status, 404)104- assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)105- assertEquals(res.headers.get('X-Custom'), 'Deno')106- assertSpyCall(onNotFound, 0)107-108- res = await app.request('http://localhost/static/plain.txt')109- assertEquals(res.status, 200)110- assertEquals(await res.text(), 'Deno!')111-112- res = await app.request('http://localhost/static/download')113- assertEquals(res.status, 200)114- assertEquals(await res.text(), 'download')115-116- res = await app.request('http://localhost/dot-static/plain.txt')117- assertEquals(res.status, 200)118- assertEquals(await res.text(), 'Deno!!')119- assertSpyCalls(onNotFound, 1)120-121- res = await app.fetch({122- method: 'GET',123- url: 'http://localhost/static/%2e%2e/static/plain.txt',124- } as Request)125- assertEquals(res.status, 404)126- assertEquals(await res.text(), '404 Not Found')127-128- res = await app.request('http://localhost/static/helloworld')129- assertEquals(res.status, 200)130- assertEquals(await res.text(), 'Hi\n')131-132- res = await app.request('http://localhost/static/hello.world')133- assertEquals(res.status, 200)134- assertEquals(await res.text(), 'Hi\n')135-})136-137-Deno.test('JWT Authentication middleware', async () => {138- const app = new Hono<{ Variables: { 'x-foo': string } }>()139- app.use('/*', async (c, next) => {140- await next()141- c.header('x-foo', c.get('x-foo') || '')142- })143- app.use('/auth/*', jwt({ secret: 'a-secret' }))144- app.get('/auth/*', (c) => {145- c.set('x-foo', 'bar')146- return new Response('auth')147- })148-149- const req = new Request('http://localhost/auth/a')150- const res = await app.request(req)151- assertEquals(res.status, 401)152- assertEquals(await res.text(), 'Unauthorized')153- assertEquals(res.headers.get('x-foo'), '')154-155- const credential =156- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'157- const reqOK = new Request('http://localhost/auth/a')158- reqOK.headers.set('Authorization', `Bearer ${credential}`)159- const resOK = await app.request(reqOK)160- assertEquals(resOK.status, 200)161- assertEquals(await resOK.text(), 'auth')162- assertEquals(resOK.headers.get('x-foo'), 'bar')163-})deleted:runtime_tests/deno/ssg.test.tsx-52 removed
1-import { assertEquals } from '@std/assert'2-import { toSSG } from '../../src/adapter/deno/ssg.ts'3-import { Hono } from '../../src/hono.ts'4-5-Deno.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- })27-28- const result = await toSSG(app, { dir: './ssg-static' })29- assertEquals(result.success, true)30- assertEquals(result.error, undefined)31- assertEquals(result.files !== undefined, true)32-33- await deleteDirectory('./ssg-static')34-})35-36-async function deleteDirectory(dirPath: string): Promise<void> {37- try {38- const stat = await Deno.stat(dirPath)39-40- 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/deno/stream.test.ts-108 removed
1-import { assertEquals } from '@std/assert'2-import { stream, streamSSE } from '../../src/helper/streaming/index.ts'3-import { Hono } from '../../src/hono.ts'4-5-Deno.test('Shuld call onAbort via stream', async () => {6- const app = new Hono()7- let aborted = false8- app.get('/stream', (c) => {9- return stream(c, (stream) => {10- stream.onAbort(() => {11- aborted = true12- })13- return new Promise<void>((resolve) => {14- stream.onAbort(resolve)15- })16- })17- })18-19- const server = Deno.serve({ port: 0 }, app.fetch)20- const ac = new AbortController()21- const req = new Request(`http://localhost:${server.addr.port}/stream`, {22- signal: ac.signal,23- })24- const res = fetch(req).catch(() => {})25- assertEquals(aborted, false)26- await new Promise((resolve) => setTimeout(resolve, 10))27- ac.abort()28- await res29- while (!aborted) {30- await new Promise((resolve) => setTimeout(resolve))31- }32- assertEquals(aborted, true)33-34- await server.shutdown()35-})36-37-Deno.test('Shuld not call onAbort via stream if already closed', async () => {38- const app = new Hono()39- let aborted = false40- app.get('/stream', (c) => {41- return stream(c, async (stream) => {42- stream.onAbort(() => {43- aborted = true44- })45- await stream.write('Hello')46- })47- })48-49- const server = Deno.serve({ port: 0 }, app.fetch)50- assertEquals(aborted, false)51- const res = await fetch(`http://localhost:${server.addr.port}/stream`)52- assertEquals(await res.text(), 'Hello')53- assertEquals(aborted, false)54- await server.shutdown()55-})56-57-Deno.test('Shuld call onAbort via streamSSE', async () => {58- const app = new Hono()59- let aborted = false60- app.get('/stream', (c) => {61- return streamSSE(c, (stream) => {62- stream.onAbort(() => {63- aborted = true64- })65- return new Promise<void>((resolve) => {66- stream.onAbort(resolve)67- })68- })69- })70-71- const server = Deno.serve({ port: 0 }, app.fetch)72- const ac = new AbortController()73- const req = new Request(`http://localhost:${server.addr.port}/stream`, {74- signal: ac.signal,75- })76- assertEquals77- const res = fetch(req).catch(() => {})78- assertEquals(aborted, false)79- await new Promise((resolve) => setTimeout(resolve, 10))80- ac.abort()81- await res82- while (!aborted) {83- await new Promise((resolve) => setTimeout(resolve))84- }85- assertEquals(aborted, true)86-87- await server.shutdown()88-})89-90-Deno.test('Shuld not call onAbort via streamSSE if already closed', async () => {91- const app = new Hono()92- let aborted = false93- app.get('/stream', (c) => {94- return streamSSE(c, async (stream) => {95- stream.onAbort(() => {96- aborted = true97- })98- await stream.write('Hello')99- })100- })101-102- const server = Deno.serve({ port: 0 }, app.fetch)103- assertEquals(aborted, false)104- const res = await fetch(`http://localhost:${server.addr.port}/stream`)105- assertEquals(await res.text(), 'Hello')106- assertEquals(aborted, false)107- await server.shutdown()108-})deleted:runtime_tests/deno-jsx/deno.precompile.json-18 removed
1-{2- "compilerOptions": {3- "jsx": "precompile",4- "jsxImportSource": "hono/jsx",5- "lib": [6- "deno.ns",7- "dom",8- "dom.iterable"9- ]10- },11- "unstable": [12- "sloppy-imports"13- ],14- "imports": {15- "@std/assert": "jsr:@std/assert@^1.0.3",16- "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"17- }18-}deleted:runtime_tests/deno-jsx/deno.react-jsx.json-18 removed
1-{2- "compilerOptions": {3- "jsx": "react-jsx",4- "jsxImportSource": "hono/jsx",5- "lib": [6- "deno.ns",7- "dom",8- "dom.iterable"9- ]10- },11- "unstable": [12- "sloppy-imports"13- ],14- "imports": {15- "@std/assert": "jsr:@std/assert@^1.0.3",16- "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"17- }18-}deleted:runtime_tests/deno-jsx/jsx.test.tsx-112 removed
1-/** @jsxImportSource ../../src/jsx */2-import { assertEquals } from '@std/assert'3-import { Style, css } from '../../src/helper/css/index.ts'4-import { Suspense, renderToReadableStream } from '../../src/jsx/streaming.ts'5-import type { HtmlEscapedString } from '../../src/utils/html.ts'6-import { HtmlEscapedCallbackPhase, resolveCallback } from '../../src/utils/html.ts'7-8-Deno.test('JSX', () => {9- const Component = ({ name }: { name: string }) => <span>{name}</span>10- const html = (11- <div>12- <h1 id={'<Hello>'}>13- <Component name={'<Hono>'} />14- </h1>15- </div>16- )17-18- assertEquals(html.toString(), '<div><h1 id="<Hello>"><span><Hono></span></h1></div>')19-})20-21-Deno.test('JSX: Fragment', () => {22- const fragment = (23- <>24- <p>1</p>25- <p>2</p>26- </>27- )28- assertEquals(fragment.toString(), '<p>1</p><p>2</p>')29-})30-31-Deno.test('JSX: Empty Fragment', () => {32- const Component = () => <></>33- const html = <Component />34- assertEquals(html.toString(), '')35-})36-37-Deno.test('JSX: Async Component', async () => {38- const Component = async ({ name }: { name: string }) =>39- new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<span>{name}</span>), 10))40- const stream = renderToReadableStream(41- <div>42- <Component name={'<Hono>'} />43- </div>44- )45-46- const chunks: string[] = []47- const textDecoder = new TextDecoder()48- // eslint-disable-next-line @typescript-eslint/no-explicit-any49- for await (const chunk of stream as any) {50- chunks.push(textDecoder.decode(chunk))51- }52-53- assertEquals(chunks.join(''), '<div><span><Hono></span></div>')54-})55-56-Deno.test('JSX: Suspense', async () => {57- const Content = () => {58- const content = new Promise<HtmlEscapedString>((resolve) =>59- setTimeout(() => resolve(<h1>Hello</h1>), 10)60- )61- return content62- }63-64- const stream = renderToReadableStream(65- <Suspense fallback={<p>Loading...</p>}>66- <Content />67- </Suspense>68- )69-70- const chunks: string[] = []71- const textDecoder = new TextDecoder()72- // eslint-disable-next-line @typescript-eslint/no-explicit-any73- for await (const chunk of stream as any) {74- chunks.push(textDecoder.decode(chunk))75- }76-77- assertEquals(chunks, [78- '<template id="H:0"></template><p>Loading...</p><!--/$-->',79- `<template data-hono-target="H:0"><h1>Hello</h1></template><script>80-((d,c,n) => {81-c=d.currentScript.previousSibling82-d=d.getElementById('H:0')83-if(!d)return84-do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')85-d.replaceWith(c.content)86-})(document)87-</script>`,88- ])89-})90-91-Deno.test('JSX: css', async () => {92- const className = css`93- color: red;94- `95- const html = (96- <html>97- <head>98- <Style />99- </head>100- <body>101- <div class={className}></div>102- </body>103- </html>104- )105-106- const awaitedHtml = await html107- const htmlEscapedString = 'callbacks' in awaitedHtml ? awaitedHtml : await awaitedHtml.toString()108- assertEquals(109- await resolveCallback(htmlEscapedString, HtmlEscapedCallbackPhase.Stringify, false, {}),110- '<html><head><style id="hono-css">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>'111- )112-})deleted:runtime_tests/fastly/index.test.ts-100 removed
1-import { SHA256 } from 'crypto-js'2-import { getRuntimeKey } from '../../src/helper/adapter'3-import { Hono } from '../../src/index'4-import { basicAuth } from '../../src/middleware/basic-auth'5-import { jwt } from '../../src/middleware/jwt'6-7-// eslint-disable-next-line @typescript-eslint/ban-ts-comment8-// @ts-ignore9-globalThis.fastly = true10-11-const app = new Hono()12-13-describe('Hello World', () => {14- app.get('/', (c) => c.text('Hello! Compute!'))15- app.get('/runtime-name', (c) => {16- return c.text(getRuntimeKey())17- })18-19- it('Should return 200', async () => {20- const res = await app.request('http://localhost/')21- expect(res.status).toBe(200)22- expect(await res.text()).toBe('Hello! Compute!')23- })24-25- it('Should return the correct runtime name', async () => {26- const res = await app.request('http://localhost/runtime-name')27- expect(res.status).toBe(200)28- expect(await res.text()).toBe('fastly')29- })30-})31-32-describe('Basic Auth Middleware without `hashFunction`', () => {33- const app = new Hono()34-35- const username = 'hono-user-a'36- const password = 'hono-password-a'37- app.use(38- '/auth/*',39- basicAuth({40- username,41- password,42- })43- )44-45- app.get('/auth/*', () => new Response('auth'))46-47- it('Should not authorize, return 401 Response', async () => {48- const req = new Request('http://localhost/auth/a')49- const res = await app.request(req)50- expect(res.status).toBe(401)51- expect(await res.text()).toBe('Unauthorized')52- })53-})54-55-describe('Basic Auth Middleware with `hashFunction`', () => {56- const app = new Hono()57-58- const username = 'hono-user-a'59- const password = 'hono-password-a'60- app.use(61- '/auth/*',62- basicAuth({63- username,64- password,65- hashFunction: (m: string) => SHA256(m).toString(),66- })67- )68-69- app.get('/auth/*', () => new Response('auth'))70-71- it('Should not authorize, return 401 Response', async () => {72- const req = new Request('http://localhost/auth/a')73- const res = await app.request(req)74- expect(res.status).toBe(401)75- expect(await res.text()).toBe('Unauthorized')76- })77-78- it('Should authorize, return 200 Response', async () => {79- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'80- const req = new Request('http://localhost/auth/a')81- req.headers.set('Authorization', `Basic ${credential}`)82- const res = await app.request(req)83- expect(res.status).toBe(200)84- expect(await res.text()).toBe('auth')85- })86-})87-88-describe('JWT Auth Middleware does not work', () => {89- const app = new Hono()90-91- // Since nodejs 20 or later, global WebCrypto object becomes stable (experimental on nodejs 18)92- // but WebCrypto does not have compatibility with Fastly Compute runtime (lacking some objects/methods in Fastly)93- // so following test should run only be polyfill-ed via vite-plugin-fastly-js-compute plugin.94- // To confirm polyfill-ed or not, check __fastlyComputeNodeDefaultCrypto field is true.95- it.runIf(!globalThis.__fastlyComputeNodeDefaultCrypto)('Should throw error', () => {96- expect(() => {97- app.use('/jwt/*', jwt({ secret: 'secret' }))98- }).toThrow(/`crypto.subtle.importKey` is undefined/)99- })100-})deleted:runtime_tests/fastly/vitest.config.ts-17 removed
1-/// <reference types="vitest" />2-import fastlyCompute from 'vite-plugin-fastly-js-compute'3-import { defineConfig } from 'vitest/config'4-import config from '../../vitest.config'5-6-export default defineConfig({7- plugins: [fastlyCompute()],8- test: {9- globals: true,10- include: ['**/runtime_tests/fastly/**/(*.)+(test).+(ts|tsx)'],11- exclude: ['**/runtime_tests/fastly/vitest.config.ts'],12- coverage: {13- ...config.test?.coverage,14- reportsDirectory: './coverage/raw/runtime-fastly',15- },16- },17-})deleted:runtime_tests/lambda/index.test.ts-969 removed
1-import { Readable } from 'stream'2-import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'3-import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'4-import type {5- ApiGatewayRequestContext,6- ApiGatewayRequestContextV2,7- LambdaContext,8-} from '../../src/adapter/aws-lambda/types'9-import { getCookie, setCookie } from '../../src/helper/cookie'10-import { streamSSE } from '../../src/helper/streaming'11-import { Hono } from '../../src/hono'12-import { basicAuth } from '../../src/middleware/basic-auth'13-import './mock'14-15-type Bindings = {16- event: LambdaEvent17- lambdaContext: LambdaContext18- requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV219-}20-21-const testApiGatewayRequestContextV2 = {22- accountId: '123456789012',23- apiId: 'urlid',24- authentication: null,25- authorizer: {26- iam: {27- accessKey: 'AKIA...',28- accountId: '111122223333',29- callerId: 'AIDA...',30- cognitoIdentity: null,31- principalOrgId: null,32- userArn: 'arn:aws:iam::111122223333:user/example-user',33- userId: 'AIDA...',34- },35- },36- domainName: 'example.com',37- domainPrefix: '<url-id>',38- http: {39- method: 'POST',40- path: '/my/path',41- protocol: 'HTTP/1.1',42- sourceIp: '123.123.123.123',43- userAgent: 'agent',44- },45- requestId: 'id',46- routeKey: '$default',47- stage: '$default',48- time: '12/Mar/2020:19:03:58 +0000',49- timeEpoch: 1583348638390,50- customProperty: 'customValue',51-}52-53-describe('AWS Lambda Adapter for Hono', () => {54- const app = new Hono<{ Bindings: Bindings }>()55-56- app.get('/', (c) => {57- return c.text('Hello Lambda!')58- })59-60- app.get('/binary', (c) => {61- return c.body('Fake Image', 200, {62- 'Content-Type': 'image/png',63- })64- })65-66- app.post('/post', async (c) => {67- const body = (await c.req.parseBody()) as { message: string }68- return c.text(body.message)69- })70-71- app.post('/post/binary', async (c) => {72- const body = await c.req.blob()73- return c.text(`${body.size} bytes`)74- })75-76- const username = 'hono-user-a'77- const password = 'hono-password-a'78- app.use('/auth/*', basicAuth({ username, password }))79- app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))80-81- app.get('/lambda-event', (c) => {82- const event = c.env.event83- return c.json(event)84- })85-86- app.get('/lambda-context', (c) => {87- const fnctx = c.env.lambdaContext88- return c.json(fnctx)89- })90-91- app.get('/custom-context/v1/apigw', (c) => {92- const lambdaContext = c.env.requestContext93- return c.json(lambdaContext)94- })95-96- app.get('/custom-context/apigw', (c) => {97- const lambdaContext = c.env.event.requestContext98- return c.json(lambdaContext)99- })100-101- app.get('/custom-context/v1/lambda', (c) => {102- const lambdaContext = c.env.requestContext103- return c.json(lambdaContext)104- })105-106- app.get('/custom-context/lambda', (c) => {107- const lambdaContext = c.env.event.requestContext108- return c.json(lambdaContext)109- })110-111- app.get('/query-params', (c) => {112- const queryParams = c.req.query()113- return c.json(queryParams)114- })115-116- app.get('/multi-query-params', (c) => {117- const multiQueryParams = c.req.queries()118- return c.json(multiQueryParams)119- })120-121- const testCookie1 = {122- key: 'id',123- value: crypto.randomUUID(),124- get serialized() {125- return `${this.key}=${this.value}; Path=/`126- },127- }128- const testCookie2 = {129- key: 'secret',130- value: crypto.randomUUID(),131- get serialized() {132- return `${this.key}=${this.value}; Path=/`133- },134- }135-136- app.post('/cookie', (c) => {137- setCookie(c, testCookie1.key, testCookie1.value)138- setCookie(c, testCookie2.key, testCookie2.value)139- return c.text('Cookies Set')140- })141-142- app.get('/cookie', (c) => {143- const validCookies =144- getCookie(c, testCookie1.key) === testCookie1.value &&145- getCookie(c, testCookie2.key) === testCookie2.value146- if (!validCookies) {147- return c.text('Invalid Cookies')148- }149- return c.text('Valid Cookies')150- })151-152- app.post('/headers', (c) => {153- if (c.req.header('foo')?.includes('bar')) {154- return c.json({ message: 'ok' })155- }156- return c.json({ message: 'fail' }, 400)157- })158-159- const handler = handle(app)160-161- const testApiGatewayRequestContext = {162- accountId: '123456789012',163- apiId: 'id',164- authorizer: {165- claims: null,166- scopes: null,167- },168- domainName: 'example.com',169- domainPrefix: 'id',170- extendedRequestId: 'request-id',171- httpMethod: 'GET',172- identity: {173- sourceIp: 'IP',174- userAgent: 'user-agent',175- },176- path: '/my/path',177- protocol: 'HTTP/1.1',178- requestId: 'id=',179- requestTime: '04/Mar/2020:19:15:17 +0000',180- requestTimeEpoch: 1583349317135,181- resourcePath: '/',182- stage: '$default',183- customProperty: 'customValue',184- }185-186- const testApiGatewayRequestContextV2 = {187- accountId: '123456789012',188- apiId: 'urlid',189- authentication: null,190- authorizer: {191- iam: {192- accessKey: 'AKIA...',193- accountId: '111122223333',194- callerId: 'AIDA...',195- cognitoIdentity: null,196- principalOrgId: null,197- userArn: 'arn:aws:iam::111122223333:user/example-user',198- userId: 'AIDA...',199- },200- },201- domainName: 'example.com',202- domainPrefix: '<url-id>',203- http: {204- method: 'POST',205- path: '/my/path',206- protocol: 'HTTP/1.1',207- sourceIp: '123.123.123.123',208- userAgent: 'agent',209- },210- requestId: 'id',211- routeKey: '$default',212- stage: '$default',213- time: '12/Mar/2020:19:03:58 +0000',214- timeEpoch: 1583348638390,215- customProperty: 'customValue',216- }217-218- const testALBRequestContext = {219- elb: {220- targetGroupArn:221- 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',222- },223- }224-225- it('Should handle a GET request and return a 200 response', async () => {226- const event = {227- version: '1.0',228- resource: '/',229- httpMethod: 'GET',230- headers: { 'content-type': 'text/plain' },231- path: '/',232- body: null,233- isBase64Encoded: false,234- requestContext: testApiGatewayRequestContext,235- }236-237- const response = await handler(event)238- expect(response.statusCode).toBe(200)239- expect(response.body).toBe('Hello Lambda!')240- expect(response.headers['content-type']).toMatch(/^text\/plain/)241- expect(response.isBase64Encoded).toBe(false)242- })243-244- it('Should handle a GET request and return a 200 response with binary', async () => {245- const event = {246- version: '1.0',247- resource: '/binary',248- httpMethod: 'GET',249- headers: {},250- path: '/binary',251- body: null,252- isBase64Encoded: false,253- requestContext: testApiGatewayRequestContext,254- }255-256- const response = await handler(event)257- expect(response.statusCode).toBe(200)258- expect(response.body).toBe('RmFrZSBJbWFnZQ==')259- expect(response.headers['content-type']).toMatch(/^image\/png/)260- expect(response.isBase64Encoded).toBe(true)261- })262-263- it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {264- const event = {265- version: '2.0',266- routeKey: '$default',267- headers: { 'content-type': 'text/plain' },268- rawPath: '/',269- rawQueryString: '',270- body: null,271- isBase64Encoded: false,272- requestContext: testApiGatewayRequestContextV2,273- }274-275- testApiGatewayRequestContextV2.http.method = 'GET'276-277- const response = await handler(event)278- expect(response.statusCode).toBe(200)279- expect(response.body).toBe('Hello Lambda!')280- expect(response.headers['content-type']).toMatch(/^text\/plain/)281- expect(response.isBase64Encoded).toBe(false)282- })283-284- it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {285- const event = {286- headers: { 'content-type': 'text/plain' },287- httpMethod: 'GET',288- path: '/',289- queryStringParameters: {290- query: '1234ABCD',291- },292- body: null,293- isBase64Encoded: false,294- requestContext: testALBRequestContext,295- }296-297- const response = await handler(event)298- expect(response.statusCode).toBe(200)299- expect(response.body).toBe('Hello Lambda!')300- expect(response.headers['content-type']).toMatch(/^text\/plain/)301- expect(response.isBase64Encoded).toBe(false)302- })303-304- it('Should handle a GET request and return a 404 response', async () => {305- const event = {306- version: '1.0',307- resource: '/nothing',308- httpMethod: 'GET',309- headers: { 'content-type': 'text/plain' },310- path: '/nothing',311- body: null,312- isBase64Encoded: false,313- requestContext: testApiGatewayRequestContext,314- }315-316- const response = await handler(event)317- expect(response.statusCode).toBe(404)318- })319-320- it('Should handle a POST request and return a 200 response', async () => {321- const searchParam = new URLSearchParams()322- searchParam.append('message', 'Good Morning Lambda!')323- const event = {324- version: '1.0',325- resource: '/post',326- httpMethod: 'POST',327- headers: {328- 'Content-Type': 'application/x-www-form-urlencoded',329- },330- path: '/post',331- body: Buffer.from(searchParam.toString()).toString('base64'),332- isBase64Encoded: true,333- requestContext: testApiGatewayRequestContext,334- }335-336- const response = await handler(event)337- expect(response.statusCode).toBe(200)338- expect(response.body).toBe('Good Morning Lambda!')339- })340-341- it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {342- const searchParam = new URLSearchParams()343- searchParam.append('message', 'Good Morning Lambda!')344- const event = {345- version: '2.0',346- routeKey: '$default',347- headers: {348- 'Content-Type': 'application/x-www-form-urlencoded',349- },350- rawPath: '/post',351- rawQueryString: '',352- body: Buffer.from(searchParam.toString()).toString('base64'),353- isBase64Encoded: true,354- requestContext: testApiGatewayRequestContextV2,355- }356-357- testApiGatewayRequestContextV2.http.method = 'POST'358-359- const response = await handler(event)360- expect(response.statusCode).toBe(200)361- expect(response.body).toBe('Good Morning Lambda!')362- })363-364- it('Should handle a POST request with binary and return a 200 response', async () => {365- const array = new Uint8Array([0xc0, 0xff, 0xee])366- const buffer = Buffer.from(array)367- const event = {368- version: '1.0',369- resource: '/post/binary',370- httpMethod: 'POST',371- headers: {372- 'Content-Type': 'application/x-www-form-urlencoded',373- },374- path: '/post/binary',375- body: buffer.toString('base64'),376- isBase64Encoded: true,377- requestContext: testApiGatewayRequestContext,378- }379-380- const response = await handler(event)381- expect(response.statusCode).toBe(200)382- expect(response.body).toBe('3 bytes')383- })384-385- it('Should handle a request and return a 401 response with Basic auth', async () => {386- const event = {387- version: '1.0',388- resource: '/auth/abc',389- httpMethod: 'GET',390- headers: {391- 'Content-Type': 'plain/text',392- },393- path: '/auth/abc',394- body: null,395- isBase64Encoded: true,396- requestContext: testApiGatewayRequestContext,397- }398-399- const response = await handler(event)400- expect(response.statusCode).toBe(401)401- })402-403- it('Should handle a request and return a 200 response with Basic auth', async () => {404- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'405- const event = {406- version: '1.0',407- resource: '/auth/abc',408- httpMethod: 'GET',409- headers: {410- 'Content-Type': 'plain/text',411- Authorization: `Basic ${credential}`,412- },413- path: '/auth/abc',414- body: null,415- isBase64Encoded: true,416- requestContext: testApiGatewayRequestContext,417- }418-419- const response = await handler(event)420- expect(response.statusCode).toBe(200)421- expect(response.body).toBe('Good Night Lambda!')422- })423-424- it('Should handle a GET request and return custom context', async () => {425- const event = {426- version: '1.0',427- resource: '/custom-context/apigw',428- httpMethod: 'GET',429- headers: { 'content-type': 'application/json' },430- path: '/custom-context/apigw',431- body: null,432- isBase64Encoded: false,433- requestContext: testApiGatewayRequestContext,434- }435-436- const response = await handler(event)437- expect(response.statusCode).toBe(200)438- expect(JSON.parse(response.body).customProperty).toEqual('customValue')439- })440-441- it('Should handle a GET request and context', async () => {442- const event = {443- version: '1.0',444- resource: '/lambda-context',445- httpMethod: 'GET',446- headers: { 'content-type': 'application/json' },447- path: '/lambda-context',448- body: null,449- isBase64Encoded: false,450- requestContext: testApiGatewayRequestContext,451- }452- const context: LambdaContext = {453- callbackWaitsForEmptyEventLoop: false,454- functionName: 'myLambdaFunction',455- functionVersion: '1.0.0',456- invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',457- memoryLimitInMB: '128',458- awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',459- logGroupName: '/aws/lambda/myLambdaFunction',460- logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',461- getRemainingTimeInMillis: () => {462- return 60000 // 60 seconds463- },464- }465- const response = await handler(event, context)466- expect(response.statusCode).toBe(200)467- expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)468- })469-470- it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {471- const apiGatewayEvent = {472- version: '1.0',473- resource: '/cookie',474- httpMethod: 'POST',475- headers: { 'content-type': 'text/plain' },476- path: '/cookie',477- body: null,478- isBase64Encoded: false,479- requestContext: testApiGatewayRequestContext,480- }481-482- const apiGatewayResponse = await handler(apiGatewayEvent)483-484- expect(apiGatewayResponse.statusCode).toBe(200)485- expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [486- testCookie1.serialized,487- testCookie2.serialized,488- ])489-490- const apiGatewayEventV2 = {491- version: '2.0',492- routeKey: '$default',493- httpMethod: 'POST',494- headers: { 'content-type': 'text/plain' },495- rawPath: '/cookie',496- rawQueryString: '',497- body: null,498- isBase64Encoded: false,499- requestContext: testApiGatewayRequestContextV2,500- }501-502- const apiGatewayResponseV2 = await handler(apiGatewayEventV2)503-504- expect(apiGatewayResponseV2.statusCode).toBe(200)505- expect(apiGatewayResponseV2).toHaveProperty('cookies', [506- testCookie1.serialized,507- testCookie2.serialized,508- ])509- })510-511- describe('headers', () => {512- describe('single-value headers', () => {513- it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {514- const event = {515- body: '{}',516- httpMethod: 'POST',517- isBase64Encoded: false,518- path: '/headers',519- headers: {520- host: 'localhost',521- foo: 'bar',522- },523- requestContext: testALBRequestContext,524- }525- const albResponse = await handler(event)526- expect(albResponse.statusCode).toBe(200)527- expect(albResponse.headers).toEqual(528- expect.objectContaining({529- 'content-type': 'application/json; charset=UTF-8',530- })531- )532- })533-534- it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {535- const apigatewayProxyEvent = {536- version: '1.0',537- resource: '/headers',538- httpMethod: 'POST',539- headers: {540- host: 'localhost',541- foo: 'bar',542- },543- path: '/headers',544- body: null,545- isBase64Encoded: false,546- requestContext: testApiGatewayRequestContext,547- }548- const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)549- expect(apiGatewayResponseV2.statusCode).toBe(200)550- })551-552- it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {553- const apigatewayProxyV2Event = {554- version: '2.0',555- routeKey: '$default',556- headers: {557- host: 'localhost',558- foo: 'bar',559- },560- rawPath: '/headers',561- rawQueryString: '',562- requestContext: testApiGatewayRequestContextV2,563- resource: '/headers',564- body: null,565- isBase64Encoded: false,566- }567- const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)568- expect(apiGatewayResponseV2.statusCode).toBe(200)569- })570- })571-572- describe('multi-value headers', () => {573- it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {574- const event = {575- body: '{}',576- httpMethod: 'POST',577- isBase64Encoded: false,578- path: '/headers',579- multiValueHeaders: {580- host: ['localhost'],581- foo: ['bar'],582- },583- requestContext: testALBRequestContext,584- }585- const albResponse = await handler(event)586- expect(albResponse.statusCode).toBe(200)587- expect(albResponse.multiValueHeaders).toBeDefined()588- expect(albResponse.multiValueHeaders).toEqual(589- expect.objectContaining({590- 'content-type': ['application/json; charset=UTF-8'],591- })592- )593- })594-595- it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {596- const apigatewayProxyEvent = {597- version: '1.0',598- resource: '/headers',599- httpMethod: 'POST',600- headers: {},601- multiValueHeaders: {602- host: ['localhost'],603- foo: ['bar'],604- },605- path: '/headers',606- body: null,607- isBase64Encoded: false,608- requestContext: testApiGatewayRequestContext,609- }610- const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)611- expect(apiGatewayResponseV2.statusCode).toBe(200)612- })613- })614- })615-616- it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {617- const apiGatewayEvent = {618- version: '1.0',619- resource: '/cookie',620- httpMethod: 'GET',621- headers: {622- 'content-type': 'text/plain',623- cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),624- },625- path: '/cookie',626- body: null,627- isBase64Encoded: false,628- requestContext: testApiGatewayRequestContext,629- }630-631- const apiGatewayResponse = await handler(apiGatewayEvent)632-633- expect(apiGatewayResponse.statusCode).toBe(200)634- expect(apiGatewayResponse.body).toBe('Valid Cookies')635- expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)636- expect(apiGatewayResponse.isBase64Encoded).toBe(false)637-638- const apiGatewayEventV2 = {639- version: '2.0',640- routeKey: '$default',641- headers: { 'content-type': 'text/plain' },642- rawPath: '/cookie',643- cookies: [testCookie1.serialized, testCookie2.serialized],644- rawQueryString: '',645- body: null,646- isBase64Encoded: false,647- requestContext: testApiGatewayRequestContextV2,648- }649- testApiGatewayRequestContextV2.http.method = 'GET'650-651- const apiGatewayResponseV2 = await handler(apiGatewayEventV2)652-653- expect(apiGatewayResponseV2.statusCode).toBe(200)654- expect(apiGatewayResponseV2.body).toBe('Valid Cookies')655- expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)656- expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)657- })658-659- it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {660- const albEventDefaultHeaders = {661- version: '1.0',662- resource: '/cookie',663- httpMethod: 'GET',664- headers: {665- 'content-type': 'text/plain',666- cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),667- },668- path: '/cookie',669- body: null,670- isBase64Encoded: false,671- requestContext: testALBRequestContext,672- }673-674- const albResponse = await handler(albEventDefaultHeaders)675-676- expect(albResponse.statusCode).toBe(200)677- expect(albResponse.body).toBe('Valid Cookies')678- expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)679- expect(albResponse.isBase64Encoded).toBe(false)680- })681-682- it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {683- const albEventMultiValueHeaders = {684- version: '1.0',685- resource: '/cookie',686- httpMethod: 'GET',687- multiValueHeaders: {688- 'content-type': ['text/plain'],689- cookie: [testCookie1.serialized, testCookie2.serialized],690- },691- path: '/cookie',692- body: null,693- isBase64Encoded: false,694- requestContext: testALBRequestContext,695- }696-697- const albResponse = await handler(albEventMultiValueHeaders)698-699- expect(albResponse.statusCode).toBe(200)700- expect(albResponse.body).toBe('Valid Cookies')701- expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)702- expect(albResponse.isBase64Encoded).toBe(false)703- })704-705- it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {706- const albEventDefaultHeaders = {707- version: '1.0',708- resource: '/cookie',709- httpMethod: 'POST',710- headers: {711- 'content-type': 'text/plain',712- cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),713- },714- path: '/cookie',715- body: null,716- isBase64Encoded: false,717- requestContext: testALBRequestContext,718- }719-720- const albResponse = await handler(albEventDefaultHeaders)721-722- expect(albResponse.statusCode).toBe(200)723- expect(albResponse.body).toBe('Cookies Set')724- expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)725- expect(albResponse.multiValueHeaders).toBeUndefined()726- expect(albResponse.headers['set-cookie']).toEqual(727- [testCookie1.serialized, testCookie2.serialized].join(', ')728- )729- expect(albResponse.isBase64Encoded).toBe(false)730- })731-732- it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {733- const albEventDefaultHeaders = {734- version: '1.0',735- resource: '/cookie',736- httpMethod: 'POST',737- multiValueHeaders: {738- 'content-type': ['text/plain'],739- cookie: [testCookie1.serialized, testCookie2.serialized],740- },741- path: '/cookie',742- body: null,743- isBase64Encoded: false,744- requestContext: testALBRequestContext,745- }746-747- const albResponse = await handler(albEventDefaultHeaders)748-749- expect(albResponse.statusCode).toBe(200)750- expect(albResponse.body).toBe('Cookies Set')751- expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)752- expect(albResponse.multiValueHeaders).toBeDefined()753- expect(albResponse.multiValueHeaders && albResponse.multiValueHeaders['set-cookie']).toEqual(754- expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])755- )756- expect(albResponse.isBase64Encoded).toBe(false)757- })758-759- it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {760- const albEventDefaultHeaders = {761- resource: '/query-params',762- httpMethod: 'GET',763- headers: {764- 'content-type': 'application/json',765- },766- queryStringParameters: {767- key1: 'value1',768- key2: 'value2',769- },770- path: '/query-params',771- body: null,772- isBase64Encoded: false,773- requestContext: testALBRequestContext,774- }775-776- const albResponse = await handler(albEventDefaultHeaders)777-778- expect(albResponse.statusCode).toBe(200)779- expect(albResponse.body).toContain(780- JSON.stringify({781- key1: 'value1',782- key2: 'value2',783- })784- )785- expect(albResponse.headers['content-type']).toMatch(/^application\/json/)786- expect(albResponse.isBase64Encoded).toBe(false)787- })788-789- it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {790- const albEventDefaultHeaders = {791- resource: '/query-params',792- httpMethod: 'GET',793- multiValueHeaders: {794- 'content-type': ['application/json'],795- },796- multiValueQueryStringParameters: {797- key1: ['value1'],798- key2: ['value2'],799- },800- path: '/query-params',801- body: null,802- isBase64Encoded: false,803- requestContext: testALBRequestContext,804- }805-806- const albResponse = await handler(albEventDefaultHeaders)807-808- expect(albResponse.statusCode).toBe(200)809- expect(albResponse.body).toContain(810- JSON.stringify({811- key1: 'value1',812- key2: 'value2',813- })814- )815- expect(albResponse.headers['content-type']).toMatch(/^application\/json/)816- expect(albResponse.isBase64Encoded).toBe(false)817- })818-819- it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {820- const albEventDefaultHeaders = {821- resource: '/query-params',822- httpMethod: 'GET',823- multiValueHeaders: {824- 'content-type': ['application/json'],825- },826- multiValueQueryStringParameters: {827- key1: ['value1'],828- key2: ['value2', 'otherValue2'],829- },830- path: '/multi-query-params',831- body: null,832- isBase64Encoded: false,833- requestContext: testALBRequestContext,834- }835-836- const albResponse = await handler(albEventDefaultHeaders)837-838- expect(albResponse.statusCode).toBe(200)839- expect(albResponse.body).toContain(840- JSON.stringify({841- key1: ['value1'],842- key2: ['value2', 'otherValue2'],843- })844- )845- expect(albResponse.headers['content-type']).toMatch(/^application\/json/)846- expect(albResponse.isBase64Encoded).toBe(false)847- })848-})849-850-describe('streamHandle function', () => {851- const app = new Hono<{ Bindings: Bindings }>()852-853- app.get('/', (c) => {854- return c.text('Hello Lambda!')855- })856-857- app.get('/stream/text', async (c) => {858- return c.streamText(async (stream) => {859- for (let i = 0; i < 3; i++) {860- await stream.writeln(`${i}`)861- await stream.sleep(1)862- }863- })864- })865-866- app.get('/sse', async (c) => {867- return streamSSE(c, async (stream) => {868- let id = 0869- const maxIterations = 2870-871- while (id < maxIterations) {872- const message = `Message\nIt is ${id}`873- await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })874- await stream.sleep(10)875- }876- })877- })878-879- const handler = streamHandle(app)880-881- it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {882- const event = {883- headers: { 'content-type': ' binary/octet-stream' },884- rawPath: '/stream/text',885- rawQueryString: '',886- body: null,887- isBase64Encoded: false,888- requestContext: testApiGatewayRequestContextV2,889- }890-891- testApiGatewayRequestContextV2.http.method = 'GET'892-893- const mockReadableStream = new Readable({894- // eslint-disable-next-line @typescript-eslint/no-empty-function895- read() {},896- })897-898- mockReadableStream.push('0\n')899- mockReadableStream.push('1\n')900- mockReadableStream.push('2\n')901- mockReadableStream.push('3\n')902- mockReadableStream.push(null) // EOF903-904- await handler(event, mockReadableStream)905-906- const chunks = []907- for await (const chunk of mockReadableStream) {908- chunks.push(chunk)909- }910- expect(chunks.join('')).toContain('0\n1\n2\n3\n')911- })912-913- it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {914- const event = {915- headers: { 'content-type': 'text/event-stream' },916- rawPath: '/sse',917- rawQueryString: '',918- body: null,919- isBase64Encoded: false,920- requestContext: testApiGatewayRequestContextV2,921- }922-923- testApiGatewayRequestContextV2.http.method = 'GET'924-925- const mockReadableStream = new Readable({926- // eslint-disable-next-line @typescript-eslint/no-empty-function927- read() {},928- })929-930- const initContentType = {931- 'Content-Type': 'application/vnd.awslambda.http-integration-response',932- }933- mockReadableStream.push(JSON.stringify(initContentType))934-935- // Send JSON formatted response headers, followed by 8 NULL characters as a separator936- const httpResponseMetadata = {937- statusCode: 200,938- headers: { 'Custom-Header': 'value' },939- cookies: ['session=abcd1234'],940- }941- const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()942- mockReadableStream.push(jsonResponsePrelude)943-944- mockReadableStream.push('data: Message\ndata: It is 0\n\n')945- mockReadableStream.push('data: Message\ndata: It is 1\n\n')946- mockReadableStream.push(null) // EOF947-948- await handler(event, mockReadableStream)949-950- const chunks = []951- for await (const chunk of mockReadableStream) {952- chunks.push(chunk)953- }954-955- // If you have chunks, you might want to convert them to strings before checking956- const output = Buffer.concat(chunks).toString()957- expect(output).toContain('data: Message\ndata: It is 0\n\n')958- expect(output).toContain('data: Message\ndata: It is 1\n\n')959-960- // Assertions for the newly added header and prelude961- expect(output).toContain('application/vnd.awslambda.http-integration-response')962- expect(output).toContain('Custom-Header')963- expect(output).toContain('session=abcd1234')964-965- // Check for JSON prelude and NULL sequence966- const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'967- expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))968- })969-})deleted:runtime_tests/lambda/mock.ts-42 removed
1-import { vi } from 'vitest'2-import type {3- APIGatewayProxyEvent,4- APIGatewayProxyEventV2,5- LambdaFunctionUrlEvent,6-} from '../../src/adapter/aws-lambda/handler'7-import type { LambdaContext } from '../../src/adapter/aws-lambda/types'8-9-type StreamifyResponseHandler = (10- handlerFunc: (11- event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,12- responseStream: NodeJS.WritableStream,13- context: LambdaContext14- ) => Promise<void>15-) => (event: APIGatewayProxyEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>16-17-const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {18- return async (event, context) => {19- const mockWritableStream: NodeJS.WritableStream = new (require('stream').Writable)({20- write(chunk, encoding, callback) {21- console.log('Writing chunk:', chunk.toString())22- callback()23- },24- final(callback) {25- console.log('Finalizing stream.')26- callback()27- },28- })29- mockWritableStream.on('finish', () => {30- console.log('Stream has finished')31- })32- await handlerFunc(event, mockWritableStream, context)33- mockWritableStream.end()34- return mockWritableStream35- }36-}37-38-const awslambda = {39- streamifyResponse: mockStreamifyResponse,40-}41-42-vi.stubGlobal('awslambda', awslambda)deleted:runtime_tests/lambda/stream-mock.ts-43 removed
1-import { vi } from 'vitest'2-import { Writable } from 'node:stream'3-import type {4- APIGatewayProxyEvent,5- APIGatewayProxyEventV2,6-} from '../../src/adapter/aws-lambda/handler'7-import type { LambdaContext } from '../../src/adapter/aws-lambda/types'8-9-type StreamifyResponseHandler = (10- handlerFunc: (11- event: APIGatewayProxyEvent | APIGatewayProxyEventV2,12- responseStream: Writable,13- context: LambdaContext14- ) => Promise<void>15-) => (event: APIGatewayProxyEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>16-17-const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {18- return async (event, context) => {19- const chunks = []20- const mockWritableStream = new Writable({21- write(chunk, encoding, callback) {22- chunks.push(chunk)23- callback()24- },25- })26- mockWritableStream.chunks = chunks27- await handlerFunc(event, mockWritableStream, context)28- mockWritableStream.end()29- return mockWritableStream30- }31-}32-33-const awslambda = {34- streamifyResponse: mockStreamifyResponse,35- HttpResponseStream: {36- from: (stream: Writable, httpResponseMetadata: unknown): Writable => {37- stream.write(Buffer.from(JSON.stringify(httpResponseMetadata)))38- return stream39- },40- },41-}42-43-vi.stubGlobal('awslambda', awslambda)deleted:runtime_tests/lambda/stream.test.ts-75 removed
1-import { streamHandle } from '../../src/adapter/aws-lambda/handler'2-import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'3-import type {4- ApiGatewayRequestContext,5- ApiGatewayRequestContextV2,6- LambdaContext,7-} from '../../src/adapter/aws-lambda/types'8-import { Hono } from '../../src/hono'9-import './stream-mock'10-11-type Bindings = {12- event: LambdaEvent13- lambdaContext: LambdaContext14- requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV215-}16-17-const 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-}48-49-describe('streamHandle function', () => {50- const app = new Hono<{ Bindings: Bindings }>()51-52- 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- })57-58- const handler = streamHandle(app)59-60- 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- }69-70- const stream = await handler(event)71-72- const metadata = JSON.parse(stream.chunks[0].toString())73- expect(metadata.cookies).toEqual(['cookie1=value1', 'cookie2=value2'])74- })75-})deleted:runtime_tests/lambda/vitest.config.ts-22 removed
1-/// <reference types="vitest" />2-import { defineConfig } from 'vitest/config'3-import config from '../../vitest.config'4-5-export default defineConfig({6- test: {7- env: {8- NAME: 'Node',9- },10- globals: true,11- include: ['**/runtime_tests/lambda/**/*.+(ts|tsx|js)'],12- exclude: [13- '**/runtime_tests/lambda/vitest.config.ts',14- '**/runtime_tests/lambda/mock.ts',15- '**/runtime_tests/lambda/stream-mock.ts',16- ],17- coverage: {18- ...config.test?.coverage,19- reportsDirectory: './coverage/raw/runtime-lambda',20- },21- },22-})deleted:runtime_tests/lambda-edge/index.test.ts-1135 removed
1-/* eslint-disable quotes */2-import type {3- Callback,4- CloudFrontConfig,5- CloudFrontRequest,6- CloudFrontResponse,7-} from '../../src/adapter/lambda-edge/handler'8-import { handle } from '../../src/adapter/lambda-edge/handler'9-import { Hono } from '../../src/hono'10-import { basicAuth } from '../../src/middleware/basic-auth'11-12-type Bindings = {13- callback: Callback14- config: CloudFrontConfig15- request: CloudFrontRequest16- response: CloudFrontResponse17-}18-19-describe('Lambda@Edge Adapter for Hono', () => {20- const app = new Hono<{ Bindings: Bindings }>()21-22- app.get('/', (c) => {23- return c.text('Hello Lambda!')24- })25-26- app.get('/binary', (c) => {27- return c.body('Fake Image', 200, {28- 'Content-Type': 'image/png',29- })30- })31-32- app.post('/post', async (c) => {33- const body = (await c.req.parseBody()) as { message: string }34- return c.text(body.message)35- })36-37- app.get('/callback/request', async (c, next) => {38- await next()39- c.env.callback(null, c.env.request)40- })41-42- app.get('/config/eventCheck', async (c, next) => {43- await next()44- if (c.env.config.eventType in ['viewer-request', 'origin-request']) {45- c.env.callback(null, c.env.request)46- } else {47- c.env.callback(null, c.env.response)48- }49- })50-51- app.get('/callback/response', async (c, next) => {52- await next()53- c.env.callback(null, c.env.response)54- })55-56- app.post('/post/binary', async (c) => {57- const body = await c.req.blob()58- return c.text(`${body.size} bytes`)59- })60-61- const username = 'hono-user-a'62- const password = 'hono-password-a'63- app.use('/auth/*', basicAuth({ username, password }))64- app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))65-66- app.get('/header/add', async (c, next) => {67- c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [68- {69- key: 'Strict-Transport-Security',70- value: 'max-age=63072000; includeSubdomains; preload',71- },72- ]73- c.env.response.headers['X-Custom'.toLowerCase()] = [74- {75- key: 'X-Custom',76- value: 'Foo',77- },78- ]79- await next()80- c.env.callback(null, c.env.response)81- })82-83- const handler = handle(app)84-85- it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {86- const event = {87- Records: [88- {89- cf: {90- config: {91- distributionDomainName: 'd111111abcdef8.cloudfront.net',92- distributionId: 'EDFDVBD6EXAMPLE',93- eventType: 'viewer-request',94- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',95- },96- request: {97- clientIp: '203.0.113.178',98- headers: {99- host: [100- {101- key: 'Host',102- value: 'd111111abcdef8.cloudfront.net',103- },104- ],105- 'user-agent': [106- {107- key: 'User-Agent',108- value: 'curl/7.66.0',109- },110- ],111- accept: [112- {113- key: 'accept',114- value: '*/*',115- },116- ],117- },118- method: 'GET',119- querystring: '',120- uri: '/',121- },122- },123- },124- ],125- }126- const response = await handler(event)127- expect(response.status).toBe('200')128- expect(response.body).toBe('Hello Lambda!')129- if (response.headers && response.headers['content-type']) {130- expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)131- } else {132- throw new Error("'content-type' header is missing in the response")133- }134- })135-136- it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {137- const event = {138- Records: [139- {140- cf: {141- config: {142- distributionDomainName: 'd111111abcdef8.cloudfront.net',143- distributionId: 'EDFDVBD6EXAMPLE',144- eventType: 'origin-request',145- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',146- },147- request: {148- clientIp: '203.0.113.178',149- headers: {150- 'x-forwarded-for': [151- {152- key: 'X-Forwarded-For',153- value: '203.0.113.178',154- },155- ],156- 'user-agent': [157- {158- key: 'User-Agent',159- value: 'Amazon CloudFront',160- },161- ],162- via: [163- {164- key: 'Via',165- value: '2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)',166- },167- ],168- host: [169- {170- key: 'Host',171- value: 'example.org',172- },173- ],174- 'cache-control': [175- {176- key: 'Cache-Control',177- value: 'no-cache',178- },179- ],180- },181- method: 'GET',182- origin: {183- custom: {184- customHeaders: {},185- domainName: 'example.org',186- keepaliveTimeout: 5,187- path: '',188- port: 443,189- protocol: 'https',190- readTimeout: 30,191- sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],192- },193- },194- querystring: '',195- uri: '/',196- },197- },198- },199- ],200- }201- const response = await handler(event)202- expect(response.status).toBe('200')203- expect(response.body).toBe('Hello Lambda!')204- if (response.headers && response.headers['content-type']) {205- expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)206- } else {207- throw new Error("'content-type' header is missing in the response")208- }209- })210-211- it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {212- const event = {213- Records: [214- {215- cf: {216- config: {217- distributionDomainName: 'd111111abcdef8.cloudfront.net',218- distributionId: 'EDFDVBD6EXAMPLE',219- eventType: 'viewer-response',220- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',221- },222- request: {223- clientIp: '203.0.113.178',224- headers: {225- host: [226- {227- key: 'Host',228- value: 'd111111abcdef8.cloudfront.net',229- },230- ],231- 'user-agent': [232- {233- key: 'User-Agent',234- value: 'curl/7.66.0',235- },236- ],237- accept: [238- {239- key: 'accept',240- value: '*/*',241- },242- ],243- },244- method: 'GET',245- querystring: '',246- uri: '/',247- },248- response: {249- headers: {250- 'access-control-allow-credentials': [251- {252- key: 'Access-Control-Allow-Credentials',253- value: 'true',254- },255- ],256- 'access-control-allow-origin': [257- {258- key: 'Access-Control-Allow-Origin',259- value: '*',260- },261- ],262- date: [263- {264- key: 'Date',265- value: 'Mon, 13 Jan 2020 20:14:56 GMT',266- },267- ],268- 'referrer-policy': [269- {270- key: 'Referrer-Policy',271- value: 'no-referrer-when-downgrade',272- },273- ],274- server: [275- {276- key: 'Server',277- value: 'ExampleCustomOriginServer',278- },279- ],280- 'x-content-type-options': [281- {282- key: 'X-Content-Type-Options',283- value: 'nosniff',284- },285- ],286- 'x-frame-options': [287- {288- key: 'X-Frame-Options',289- value: 'DENY',290- },291- ],292- 'x-xss-protection': [293- {294- key: 'X-XSS-Protection',295- value: '1; mode=block',296- },297- ],298- age: [299- {300- key: 'Age',301- value: '2402',302- },303- ],304- 'content-type': [305- {306- key: 'Content-Type',307- value: 'text/html; charset=utf-8',308- },309- ],310- 'content-length': [311- {312- key: 'Content-Length',313- value: '9593',314- },315- ],316- },317- status: '200',318- statusDescription: 'OK',319- },320- },321- },322- ],323- }324- const response = await handler(event)325- expect(response.status).toBe('200')326- expect(response.body).toBe('Hello Lambda!')327- if (response.headers && response.headers['content-type']) {328- expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)329- } else {330- throw new Error("'content-type' header is missing in the response")331- }332- })333-334- it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {335- const event = {336- Records: [337- {338- cf: {339- config: {340- distributionDomainName: 'd111111abcdef8.cloudfront.net',341- distributionId: 'EDFDVBD6EXAMPLE',342- eventType: 'origin-response',343- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',344- },345- request: {346- clientIp: '203.0.113.178',347- headers: {348- 'x-forwarded-for': [349- {350- key: 'X-Forwarded-For',351- value: '203.0.113.178',352- },353- ],354- 'user-agent': [355- {356- key: 'User-Agent',357- value: 'Amazon CloudFront',358- },359- ],360- via: [361- {362- key: 'Via',363- value: '2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)',364- },365- ],366- host: [367- {368- key: 'Host',369- value: 'example.org',370- },371- ],372- 'cache-control': [373- {374- key: 'Cache-Control',375- value: 'no-cache',376- },377- ],378- },379- method: 'GET',380- origin: {381- custom: {382- customHeaders: {},383- domainName: 'example.org',384- keepaliveTimeout: 5,385- path: '',386- port: 443,387- protocol: 'https',388- readTimeout: 30,389- sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],390- },391- },392- querystring: '',393- uri: '/',394- },395- response: {396- headers: {397- 'access-control-allow-credentials': [398- {399- key: 'Access-Control-Allow-Credentials',400- value: 'true',401- },402- ],403- 'access-control-allow-origin': [404- {405- key: 'Access-Control-Allow-Origin',406- value: '*',407- },408- ],409- date: [410- {411- key: 'Date',412- value: 'Mon, 13 Jan 2020 20:12:38 GMT',413- },414- ],415- 'referrer-policy': [416- {417- key: 'Referrer-Policy',418- value: 'no-referrer-when-downgrade',419- },420- ],421- server: [422- {423- key: 'Server',424- value: 'ExampleCustomOriginServer',425- },426- ],427- 'x-content-type-options': [428- {429- key: 'X-Content-Type-Options',430- value: 'nosniff',431- },432- ],433- 'x-frame-options': [434- {435- key: 'X-Frame-Options',436- value: 'DENY',437- },438- ],439- 'x-xss-protection': [440- {441- key: 'X-XSS-Protection',442- value: '1; mode=block',443- },444- ],445- 'content-type': [446- {447- key: 'Content-Type',448- value: 'text/html; charset=utf-8',449- },450- ],451- 'content-length': [452- {453- key: 'Content-Length',454- value: '9593',455- },456- ],457- },458- status: '200',459- statusDescription: 'OK',460- },461- },462- },463- ],464- }465- const response = await handler(event)466- expect(response.status).toBe('200')467- expect(response.body).toBe('Hello Lambda!')468- if (response.headers && response.headers['content-type']) {469- expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)470- } else {471- throw new Error("'content-type' header is missing in the response")472- }473- })474-475- it('Should handle a GET request and return a 200 response with binary', async () => {476- const event = {477- Records: [478- {479- cf: {480- config: {481- distributionDomainName: 'example.com',482- distributionId: 'EXAMPLE123',483- eventType: 'viewer-request',484- requestId: 'exampleRequestId',485- },486- request: {487- clientIp: '123.123.123.123',488- headers: {489- host: [490- {491- key: 'Host',492- value: 'example.com',493- },494- ],495- },496- method: 'GET',497- querystring: '',498- uri: '/binary',499- },500- },501- },502- ],503- }504-505- const response = await handler(event)506-507- expect(response.status).toBe('200')508- expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded fake image509- if (response.headers && response.headers['content-type']) {510- expect(response.headers['content-type'][0].value).toMatch(/^image\/png/)511- } else {512- throw new Error("'content-type' header is missing in the response")513- }514- })515-516- it('Should handle a GET request and return a 404 response', async () => {517- const event = {518- Records: [519- {520- cf: {521- config: {522- distributionDomainName: 'example.com',523- distributionId: 'EXAMPLE123',524- eventType: 'viewer-request',525- requestId: 'exampleRequestId',526- },527- request: {528- clientIp: '123.123.123.123',529- headers: {530- host: [531- {532- key: 'Host',533- value: 'example.com',534- },535- ],536- },537- method: 'GET',538- querystring: '',539- uri: '/nothing',540- },541- },542- },543- ],544- }545-546- const response = await handler(event)547-548- expect(response.status).toBe('404')549- })550-551- it('Should handle a POST request and return a 200 response', async () => {552- const searchParam = new URLSearchParams()553- searchParam.append('message', 'Good Morning Lambda!')554-555- const event = {556- Records: [557- {558- cf: {559- config: {560- distributionDomainName: 'example.com',561- distributionId: 'EXAMPLE123',562- eventType: 'viewer-request',563- requestId: 'exampleRequestId',564- },565- request: {566- clientIp: '123.123.123.123',567- headers: {568- host: [569- {570- key: 'Host',571- value: 'example.com',572- },573- ],574- 'content-type': [575- {576- key: 'Content-Type',577- value: 'application/x-www-form-urlencoded',578- },579- ],580- },581- method: 'POST',582- querystring: '',583- uri: '/post',584- body: {585- inputTruncated: false,586- action: 'read-only',587- encoding: 'base64',588- data: Buffer.from(searchParam.toString()).toString('base64'),589- },590- },591- },592- },593- ],594- }595-596- const response = await handler(event)597-598- expect(response.status).toBe('200')599- expect(response.body).toBe('Good Morning Lambda!')600- })601-602- it('Should handle a POST request with binary and return a 200 response', async () => {603- const array = new Uint8Array([0xc0, 0xff, 0xee])604- const buffer = Buffer.from(array)605- const event = {606- Records: [607- {608- cf: {609- config: {610- distributionDomainName: 'example.com',611- distributionId: 'EXAMPLE123',612- eventType: 'viewer-request',613- requestId: 'exampleRequestId',614- },615- request: {616- clientIp: '123.123.123.123',617- headers: {618- host: [619- {620- key: 'Host',621- value: 'example.com',622- },623- ],624- 'content-type': [625- {626- key: 'Content-Type',627- value: 'application/x-www-form-urlencoded',628- },629- ],630- },631- method: 'POST',632- querystring: '',633- uri: '/post/binary',634- body: {635- inputTruncated: false,636- action: 'read-only',637- encoding: 'base64',638- data: buffer.toString('base64'),639- },640- },641- },642- },643- ],644- }645-646- const response = await handler(event)647- expect(response.status).toBe('200')648- expect(response.body).toBe('3 bytes')649- })650-651- it('Should handle a request and return a 401 response with Basic auth', async () => {652- const event = {653- Records: [654- {655- cf: {656- config: {657- distributionDomainName: 'example.com',658- distributionId: 'EXAMPLE123',659- eventType: 'viewer-request',660- requestId: 'exampleRequestId',661- },662- request: {663- clientIp: '123.123.123.123',664- headers: {665- host: [666- {667- key: 'Host',668- value: 'example.com',669- },670- ],671- 'content-type': [672- {673- key: 'Content-Type',674- value: 'plain/text',675- },676- ],677- },678- method: 'GET',679- querystring: '',680- uri: '/auth/abc',681- },682- },683- },684- ],685- }686-687- const response = await handler(event)688-689- expect(response.status).toBe('401')690- })691-692- it('Should handle a request and return a 401 response with Basic auth', async () => {693- const event = {694- Records: [695- {696- cf: {697- config: {698- distributionDomainName: 'example.com',699- distributionId: 'EXAMPLE123',700- eventType: 'viewer-request',701- requestId: 'exampleRequestId',702- },703- request: {704- clientIp: '123.123.123.123',705- headers: {706- host: [707- {708- key: 'Host',709- value: 'example.com',710- },711- ],712- 'content-type': [713- {714- key: 'Content-Type',715- value: 'plain/text',716- },717- ],718- },719- method: 'GET',720- querystring: '',721- uri: '/auth/abc',722- },723- },724- },725- ],726- }727-728- const response = await handler(event)729-730- expect(response.status).toBe('401')731- })732-733- it('Should call a callback to continue processing the request', async () => {734- const event = {735- Records: [736- {737- cf: {738- config: {739- distributionDomainName: 'example.com',740- distributionId: 'EXAMPLE123',741- eventType: 'viewer-request',742- requestId: 'exampleRequestId',743- },744- request: {745- clientIp: '123.123.123.123',746- headers: {},747- method: 'GET',748- querystring: '',749- uri: '/callback/request',750- },751- },752- },753- ],754- }755-756- let called = false757- let requestClientIp = ''758-759- await handler(event, {}, (_err, result) => {760- if (result && 'clientIp' in result) {761- requestClientIp = result.clientIp762- }763- called = true764- })765-766- expect(called).toBe(true)767- expect(requestClientIp).toBe('123.123.123.123')768- })769-770- it('Should call a callback to continue processing the response', async () => {771- const event = {772- Records: [773- {774- cf: {775- config: {776- distributionDomainName: 'example.com',777- distributionId: 'EDFDVBD6EXAMPLE',778- eventType: 'viewer-response',779- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',780- },781- request: {782- clientIp: '203.0.113.178',783- headers: {784- host: [785- {786- key: 'Host',787- value: 'example.com',788- },789- ],790- 'user-agent': [791- {792- key: 'User-Agent',793- value: 'curl/7.66.0',794- },795- ],796- accept: [797- {798- key: 'accept',799- value: '*/*',800- },801- ],802- },803- method: 'GET',804- querystring: '',805- uri: '/callback/response',806- },807- response: {808- headers: {809- 'access-control-allow-credentials': [810- {811- key: 'Access-Control-Allow-Credentials',812- value: 'true',813- },814- ],815- 'access-control-allow-origin': [816- {817- key: 'Access-Control-Allow-Origin',818- value: '*',819- },820- ],821- date: [822- {823- key: 'Date',824- value: 'Mon, 13 Jan 2020 20:14:56 GMT',825- },826- ],827- 'referrer-policy': [828- {829- key: 'Referrer-Policy',830- value: 'no-referrer-when-downgrade',831- },832- ],833- server: [834- {835- key: 'Server',836- value: 'ExampleCustomOriginServer',837- },838- ],839- 'x-content-type-options': [840- {841- key: 'X-Content-Type-Options',842- value: 'nosniff',843- },844- ],845- 'x-frame-options': [846- {847- key: 'X-Frame-Options',848- value: 'DENY',849- },850- ],851- 'x-xss-protection': [852- {853- key: 'X-XSS-Protection',854- value: '1; mode=block',855- },856- ],857- age: [858- {859- key: 'Age',860- value: '2402',861- },862- ],863- 'content-type': [864- {865- key: 'Content-Type',866- value: 'text/html; charset=utf-8',867- },868- ],869- 'content-length': [870- {871- key: 'Content-Length',872- value: '9593',873- },874- ],875- },876- status: '200',877- statusDescription: 'OK',878- },879- },880- },881- ],882- }883-884- interface CloudFrontHeaders {885- [name: string]: [886- {887- key: string888- value: string889- }890- ]891- }892- let called = false893- let headers: CloudFrontHeaders = {}894- await handler(event, {}, (_err, result) => {895- if (result && result.headers) {896- headers = result.headers as CloudFrontHeaders897- }898- called = true899- })900-901- expect(called).toBe(true)902- expect(headers['access-control-allow-credentials']).toEqual([903- {904- key: 'Access-Control-Allow-Credentials',905- value: 'true',906- },907- ])908- expect(headers['access-control-allow-origin']).toEqual([909- {910- key: 'Access-Control-Allow-Origin',911- value: '*',912- },913- ])914- })915-916- it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {917- const event = {918- Records: [919- {920- cf: {921- config: {922- distributionDomainName: 'example.com',923- distributionId: 'EDFDVBD6EXAMPLE',924- eventType: 'viewer-response',925- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',926- },927- request: {928- clientIp: '203.0.113.178',929- headers: {930- host: [931- {932- key: 'Host',933- value: 'example.com',934- },935- ],936- 'user-agent': [937- {938- key: 'User-Agent',939- value: 'curl/7.66.0',940- },941- ],942- accept: [943- {944- key: 'accept',945- value: '*/*',946- },947- ],948- },949- method: 'GET',950- querystring: '',951- uri: '/header/add',952- },953- response: {954- headers: {955- 'access-control-allow-credentials': [956- {957- key: 'Access-Control-Allow-Credentials',958- value: 'true',959- },960- ],961- 'access-control-allow-origin': [962- {963- key: 'Access-Control-Allow-Origin',964- value: '*',965- },966- ],967- date: [968- {969- key: 'Date',970- value: 'Mon, 13 Jan 2020 20:14:56 GMT',971- },972- ],973- 'referrer-policy': [974- {975- key: 'Referrer-Policy',976- value: 'no-referrer-when-downgrade',977- },978- ],979- server: [980- {981- key: 'Server',982- value: 'ExampleCustomOriginServer',983- },984- ],985- 'x-content-type-options': [986- {987- key: 'X-Content-Type-Options',988- value: 'nosniff',989- },990- ],991- 'x-frame-options': [992- {993- key: 'X-Frame-Options',994- value: 'DENY',995- },996- ],997- 'x-xss-protection': [998- {999- key: 'X-XSS-Protection',1000- value: '1; mode=block',1001- },1002- ],1003- age: [1004- {1005- key: 'Age',1006- value: '2402',1007- },1008- ],1009- 'content-type': [1010- {1011- key: 'Content-Type',1012- value: 'text/html; charset=utf-8',1013- },1014- ],1015- 'content-length': [1016- {1017- key: 'Content-Length',1018- value: '9593',1019- },1020- ],1021- },1022- status: '200',1023- statusDescription: 'OK',1024- },1025- },1026- },1027- ],1028- }1029-1030- interface CloudFrontHeaders {1031- [name: string]: [1032- {1033- key: string1034- value: string1035- }1036- ]1037- }1038- let called = false1039- let headers: CloudFrontHeaders = {}1040- await handler(event, {}, (_err, result) => {1041- if (result && result.headers) {1042- headers = result.headers as CloudFrontHeaders1043- }1044- called = true1045- })1046-1047- expect(called).toBe(true)1048- expect(headers['strict-transport-security']).toEqual([1049- {1050- key: 'Strict-Transport-Security',1051- value: 'max-age=63072000; includeSubdomains; preload',1052- },1053- ])1054- expect(headers['x-custom']).toEqual([1055- {1056- key: 'X-Custom',1057- value: 'Foo',1058- },1059- ])1060- })1061-1062- it('Callback Event (Lambda@Edge response)', async () => {1063- const event = {1064- Records: [1065- {1066- cf: {1067- config: {1068- distributionDomainName: 'example.com',1069- distributionId: 'EDFDVBD6EXAMPLE',1070- eventType: 'viewer-response',1071- requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',1072- },1073- request: {1074- clientIp: '203.0.113.178',1075- headers: {1076- host: [1077- {1078- key: 'Host',1079- value: 'example.com',1080- },1081- ],1082- },1083- method: 'GET',1084- querystring: '',1085- uri: '/config/eventCheck',1086- },1087- },1088- },1089- ],1090- }1091-1092- let called = false1093- await handler(event, {}, () => {1094- called = true1095- })1096-1097- expect(called).toBe(true)1098- })1099-1100- it('Should return a response where bodyEncoding is "base64" with binary', async () => {1101- const event = {1102- Records: [1103- {1104- cf: {1105- config: {1106- distributionDomainName: 'example.com',1107- distributionId: 'EXAMPLE123',1108- eventType: 'viewer-request',1109- requestId: 'exampleRequestId',1110- },1111- request: {1112- clientIp: '123.123.123.123',1113- headers: {1114- host: [1115- {1116- key: 'Host',1117- value: 'example.com',1118- },1119- ],1120- },1121- method: 'GET',1122- querystring: '',1123- uri: '/binary',1124- },1125- },1126- },1127- ],1128- }1129-1130- const response = await handler(event)1131-1132- expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded "Fake Image"1133- expect(response.bodyEncoding).toBe('base64')1134- })1135-})deleted:runtime_tests/lambda-edge/vitest.config.ts-18 removed
1-/// <reference types="vitest" />2-import { defineConfig } from 'vitest/config'3-import config from '../../vitest.config'4-5-export default defineConfig({6- test: {7- env: {8- NAME: 'Node',9- },10- globals: true,11- include: ['**/runtime_tests/lambda-edge/**/*.+(ts|tsx|js)'],12- exclude: ['**/runtime_tests/lambda-edge/vitest.config.ts'],13- coverage: {14- ...config.test?.coverage,15- reportsDirectory: './coverage/raw/runtime-lambda-edge',16- },17- },18-})deleted:runtime_tests/node/index.test.ts-248 removed
1-import { createAdaptorServer, serve } from '@hono/node-server'2-import request from 'supertest'3-import type { Server } from 'node:http'4-import type { AddressInfo } from 'node:net'5-import { Hono } from '../../src'6-import { Context } from '../../src/context'7-import { env, getRuntimeKey } from '../../src/helper/adapter'8-import { stream, streamSSE } from '../../src/helper/streaming'9-import { basicAuth } from '../../src/middleware/basic-auth'10-import { compress } from '../../src/middleware/compress'11-import { jwt } from '../../src/middleware/jwt'12-13-// Test only minimal patterns.14-// See <https://github.com/honojs/node-server> for more tests and information.15-16-describe('Basic', () => {17- const app = new Hono()18-19- app.get('/', (c) => {20- return c.text('Hello! Node.js!')21- })22- app.get('/runtime-name', (c) => {23- return c.text(getRuntimeKey())24- })25-26- const server = createAdaptorServer(app)27-28- it('Should return 200 response', async () => {29- const res = await request(server).get('/')30- expect(res.status).toBe(200)31- expect(res.text).toBe('Hello! Node.js!')32- })33-34- it('Should return correct runtime name', async () => {35- const res = await request(server).get('/runtime-name')36- expect(res.status).toBe(200)37- expect(res.text).toBe('node')38- })39-})40-41-describe('Environment Variables', () => {42- it('Should return the environment variable', async () => {43- const c = new Context(new Request('http://localhost/'))44- const { NAME } = env<{ NAME: string }>(c)45- expect(NAME).toBe('Node')46- })47-})48-49-describe('Basic Auth Middleware', () => {50- const app = new Hono()51-52- const username = 'hono-user-a'53- const password = 'hono-password-a'54- app.use(55- '/auth/*',56- basicAuth({57- username,58- password,59- })60- )61-62- app.get('/auth/*', () => new Response('auth'))63-64- const server = createAdaptorServer(app)65-66- it('Should not authorize, return 401 Response', async () => {67- const res = await request(server).get('/auth/a')68- expect(res.status).toBe(401)69- expect(res.text).toBe('Unauthorized')70- })71-72- it('Should authorize, return 200 Response', async () => {73- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'74- const res = await request(server).get('/auth/a').set('Authorization', `Basic ${credential}`)75- expect(res.status).toBe(200)76- expect(res.text).toBe('auth')77- })78-})79-80-describe('JWT Auth Middleware', () => {81- const app = new Hono()82-83- app.use('/jwt/*', jwt({ secret: 'a-secret' }))84- app.get('/jwt/a', (c) => c.text('auth'))85-86- const server = createAdaptorServer(app)87-88- it('Should not authorize, return 401 Response', async () => {89- const res = await request(server).get('/jwt/a')90- expect(res.status).toBe(401)91- expect(res.text).toBe('Unauthorized')92- })93-94- it('Should authorize, return 200 Response', async () => {95- const credential =96- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'97- const res = await request(server).get('/jwt/a').set('Authorization', `Bearer ${credential}`)98- expect(res.status).toBe(200)99- expect(res.text).toBe('auth')100- })101-})102-103-describe('stream', () => {104- const app = new Hono()105-106- let aborted = false107-108- app.get('/stream', (c) => {109- return stream(c, async (stream) => {110- stream.onAbort(() => {111- aborted = true112- })113- return new Promise<void>((resolve) => {114- stream.onAbort(resolve)115- })116- })117- })118- app.get('/streamHello', (c) => {119- return stream(c, async (stream) => {120- stream.onAbort(() => {121- aborted = true122- })123- await stream.write('Hello')124- })125- })126-127- const server = createAdaptorServer(app)128-129- beforeEach(() => {130- aborted = false131- })132-133- it('Should call onAbort', async () => {134- const req = request(server)135- .get('/stream')136- .end(() => {})137-138- expect(aborted).toBe(false)139- await new Promise((resolve) => setTimeout(resolve, 10))140- req.abort()141- while (!aborted) {142- await new Promise((resolve) => setTimeout(resolve))143- }144- expect(aborted).toBe(true)145- })146-147- it('Should not be called onAbort if already closed', async () => {148- expect(aborted).toBe(false)149- const res = await request(server).get('/streamHello')150- expect(res.status).toBe(200)151- expect(res.text).toBe('Hello')152- expect(aborted).toBe(false)153- })154-})155-156-describe('streamSSE', () => {157- const app = new Hono()158-159- let aborted = false160-161- app.get('/stream', (c) => {162- return streamSSE(c, async (stream) => {163- stream.onAbort(() => {164- aborted = true165- })166- return new Promise<void>((resolve) => {167- stream.onAbort(resolve)168- })169- })170- })171- app.get('/streamHello', (c) => {172- return streamSSE(c, async (stream) => {173- stream.onAbort(() => {174- aborted = true175- })176- await stream.write('Hello')177- })178- })179-180- const server = createAdaptorServer(app)181-182- beforeEach(() => {183- aborted = false184- })185-186- it('Should call onAbort', async () => {187- const req = request(server)188- .get('/stream')189- .end(() => {})190-191- expect(aborted).toBe(false)192- await new Promise((resolve) => setTimeout(resolve, 10))193- req.abort()194- while (!aborted) {195- await new Promise((resolve) => setTimeout(resolve))196- }197- expect(aborted).toBe(true)198- })199-200- it('Should not be called onAbort if already closed', async () => {201- expect(aborted).toBe(false)202- const res = await request(server).get('/streamHello')203- expect(res.status).toBe(200)204- expect(res.text).toBe('Hello')205- expect(aborted).toBe(false)206- })207-})208-209-describe('compress', async () => {210- const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n')211- const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => {212- const externalApp = new Hono()213- externalApp.get('/style.css', (c) =>214- c.text(cssContent, {215- headers: {216- 'Content-Type': 'text/css',217- },218- })219- )220- const server = serve(221- {222- fetch: externalApp.fetch,223- port: 0,224- },225- (serverInfo) => {226- resolve([server as Server, serverInfo])227- }228- )229- })230-231- const app = new Hono()232- app.use(compress())233- app.get('/fetch/:file', (c) => {234- return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`)235- })236- const server = createAdaptorServer(app)237-238- afterAll(() => {239- externalServer.close()240- })241-242- it('Should be compressed a fetch response', async () => {243- const res = await request(server).get('/fetch/style.css')244- expect(res.status).toBe(200)245- expect(res.headers['content-encoding']).toBe('gzip')246- expect(res.text).toBe(cssContent)247- })248-})deleted:runtime_tests/node/vitest.config.ts-18 removed
1-/// <reference types="vitest" />2-import { defineConfig } from 'vitest/config'3-import config from '../../vitest.config'4-5-export default defineConfig({6- test: {7- env: {8- NAME: 'Node',9- },10- globals: true,11- include: ['**/runtime_tests/node/**/*.+(ts|tsx|js)'],12- exclude: ['**/runtime_tests/node/vitest.config.ts'],13- coverage: {14- ...config.test?.coverage,15- reportsDirectory: './coverage/raw/runtime-node',16- },17- },18-})deleted:runtime_tests/workerd/index.test.ts-69 removed
1-import { unstable_dev } from 'wrangler'2-import type { UnstableDevWorker } from 'wrangler'3-import { WebSocket } from 'ws'4-5-describe('workerd', () => {6- let worker: UnstableDevWorker7-8- beforeAll(async () => {9- worker = await unstable_dev('./runtime_tests/workerd/index.ts', {10- vars: {11- NAME: 'Hono',12- },13- experimental: { disableExperimentalWarning: true },14- })15- })16-17- afterAll(async () => {18- await worker.stop()19- })20-21- it('Should return 200 response with the runtime key', async () => {22- const res = await worker.fetch('/')23- expect(res.status).toBe(200)24- expect(await res.text()).toBe('Hello from workerd')25- })26-27- it('Should return 200 response with the environment variable', async () => {28- const res = await worker.fetch('/env')29- expect(res.status).toBe(200)30- expect(await res.text()).toBe('Hono')31- })32-})33-34-describe('workerd with WebSocket', () => {35- // worker.fetch does not support WebSocket:36- // https://github.com/cloudflare/workers-sdk/issues/4573#issuecomment-185042097337- it('Should handle the WebSocket connection correctly', async () => {38- const worker = await unstable_dev('./runtime_tests/workerd/index.ts', {39- experimental: { disableExperimentalWarning: true },40- })41- const ws = new WebSocket(`ws://${worker.address}:${worker.port}/ws`)42-43- const openHandler = vi.fn()44- const messageHandler = vi.fn()45- const closeHandler = vi.fn()46-47- const waitForOpen = new Promise((resolve) => {48- ws.addEventListener('open', () => {49- openHandler()50- ws.send('Hello')51- resolve(undefined)52- })53- ws.addEventListener('close', async () => {54- closeHandler()55- })56- ws.addEventListener('message', async (event) => {57- messageHandler(event.data)58- ws.close()59- })60- })61-62- await waitForOpen63- await worker.stop()64-65- expect(openHandler).toHaveBeenCalled()66- expect(messageHandler).toHaveBeenCalledWith('Hello')67- expect(closeHandler).toHaveBeenCalled()68- })69-})deleted:runtime_tests/workerd/index.ts-25 removed
1-import { upgradeWebSocket } from '../../src/adapter/cloudflare-workers'2-import { env, getRuntimeKey } from '../../src/helper/adapter'3-import { Hono } from '../../src/hono'4-5-const app = new Hono()6-7-app.get('/', (c) => c.text(`Hello from ${getRuntimeKey()}`))8-9-app.get('/env', (c) => {10- const { NAME } = env<{ NAME: string }>(c)11- return c.text(NAME)12-})13-14-app.get(15- '/ws',16- upgradeWebSocket(() => {17- return {18- onMessage(event, ws) {19- ws.send(event.data as string)20- },21- }22- })23-)24-25-export default appdeleted:runtime_tests/workerd/vitest.config.ts-15 removed
1-/// <reference types="vitest" />2-import { defineConfig } from 'vitest/config'3-import config from '../../vitest.config'4-5-export default defineConfig({6- test: {7- globals: true,8- include: ['**/runtime_tests/workerd/**/(*.)+(test).+(ts|tsx)'],9- exclude: ['**/runtime_tests/workerd/vitest.config.ts'],10- coverage: {11- ...config.test?.coverage,12- reportsDirectory: './coverage/raw/runtime-workerd',13- },14- },15-})deleted:runtime_tests/tsconfig.json-7 removed
1-{2- "extends": "../tsconfig.json",3- "include": [4- "**/*.ts",5- "**/*.tsx"6- ]7-}added:runtime-tests/bun/.static/plain.txt+1 added
1+Bun!!added:runtime-tests/bun/static/hello.world/index.html+1 added
1+Hiadded:runtime-tests/bun/static/helloworld/index.html+1 added
1+Hiadded:runtime-tests/bun/static/download+1 added
1+downloadadded:runtime-tests/bun/static/plain.txt+1 added
1+Bun!added:runtime-tests/bun/favicon.icobinary
A binary file, added.
added:runtime-tests/bun/index.test.tsx+432 added
1+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2+import { stream, streamSSE } from '../..//src/helper/streaming'3+import { serveStatic, toSSG } from '../../src/adapter/bun'4+import { createBunWebSocket } from '../../src/adapter/bun/websocket'5+import type { BunWebSocketData } from '../../src/adapter/bun/websocket'6+import { Context } from '../../src/context'7+import { env, getRuntimeKey } from '../../src/helper/adapter'8+import type { WSMessageReceive } from '../../src/helper/websocket'9+import { Hono } from '../../src/index'10+// eslint-disable-next-line @typescript-eslint/no-unused-vars11+import { jsx } from '../../src/jsx'12+import { basicAuth } from '../../src/middleware/basic-auth'13+import { jwt } from '../../src/middleware/jwt'14+import { HonoRequest } from '../../src/request'15+16+// Test just only minimal patterns.17+// Because others are tested well in Cloudflare Workers environment already.18+19+Bun.env.NAME = 'Bun'20+21+describe('Basic', () => {22+ const app = new Hono()23+ app.get('/a/:foo', (c) => {24+ c.header('x-param', c.req.param('foo'))25+ c.header('x-query', c.req.query('q'))26+ return c.text('Hello Bun!')27+ })28+29+ it('Should return 200 Response', async () => {30+ const req = new Request('http://localhost/a/foo?q=bar')31+ const res = await app.request(req)32+ expect(res.status).toBe(200)33+ expect(await res.text()).toBe('Hello Bun!')34+ expect(res.headers.get('x-param')).toBe('foo')35+ expect(res.headers.get('x-query')).toBe('bar')36+ })37+38+ it('returns current runtime (bun)', async () => {39+ expect(getRuntimeKey()).toBe('bun')40+ })41+})42+43+describe('Environment Variables', () => {44+ it('Should return the environment variable', async () => {45+ const c = new Context(new HonoRequest(new Request('http://localhost/')))46+ const { NAME } = env<{ NAME: string }>(c)47+ expect(NAME).toBe('Bun')48+ })49+})50+51+describe('Basic Auth Middleware', () => {52+ const app = new Hono()53+54+ const username = 'hono-user-a'55+ const password = 'hono-password-a'56+ app.use(57+ '/auth/*',58+ basicAuth({59+ username,60+ password,61+ })62+ )63+64+ app.get('/auth/*', () => new Response('auth'))65+66+ it('Should not authorize, return 401 Response', async () => {67+ const req = new Request('http://localhost/auth/a')68+ const res = await app.request(req)69+ expect(res.status).toBe(401)70+ expect(await res.text()).toBe('Unauthorized')71+ })72+73+ it('Should authorize, return 200 Response', async () => {74+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'75+ const req = new Request('http://localhost/auth/a')76+ req.headers.set('Authorization', `Basic ${credential}`)77+ const res = await app.request(req)78+ expect(res.status).toBe(200)79+ expect(await res.text()).toBe('auth')80+ })81+})82+83+describe('Serve Static Middleware', () => {84+ const app = new Hono()85+ const onNotFound = vi.fn(() => {})86+ app.all('/favicon.ico', serveStatic({ path: './runtime-tests/bun/favicon.ico' }))87+ app.all(88+ '/favicon-notfound.ico',89+ serveStatic({ path: './runtime-tests/bun/favicon-notfound.ico', onNotFound })90+ )91+ app.use('/favicon-notfound.ico', async (c, next) => {92+ await next()93+ c.header('X-Custom', 'Bun')94+ })95+ app.get(96+ '/static/*',97+ serveStatic({98+ root: './runtime-tests/bun/',99+ onNotFound,100+ })101+ )102+ app.get(103+ '/dot-static/*',104+ serveStatic({105+ root: './runtime-tests/bun/',106+ rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),107+ })108+ )109+110+ beforeEach(() => onNotFound.mockClear())111+112+ it('Should return static file correctly', async () => {113+ const res = await app.request(new Request('http://localhost/favicon.ico'))114+ await res.arrayBuffer()115+ expect(res.status).toBe(200)116+ expect(res.headers.get('Content-Type')).toBe('image/x-icon')117+ })118+119+ it('Should return 404 response', async () => {120+ const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))121+ expect(res.status).toBe(404)122+ expect(res.headers.get('X-Custom')).toBe('Bun')123+ expect(onNotFound).toHaveBeenCalledWith(124+ './runtime-tests/bun/favicon-notfound.ico',125+ expect.anything()126+ )127+ })128+129+ it('Should return 200 response - /static/plain.txt', async () => {130+ const res = await app.request(new Request('http://localhost/static/plain.txt'))131+ expect(res.status).toBe(200)132+ expect(await res.text()).toBe('Bun!')133+ expect(onNotFound).not.toHaveBeenCalled()134+ })135+136+ it('Should return 200 response - /static/download', async () => {137+ const res = await app.request(new Request('http://localhost/static/download'))138+ expect(res.status).toBe(200)139+ expect(await res.text()).toBe('download')140+ expect(onNotFound).not.toHaveBeenCalled()141+ })142+143+ it('Should return 200 response - /dot-static/plain.txt', async () => {144+ const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))145+ expect(res.status).toBe(200)146+ expect(await res.text()).toBe('Bun!!')147+ })148+149+ it('Should return 200 response - /static/helloworld', async () => {150+ const res = await app.request('http://localhost/static/helloworld')151+ expect(res.status).toBe(200)152+ expect(await res.text()).toBe('Hi\n')153+ })154+155+ it('Should return 200 response - /static/hello.world', async () => {156+ const res = await app.request('http://localhost/static/hello.world')157+ expect(res.status).toBe(200)158+ expect(await res.text()).toBe('Hi\n')159+ })160+})161+162+// Bun support WebCrypto since v0.2.2163+// So, JWT middleware works well.164+describe('JWT Auth Middleware', () => {165+ const app = new Hono()166+ app.use('/jwt/*', jwt({ secret: 'a-secret' }))167+ app.get('/jwt/a', (c) => c.text('auth'))168+169+ it('Should not authorize, return 401 Response', async () => {170+ const req = new Request('http://localhost/jwt/a')171+ const res = await app.request(req)172+ expect(res.status).toBe(401)173+ expect(await res.text()).toBe('Unauthorized')174+ })175+176+ it('Should authorize, return 200 Response', async () => {177+ const credential =178+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'179+ const req = new Request('http://localhost/jwt/a')180+ req.headers.set('Authorization', `Bearer ${credential}`)181+ const res = await app.request(req)182+ expect(res.status).toBe(200)183+ expect(await res.text()).toBe('auth')184+ })185+})186+187+// To enable JSX middleware,188+// set "jsxImportSource": "hono/jsx" in the tsconfig.json189+describe('JSX Middleware', () => {190+ const app = new Hono()191+192+ const Layout = (props: { children?: string }) => {193+ return <html>{props.children}</html>194+ }195+196+ app.get('/', (c) => {197+ return c.html(<h1>Hello</h1>)198+ })199+ app.get('/nest', (c) => {200+ return c.html(201+ <h1>202+ <a href='/top'>Hello</a>203+ </h1>204+ )205+ })206+ app.get('/layout', (c) => {207+ return c.html(208+ <Layout>209+ <p>hello</p>210+ </Layout>211+ )212+ })213+214+ it('Should return rendered HTML', async () => {215+ const res = await app.request(new Request('http://localhost/'))216+ expect(res.status).toBe(200)217+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')218+ expect(await res.text()).toBe('<h1>Hello</h1>')219+ })220+221+ it('Should return rendered HTML with nest', async () => {222+ const res = await app.request(new Request('http://localhost/nest'))223+ expect(res.status).toBe(200)224+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')225+ expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')226+ })227+228+ it('Should return rendered HTML with Layout', async () => {229+ const res = await app.request(new Request('http://localhost/layout'))230+ expect(res.status).toBe(200)231+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')232+ expect(await res.text()).toBe('<html><p>hello</p></html>')233+ })234+})235+236+describe('toSSG function', () => {237+ let app: Hono238+239+ beforeEach(() => {240+ app = new Hono()241+ app.get('/', (c) => c.text('Hello, World!'))242+ app.get('/about', (c) => c.text('About Page'))243+ app.get('/about/some', (c) => c.text('About Page 2tier'))244+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))245+ app.get('/bravo', (c) => c.html('Bravo Page'))246+ app.get('/Charlie', async (c, next) => {247+ c.setRenderer((content, head) => {248+ return c.html(249+ <html>250+ <head>251+ <title>{head.title || ''}</title>252+ </head>253+ <body>254+ <p>{content}</p>255+ </body>256+ </html>257+ )258+ })259+ await next()260+ })261+ app.get('/Charlie', (c) => {262+ return c.render('Hello!', { title: 'Charlies Page' })263+ })264+ })265+266+ it('Should correctly generate static HTML files for Hono routes', async () => {267+ const result = await toSSG(app, { dir: './static' })268+ expect(result.success).toBeTruly269+ expect(result.error).toBeUndefined()270+ expect(result.files).toBeDefined()271+ afterAll(async () => {272+ await deleteDirectory('./static')273+ })274+ })275+})276+277+describe('WebSockets Helper', () => {278+ const app = new Hono()279+ const { websocket, upgradeWebSocket } = createBunWebSocket()280+281+ it('Should websockets is working', async () => {282+ const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>283+ app.get(284+ '/ws',285+ upgradeWebSocket(() => ({286+ onMessage(evt) {287+ resolve(evt.data)288+ },289+ }))290+ )291+ )292+ const upgradedData = await new Promise<BunWebSocketData>((resolve) =>293+ app.fetch(new Request('http://localhost/ws'), {294+ upgrade: (_req: Request, data: { data: BunWebSocketData }) => {295+ resolve(data.data)296+ },297+ })298+ )299+ const message = Math.random().toString()300+ websocket.message(301+ {302+ close: () => undefined,303+ readyState: 3,304+ data: upgradedData,305+ send: () => undefined,306+ },307+ message308+ )309+ const receivedMessage = await receivedMessagePromise310+ expect(receivedMessage).toBe(message)311+ })312+})313+const fs = require('fs').promises314+const path = require('path')315+316+async function deleteDirectory(dirPath) {317+ if (318+ await fs319+ .stat(dirPath)320+ .then((stat) => stat.isDirectory())321+ .catch(() => false)322+ ) {323+ for (const entry of await fs.readdir(dirPath)) {324+ const entryPath = path.join(dirPath, entry)325+ await deleteDirectory(entryPath)326+ }327+ await fs.rmdir(dirPath)328+ } else {329+ await fs.unlink(dirPath)330+ }331+}332+333+describe('streaming', () => {334+ const app = new Hono()335+ let server: ReturnType<typeof Bun.serve>336+ let aborted = false337+338+ app.get('/stream', (c) => {339+ return stream(c, async (stream) => {340+ stream.onAbort(() => {341+ aborted = true342+ })343+ return new Promise<void>((resolve) => {344+ stream.onAbort(resolve)345+ })346+ })347+ })348+ app.get('/streamHello', (c) => {349+ return stream(c, async (stream) => {350+ stream.onAbort(() => {351+ aborted = true352+ })353+ await stream.write('Hello')354+ })355+ })356+ app.get('/streamSSE', (c) => {357+ return streamSSE(c, async (stream) => {358+ stream.onAbort(() => {359+ aborted = true360+ })361+ return new Promise<void>((resolve) => {362+ stream.onAbort(resolve)363+ })364+ })365+ })366+ app.get('/streamSSEHello', (c) => {367+ return streamSSE(c, async (stream) => {368+ stream.onAbort(() => {369+ aborted = true370+ })371+ await stream.write('Hello')372+ })373+ })374+375+ beforeEach(() => {376+ aborted = false377+ server = Bun.serve({ port: 0, fetch: app.fetch })378+ })379+380+ afterEach(() => {381+ server.stop()382+ })383+384+ describe('stream', () => {385+ it('Should call onAbort', async () => {386+ const ac = new AbortController()387+ const req = new Request(`http://localhost:${server.port}/stream`, {388+ signal: ac.signal,389+ })390+ expect(aborted).toBe(false)391+ const res = fetch(req).catch(() => {})392+ await new Promise((resolve) => setTimeout(resolve, 10))393+ ac.abort()394+ await res395+ while (!aborted) {396+ await new Promise((resolve) => setTimeout(resolve))397+ }398+ expect(aborted).toBe(true)399+ })400+401+ it('Should not be called onAbort if already closed', async () => {402+ expect(aborted).toBe(false)403+ const res = await fetch(`http://localhost:${server.port}/streamHello`)404+ expect(await res.text()).toBe('Hello')405+ expect(aborted).toBe(false)406+ })407+ })408+409+ describe('streamSSE', () => {410+ it('Should call onAbort', async () => {411+ const ac = new AbortController()412+ const req = new Request(`http://localhost:${server.port}/streamSSE`, {413+ signal: ac.signal,414+ })415+ const res = fetch(req).catch(() => {})416+ await new Promise((resolve) => setTimeout(resolve, 10))417+ ac.abort()418+ await res419+ while (!aborted) {420+ await new Promise((resolve) => setTimeout(resolve))421+ }422+ expect(aborted).toBe(true)423+ })424+425+ it('Should not be called onAbort if already closed', async () => {426+ expect(aborted).toBe(false)427+ const res = await fetch(`http://localhost:${server.port}/streamSSEHello`)428+ expect(await res.text()).toBe('Hello')429+ expect(aborted).toBe(false)430+ })431+ })432+})added:runtime-tests/bun/vitest.config.ts+14 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+import config from '../../vitest.config'4+5+export default defineConfig({6+ test: {7+ globals: true,8+ include: ['**/runtime-tests/bun/**/*.+(ts|tsx|js)'],9+ coverage: {10+ ...config.test?.coverage,11+ reportsDirectory: './coverage/raw/runtime-bun',12+ },13+ },14+})added:runtime-tests/deno/.static/plain.txt+1 added
1+Deno!!added:runtime-tests/deno/.vscode/settings.json+7 added
1+{2+ "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],3+ "editor.codeActionsOnSave": {4+ "source.fixAll.eslint": true5+ },6+ "deno.enable": true7+}added:runtime-tests/deno/static/hello.world/index.html+1 added
1+Hiadded:runtime-tests/deno/static/helloworld/index.html+1 added
1+Hiadded:runtime-tests/deno/static/download+1 added
1+downloadadded:runtime-tests/deno/static/plain.txt+1 added
1+Deno!added:runtime-tests/deno/deno.json+19 added
1+{2+ "compilerOptions": {3+ "jsx": "react-jsx",4+ "jsxImportSource": "hono/jsx",5+ "lib": [6+ "deno.ns",7+ "dom",8+ "dom.iterable"9+ ]10+ },11+ "unstable": [12+ "sloppy-imports"13+ ],14+ "imports": {15+ "@std/assert": "jsr:@std/assert@^1.0.3",16+ "@std/testing": "jsr:@std/testing@^1.0.1",17+ "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"18+ }19+}added:runtime-tests/deno/deno.lock+34 added
1+{2+ "version": "3",3+ "packages": {4+ "specifiers": {5+ "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.3",6+ "jsr:@std/internal@^1.0.2": "jsr:@std/internal@1.0.2",7+ "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.1"8+ },9+ "jsr": {10+ "@std/assert@1.0.3": {11+ "integrity": "b0d03ce1ced880df67132eea140623010d415848df66f6aa5df76507ca7c26d8",12+ "dependencies": [13+ "jsr:@std/internal@^1.0.2"14+ ]15+ },16+ "@std/internal@1.0.2": {17+ "integrity": "f4cabe2021352e8bfc24e6569700df87bf070914fc38d4b23eddd20108ac4495"18+ },19+ "@std/testing@1.0.1": {20+ "integrity": "9c25841137ee818933e1722091bb9ed5fdc251c35e84c97979a52196bdb6c5c3",21+ "dependencies": [22+ "jsr:@std/assert@^1.0.3"23+ ]24+ }25+ }26+ },27+ "remote": {},28+ "workspace": {29+ "dependencies": [30+ "jsr:@std/assert@^1.0.3",31+ "jsr:@std/testing@^1.0.1"32+ ]33+ }34+}added:runtime-tests/deno/favicon.icobinary
A binary file, added.
added:runtime-tests/deno/hono.test.ts+34 added
1+import { assertEquals } from '@std/assert'2+import { Context } from '../../src/context.ts'3+import { env, getRuntimeKey } from '../../src/helper/adapter/index.ts'4+import { Hono } from '../../src/hono.ts'5+6+// Test just only minimal patterns.7+// Because others are tested well in Cloudflare Workers environment already.8+9+Deno.env.set('NAME', 'Deno')10+11+Deno.test('Hello World', async () => {12+ const app = new Hono()13+ app.get('/:foo', (c) => {14+ c.header('x-param', c.req.param('foo'))15+ c.header('x-query', c.req.query('q') || '')16+ return c.text('Hello Deno!')17+ })18+19+ const res = await app.request('/foo?q=bar')20+ assertEquals(res.status, 200)21+ assertEquals(await res.text(), 'Hello Deno!')22+ assertEquals(res.headers.get('x-param'), 'foo')23+ assertEquals(res.headers.get('x-query'), 'bar')24+})25+26+Deno.test('runtime', () => {27+ assertEquals(getRuntimeKey(), 'deno')28+})29+30+Deno.test('environment variables', () => {31+ const c = new Context(new Request('http://localhost/'))32+ const { NAME } = env<{ NAME: string }>(c)33+ assertEquals(NAME, 'Deno')34+})added:runtime-tests/deno/middleware.test.tsx+163 added
1+import { assertEquals, assertMatch } from '@std/assert'2+import { assertSpyCall, assertSpyCalls, spy } from '@std/testing/mock'3+import { serveStatic } from '../../src/adapter/deno/index.ts'4+import { Hono } from '../../src/hono.ts'5+import { basicAuth } from '../../src/middleware/basic-auth/index.ts'6+import { jwt } from '../../src/middleware/jwt/index.ts'7+8+// Test just only minimal patterns.9+// Because others are already tested well in Cloudflare Workers environment.10+11+Deno.test('Basic Auth Middleware', async () => {12+ const app = new Hono()13+14+ const username = 'hono'15+ const password = 'acoolproject'16+17+ app.use(18+ '/auth/*',19+ basicAuth({20+ username,21+ password,22+ })23+ )24+25+ app.get('/auth/*', () => new Response('auth'))26+27+ const res = await app.request('http://localhost/auth/a')28+ assertEquals(res.status, 401)29+ assertEquals(await res.text(), 'Unauthorized')30+31+ const credential = 'aG9ubzphY29vbHByb2plY3Q='32+33+ const req = new Request('http://localhost/auth/a')34+ req.headers.set('Authorization', `Basic ${credential}`)35+ const resOK = await app.request(req)36+ assertEquals(resOK.status, 200)37+ assertEquals(await resOK.text(), 'auth')38+39+ const invalidCredential = 'G9ubzphY29vbHByb2plY3Q='40+41+ const req2 = new Request('http://localhost/auth/a')42+ req2.headers.set('Authorization', `Basic ${invalidCredential}`)43+ const resNG = await app.request(req2)44+ assertEquals(resNG.status, 401)45+ assertEquals(await resNG.text(), 'Unauthorized')46+})47+48+Deno.test('JSX middleware', async () => {49+ const app = new Hono()50+ app.get('/', (c) => {51+ return c.html(<h1>Hello</h1>)52+ })53+ const res = await app.request('http://localhost/')54+ assertEquals(res.status, 200)55+ assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')56+ assertEquals(await res.text(), '<h1>Hello</h1>')57+58+ // Fragment59+ const template = (60+ <>61+ <p>1</p>62+ <p>2</p>63+ </>64+ )65+ assertEquals(template.toString(), '<p>1</p><p>2</p>')66+})67+68+Deno.test('Serve Static middleware', async () => {69+ const app = new Hono()70+ const onNotFound = spy(() => {})71+ app.all('/favicon.ico', serveStatic({ path: './runtime-tests/deno/favicon.ico' }))72+ app.all(73+ '/favicon-notfound.ico',74+ serveStatic({ path: './runtime-tests/deno/favicon-notfound.ico', onNotFound })75+ )76+ app.use('/favicon-notfound.ico', async (c, next) => {77+ await next()78+ c.header('X-Custom', 'Deno')79+ })80+81+ app.get(82+ '/static/*',83+ serveStatic({84+ root: './runtime-tests/deno',85+ onNotFound,86+ })87+ )88+89+ app.get(90+ '/dot-static/*',91+ serveStatic({92+ root: './runtime-tests/deno',93+ rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),94+ })95+ )96+97+ let res = await app.request('http://localhost/favicon.ico')98+ assertEquals(res.status, 200)99+ assertEquals(res.headers.get('Content-Type'), 'image/x-icon')100+ await res.body?.cancel()101+102+ res = await app.request('http://localhost/favicon-notfound.ico')103+ assertEquals(res.status, 404)104+ assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)105+ assertEquals(res.headers.get('X-Custom'), 'Deno')106+ assertSpyCall(onNotFound, 0)107+108+ res = await app.request('http://localhost/static/plain.txt')109+ assertEquals(res.status, 200)110+ assertEquals(await res.text(), 'Deno!')111+112+ res = await app.request('http://localhost/static/download')113+ assertEquals(res.status, 200)114+ assertEquals(await res.text(), 'download')115+116+ res = await app.request('http://localhost/dot-static/plain.txt')117+ assertEquals(res.status, 200)118+ assertEquals(await res.text(), 'Deno!!')119+ assertSpyCalls(onNotFound, 1)120+121+ res = await app.fetch({122+ method: 'GET',123+ url: 'http://localhost/static/%2e%2e/static/plain.txt',124+ } as Request)125+ assertEquals(res.status, 404)126+ assertEquals(await res.text(), '404 Not Found')127+128+ res = await app.request('http://localhost/static/helloworld')129+ assertEquals(res.status, 200)130+ assertEquals(await res.text(), 'Hi\n')131+132+ res = await app.request('http://localhost/static/hello.world')133+ assertEquals(res.status, 200)134+ assertEquals(await res.text(), 'Hi\n')135+})136+137+Deno.test('JWT Authentication middleware', async () => {138+ const app = new Hono<{ Variables: { 'x-foo': string } }>()139+ app.use('/*', async (c, next) => {140+ await next()141+ c.header('x-foo', c.get('x-foo') || '')142+ })143+ app.use('/auth/*', jwt({ secret: 'a-secret' }))144+ app.get('/auth/*', (c) => {145+ c.set('x-foo', 'bar')146+ return new Response('auth')147+ })148+149+ const req = new Request('http://localhost/auth/a')150+ const res = await app.request(req)151+ assertEquals(res.status, 401)152+ assertEquals(await res.text(), 'Unauthorized')153+ assertEquals(res.headers.get('x-foo'), '')154+155+ const credential =156+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'157+ const reqOK = new Request('http://localhost/auth/a')158+ reqOK.headers.set('Authorization', `Bearer ${credential}`)159+ const resOK = await app.request(reqOK)160+ assertEquals(resOK.status, 200)161+ assertEquals(await resOK.text(), 'auth')162+ assertEquals(resOK.headers.get('x-foo'), 'bar')163+})added:runtime-tests/deno/ssg.test.tsx+52 added
1+import { assertEquals } from '@std/assert'2+import { toSSG } from '../../src/adapter/deno/ssg.ts'3+import { Hono } from '../../src/hono.ts'4+5+Deno.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+ })27+28+ const result = await toSSG(app, { dir: './ssg-static' })29+ assertEquals(result.success, true)30+ assertEquals(result.error, undefined)31+ assertEquals(result.files !== undefined, true)32+33+ await deleteDirectory('./ssg-static')34+})35+36+async function deleteDirectory(dirPath: string): Promise<void> {37+ try {38+ const stat = await Deno.stat(dirPath)39+40+ 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+}added:runtime-tests/deno/stream.test.ts+108 added
1+import { assertEquals } from '@std/assert'2+import { stream, streamSSE } from '../../src/helper/streaming/index.ts'3+import { Hono } from '../../src/hono.ts'4+5+Deno.test('Shuld call onAbort via stream', async () => {6+ const app = new Hono()7+ let aborted = false8+ app.get('/stream', (c) => {9+ return stream(c, (stream) => {10+ stream.onAbort(() => {11+ aborted = true12+ })13+ return new Promise<void>((resolve) => {14+ stream.onAbort(resolve)15+ })16+ })17+ })18+19+ const server = Deno.serve({ port: 0 }, app.fetch)20+ const ac = new AbortController()21+ const req = new Request(`http://localhost:${server.addr.port}/stream`, {22+ signal: ac.signal,23+ })24+ const res = fetch(req).catch(() => {})25+ assertEquals(aborted, false)26+ await new Promise((resolve) => setTimeout(resolve, 10))27+ ac.abort()28+ await res29+ while (!aborted) {30+ await new Promise((resolve) => setTimeout(resolve))31+ }32+ assertEquals(aborted, true)33+34+ await server.shutdown()35+})36+37+Deno.test('Shuld not call onAbort via stream if already closed', async () => {38+ const app = new Hono()39+ let aborted = false40+ app.get('/stream', (c) => {41+ return stream(c, async (stream) => {42+ stream.onAbort(() => {43+ aborted = true44+ })45+ await stream.write('Hello')46+ })47+ })48+49+ const server = Deno.serve({ port: 0 }, app.fetch)50+ assertEquals(aborted, false)51+ const res = await fetch(`http://localhost:${server.addr.port}/stream`)52+ assertEquals(await res.text(), 'Hello')53+ assertEquals(aborted, false)54+ await server.shutdown()55+})56+57+Deno.test('Shuld call onAbort via streamSSE', async () => {58+ const app = new Hono()59+ let aborted = false60+ app.get('/stream', (c) => {61+ return streamSSE(c, (stream) => {62+ stream.onAbort(() => {63+ aborted = true64+ })65+ return new Promise<void>((resolve) => {66+ stream.onAbort(resolve)67+ })68+ })69+ })70+71+ const server = Deno.serve({ port: 0 }, app.fetch)72+ const ac = new AbortController()73+ const req = new Request(`http://localhost:${server.addr.port}/stream`, {74+ signal: ac.signal,75+ })76+ assertEquals77+ const res = fetch(req).catch(() => {})78+ assertEquals(aborted, false)79+ await new Promise((resolve) => setTimeout(resolve, 10))80+ ac.abort()81+ await res82+ while (!aborted) {83+ await new Promise((resolve) => setTimeout(resolve))84+ }85+ assertEquals(aborted, true)86+87+ await server.shutdown()88+})89+90+Deno.test('Shuld not call onAbort via streamSSE if already closed', async () => {91+ const app = new Hono()92+ let aborted = false93+ app.get('/stream', (c) => {94+ return streamSSE(c, async (stream) => {95+ stream.onAbort(() => {96+ aborted = true97+ })98+ await stream.write('Hello')99+ })100+ })101+102+ const server = Deno.serve({ port: 0 }, app.fetch)103+ assertEquals(aborted, false)104+ const res = await fetch(`http://localhost:${server.addr.port}/stream`)105+ assertEquals(await res.text(), 'Hello')106+ assertEquals(aborted, false)107+ await server.shutdown()108+})added:runtime-tests/deno-jsx/deno.precompile.json+18 added
1+{2+ "compilerOptions": {3+ "jsx": "precompile",4+ "jsxImportSource": "hono/jsx",5+ "lib": [6+ "deno.ns",7+ "dom",8+ "dom.iterable"9+ ]10+ },11+ "unstable": [12+ "sloppy-imports"13+ ],14+ "imports": {15+ "@std/assert": "jsr:@std/assert@^1.0.3",16+ "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"17+ }18+}added:runtime-tests/deno-jsx/deno.react-jsx.json+18 added
1+{2+ "compilerOptions": {3+ "jsx": "react-jsx",4+ "jsxImportSource": "hono/jsx",5+ "lib": [6+ "deno.ns",7+ "dom",8+ "dom.iterable"9+ ]10+ },11+ "unstable": [12+ "sloppy-imports"13+ ],14+ "imports": {15+ "@std/assert": "jsr:@std/assert@^1.0.3",16+ "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"17+ }18+}added:runtime-tests/deno-jsx/jsx.test.tsx+112 added
1+/** @jsxImportSource ../../src/jsx */2+import { assertEquals } from '@std/assert'3+import { Style, css } from '../../src/helper/css/index.ts'4+import { Suspense, renderToReadableStream } from '../../src/jsx/streaming.ts'5+import type { HtmlEscapedString } from '../../src/utils/html.ts'6+import { HtmlEscapedCallbackPhase, resolveCallback } from '../../src/utils/html.ts'7+8+Deno.test('JSX', () => {9+ const Component = ({ name }: { name: string }) => <span>{name}</span>10+ const html = (11+ <div>12+ <h1 id={'<Hello>'}>13+ <Component name={'<Hono>'} />14+ </h1>15+ </div>16+ )17+18+ assertEquals(html.toString(), '<div><h1 id="<Hello>"><span><Hono></span></h1></div>')19+})20+21+Deno.test('JSX: Fragment', () => {22+ const fragment = (23+ <>24+ <p>1</p>25+ <p>2</p>26+ </>27+ )28+ assertEquals(fragment.toString(), '<p>1</p><p>2</p>')29+})30+31+Deno.test('JSX: Empty Fragment', () => {32+ const Component = () => <></>33+ const html = <Component />34+ assertEquals(html.toString(), '')35+})36+37+Deno.test('JSX: Async Component', async () => {38+ const Component = async ({ name }: { name: string }) =>39+ new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<span>{name}</span>), 10))40+ const stream = renderToReadableStream(41+ <div>42+ <Component name={'<Hono>'} />43+ </div>44+ )45+46+ const chunks: string[] = []47+ const textDecoder = new TextDecoder()48+ // eslint-disable-next-line @typescript-eslint/no-explicit-any49+ for await (const chunk of stream as any) {50+ chunks.push(textDecoder.decode(chunk))51+ }52+53+ assertEquals(chunks.join(''), '<div><span><Hono></span></div>')54+})55+56+Deno.test('JSX: Suspense', async () => {57+ const Content = () => {58+ const content = new Promise<HtmlEscapedString>((resolve) =>59+ setTimeout(() => resolve(<h1>Hello</h1>), 10)60+ )61+ return content62+ }63+64+ const stream = renderToReadableStream(65+ <Suspense fallback={<p>Loading...</p>}>66+ <Content />67+ </Suspense>68+ )69+70+ const chunks: string[] = []71+ const textDecoder = new TextDecoder()72+ // eslint-disable-next-line @typescript-eslint/no-explicit-any73+ for await (const chunk of stream as any) {74+ chunks.push(textDecoder.decode(chunk))75+ }76+77+ assertEquals(chunks, [78+ '<template id="H:0"></template><p>Loading...</p><!--/$-->',79+ `<template data-hono-target="H:0"><h1>Hello</h1></template><script>80+((d,c,n) => {81+c=d.currentScript.previousSibling82+d=d.getElementById('H:0')83+if(!d)return84+do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')85+d.replaceWith(c.content)86+})(document)87+</script>`,88+ ])89+})90+91+Deno.test('JSX: css', async () => {92+ const className = css`93+ color: red;94+ `95+ const html = (96+ <html>97+ <head>98+ <Style />99+ </head>100+ <body>101+ <div class={className}></div>102+ </body>103+ </html>104+ )105+106+ const awaitedHtml = await html107+ const htmlEscapedString = 'callbacks' in awaitedHtml ? awaitedHtml : await awaitedHtml.toString()108+ assertEquals(109+ await resolveCallback(htmlEscapedString, HtmlEscapedCallbackPhase.Stringify, false, {}),110+ '<html><head><style id="hono-css">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>'111+ )112+})added:runtime-tests/fastly/index.test.ts+100 added
1+import { SHA256 } from 'crypto-js'2+import { getRuntimeKey } from '../../src/helper/adapter'3+import { Hono } from '../../src/index'4+import { basicAuth } from '../../src/middleware/basic-auth'5+import { jwt } from '../../src/middleware/jwt'6+7+// eslint-disable-next-line @typescript-eslint/ban-ts-comment8+// @ts-ignore9+globalThis.fastly = true10+11+const app = new Hono()12+13+describe('Hello World', () => {14+ app.get('/', (c) => c.text('Hello! Compute!'))15+ app.get('/runtime-name', (c) => {16+ return c.text(getRuntimeKey())17+ })18+19+ it('Should return 200', async () => {20+ const res = await app.request('http://localhost/')21+ expect(res.status).toBe(200)22+ expect(await res.text()).toBe('Hello! Compute!')23+ })24+25+ it('Should return the correct runtime name', async () => {26+ const res = await app.request('http://localhost/runtime-name')27+ expect(res.status).toBe(200)28+ expect(await res.text()).toBe('fastly')29+ })30+})31+32+describe('Basic Auth Middleware without `hashFunction`', () => {33+ const app = new Hono()34+35+ const username = 'hono-user-a'36+ const password = 'hono-password-a'37+ app.use(38+ '/auth/*',39+ basicAuth({40+ username,41+ password,42+ })43+ )44+45+ app.get('/auth/*', () => new Response('auth'))46+47+ it('Should not authorize, return 401 Response', async () => {48+ const req = new Request('http://localhost/auth/a')49+ const res = await app.request(req)50+ expect(res.status).toBe(401)51+ expect(await res.text()).toBe('Unauthorized')52+ })53+})54+55+describe('Basic Auth Middleware with `hashFunction`', () => {56+ const app = new Hono()57+58+ const username = 'hono-user-a'59+ const password = 'hono-password-a'60+ app.use(61+ '/auth/*',62+ basicAuth({63+ username,64+ password,65+ hashFunction: (m: string) => SHA256(m).toString(),66+ })67+ )68+69+ app.get('/auth/*', () => new Response('auth'))70+71+ it('Should not authorize, return 401 Response', async () => {72+ const req = new Request('http://localhost/auth/a')73+ const res = await app.request(req)74+ expect(res.status).toBe(401)75+ expect(await res.text()).toBe('Unauthorized')76+ })77+78+ it('Should authorize, return 200 Response', async () => {79+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'80+ const req = new Request('http://localhost/auth/a')81+ req.headers.set('Authorization', `Basic ${credential}`)82+ const res = await app.request(req)83+ expect(res.status).toBe(200)84+ expect(await res.text()).toBe('auth')85+ })86+})87+88+describe('JWT Auth Middleware does not work', () => {89+ const app = new Hono()90+91+ // Since nodejs 20 or later, global WebCrypto object becomes stable (experimental on nodejs 18)92+ // but WebCrypto does not have compatibility with Fastly Compute runtime (lacking some objects/methods in Fastly)93+ // so following test should run only be polyfill-ed via vite-plugin-fastly-js-compute plugin.94+ // To confirm polyfill-ed or not, check __fastlyComputeNodeDefaultCrypto field is true.95+ it.runIf(!globalThis.__fastlyComputeNodeDefaultCrypto)('Should throw error', () => {96+ expect(() => {97+ app.use('/jwt/*', jwt({ secret: 'secret' }))98+ }).toThrow(/`crypto.subtle.importKey` is undefined/)99+ })100+})added:runtime-tests/fastly/vitest.config.ts+17 added
1+/// <reference types="vitest" />2+import fastlyCompute from 'vite-plugin-fastly-js-compute'3+import { defineConfig } from 'vitest/config'4+import config from '../../vitest.config'5+6+export default defineConfig({7+ plugins: [fastlyCompute()],8+ test: {9+ globals: true,10+ include: ['**/runtime-tests/fastly/**/(*.)+(test).+(ts|tsx)'],11+ exclude: ['**/runtime-tests/fastly/vitest.config.ts'],12+ coverage: {13+ ...config.test?.coverage,14+ reportsDirectory: './coverage/raw/runtime-fastly',15+ },16+ },17+})added:runtime-tests/lambda/index.test.ts+969 added
1+import { Readable } from 'stream'2+import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'3+import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'4+import type {5+ ApiGatewayRequestContext,6+ ApiGatewayRequestContextV2,7+ LambdaContext,8+} from '../../src/adapter/aws-lambda/types'9+import { getCookie, setCookie } from '../../src/helper/cookie'10+import { streamSSE } from '../../src/helper/streaming'11+import { Hono } from '../../src/hono'12+import { basicAuth } from '../../src/middleware/basic-auth'13+import './mock'14+15+type Bindings = {16+ event: LambdaEvent17+ lambdaContext: LambdaContext18+ requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV219+}20+21+const testApiGatewayRequestContextV2 = {22+ accountId: '123456789012',23+ apiId: 'urlid',24+ authentication: null,25+ authorizer: {26+ iam: {27+ accessKey: 'AKIA...',28+ accountId: '111122223333',29+ callerId: 'AIDA...',30+ cognitoIdentity: null,31+ principalOrgId: null,32+ userArn: 'arn:aws:iam::111122223333:user/example-user',33+ userId: 'AIDA...',34+ },35+ },36+ domainName: 'example.com',37+ domainPrefix: '<url-id>',38+ http: {39+ method: 'POST',40+ path: '/my/path',41+ protocol: 'HTTP/1.1',42+ sourceIp: '123.123.123.123',43+ userAgent: 'agent',44+ },45+ requestId: 'id',46+ routeKey: '$default',47+ stage: '$default',48+ time: '12/Mar/2020:19:03:58 +0000',49+ timeEpoch: 1583348638390,50+ customProperty: 'customValue',51+}52+53+describe('AWS Lambda Adapter for Hono', () => {54+ const app = new Hono<{ Bindings: Bindings }>()55+56+ app.get('/', (c) => {57+ return c.text('Hello Lambda!')58+ })59+60+ app.get('/binary', (c) => {61+ return c.body('Fake Image', 200, {62+ 'Content-Type': 'image/png',63+ })64+ })65+66+ app.post('/post', async (c) => {67+ const body = (await c.req.parseBody()) as { message: string }68+ return c.text(body.message)69+ })70+71+ app.post('/post/binary', async (c) => {72+ const body = await c.req.blob()73+ return c.text(`${body.size} bytes`)74+ })75+76+ const username = 'hono-user-a'77+ const password = 'hono-password-a'78+ app.use('/auth/*', basicAuth({ username, password }))79+ app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))80+81+ app.get('/lambda-event', (c) => {82+ const event = c.env.event83+ return c.json(event)84+ })85+86+ app.get('/lambda-context', (c) => {87+ const fnctx = c.env.lambdaContext88+ return c.json(fnctx)89+ })90+91+ app.get('/custom-context/v1/apigw', (c) => {92+ const lambdaContext = c.env.requestContext93+ return c.json(lambdaContext)94+ })95+96+ app.get('/custom-context/apigw', (c) => {97+ const lambdaContext = c.env.event.requestContext98+ return c.json(lambdaContext)99+ })100+101+ app.get('/custom-context/v1/lambda', (c) => {102+ const lambdaContext = c.env.requestContext103+ return c.json(lambdaContext)104+ })105+106+ app.get('/custom-context/lambda', (c) => {107+ const lambdaContext = c.env.event.requestContext108+ return c.json(lambdaContext)109+ })110+111+ app.get('/query-params', (c) => {112+ const queryParams = c.req.query()113+ return c.json(queryParams)114+ })115+116+ app.get('/multi-query-params', (c) => {117+ const multiQueryParams = c.req.queries()118+ return c.json(multiQueryParams)119+ })120+121+ const testCookie1 = {122+ key: 'id',123+ value: crypto.randomUUID(),124+ get serialized() {125+ return `${this.key}=${this.value}; Path=/`126+ },127+ }128+ const testCookie2 = {129+ key: 'secret',130+ value: crypto.randomUUID(),131+ get serialized() {132+ return `${this.key}=${this.value}; Path=/`133+ },134+ }135+136+ app.post('/cookie', (c) => {137+ setCookie(c, testCookie1.key, testCookie1.value)138+ setCookie(c, testCookie2.key, testCookie2.value)139+ return c.text('Cookies Set')140+ })141+142+ app.get('/cookie', (c) => {143+ const validCookies =144+ getCookie(c, testCookie1.key) === testCookie1.value &&145+ getCookie(c, testCookie2.key) === testCookie2.value146+ if (!validCookies) {147+ return c.text('Invalid Cookies')148+ }149+ return c.text('Valid Cookies')150+ })151+152+ app.post('/headers', (c) => {153+ if (c.req.header('foo')?.includes('bar')) {154+ return c.json({ message: 'ok' })155+ }156+ return c.json({ message: 'fail' }, 400)157+ })158+159+ const handler = handle(app)160+161+ const testApiGatewayRequestContext = {162+ accountId: '123456789012',163+ apiId: 'id',164+ authorizer: {165+ claims: null,166+ scopes: null,167+ },168+ domainName: 'example.com',169+ domainPrefix: 'id',170+ extendedRequestId: 'request-id',171+ httpMethod: 'GET',172+ identity: {173+ sourceIp: 'IP',174+ userAgent: 'user-agent',175+ },176+ path: '/my/path',177+ protocol: 'HTTP/1.1',178+ requestId: 'id=',179+ requestTime: '04/Mar/2020:19:15:17 +0000',180+ requestTimeEpoch: 1583349317135,181+ resourcePath: '/',182+ stage: '$default',183+ customProperty: 'customValue',184+ }185+186+ const testApiGatewayRequestContextV2 = {187+ accountId: '123456789012',188+ apiId: 'urlid',189+ authentication: null,190+ authorizer: {191+ iam: {192+ accessKey: 'AKIA...',193+ accountId: '111122223333',194+ callerId: 'AIDA...',195+ cognitoIdentity: null,196+ principalOrgId: null,197+ userArn: 'arn:aws:iam::111122223333:user/example-user',198+ userId: 'AIDA...',199+ },200+ },201+ domainName: 'example.com',202+ domainPrefix: '<url-id>',203+ http: {204+ method: 'POST',205+ path: '/my/path',206+ protocol: 'HTTP/1.1',207+ sourceIp: '123.123.123.123',208+ userAgent: 'agent',209+ },210+ requestId: 'id',211+ routeKey: '$default',212+ stage: '$default',213+ time: '12/Mar/2020:19:03:58 +0000',214+ timeEpoch: 1583348638390,215+ customProperty: 'customValue',216+ }217+218+ const testALBRequestContext = {219+ elb: {220+ targetGroupArn:221+ 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',222+ },223+ }224+225+ it('Should handle a GET request and return a 200 response', async () => {226+ const event = {227+ version: '1.0',228+ resource: '/',229+ httpMethod: 'GET',230+ headers: { 'content-type': 'text/plain' },231+ path: '/',232+ body: null,233+ isBase64Encoded: false,234+ requestContext: testApiGatewayRequestContext,235+ }236+237+ const response = await handler(event)238+ expect(response.statusCode).toBe(200)239+ expect(response.body).toBe('Hello Lambda!')240+ expect(response.headers['content-type']).toMatch(/^text\/plain/)241+ expect(response.isBase64Encoded).toBe(false)242+ })243+244+ it('Should handle a GET request and return a 200 response with binary', async () => {245+ const event = {246+ version: '1.0',247+ resource: '/binary',248+ httpMethod: 'GET',249+ headers: {},250+ path: '/binary',251+ body: null,252+ isBase64Encoded: false,253+ requestContext: testApiGatewayRequestContext,254+ }255+256+ const response = await handler(event)257+ expect(response.statusCode).toBe(200)258+ expect(response.body).toBe('RmFrZSBJbWFnZQ==')259+ expect(response.headers['content-type']).toMatch(/^image\/png/)260+ expect(response.isBase64Encoded).toBe(true)261+ })262+263+ it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {264+ const event = {265+ version: '2.0',266+ routeKey: '$default',267+ headers: { 'content-type': 'text/plain' },268+ rawPath: '/',269+ rawQueryString: '',270+ body: null,271+ isBase64Encoded: false,272+ requestContext: testApiGatewayRequestContextV2,273+ }274+275+ testApiGatewayRequestContextV2.http.method = 'GET'276+277+ const response = await handler(event)278+ expect(response.statusCode).toBe(200)279+ expect(response.body).toBe('Hello Lambda!')280+ expect(response.headers['content-type']).toMatch(/^text\/plain/)281+ expect(response.isBase64Encoded).toBe(false)282+ })283+284+ it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {285+ const event = {286+ headers: { 'content-type': 'text/plain' },287+ httpMethod: 'GET',288+ path: '/',289+ queryStringParameters: {290+ query: '1234ABCD',291+ },292+ body: null,293+ isBase64Encoded: false,294+ requestContext: testALBRequestContext,295+ }296+297+ const response = await handler(event)298+ expect(response.statusCode).toBe(200)299+ expect(response.body).toBe('Hello Lambda!')300+ expect(response.headers['content-type']).toMatch(/^text\/plain/)301+ expect(response.isBase64Encoded).toBe(false)302+ })303+304+ it('Should handle a GET request and return a 404 response', async () => {305+ const event = {306+ version: '1.0',307+ resource: '/nothing',308+ httpMethod: 'GET',309+ headers: { 'content-type': 'text/plain' },310+ path: '/nothing',311+ body: null,312+ isBase64Encoded: false,313+ requestContext: testApiGatewayRequestContext,314+ }315+316+ const response = await handler(event)317+ expect(response.statusCode).toBe(404)318+ })319+320+ it('Should handle a POST request and return a 200 response', async () => {321+ const searchParam = new URLSearchParams()322+ searchParam.append('message', 'Good Morning Lambda!')323+ const event = {324+ version: '1.0',325+ resource: '/post',326+ httpMethod: 'POST',327+ headers: {328+ 'Content-Type': 'application/x-www-form-urlencoded',329+ },330+ path: '/post',331+ body: Buffer.from(searchParam.toString()).toString('base64'),332+ isBase64Encoded: true,333+ requestContext: testApiGatewayRequestContext,334+ }335+336+ const response = await handler(event)337+ expect(response.statusCode).toBe(200)338+ expect(response.body).toBe('Good Morning Lambda!')339+ })340+341+ it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {342+ const searchParam = new URLSearchParams()343+ searchParam.append('message', 'Good Morning Lambda!')344+ const event = {345+ version: '2.0',346+ routeKey: '$default',347+ headers: {348+ 'Content-Type': 'application/x-www-form-urlencoded',349+ },350+ rawPath: '/post',351+ rawQueryString: '',352+ body: Buffer.from(searchParam.toString()).toString('base64'),353+ isBase64Encoded: true,354+ requestContext: testApiGatewayRequestContextV2,355+ }356+357+ testApiGatewayRequestContextV2.http.method = 'POST'358+359+ const response = await handler(event)360+ expect(response.statusCode).toBe(200)361+ expect(response.body).toBe('Good Morning Lambda!')362+ })363+364+ it('Should handle a POST request with binary and return a 200 response', async () => {365+ const array = new Uint8Array([0xc0, 0xff, 0xee])366+ const buffer = Buffer.from(array)367+ const event = {368+ version: '1.0',369+ resource: '/post/binary',370+ httpMethod: 'POST',371+ headers: {372+ 'Content-Type': 'application/x-www-form-urlencoded',373+ },374+ path: '/post/binary',375+ body: buffer.toString('base64'),376+ isBase64Encoded: true,377+ requestContext: testApiGatewayRequestContext,378+ }379+380+ const response = await handler(event)381+ expect(response.statusCode).toBe(200)382+ expect(response.body).toBe('3 bytes')383+ })384+385+ it('Should handle a request and return a 401 response with Basic auth', async () => {386+ const event = {387+ version: '1.0',388+ resource: '/auth/abc',389+ httpMethod: 'GET',390+ headers: {391+ 'Content-Type': 'plain/text',392+ },393+ path: '/auth/abc',394+ body: null,395+ isBase64Encoded: true,396+ requestContext: testApiGatewayRequestContext,397+ }398+399+ const response = await handler(event)400+ expect(response.statusCode).toBe(401)401+ })402+403+ it('Should handle a request and return a 200 response with Basic auth', async () => {404+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'405+ const event = {406+ version: '1.0',407+ resource: '/auth/abc',408+ httpMethod: 'GET',409+ headers: {410+ 'Content-Type': 'plain/text',411+ Authorization: `Basic ${credential}`,412+ },413+ path: '/auth/abc',414+ body: null,415+ isBase64Encoded: true,416+ requestContext: testApiGatewayRequestContext,417+ }418+419+ const response = await handler(event)420+ expect(response.statusCode).toBe(200)421+ expect(response.body).toBe('Good Night Lambda!')422+ })423+424+ it('Should handle a GET request and return custom context', async () => {425+ const event = {426+ version: '1.0',427+ resource: '/custom-context/apigw',428+ httpMethod: 'GET',429+ headers: { 'content-type': 'application/json' },430+ path: '/custom-context/apigw',431+ body: null,432+ isBase64Encoded: false,433+ requestContext: testApiGatewayRequestContext,434+ }435+436+ const response = await handler(event)437+ expect(response.statusCode).toBe(200)438+ expect(JSON.parse(response.body).customProperty).toEqual('customValue')439+ })440+441+ it('Should handle a GET request and context', async () => {442+ const event = {443+ version: '1.0',444+ resource: '/lambda-context',445+ httpMethod: 'GET',446+ headers: { 'content-type': 'application/json' },447+ path: '/lambda-context',448+ body: null,449+ isBase64Encoded: false,450+ requestContext: testApiGatewayRequestContext,451+ }452+ const context: LambdaContext = {453+ callbackWaitsForEmptyEventLoop: false,454+ functionName: 'myLambdaFunction',455+ functionVersion: '1.0.0',456+ invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',457+ memoryLimitInMB: '128',458+ awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',459+ logGroupName: '/aws/lambda/myLambdaFunction',460+ logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',461+ getRemainingTimeInMillis: () => {462+ return 60000 // 60 seconds463+ },464+ }465+ const response = await handler(event, context)466+ expect(response.statusCode).toBe(200)467+ expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)468+ })469+470+ it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {471+ const apiGatewayEvent = {472+ version: '1.0',473+ resource: '/cookie',474+ httpMethod: 'POST',475+ headers: { 'content-type': 'text/plain' },476+ path: '/cookie',477+ body: null,478+ isBase64Encoded: false,479+ requestContext: testApiGatewayRequestContext,480+ }481+482+ const apiGatewayResponse = await handler(apiGatewayEvent)483+484+ expect(apiGatewayResponse.statusCode).toBe(200)485+ expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [486+ testCookie1.serialized,487+ testCookie2.serialized,488+ ])489+490+ const apiGatewayEventV2 = {491+ version: '2.0',492+ routeKey: '$default',493+ httpMethod: 'POST',494+ headers: { 'content-type': 'text/plain' },495+ rawPath: '/cookie',496+ rawQueryString: '',497+ body: null,498+ isBase64Encoded: false,499+ requestContext: testApiGatewayRequestContextV2,500+ }501+502+ const apiGatewayResponseV2 = await handler(apiGatewayEventV2)503+504+ expect(apiGatewayResponseV2.statusCode).toBe(200)505+ expect(apiGatewayResponseV2).toHaveProperty('cookies', [506+ testCookie1.serialized,507+ testCookie2.serialized,508+ ])509+ })510+511+ describe('headers', () => {512+ describe('single-value headers', () => {513+ it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {514+ const event = {515+ body: '{}',516+ httpMethod: 'POST',517+ isBase64Encoded: false,518+ path: '/headers',519+ headers: {520+ host: 'localhost',521+ foo: 'bar',522+ },523+ requestContext: testALBRequestContext,524+ }525+ const albResponse = await handler(event)526+ expect(albResponse.statusCode).toBe(200)527+ expect(albResponse.headers).toEqual(528+ expect.objectContaining({529+ 'content-type': 'application/json; charset=UTF-8',530+ })531+ )532+ })533+534+ it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {535+ const apigatewayProxyEvent = {536+ version: '1.0',537+ resource: '/headers',538+ httpMethod: 'POST',539+ headers: {540+ host: 'localhost',541+ foo: 'bar',542+ },543+ path: '/headers',544+ body: null,545+ isBase64Encoded: false,546+ requestContext: testApiGatewayRequestContext,547+ }548+ const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)549+ expect(apiGatewayResponseV2.statusCode).toBe(200)550+ })551+552+ it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {553+ const apigatewayProxyV2Event = {554+ version: '2.0',555+ routeKey: '$default',556+ headers: {557+ host: 'localhost',558+ foo: 'bar',559+ },560+ rawPath: '/headers',561+ rawQueryString: '',562+ requestContext: testApiGatewayRequestContextV2,563+ resource: '/headers',564+ body: null,565+ isBase64Encoded: false,566+ }567+ const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)568+ expect(apiGatewayResponseV2.statusCode).toBe(200)569+ })570+ })571+572+ describe('multi-value headers', () => {573+ it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {574+ const event = {575+ body: '{}',576+ httpMethod: 'POST',577+ isBase64Encoded: false,578+ path: '/headers',579+ multiValueHeaders: {580+ host: ['localhost'],581+ foo: ['bar'],582+ },583+ requestContext: testALBRequestContext,584+ }585+ const albResponse = await handler(event)586+ expect(albResponse.statusCode).toBe(200)587+ expect(albResponse.multiValueHeaders).toBeDefined()588+ expect(albResponse.multiValueHeaders).toEqual(589+ expect.objectContaining({590+ 'content-type': ['application/json; charset=UTF-8'],591+ })592+ )593+ })594+595+ it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {596+ const apigatewayProxyEvent = {597+ version: '1.0',598+ resource: '/headers',599+ httpMethod: 'POST',600+ headers: {},601+ multiValueHeaders: {602+ host: ['localhost'],603+ foo: ['bar'],604+ },605+ path: '/headers',606+ body: null,607+ isBase64Encoded: false,608+ requestContext: testApiGatewayRequestContext,609+ }610+ const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)611+ expect(apiGatewayResponseV2.statusCode).toBe(200)612+ })613+ })614+ })615+616+ it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {617+ const apiGatewayEvent = {618+ version: '1.0',619+ resource: '/cookie',620+ httpMethod: 'GET',621+ headers: {622+ 'content-type': 'text/plain',623+ cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),624+ },625+ path: '/cookie',626+ body: null,627+ isBase64Encoded: false,628+ requestContext: testApiGatewayRequestContext,629+ }630+631+ const apiGatewayResponse = await handler(apiGatewayEvent)632+633+ expect(apiGatewayResponse.statusCode).toBe(200)634+ expect(apiGatewayResponse.body).toBe('Valid Cookies')635+ expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)636+ expect(apiGatewayResponse.isBase64Encoded).toBe(false)637+638+ const apiGatewayEventV2 = {639+ version: '2.0',640+ routeKey: '$default',641+ headers: { 'content-type': 'text/plain' },642+ rawPath: '/cookie',643+ cookies: [testCookie1.serialized, testCookie2.serialized],644+ rawQueryString: '',645+ body: null,646+ isBase64Encoded: false,647+ requestContext: testApiGatewayRequestContextV2,648+ }649+ testApiGatewayRequestContextV2.http.method = 'GET'650+651+ const apiGatewayResponseV2 = await handler(apiGatewayEventV2)652+653+ expect(apiGatewayResponseV2.statusCode).toBe(200)654+ expect(apiGatewayResponseV2.body).toBe('Valid Cookies')655+ expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)656+ expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)657+ })658+659+ it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {660+ const albEventDefaultHeaders = {661+ version: '1.0',662+ resource: '/cookie',663+ httpMethod: 'GET',664+ headers: {665+ 'content-type': 'text/plain',666+ cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),667+ },668+ path: '/cookie',669+ body: null,670+ isBase64Encoded: false,671+ requestContext: testALBRequestContext,672+ }673+674+ const albResponse = await handler(albEventDefaultHeaders)675+676+ expect(albResponse.statusCode).toBe(200)677+ expect(albResponse.body).toBe('Valid Cookies')678+ expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)679+ expect(albResponse.isBase64Encoded).toBe(false)680+ })681+682+ it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {683+ const albEventMultiValueHeaders = {684+ version: '1.0',685+ resource: '/cookie',686+ httpMethod: 'GET',687+ multiValueHeaders: {688+ 'content-type': ['text/plain'],689+ cookie: [testCookie1.serialized, testCookie2.serialized],690+ },691+ path: '/cookie',692+ body: null,693+ isBase64Encoded: false,694+ requestContext: testALBRequestContext,695+ }696+697+ const albResponse = await handler(albEventMultiValueHeaders)698+699+ expect(albResponse.statusCode).toBe(200)700+ expect(albResponse.body).toBe('Valid Cookies')701+ expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)702+ expect(albResponse.isBase64Encoded).toBe(false)703+ })704+705+ it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {706+ const albEventDefaultHeaders = {707+ version: '1.0',708+ resource: '/cookie',709+ httpMethod: 'POST',710+ headers: {711+ 'content-type': 'text/plain',712+ cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),713+ },714+ path: '/cookie',715+ body: null,716+ isBase64Encoded: false,717+ requestContext: testALBRequestContext,718+ }719+720+ const albResponse = await handler(albEventDefaultHeaders)721+722+ expect(albResponse.statusCode).toBe(200)723+ expect(albResponse.body).toBe('Cookies Set')724+ expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)725+ expect(albResponse.multiValueHeaders).toBeUndefined()726+ expect(albResponse.headers['set-cookie']).toEqual(727+ [testCookie1.serialized, testCookie2.serialized].join(', ')728+ )729+ expect(albResponse.isBase64Encoded).toBe(false)730+ })731+732+ it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {733+ const albEventDefaultHeaders = {734+ version: '1.0',735+ resource: '/cookie',736+ httpMethod: 'POST',737+ multiValueHeaders: {738+ 'content-type': ['text/plain'],739+ cookie: [testCookie1.serialized, testCookie2.serialized],740+ },741+ path: '/cookie',742+ body: null,743+ isBase64Encoded: false,744+ requestContext: testALBRequestContext,745+ }746+747+ const albResponse = await handler(albEventDefaultHeaders)748+749+ expect(albResponse.statusCode).toBe(200)750+ expect(albResponse.body).toBe('Cookies Set')751+ expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)752+ expect(albResponse.multiValueHeaders).toBeDefined()753+ expect(albResponse.multiValueHeaders && albResponse.multiValueHeaders['set-cookie']).toEqual(754+ expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])755+ )756+ expect(albResponse.isBase64Encoded).toBe(false)757+ })758+759+ it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {760+ const albEventDefaultHeaders = {761+ resource: '/query-params',762+ httpMethod: 'GET',763+ headers: {764+ 'content-type': 'application/json',765+ },766+ queryStringParameters: {767+ key1: 'value1',768+ key2: 'value2',769+ },770+ path: '/query-params',771+ body: null,772+ isBase64Encoded: false,773+ requestContext: testALBRequestContext,774+ }775+776+ const albResponse = await handler(albEventDefaultHeaders)777+778+ expect(albResponse.statusCode).toBe(200)779+ expect(albResponse.body).toContain(780+ JSON.stringify({781+ key1: 'value1',782+ key2: 'value2',783+ })784+ )785+ expect(albResponse.headers['content-type']).toMatch(/^application\/json/)786+ expect(albResponse.isBase64Encoded).toBe(false)787+ })788+789+ it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {790+ const albEventDefaultHeaders = {791+ resource: '/query-params',792+ httpMethod: 'GET',793+ multiValueHeaders: {794+ 'content-type': ['application/json'],795+ },796+ multiValueQueryStringParameters: {797+ key1: ['value1'],798+ key2: ['value2'],799+ },800+ path: '/query-params',801+ body: null,802+ isBase64Encoded: false,803+ requestContext: testALBRequestContext,804+ }805+806+ const albResponse = await handler(albEventDefaultHeaders)807+808+ expect(albResponse.statusCode).toBe(200)809+ expect(albResponse.body).toContain(810+ JSON.stringify({811+ key1: 'value1',812+ key2: 'value2',813+ })814+ )815+ expect(albResponse.headers['content-type']).toMatch(/^application\/json/)816+ expect(albResponse.isBase64Encoded).toBe(false)817+ })818+819+ it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {820+ const albEventDefaultHeaders = {821+ resource: '/query-params',822+ httpMethod: 'GET',823+ multiValueHeaders: {824+ 'content-type': ['application/json'],825+ },826+ multiValueQueryStringParameters: {827+ key1: ['value1'],828+ key2: ['value2', 'otherValue2'],829+ },830+ path: '/multi-query-params',831+ body: null,832+ isBase64Encoded: false,833+ requestContext: testALBRequestContext,834+ }835+836+ const albResponse = await handler(albEventDefaultHeaders)837+838+ expect(albResponse.statusCode).toBe(200)839+ expect(albResponse.body).toContain(840+ JSON.stringify({841+ key1: ['value1'],842+ key2: ['value2', 'otherValue2'],843+ })844+ )845+ expect(albResponse.headers['content-type']).toMatch(/^application\/json/)846+ expect(albResponse.isBase64Encoded).toBe(false)847+ })848+})849+850+describe('streamHandle function', () => {851+ const app = new Hono<{ Bindings: Bindings }>()852+853+ app.get('/', (c) => {854+ return c.text('Hello Lambda!')855+ })856+857+ app.get('/stream/text', async (c) => {858+ return c.streamText(async (stream) => {859+ for (let i = 0; i < 3; i++) {860+ await stream.writeln(`${i}`)861+ await stream.sleep(1)862+ }863+ })864+ })865+866+ app.get('/sse', async (c) => {867+ return streamSSE(c, async (stream) => {868+ let id = 0869+ const maxIterations = 2870+871+ while (id < maxIterations) {872+ const message = `Message\nIt is ${id}`873+ await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })874+ await stream.sleep(10)875+ }876+ })877+ })878+879+ const handler = streamHandle(app)880+881+ it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {882+ const event = {883+ headers: { 'content-type': ' binary/octet-stream' },884+ rawPath: '/stream/text',885+ rawQueryString: '',886+ body: null,887+ isBase64Encoded: false,888+ requestContext: testApiGatewayRequestContextV2,889+ }890+891+ testApiGatewayRequestContextV2.http.method = 'GET'892+893+ const mockReadableStream = new Readable({894+ // eslint-disable-next-line @typescript-eslint/no-empty-function895+ read() {},896+ })897+898+ mockReadableStream.push('0\n')899+ mockReadableStream.push('1\n')900+ mockReadableStream.push('2\n')901+ mockReadableStream.push('3\n')902+ mockReadableStream.push(null) // EOF903+904+ await handler(event, mockReadableStream)905+906+ const chunks = []907+ for await (const chunk of mockReadableStream) {908+ chunks.push(chunk)909+ }910+ expect(chunks.join('')).toContain('0\n1\n2\n3\n')911+ })912+913+ it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {914+ const event = {915+ headers: { 'content-type': 'text/event-stream' },916+ rawPath: '/sse',917+ rawQueryString: '',918+ body: null,919+ isBase64Encoded: false,920+ requestContext: testApiGatewayRequestContextV2,921+ }922+923+ testApiGatewayRequestContextV2.http.method = 'GET'924+925+ const mockReadableStream = new Readable({926+ // eslint-disable-next-line @typescript-eslint/no-empty-function927+ read() {},928+ })929+930+ const initContentType = {931+ 'Content-Type': 'application/vnd.awslambda.http-integration-response',932+ }933+ mockReadableStream.push(JSON.stringify(initContentType))934+935+ // Send JSON formatted response headers, followed by 8 NULL characters as a separator936+ const httpResponseMetadata = {937+ statusCode: 200,938+ headers: { 'Custom-Header': 'value' },939+ cookies: ['session=abcd1234'],940+ }941+ const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()942+ mockReadableStream.push(jsonResponsePrelude)943+944+ mockReadableStream.push('data: Message\ndata: It is 0\n\n')945+ mockReadableStream.push('data: Message\ndata: It is 1\n\n')946+ mockReadableStream.push(null) // EOF947+948+ await handler(event, mockReadableStream)949+950+ const chunks = []951+ for await (const chunk of mockReadableStream) {952+ chunks.push(chunk)953+ }954+955+ // If you have chunks, you might want to convert them to strings before checking956+ const output = Buffer.concat(chunks).toString()957+ expect(output).toContain('data: Message\ndata: It is 0\n\n')958+ expect(output).toContain('data: Message\ndata: It is 1\n\n')959+960+ // Assertions for the newly added header and prelude961+ expect(output).toContain('application/vnd.awslambda.http-integration-response')962+ expect(output).toContain('Custom-Header')963+ expect(output).toContain('session=abcd1234')964+965+ // Check for JSON prelude and NULL sequence966+ const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'967+ expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))968+ })969+})added:runtime-tests/lambda/mock.ts+42 added
1+import { vi } from 'vitest'2+import type {3+ APIGatewayProxyEvent,4+ APIGatewayProxyEventV2,5+ LambdaFunctionUrlEvent,6+} from '../../src/adapter/aws-lambda/handler'7+import type { LambdaContext } from '../../src/adapter/aws-lambda/types'8+9+type StreamifyResponseHandler = (10+ handlerFunc: (11+ event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,12+ responseStream: NodeJS.WritableStream,13+ context: LambdaContext14+ ) => Promise<void>15+) => (event: APIGatewayProxyEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>16+17+const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {18+ return async (event, context) => {19+ const mockWritableStream: NodeJS.WritableStream = new (require('stream').Writable)({20+ write(chunk, encoding, callback) {21+ console.log('Writing chunk:', chunk.toString())22+ callback()23+ },24+ final(callback) {25+ console.log('Finalizing stream.')26+ callback()27+ },28+ })29+ mockWritableStream.on('finish', () => {30+ console.log('Stream has finished')31+ })32+ await handlerFunc(event, mockWritableStream, context)33+ mockWritableStream.end()34+ return mockWritableStream35+ }36+}37+38+const awslambda = {39+ streamifyResponse: mockStreamifyResponse,40+}41+42+vi.stubGlobal('awslambda', awslambda)added:runtime-tests/lambda/stream-mock.ts+43 added
1+import { vi } from 'vitest'2+import { Writable } from 'node:stream'3+import type {4+ APIGatewayProxyEvent,5+ APIGatewayProxyEventV2,6+} from '../../src/adapter/aws-lambda/handler'7+import type { LambdaContext } from '../../src/adapter/aws-lambda/types'8+9+type StreamifyResponseHandler = (10+ handlerFunc: (11+ event: APIGatewayProxyEvent | APIGatewayProxyEventV2,12+ responseStream: Writable,13+ context: LambdaContext14+ ) => Promise<void>15+) => (event: APIGatewayProxyEvent, context: LambdaContext) => Promise<NodeJS.WritableStream>16+17+const mockStreamifyResponse: StreamifyResponseHandler = (handlerFunc) => {18+ return async (event, context) => {19+ const chunks = []20+ const mockWritableStream = new Writable({21+ write(chunk, encoding, callback) {22+ chunks.push(chunk)23+ callback()24+ },25+ })26+ mockWritableStream.chunks = chunks27+ await handlerFunc(event, mockWritableStream, context)28+ mockWritableStream.end()29+ return mockWritableStream30+ }31+}32+33+const awslambda = {34+ streamifyResponse: mockStreamifyResponse,35+ HttpResponseStream: {36+ from: (stream: Writable, httpResponseMetadata: unknown): Writable => {37+ stream.write(Buffer.from(JSON.stringify(httpResponseMetadata)))38+ return stream39+ },40+ },41+}42+43+vi.stubGlobal('awslambda', awslambda)added:runtime-tests/lambda/stream.test.ts+75 added
1+import { streamHandle } from '../../src/adapter/aws-lambda/handler'2+import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'3+import type {4+ ApiGatewayRequestContext,5+ ApiGatewayRequestContextV2,6+ LambdaContext,7+} from '../../src/adapter/aws-lambda/types'8+import { Hono } from '../../src/hono'9+import './stream-mock'10+11+type Bindings = {12+ event: LambdaEvent13+ lambdaContext: LambdaContext14+ requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV215+}16+17+const 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+}48+49+describe('streamHandle function', () => {50+ const app = new Hono<{ Bindings: Bindings }>()51+52+ 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+ })57+58+ const handler = streamHandle(app)59+60+ 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+ }69+70+ const stream = await handler(event)71+72+ const metadata = JSON.parse(stream.chunks[0].toString())73+ expect(metadata.cookies).toEqual(['cookie1=value1', 'cookie2=value2'])74+ })75+})added:runtime-tests/lambda/vitest.config.ts+22 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+import config from '../../vitest.config'4+5+export default defineConfig({6+ test: {7+ env: {8+ NAME: 'Node',9+ },10+ globals: true,11+ include: ['**/runtime-tests/lambda/**/*.+(ts|tsx|js)'],12+ exclude: [13+ '**/runtime-tests/lambda/vitest.config.ts',14+ '**/runtime-tests/lambda/mock.ts',15+ '**/runtime-tests/lambda/stream-mock.ts',16+ ],17+ coverage: {18+ ...config.test?.coverage,19+ reportsDirectory: './coverage/raw/runtime-lambda',20+ },21+ },22+})added:runtime-tests/lambda-edge/index.test.ts+1135 added
1+/* eslint-disable quotes */2+import type {3+ Callback,4+ CloudFrontConfig,5+ CloudFrontRequest,6+ CloudFrontResponse,7+} from '../../src/adapter/lambda-edge/handler'8+import { handle } from '../../src/adapter/lambda-edge/handler'9+import { Hono } from '../../src/hono'10+import { basicAuth } from '../../src/middleware/basic-auth'11+12+type Bindings = {13+ callback: Callback14+ config: CloudFrontConfig15+ request: CloudFrontRequest16+ response: CloudFrontResponse17+}18+19+describe('Lambda@Edge Adapter for Hono', () => {20+ const app = new Hono<{ Bindings: Bindings }>()21+22+ app.get('/', (c) => {23+ return c.text('Hello Lambda!')24+ })25+26+ app.get('/binary', (c) => {27+ return c.body('Fake Image', 200, {28+ 'Content-Type': 'image/png',29+ })30+ })31+32+ app.post('/post', async (c) => {33+ const body = (await c.req.parseBody()) as { message: string }34+ return c.text(body.message)35+ })36+37+ app.get('/callback/request', async (c, next) => {38+ await next()39+ c.env.callback(null, c.env.request)40+ })41+42+ app.get('/config/eventCheck', async (c, next) => {43+ await next()44+ if (c.env.config.eventType in ['viewer-request', 'origin-request']) {45+ c.env.callback(null, c.env.request)46+ } else {47+ c.env.callback(null, c.env.response)48+ }49+ })50+51+ app.get('/callback/response', async (c, next) => {52+ await next()53+ c.env.callback(null, c.env.response)54+ })55+56+ app.post('/post/binary', async (c) => {57+ const body = await c.req.blob()58+ return c.text(`${body.size} bytes`)59+ })60+61+ const username = 'hono-user-a'62+ const password = 'hono-password-a'63+ app.use('/auth/*', basicAuth({ username, password }))64+ app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))65+66+ app.get('/header/add', async (c, next) => {67+ c.env.response.headers['Strict-Transport-Security'.toLowerCase()] = [68+ {69+ key: 'Strict-Transport-Security',70+ value: 'max-age=63072000; includeSubdomains; preload',71+ },72+ ]73+ c.env.response.headers['X-Custom'.toLowerCase()] = [74+ {75+ key: 'X-Custom',76+ value: 'Foo',77+ },78+ ]79+ await next()80+ c.env.callback(null, c.env.response)81+ })82+83+ const handler = handle(app)84+85+ it('Should handle a GET request and return a 200 response (Lambda@Edge viewer request)', async () => {86+ const event = {87+ Records: [88+ {89+ cf: {90+ config: {91+ distributionDomainName: 'd111111abcdef8.cloudfront.net',92+ distributionId: 'EDFDVBD6EXAMPLE',93+ eventType: 'viewer-request',94+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',95+ },96+ request: {97+ clientIp: '203.0.113.178',98+ headers: {99+ host: [100+ {101+ key: 'Host',102+ value: 'd111111abcdef8.cloudfront.net',103+ },104+ ],105+ 'user-agent': [106+ {107+ key: 'User-Agent',108+ value: 'curl/7.66.0',109+ },110+ ],111+ accept: [112+ {113+ key: 'accept',114+ value: '*/*',115+ },116+ ],117+ },118+ method: 'GET',119+ querystring: '',120+ uri: '/',121+ },122+ },123+ },124+ ],125+ }126+ const response = await handler(event)127+ expect(response.status).toBe('200')128+ expect(response.body).toBe('Hello Lambda!')129+ if (response.headers && response.headers['content-type']) {130+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)131+ } else {132+ throw new Error("'content-type' header is missing in the response")133+ }134+ })135+136+ it('Should handle a GET request and return a 200 response (Lambda@Edge origin request)', async () => {137+ const event = {138+ Records: [139+ {140+ cf: {141+ config: {142+ distributionDomainName: 'd111111abcdef8.cloudfront.net',143+ distributionId: 'EDFDVBD6EXAMPLE',144+ eventType: 'origin-request',145+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',146+ },147+ request: {148+ clientIp: '203.0.113.178',149+ headers: {150+ 'x-forwarded-for': [151+ {152+ key: 'X-Forwarded-For',153+ value: '203.0.113.178',154+ },155+ ],156+ 'user-agent': [157+ {158+ key: 'User-Agent',159+ value: 'Amazon CloudFront',160+ },161+ ],162+ via: [163+ {164+ key: 'Via',165+ value: '2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)',166+ },167+ ],168+ host: [169+ {170+ key: 'Host',171+ value: 'example.org',172+ },173+ ],174+ 'cache-control': [175+ {176+ key: 'Cache-Control',177+ value: 'no-cache',178+ },179+ ],180+ },181+ method: 'GET',182+ origin: {183+ custom: {184+ customHeaders: {},185+ domainName: 'example.org',186+ keepaliveTimeout: 5,187+ path: '',188+ port: 443,189+ protocol: 'https',190+ readTimeout: 30,191+ sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],192+ },193+ },194+ querystring: '',195+ uri: '/',196+ },197+ },198+ },199+ ],200+ }201+ const response = await handler(event)202+ expect(response.status).toBe('200')203+ expect(response.body).toBe('Hello Lambda!')204+ if (response.headers && response.headers['content-type']) {205+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)206+ } else {207+ throw new Error("'content-type' header is missing in the response")208+ }209+ })210+211+ it('Should handle a GET request and return a 200 response (Lambda@Edge viewer response)', async () => {212+ const event = {213+ Records: [214+ {215+ cf: {216+ config: {217+ distributionDomainName: 'd111111abcdef8.cloudfront.net',218+ distributionId: 'EDFDVBD6EXAMPLE',219+ eventType: 'viewer-response',220+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',221+ },222+ request: {223+ clientIp: '203.0.113.178',224+ headers: {225+ host: [226+ {227+ key: 'Host',228+ value: 'd111111abcdef8.cloudfront.net',229+ },230+ ],231+ 'user-agent': [232+ {233+ key: 'User-Agent',234+ value: 'curl/7.66.0',235+ },236+ ],237+ accept: [238+ {239+ key: 'accept',240+ value: '*/*',241+ },242+ ],243+ },244+ method: 'GET',245+ querystring: '',246+ uri: '/',247+ },248+ response: {249+ headers: {250+ 'access-control-allow-credentials': [251+ {252+ key: 'Access-Control-Allow-Credentials',253+ value: 'true',254+ },255+ ],256+ 'access-control-allow-origin': [257+ {258+ key: 'Access-Control-Allow-Origin',259+ value: '*',260+ },261+ ],262+ date: [263+ {264+ key: 'Date',265+ value: 'Mon, 13 Jan 2020 20:14:56 GMT',266+ },267+ ],268+ 'referrer-policy': [269+ {270+ key: 'Referrer-Policy',271+ value: 'no-referrer-when-downgrade',272+ },273+ ],274+ server: [275+ {276+ key: 'Server',277+ value: 'ExampleCustomOriginServer',278+ },279+ ],280+ 'x-content-type-options': [281+ {282+ key: 'X-Content-Type-Options',283+ value: 'nosniff',284+ },285+ ],286+ 'x-frame-options': [287+ {288+ key: 'X-Frame-Options',289+ value: 'DENY',290+ },291+ ],292+ 'x-xss-protection': [293+ {294+ key: 'X-XSS-Protection',295+ value: '1; mode=block',296+ },297+ ],298+ age: [299+ {300+ key: 'Age',301+ value: '2402',302+ },303+ ],304+ 'content-type': [305+ {306+ key: 'Content-Type',307+ value: 'text/html; charset=utf-8',308+ },309+ ],310+ 'content-length': [311+ {312+ key: 'Content-Length',313+ value: '9593',314+ },315+ ],316+ },317+ status: '200',318+ statusDescription: 'OK',319+ },320+ },321+ },322+ ],323+ }324+ const response = await handler(event)325+ expect(response.status).toBe('200')326+ expect(response.body).toBe('Hello Lambda!')327+ if (response.headers && response.headers['content-type']) {328+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)329+ } else {330+ throw new Error("'content-type' header is missing in the response")331+ }332+ })333+334+ it('Should handle a GET request and return a 200 response (Lambda@Edge origin response)', async () => {335+ const event = {336+ Records: [337+ {338+ cf: {339+ config: {340+ distributionDomainName: 'd111111abcdef8.cloudfront.net',341+ distributionId: 'EDFDVBD6EXAMPLE',342+ eventType: 'origin-response',343+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',344+ },345+ request: {346+ clientIp: '203.0.113.178',347+ headers: {348+ 'x-forwarded-for': [349+ {350+ key: 'X-Forwarded-For',351+ value: '203.0.113.178',352+ },353+ ],354+ 'user-agent': [355+ {356+ key: 'User-Agent',357+ value: 'Amazon CloudFront',358+ },359+ ],360+ via: [361+ {362+ key: 'Via',363+ value: '2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)',364+ },365+ ],366+ host: [367+ {368+ key: 'Host',369+ value: 'example.org',370+ },371+ ],372+ 'cache-control': [373+ {374+ key: 'Cache-Control',375+ value: 'no-cache',376+ },377+ ],378+ },379+ method: 'GET',380+ origin: {381+ custom: {382+ customHeaders: {},383+ domainName: 'example.org',384+ keepaliveTimeout: 5,385+ path: '',386+ port: 443,387+ protocol: 'https',388+ readTimeout: 30,389+ sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],390+ },391+ },392+ querystring: '',393+ uri: '/',394+ },395+ response: {396+ headers: {397+ 'access-control-allow-credentials': [398+ {399+ key: 'Access-Control-Allow-Credentials',400+ value: 'true',401+ },402+ ],403+ 'access-control-allow-origin': [404+ {405+ key: 'Access-Control-Allow-Origin',406+ value: '*',407+ },408+ ],409+ date: [410+ {411+ key: 'Date',412+ value: 'Mon, 13 Jan 2020 20:12:38 GMT',413+ },414+ ],415+ 'referrer-policy': [416+ {417+ key: 'Referrer-Policy',418+ value: 'no-referrer-when-downgrade',419+ },420+ ],421+ server: [422+ {423+ key: 'Server',424+ value: 'ExampleCustomOriginServer',425+ },426+ ],427+ 'x-content-type-options': [428+ {429+ key: 'X-Content-Type-Options',430+ value: 'nosniff',431+ },432+ ],433+ 'x-frame-options': [434+ {435+ key: 'X-Frame-Options',436+ value: 'DENY',437+ },438+ ],439+ 'x-xss-protection': [440+ {441+ key: 'X-XSS-Protection',442+ value: '1; mode=block',443+ },444+ ],445+ 'content-type': [446+ {447+ key: 'Content-Type',448+ value: 'text/html; charset=utf-8',449+ },450+ ],451+ 'content-length': [452+ {453+ key: 'Content-Length',454+ value: '9593',455+ },456+ ],457+ },458+ status: '200',459+ statusDescription: 'OK',460+ },461+ },462+ },463+ ],464+ }465+ const response = await handler(event)466+ expect(response.status).toBe('200')467+ expect(response.body).toBe('Hello Lambda!')468+ if (response.headers && response.headers['content-type']) {469+ expect(response.headers['content-type'][0].value).toMatch(/^text\/plain/)470+ } else {471+ throw new Error("'content-type' header is missing in the response")472+ }473+ })474+475+ it('Should handle a GET request and return a 200 response with binary', async () => {476+ const event = {477+ Records: [478+ {479+ cf: {480+ config: {481+ distributionDomainName: 'example.com',482+ distributionId: 'EXAMPLE123',483+ eventType: 'viewer-request',484+ requestId: 'exampleRequestId',485+ },486+ request: {487+ clientIp: '123.123.123.123',488+ headers: {489+ host: [490+ {491+ key: 'Host',492+ value: 'example.com',493+ },494+ ],495+ },496+ method: 'GET',497+ querystring: '',498+ uri: '/binary',499+ },500+ },501+ },502+ ],503+ }504+505+ const response = await handler(event)506+507+ expect(response.status).toBe('200')508+ expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded fake image509+ if (response.headers && response.headers['content-type']) {510+ expect(response.headers['content-type'][0].value).toMatch(/^image\/png/)511+ } else {512+ throw new Error("'content-type' header is missing in the response")513+ }514+ })515+516+ it('Should handle a GET request and return a 404 response', async () => {517+ const event = {518+ Records: [519+ {520+ cf: {521+ config: {522+ distributionDomainName: 'example.com',523+ distributionId: 'EXAMPLE123',524+ eventType: 'viewer-request',525+ requestId: 'exampleRequestId',526+ },527+ request: {528+ clientIp: '123.123.123.123',529+ headers: {530+ host: [531+ {532+ key: 'Host',533+ value: 'example.com',534+ },535+ ],536+ },537+ method: 'GET',538+ querystring: '',539+ uri: '/nothing',540+ },541+ },542+ },543+ ],544+ }545+546+ const response = await handler(event)547+548+ expect(response.status).toBe('404')549+ })550+551+ it('Should handle a POST request and return a 200 response', async () => {552+ const searchParam = new URLSearchParams()553+ searchParam.append('message', 'Good Morning Lambda!')554+555+ const event = {556+ Records: [557+ {558+ cf: {559+ config: {560+ distributionDomainName: 'example.com',561+ distributionId: 'EXAMPLE123',562+ eventType: 'viewer-request',563+ requestId: 'exampleRequestId',564+ },565+ request: {566+ clientIp: '123.123.123.123',567+ headers: {568+ host: [569+ {570+ key: 'Host',571+ value: 'example.com',572+ },573+ ],574+ 'content-type': [575+ {576+ key: 'Content-Type',577+ value: 'application/x-www-form-urlencoded',578+ },579+ ],580+ },581+ method: 'POST',582+ querystring: '',583+ uri: '/post',584+ body: {585+ inputTruncated: false,586+ action: 'read-only',587+ encoding: 'base64',588+ data: Buffer.from(searchParam.toString()).toString('base64'),589+ },590+ },591+ },592+ },593+ ],594+ }595+596+ const response = await handler(event)597+598+ expect(response.status).toBe('200')599+ expect(response.body).toBe('Good Morning Lambda!')600+ })601+602+ it('Should handle a POST request with binary and return a 200 response', async () => {603+ const array = new Uint8Array([0xc0, 0xff, 0xee])604+ const buffer = Buffer.from(array)605+ const event = {606+ Records: [607+ {608+ cf: {609+ config: {610+ distributionDomainName: 'example.com',611+ distributionId: 'EXAMPLE123',612+ eventType: 'viewer-request',613+ requestId: 'exampleRequestId',614+ },615+ request: {616+ clientIp: '123.123.123.123',617+ headers: {618+ host: [619+ {620+ key: 'Host',621+ value: 'example.com',622+ },623+ ],624+ 'content-type': [625+ {626+ key: 'Content-Type',627+ value: 'application/x-www-form-urlencoded',628+ },629+ ],630+ },631+ method: 'POST',632+ querystring: '',633+ uri: '/post/binary',634+ body: {635+ inputTruncated: false,636+ action: 'read-only',637+ encoding: 'base64',638+ data: buffer.toString('base64'),639+ },640+ },641+ },642+ },643+ ],644+ }645+646+ const response = await handler(event)647+ expect(response.status).toBe('200')648+ expect(response.body).toBe('3 bytes')649+ })650+651+ it('Should handle a request and return a 401 response with Basic auth', async () => {652+ const event = {653+ Records: [654+ {655+ cf: {656+ config: {657+ distributionDomainName: 'example.com',658+ distributionId: 'EXAMPLE123',659+ eventType: 'viewer-request',660+ requestId: 'exampleRequestId',661+ },662+ request: {663+ clientIp: '123.123.123.123',664+ headers: {665+ host: [666+ {667+ key: 'Host',668+ value: 'example.com',669+ },670+ ],671+ 'content-type': [672+ {673+ key: 'Content-Type',674+ value: 'plain/text',675+ },676+ ],677+ },678+ method: 'GET',679+ querystring: '',680+ uri: '/auth/abc',681+ },682+ },683+ },684+ ],685+ }686+687+ const response = await handler(event)688+689+ expect(response.status).toBe('401')690+ })691+692+ it('Should handle a request and return a 401 response with Basic auth', async () => {693+ const event = {694+ Records: [695+ {696+ cf: {697+ config: {698+ distributionDomainName: 'example.com',699+ distributionId: 'EXAMPLE123',700+ eventType: 'viewer-request',701+ requestId: 'exampleRequestId',702+ },703+ request: {704+ clientIp: '123.123.123.123',705+ headers: {706+ host: [707+ {708+ key: 'Host',709+ value: 'example.com',710+ },711+ ],712+ 'content-type': [713+ {714+ key: 'Content-Type',715+ value: 'plain/text',716+ },717+ ],718+ },719+ method: 'GET',720+ querystring: '',721+ uri: '/auth/abc',722+ },723+ },724+ },725+ ],726+ }727+728+ const response = await handler(event)729+730+ expect(response.status).toBe('401')731+ })732+733+ it('Should call a callback to continue processing the request', async () => {734+ const event = {735+ Records: [736+ {737+ cf: {738+ config: {739+ distributionDomainName: 'example.com',740+ distributionId: 'EXAMPLE123',741+ eventType: 'viewer-request',742+ requestId: 'exampleRequestId',743+ },744+ request: {745+ clientIp: '123.123.123.123',746+ headers: {},747+ method: 'GET',748+ querystring: '',749+ uri: '/callback/request',750+ },751+ },752+ },753+ ],754+ }755+756+ let called = false757+ let requestClientIp = ''758+759+ await handler(event, {}, (_err, result) => {760+ if (result && 'clientIp' in result) {761+ requestClientIp = result.clientIp762+ }763+ called = true764+ })765+766+ expect(called).toBe(true)767+ expect(requestClientIp).toBe('123.123.123.123')768+ })769+770+ it('Should call a callback to continue processing the response', async () => {771+ const event = {772+ Records: [773+ {774+ cf: {775+ config: {776+ distributionDomainName: 'example.com',777+ distributionId: 'EDFDVBD6EXAMPLE',778+ eventType: 'viewer-response',779+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',780+ },781+ request: {782+ clientIp: '203.0.113.178',783+ headers: {784+ host: [785+ {786+ key: 'Host',787+ value: 'example.com',788+ },789+ ],790+ 'user-agent': [791+ {792+ key: 'User-Agent',793+ value: 'curl/7.66.0',794+ },795+ ],796+ accept: [797+ {798+ key: 'accept',799+ value: '*/*',800+ },801+ ],802+ },803+ method: 'GET',804+ querystring: '',805+ uri: '/callback/response',806+ },807+ response: {808+ headers: {809+ 'access-control-allow-credentials': [810+ {811+ key: 'Access-Control-Allow-Credentials',812+ value: 'true',813+ },814+ ],815+ 'access-control-allow-origin': [816+ {817+ key: 'Access-Control-Allow-Origin',818+ value: '*',819+ },820+ ],821+ date: [822+ {823+ key: 'Date',824+ value: 'Mon, 13 Jan 2020 20:14:56 GMT',825+ },826+ ],827+ 'referrer-policy': [828+ {829+ key: 'Referrer-Policy',830+ value: 'no-referrer-when-downgrade',831+ },832+ ],833+ server: [834+ {835+ key: 'Server',836+ value: 'ExampleCustomOriginServer',837+ },838+ ],839+ 'x-content-type-options': [840+ {841+ key: 'X-Content-Type-Options',842+ value: 'nosniff',843+ },844+ ],845+ 'x-frame-options': [846+ {847+ key: 'X-Frame-Options',848+ value: 'DENY',849+ },850+ ],851+ 'x-xss-protection': [852+ {853+ key: 'X-XSS-Protection',854+ value: '1; mode=block',855+ },856+ ],857+ age: [858+ {859+ key: 'Age',860+ value: '2402',861+ },862+ ],863+ 'content-type': [864+ {865+ key: 'Content-Type',866+ value: 'text/html; charset=utf-8',867+ },868+ ],869+ 'content-length': [870+ {871+ key: 'Content-Length',872+ value: '9593',873+ },874+ ],875+ },876+ status: '200',877+ statusDescription: 'OK',878+ },879+ },880+ },881+ ],882+ }883+884+ interface CloudFrontHeaders {885+ [name: string]: [886+ {887+ key: string888+ value: string889+ }890+ ]891+ }892+ let called = false893+ let headers: CloudFrontHeaders = {}894+ await handler(event, {}, (_err, result) => {895+ if (result && result.headers) {896+ headers = result.headers as CloudFrontHeaders897+ }898+ called = true899+ })900+901+ expect(called).toBe(true)902+ expect(headers['access-control-allow-credentials']).toEqual([903+ {904+ key: 'Access-Control-Allow-Credentials',905+ value: 'true',906+ },907+ ])908+ expect(headers['access-control-allow-origin']).toEqual([909+ {910+ key: 'Access-Control-Allow-Origin',911+ value: '*',912+ },913+ ])914+ })915+916+ it('Should handle a GET request and add header (Lambda@Edge viewer response)', async () => {917+ const event = {918+ Records: [919+ {920+ cf: {921+ config: {922+ distributionDomainName: 'example.com',923+ distributionId: 'EDFDVBD6EXAMPLE',924+ eventType: 'viewer-response',925+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',926+ },927+ request: {928+ clientIp: '203.0.113.178',929+ headers: {930+ host: [931+ {932+ key: 'Host',933+ value: 'example.com',934+ },935+ ],936+ 'user-agent': [937+ {938+ key: 'User-Agent',939+ value: 'curl/7.66.0',940+ },941+ ],942+ accept: [943+ {944+ key: 'accept',945+ value: '*/*',946+ },947+ ],948+ },949+ method: 'GET',950+ querystring: '',951+ uri: '/header/add',952+ },953+ response: {954+ headers: {955+ 'access-control-allow-credentials': [956+ {957+ key: 'Access-Control-Allow-Credentials',958+ value: 'true',959+ },960+ ],961+ 'access-control-allow-origin': [962+ {963+ key: 'Access-Control-Allow-Origin',964+ value: '*',965+ },966+ ],967+ date: [968+ {969+ key: 'Date',970+ value: 'Mon, 13 Jan 2020 20:14:56 GMT',971+ },972+ ],973+ 'referrer-policy': [974+ {975+ key: 'Referrer-Policy',976+ value: 'no-referrer-when-downgrade',977+ },978+ ],979+ server: [980+ {981+ key: 'Server',982+ value: 'ExampleCustomOriginServer',983+ },984+ ],985+ 'x-content-type-options': [986+ {987+ key: 'X-Content-Type-Options',988+ value: 'nosniff',989+ },990+ ],991+ 'x-frame-options': [992+ {993+ key: 'X-Frame-Options',994+ value: 'DENY',995+ },996+ ],997+ 'x-xss-protection': [998+ {999+ key: 'X-XSS-Protection',1000+ value: '1; mode=block',1001+ },1002+ ],1003+ age: [1004+ {1005+ key: 'Age',1006+ value: '2402',1007+ },1008+ ],1009+ 'content-type': [1010+ {1011+ key: 'Content-Type',1012+ value: 'text/html; charset=utf-8',1013+ },1014+ ],1015+ 'content-length': [1016+ {1017+ key: 'Content-Length',1018+ value: '9593',1019+ },1020+ ],1021+ },1022+ status: '200',1023+ statusDescription: 'OK',1024+ },1025+ },1026+ },1027+ ],1028+ }1029+1030+ interface CloudFrontHeaders {1031+ [name: string]: [1032+ {1033+ key: string1034+ value: string1035+ }1036+ ]1037+ }1038+ let called = false1039+ let headers: CloudFrontHeaders = {}1040+ await handler(event, {}, (_err, result) => {1041+ if (result && result.headers) {1042+ headers = result.headers as CloudFrontHeaders1043+ }1044+ called = true1045+ })1046+1047+ expect(called).toBe(true)1048+ expect(headers['strict-transport-security']).toEqual([1049+ {1050+ key: 'Strict-Transport-Security',1051+ value: 'max-age=63072000; includeSubdomains; preload',1052+ },1053+ ])1054+ expect(headers['x-custom']).toEqual([1055+ {1056+ key: 'X-Custom',1057+ value: 'Foo',1058+ },1059+ ])1060+ })1061+1062+ it('Callback Event (Lambda@Edge response)', async () => {1063+ const event = {1064+ Records: [1065+ {1066+ cf: {1067+ config: {1068+ distributionDomainName: 'example.com',1069+ distributionId: 'EDFDVBD6EXAMPLE',1070+ eventType: 'viewer-response',1071+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',1072+ },1073+ request: {1074+ clientIp: '203.0.113.178',1075+ headers: {1076+ host: [1077+ {1078+ key: 'Host',1079+ value: 'example.com',1080+ },1081+ ],1082+ },1083+ method: 'GET',1084+ querystring: '',1085+ uri: '/config/eventCheck',1086+ },1087+ },1088+ },1089+ ],1090+ }1091+1092+ let called = false1093+ await handler(event, {}, () => {1094+ called = true1095+ })1096+1097+ expect(called).toBe(true)1098+ })1099+1100+ it('Should return a response where bodyEncoding is "base64" with binary', async () => {1101+ const event = {1102+ Records: [1103+ {1104+ cf: {1105+ config: {1106+ distributionDomainName: 'example.com',1107+ distributionId: 'EXAMPLE123',1108+ eventType: 'viewer-request',1109+ requestId: 'exampleRequestId',1110+ },1111+ request: {1112+ clientIp: '123.123.123.123',1113+ headers: {1114+ host: [1115+ {1116+ key: 'Host',1117+ value: 'example.com',1118+ },1119+ ],1120+ },1121+ method: 'GET',1122+ querystring: '',1123+ uri: '/binary',1124+ },1125+ },1126+ },1127+ ],1128+ }1129+1130+ const response = await handler(event)1131+1132+ expect(response.body).toBe('RmFrZSBJbWFnZQ==') // base64 encoded "Fake Image"1133+ expect(response.bodyEncoding).toBe('base64')1134+ })1135+})added:runtime-tests/lambda-edge/vitest.config.ts+18 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+import config from '../../vitest.config'4+5+export default defineConfig({6+ test: {7+ env: {8+ NAME: 'Node',9+ },10+ globals: true,11+ include: ['**/runtime-tests/lambda-edge/**/*.+(ts|tsx|js)'],12+ exclude: ['**/runtime-tests/lambda-edge/vitest.config.ts'],13+ coverage: {14+ ...config.test?.coverage,15+ reportsDirectory: './coverage/raw/runtime-lambda-edge',16+ },17+ },18+})added:runtime-tests/node/index.test.ts+248 added
1+import { createAdaptorServer, serve } from '@hono/node-server'2+import request from 'supertest'3+import type { Server } from 'node:http'4+import type { AddressInfo } from 'node:net'5+import { Hono } from '../../src'6+import { Context } from '../../src/context'7+import { env, getRuntimeKey } from '../../src/helper/adapter'8+import { stream, streamSSE } from '../../src/helper/streaming'9+import { basicAuth } from '../../src/middleware/basic-auth'10+import { compress } from '../../src/middleware/compress'11+import { jwt } from '../../src/middleware/jwt'12+13+// Test only minimal patterns.14+// See <https://github.com/honojs/node-server> for more tests and information.15+16+describe('Basic', () => {17+ const app = new Hono()18+19+ app.get('/', (c) => {20+ return c.text('Hello! Node.js!')21+ })22+ app.get('/runtime-name', (c) => {23+ return c.text(getRuntimeKey())24+ })25+26+ const server = createAdaptorServer(app)27+28+ it('Should return 200 response', async () => {29+ const res = await request(server).get('/')30+ expect(res.status).toBe(200)31+ expect(res.text).toBe('Hello! Node.js!')32+ })33+34+ it('Should return correct runtime name', async () => {35+ const res = await request(server).get('/runtime-name')36+ expect(res.status).toBe(200)37+ expect(res.text).toBe('node')38+ })39+})40+41+describe('Environment Variables', () => {42+ it('Should return the environment variable', async () => {43+ const c = new Context(new Request('http://localhost/'))44+ const { NAME } = env<{ NAME: string }>(c)45+ expect(NAME).toBe('Node')46+ })47+})48+49+describe('Basic Auth Middleware', () => {50+ const app = new Hono()51+52+ const username = 'hono-user-a'53+ const password = 'hono-password-a'54+ app.use(55+ '/auth/*',56+ basicAuth({57+ username,58+ password,59+ })60+ )61+62+ app.get('/auth/*', () => new Response('auth'))63+64+ const server = createAdaptorServer(app)65+66+ it('Should not authorize, return 401 Response', async () => {67+ const res = await request(server).get('/auth/a')68+ expect(res.status).toBe(401)69+ expect(res.text).toBe('Unauthorized')70+ })71+72+ it('Should authorize, return 200 Response', async () => {73+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'74+ const res = await request(server).get('/auth/a').set('Authorization', `Basic ${credential}`)75+ expect(res.status).toBe(200)76+ expect(res.text).toBe('auth')77+ })78+})79+80+describe('JWT Auth Middleware', () => {81+ const app = new Hono()82+83+ app.use('/jwt/*', jwt({ secret: 'a-secret' }))84+ app.get('/jwt/a', (c) => c.text('auth'))85+86+ const server = createAdaptorServer(app)87+88+ it('Should not authorize, return 401 Response', async () => {89+ const res = await request(server).get('/jwt/a')90+ expect(res.status).toBe(401)91+ expect(res.text).toBe('Unauthorized')92+ })93+94+ it('Should authorize, return 200 Response', async () => {95+ const credential =96+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'97+ const res = await request(server).get('/jwt/a').set('Authorization', `Bearer ${credential}`)98+ expect(res.status).toBe(200)99+ expect(res.text).toBe('auth')100+ })101+})102+103+describe('stream', () => {104+ const app = new Hono()105+106+ let aborted = false107+108+ app.get('/stream', (c) => {109+ return stream(c, async (stream) => {110+ stream.onAbort(() => {111+ aborted = true112+ })113+ return new Promise<void>((resolve) => {114+ stream.onAbort(resolve)115+ })116+ })117+ })118+ app.get('/streamHello', (c) => {119+ return stream(c, async (stream) => {120+ stream.onAbort(() => {121+ aborted = true122+ })123+ await stream.write('Hello')124+ })125+ })126+127+ const server = createAdaptorServer(app)128+129+ beforeEach(() => {130+ aborted = false131+ })132+133+ it('Should call onAbort', async () => {134+ const req = request(server)135+ .get('/stream')136+ .end(() => {})137+138+ expect(aborted).toBe(false)139+ await new Promise((resolve) => setTimeout(resolve, 10))140+ req.abort()141+ while (!aborted) {142+ await new Promise((resolve) => setTimeout(resolve))143+ }144+ expect(aborted).toBe(true)145+ })146+147+ it('Should not be called onAbort if already closed', async () => {148+ expect(aborted).toBe(false)149+ const res = await request(server).get('/streamHello')150+ expect(res.status).toBe(200)151+ expect(res.text).toBe('Hello')152+ expect(aborted).toBe(false)153+ })154+})155+156+describe('streamSSE', () => {157+ const app = new Hono()158+159+ let aborted = false160+161+ app.get('/stream', (c) => {162+ return streamSSE(c, async (stream) => {163+ stream.onAbort(() => {164+ aborted = true165+ })166+ return new Promise<void>((resolve) => {167+ stream.onAbort(resolve)168+ })169+ })170+ })171+ app.get('/streamHello', (c) => {172+ return streamSSE(c, async (stream) => {173+ stream.onAbort(() => {174+ aborted = true175+ })176+ await stream.write('Hello')177+ })178+ })179+180+ const server = createAdaptorServer(app)181+182+ beforeEach(() => {183+ aborted = false184+ })185+186+ it('Should call onAbort', async () => {187+ const req = request(server)188+ .get('/stream')189+ .end(() => {})190+191+ expect(aborted).toBe(false)192+ await new Promise((resolve) => setTimeout(resolve, 10))193+ req.abort()194+ while (!aborted) {195+ await new Promise((resolve) => setTimeout(resolve))196+ }197+ expect(aborted).toBe(true)198+ })199+200+ it('Should not be called onAbort if already closed', async () => {201+ expect(aborted).toBe(false)202+ const res = await request(server).get('/streamHello')203+ expect(res.status).toBe(200)204+ expect(res.text).toBe('Hello')205+ expect(aborted).toBe(false)206+ })207+})208+209+describe('compress', async () => {210+ const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n')211+ const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => {212+ const externalApp = new Hono()213+ externalApp.get('/style.css', (c) =>214+ c.text(cssContent, {215+ headers: {216+ 'Content-Type': 'text/css',217+ },218+ })219+ )220+ const server = serve(221+ {222+ fetch: externalApp.fetch,223+ port: 0,224+ },225+ (serverInfo) => {226+ resolve([server as Server, serverInfo])227+ }228+ )229+ })230+231+ const app = new Hono()232+ app.use(compress())233+ app.get('/fetch/:file', (c) => {234+ return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`)235+ })236+ const server = createAdaptorServer(app)237+238+ afterAll(() => {239+ externalServer.close()240+ })241+242+ it('Should be compressed a fetch response', async () => {243+ const res = await request(server).get('/fetch/style.css')244+ expect(res.status).toBe(200)245+ expect(res.headers['content-encoding']).toBe('gzip')246+ expect(res.text).toBe(cssContent)247+ })248+})added:runtime-tests/node/vitest.config.ts+18 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+import config from '../../vitest.config'4+5+export default defineConfig({6+ test: {7+ env: {8+ NAME: 'Node',9+ },10+ globals: true,11+ include: ['**/runtime-tests/node/**/*.+(ts|tsx|js)'],12+ exclude: ['**/runtime-tests/node/vitest.config.ts'],13+ coverage: {14+ ...config.test?.coverage,15+ reportsDirectory: './coverage/raw/runtime-node',16+ },17+ },18+})added:runtime-tests/workerd/index.test.ts+69 added
1+import { unstable_dev } from 'wrangler'2+import type { UnstableDevWorker } from 'wrangler'3+import { WebSocket } from 'ws'4+5+describe('workerd', () => {6+ let worker: UnstableDevWorker7+8+ beforeAll(async () => {9+ worker = await unstable_dev('./runtime-tests/workerd/index.ts', {10+ vars: {11+ NAME: 'Hono',12+ },13+ experimental: { disableExperimentalWarning: true },14+ })15+ })16+17+ afterAll(async () => {18+ await worker.stop()19+ })20+21+ it('Should return 200 response with the runtime key', async () => {22+ const res = await worker.fetch('/')23+ expect(res.status).toBe(200)24+ expect(await res.text()).toBe('Hello from workerd')25+ })26+27+ it('Should return 200 response with the environment variable', async () => {28+ const res = await worker.fetch('/env')29+ expect(res.status).toBe(200)30+ expect(await res.text()).toBe('Hono')31+ })32+})33+34+describe('workerd with WebSocket', () => {35+ // worker.fetch does not support WebSocket:36+ // https://github.com/cloudflare/workers-sdk/issues/4573#issuecomment-185042097337+ it('Should handle the WebSocket connection correctly', async () => {38+ const worker = await unstable_dev('./runtime-tests/workerd/index.ts', {39+ experimental: { disableExperimentalWarning: true },40+ })41+ const ws = new WebSocket(`ws://${worker.address}:${worker.port}/ws`)42+43+ const openHandler = vi.fn()44+ const messageHandler = vi.fn()45+ const closeHandler = vi.fn()46+47+ const waitForOpen = new Promise((resolve) => {48+ ws.addEventListener('open', () => {49+ openHandler()50+ ws.send('Hello')51+ resolve(undefined)52+ })53+ ws.addEventListener('close', async () => {54+ closeHandler()55+ })56+ ws.addEventListener('message', async (event) => {57+ messageHandler(event.data)58+ ws.close()59+ })60+ })61+62+ await waitForOpen63+ await worker.stop()64+65+ expect(openHandler).toHaveBeenCalled()66+ expect(messageHandler).toHaveBeenCalledWith('Hello')67+ expect(closeHandler).toHaveBeenCalled()68+ })69+})added:runtime-tests/workerd/index.ts+25 added
1+import { upgradeWebSocket } from '../../src/adapter/cloudflare-workers'2+import { env, getRuntimeKey } from '../../src/helper/adapter'3+import { Hono } from '../../src/hono'4+5+const app = new Hono()6+7+app.get('/', (c) => c.text(`Hello from ${getRuntimeKey()}`))8+9+app.get('/env', (c) => {10+ const { NAME } = env<{ NAME: string }>(c)11+ return c.text(NAME)12+})13+14+app.get(15+ '/ws',16+ upgradeWebSocket(() => {17+ return {18+ onMessage(event, ws) {19+ ws.send(event.data as string)20+ },21+ }22+ })23+)24+25+export default appadded:runtime-tests/workerd/vitest.config.ts+15 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+import config from '../../vitest.config'4+5+export default defineConfig({6+ test: {7+ globals: true,8+ include: ['**/runtime-tests/workerd/**/(*.)+(test).+(ts|tsx)'],9+ exclude: ['**/runtime-tests/workerd/vitest.config.ts'],10+ coverage: {11+ ...config.test?.coverage,12+ reportsDirectory: './coverage/raw/runtime-workerd',13+ },14+ },15+})added:runtime-tests/tsconfig.json+7 added
1+{2+ "extends": "../tsconfig.json",3+ "include": [4+ "**/*.ts",5+ "**/*.tsx"6+ ]7+}modified:package.json+12 added-12 removed
10 unmodified lines11 ],12 "scripts": {13 "test": "tsc --noEmit && vitest --run && vitest -c .vitest.config/jsx-runtime-default.ts --run && vitest -c .vitest.config/jsx-runtime-dom.ts --run",14 "test:watch": "vitest --watch",15- "test:deno": "deno test --allow-read --allow-env --allow-write --allow-net -c runtime_tests/deno/deno.json runtime_tests/deno && deno test --no-lock -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx && deno test --no-lock -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx",16- "test:bun": "bun test --jsx-import-source ../../src/jsx runtime_tests/bun/index.test.tsx",17- "test:fastly": "vitest --run --config ./runtime_tests/fastly/vitest.config.ts",18- "test:node": "vitest --run --config ./runtime_tests/node/vitest.config.ts",19- "test:workerd": "vitest --run --config ./runtime_tests/workerd/vitest.config.ts",20- "test:lambda": "vitest --run --config ./runtime_tests/lambda/vitest.config.ts",21- "test:lambda-edge": "vitest --run --config ./runtime_tests/lambda-edge/vitest.config.ts",15+ "test:deno": "deno test --allow-read --allow-env --allow-write --allow-net -c runtime-tests/deno/deno.json runtime-tests/deno && deno test --no-lock -c runtime-tests/deno-jsx/deno.precompile.json runtime-tests/deno-jsx && deno test --no-lock -c runtime-tests/deno-jsx/deno.react-jsx.json runtime-tests/deno-jsx",16+ "test:bun": "bun test --jsx-import-source ../../src/jsx runtime-tests/bun/index.test.tsx",17+ "test:fastly": "vitest --run --config ./runtime-tests/fastly/vitest.config.ts",18+ "test:node": "vitest --run --config ./runtime-tests/node/vitest.config.ts",19+ "test:workerd": "vitest --run --config ./runtime-tests/workerd/vitest.config.ts",20+ "test:lambda": "vitest --run --config ./runtime-tests/lambda/vitest.config.ts",21+ "test:lambda-edge": "vitest --run --config ./runtime-tests/lambda-edge/vitest.config.ts",22 "test:all": "bun run test && bun test:deno && bun test:bun && bun test:fastly && bun test:node && bun test:workerd && bun test:lambda && bun test:lambda-edge",23- "lint": "eslint src runtime_tests",24- "lint:fix": "eslint src runtime_tests --fix",25- "format": "prettier --check --cache \"src/**/*.{js,ts,tsx}\" \"runtime_tests/**/*.{js,ts,tsx}\"",26- "format:fix": "prettier --write --cache --cache-strategy metadata \"src/**/*.{js,ts,tsx}\" \"runtime_tests/**/*.{js,ts,tsx}\"",23+ "lint": "eslint src runtime-tests",24+ "lint:fix": "eslint src runtime-tests --fix",25+ "format": "prettier --check --cache \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\"",26+ "format:fix": "prettier --write --cache --cache-strategy metadata \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\"",27 "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json ",28 "build": "bun run --shell bun remove-dist && bun ./build.ts && bun run copy:package.cjs.json",29 "postbuild": "publint",30 "watch": "bun run --shell bun remove-dist && bun ./build.ts --watch && bun run copy:package.cjs.json",615 unmodified lines646 },647 "engines": {648 "node": ">=16.9.0"649 }650-}650+}modified:vitest.config.ts+1 added-1 removed
17 unmodified lines18 reporter: ['json', 'text', 'html'],19 exclude: [20 ...(configDefaults.coverage.exclude ?? []),21 'benchmarks',22- 'runtime_tests',22+ 'runtime-tests',23 'build.ts',24 'src/test-utils',25 26 // types are compile-time only, so their coverage cannot be measured8 unmodified lines