Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next #3394

Merged
merged 13 commits into from
Sep 11, 2024
Merged

Next #3394

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jsr.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"./cookie": "./src/helper/cookie/index.ts",
"./accepts": "./src/helper/accepts/index.ts",
"./compress": "./src/middleware/compress/index.ts",
"./context-storage": "./src/middleware/context-storage/index.ts",
"./cors": "./src/middleware/cors/index.ts",
"./csrf": "./src/middleware/csrf/index.ts",
"./etag": "./src/middleware/etag/index.ts",
Expand Down
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@
"import": "./dist/middleware/compress/index.js",
"require": "./dist/cjs/middleware/compress/index.js"
},
"./context-storage": {
"types": "./dist/types/middleware/context-storage/index.d.ts",
"import": "./dist/middleware/context-storage/index.js",
"require": "./dist/cjs/middleware/context-storage/index.js"
},
"./cors": {
"types": "./dist/types/middleware/cors/index.d.ts",
"import": "./dist/middleware/cors/index.js",
Expand Down Expand Up @@ -421,6 +426,9 @@
"compress": [
"./dist/types/middleware/compress"
],
"context-storage": [
"./dist/types/middleware/context-storage"
],
"cors": [
"./dist/types/middleware/cors"
],
Expand Down
49 changes: 46 additions & 3 deletions runtime_tests/node/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { createAdaptorServer } from '@hono/node-server'
import type { Server } from 'node:http'
import { createAdaptorServer, serve } from '@hono/node-server'
import request from 'supertest'
import { Hono } from '../../src'
import { Context } from '../../src/context'
import { env, getRuntimeKey } from '../../src/helper/adapter'
import { basicAuth } from '../../src/middleware/basic-auth'
import { jwt } from '../../src/middleware/jwt'
import { HonoRequest } from '../../src/request'
import { compress } from '../../src/middleware/compress'
import { stream, streamSSE } from '../../src/helper/streaming'
import type { AddressInfo } from 'node:net'

// Test only minimal patterns.
// See <https://github.com/honojs/node-server> for more tests and information.
Expand Down Expand Up @@ -38,7 +40,7 @@ describe('Basic', () => {

describe('Environment Variables', () => {
it('Should return the environment variable', async () => {
const c = new Context(new HonoRequest(new Request('http://localhost/')))
const c = new Context(new Request('http://localhost/'))
const { NAME } = env<{ NAME: string }>(c)
expect(NAME).toBe('Node')
})
Expand Down Expand Up @@ -203,3 +205,44 @@ describe('streamSSE', () => {
expect(aborted).toBe(false)
})
})

describe('compress', async () => {
const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n')
const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => {
const externalApp = new Hono()
externalApp.get('/style.css', (c) =>
c.text(cssContent, {
headers: {
'Content-Type': 'text/css',
},
})
)
const server = serve(
{
fetch: externalApp.fetch,
port: 0,
},
(serverInfo) => {
resolve([server as Server, serverInfo])
}
)
})

const app = new Hono()
app.use(compress())
app.get('/fetch/:file', (c) => {
return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`)
})
const server = createAdaptorServer(app)

afterAll(() => {
externalServer.close()
})

it('Should be compressed a fetch response', async () => {
const res = await request(server).get('/fetch/style.css')
expect(res.status).toBe(200)
expect(res.headers['content-encoding']).toBe('gzip')
expect(res.text).toBe(cssContent)
})
})
13 changes: 6 additions & 7 deletions src/adapter/bun/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@ interface BunWebSocketHandler<T> {
close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void
message(ws: BunServerWebSocket<T>, message: string | Uint8Array): void
}
interface CreateWebSocket {
(): {
upgradeWebSocket: UpgradeWebSocket
websocket: BunWebSocketHandler<BunWebSocketData>
}
interface CreateWebSocket<T> {
upgradeWebSocket: UpgradeWebSocket<T>
websocket: BunWebSocketHandler<BunWebSocketData>
}
export interface BunWebSocketData {
connId: number
Expand All @@ -49,10 +47,11 @@ const createWSContext = (ws: BunServerWebSocket<BunWebSocketData>): WSContext =>
}
}

export const createBunWebSocket: CreateWebSocket = () => {
export const createBunWebSocket = <T>(): CreateWebSocket<T> => {
const websocketConns: WSEvents[] = []

const upgradeWebSocket: UpgradeWebSocket = (createEvents) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const upgradeWebSocket: UpgradeWebSocket<any> = (createEvents) => {
return async (c, next) => {
const server = getBunServer(c)
if (!server) {
Expand Down
12 changes: 12 additions & 0 deletions src/adapter/cloudflare-pages/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,18 @@ describe('Middleware adapter for Cloudflare Pages', () => {
await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')
expect(next).not.toHaveBeenCalled()
})

it('Should set the data in eventContext.data', async () => {
const next = vi.fn()
const eventContext = createEventContext({ next })
const handler = handleMiddleware(async (c, next) => {
c.env.eventContext.data.user = 'Joe'
await next()
})
expect(eventContext.data.user).toBeUndefined()
await handler(eventContext)
expect(eventContext.data.user).toBe('Joe')
})
})

describe('serveStatic()', () => {
Expand Down
16 changes: 12 additions & 4 deletions src/adapter/cloudflare-pages/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { BlankSchema, Env, Input, MiddlewareHandler, Schema } from '../../t
type Params<P extends string = any> = Record<P, string | string[]>

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EventContext<Env = {}, P extends string = any, Data = {}> = {
export type EventContext<Env = {}, P extends string = any, Data = Record<string, unknown>> = {
request: Request
functionPath: string
waitUntil: (promise: Promise<unknown>) => void
Expand Down Expand Up @@ -43,12 +43,20 @@ export const handle =
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function handleMiddleware<E extends Env = any, P extends string = any, I extends Input = {}>(
middleware: MiddlewareHandler<E, P, I>
export function handleMiddleware<E extends Env = {}, P extends string = any, I extends Input = {}>(
middleware: MiddlewareHandler<
E & {
Bindings: {
eventContext: EventContext
}
},
P,
I
>
): PagesFunction<E['Bindings']> {
return async (executionCtx) => {
const context = new Context(executionCtx.request, {
env: executionCtx.env,
env: { ...executionCtx.env, eventContext: executionCtx },
executionCtx,
})

Expand Down
4 changes: 2 additions & 2 deletions src/adapter/cloudflare-workers/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'

// Based on https://github.com/honojs/hono/issues/1153#issuecomment-1767321332
export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {
export const upgradeWebSocket: UpgradeWebSocket<WebSocket> = (createEvents) => async (c, next) => {
const events = await createEvents(c)

const upgradeHeader = c.req.header('Upgrade')
Expand All @@ -14,7 +14,7 @@ export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, ne
const client: WebSocket = webSocketPair[0]
const server: WebSocket = webSocketPair[1]

const wsContext: WSContext = {
const wsContext: WSContext<WebSocket> = {
binaryType: 'arraybuffer',
close: (code, reason) => server.close(code, reason),
get protocol() {
Expand Down
4 changes: 2 additions & 2 deletions src/adapter/deno/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface UpgradeWebSocketOptions {
idleTimeout?: number
}

export const upgradeWebSocket: UpgradeWebSocket<UpgradeWebSocketOptions> =
export const upgradeWebSocket: UpgradeWebSocket<WebSocket, UpgradeWebSocketOptions> =
(createEvents, options) => async (c, next) => {
if (c.req.header('upgrade') !== 'websocket') {
return await next()
Expand All @@ -29,7 +29,7 @@ export const upgradeWebSocket: UpgradeWebSocket<UpgradeWebSocketOptions> =
const events = await createEvents(c)
const { response, socket } = Deno.upgradeWebSocket(c.req.raw, options || {})

const wsContext: WSContext = {
const wsContext: WSContext<WebSocket> = {
binaryType: 'arraybuffer',
close: (code, reason) => socket.close(code, reason),
get protocol() {
Expand Down
45 changes: 45 additions & 0 deletions src/context.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
import { Context } from './context'
import { setCookie } from './helper/cookie'

const makeResponseHeaderImmutable = (res: Response) => {
Object.defineProperty(res, 'headers', {
value: new Proxy(res.headers, {
set(target, prop, value) {
if (prop === 'set') {
throw new TypeError('Cannot modify headers: Headers are immutable')
}
return Reflect.set(target, prop, value)
},
get(target, prop) {
if (prop === 'set') {
return function () {
throw new TypeError('Cannot modify headers: Headers are immutable')
}
}
return Reflect.get(target, prop)
},
}),
writable: false,
})
return res
}

describe('Context', () => {
const req = new Request('http://localhost/')

Expand Down Expand Up @@ -360,6 +383,28 @@ describe('Context header', () => {
const res = c.text('Hi')
expect(res.headers.get('set-cookie')).toBe('a, b, c')
})

it('Should be able to overwrite a fetch response with a new response.', async () => {
c.res = makeResponseHeaderImmutable(new Response('bar'))
c.res = new Response('foo', {
headers: {
'X-Custom': 'Message',
},
})
expect(c.res.text()).resolves.toBe('foo')
expect(c.res.headers.get('X-Custom')).toBe('Message')
})

it('Should be able to overwrite a response with a fetch response.', async () => {
c.res = new Response('foo', {
headers: {
'X-Custom': 'Message',
},
})
c.res = makeResponseHeaderImmutable(new Response('bar'))
expect(c.res.text()).resolves.toBe('bar')
expect(c.res.headers.get('X-Custom')).toBe('Message')
})
})

describe('Pass a ResponseInit to respond methods', () => {
Expand Down
48 changes: 28 additions & 20 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,16 +465,31 @@ export class Context<
set res(_res: Response | undefined) {
this.#isFresh = false
if (this.#res && _res) {
this.#res.headers.delete('content-type')
for (const [k, v] of this.#res.headers.entries()) {
if (k === 'set-cookie') {
const cookies = this.#res.headers.getSetCookie()
_res.headers.delete('set-cookie')
for (const cookie of cookies) {
_res.headers.append('set-cookie', cookie)
try {
for (const [k, v] of this.#res.headers.entries()) {
if (k === 'content-type') {
continue
}
if (k === 'set-cookie') {
const cookies = this.#res.headers.getSetCookie()
_res.headers.delete('set-cookie')
for (const cookie of cookies) {
_res.headers.append('set-cookie', cookie)
}
} else {
_res.headers.set(k, v)
}
}
} catch (e) {
if (e instanceof TypeError && e.message.includes('immutable')) {
// `_res` is immutable (probably a response from a fetch API), so retry with a new response.
this.res = new Response(_res.body, {
headers: _res.headers,
status: _res.status,
})
return
} else {
_res.headers.set(k, v)
throw e
}
}
}
Expand Down Expand Up @@ -844,18 +859,11 @@ export class Context<
this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'

if (typeof html === 'object') {
if (!(html instanceof Promise)) {
html = (html as string).toString() // HtmlEscapedString object to string
}
if ((html as string | Promise<string>) instanceof Promise) {
return (html as unknown as Promise<string>)
.then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))
.then((html) => {
return typeof arg === 'number'
? this.newResponse(html, arg, headers)
: this.newResponse(html, arg)
})
}
return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html) => {
return typeof arg === 'number'
? this.newResponse(html, arg, headers)
: this.newResponse(html, arg)
})
}

return typeof arg === 'number'
Expand Down
Loading
Loading