Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/eleven-corners-smash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/node-ws': minor
---

load custom env when init
28 changes: 26 additions & 2 deletions packages/node-ws/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import type { ServerType } from '@hono/node-server/dist/types'
import { Hono } from 'hono'
import { Env, Hono, Context } from 'hono'

Check failure on line 5 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

Imports "Env" and "Context" are only used as type
import { cors } from 'hono/cors'
import { HTTPException } from 'hono/http-exception'
import type { WSMessageReceive } from 'hono/ws'
import { WebSocket } from 'ws'
import { createNodeWebSocket } from '.'

Check failure on line 10 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

`.` import should occur after type import of `node:http2`
import type { IncomingMessage } from 'node:http'
import type { Http2ServerRequest } from 'node:http2'

interface CustomEnv extends Env {
Bindings: {
customVar: string
}
}

describe('WebSocket helper', () => {
let app: Hono
Expand All @@ -18,15 +26,18 @@

beforeEach(async () => {
app = new Hono()
;({ injectWebSocket, upgradeWebSocket, wss } = createNodeWebSocket({ app }))
const getEnv = (req: IncomingMessage | Http2ServerRequest) => {
return { customVar: req.headers.upgrade }
}
;({ injectWebSocket, upgradeWebSocket, wss } = createNodeWebSocket({ app, getEnv }))

server = await new Promise<ServerType>((resolve) => {
const server = serve({ fetch: app.fetch, port: 3030 }, () => {
resolve(server)
})
})
injectWebSocket(server)

Check failure on line 39 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type error typed assigned to a parameter of type `Server<typeof IncomingMessage, typeof ServerResponse> | Http2Server<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse> | Http2SecureServer<...>`
})

Check failure on line 40 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type error typed assigned to a parameter of type `Server<typeof IncomingMessage, typeof ServerResponse> | Http2Server<typeof IncomingMessage, typeof ServerResponse, typeof Http2ServerRequest, typeof Http2ServerResponse> | Http2SecureServer<...>`

afterEach(() => {
server.close()
Expand Down Expand Up @@ -329,4 +340,17 @@
})
)
})

it('Should server can obtain environment variables', async () => {
const mainPromise = new Promise<string>((resolve) =>
app.get('/', (c: Context<CustomEnv>, next) => {
let ws = upgradeWebSocket((_c) => ({}))

Check warning on line 347 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

'_c' is defined but never used

Check warning on line 347 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

'ws' is never reassigned. Use 'const' instead
resolve(c.env.customVar)
return ws(c, next)

Check failure on line 349 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `Context<CustomEnv, any, {}>` assigned to a parameter of type `Context<any, string, { outputFormat: "ws"; }>`
})

Check failure on line 350 in packages/node-ws/src/index.test.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `Context<CustomEnv, any, {}>` assigned to a parameter of type `Context<any, string, { outputFormat: "ws"; }>`
)

new WebSocket('ws://localhost:3030/')
expect(await mainPromise).toBe('websocket')
})
})
7 changes: 5 additions & 2 deletions packages/node-ws/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { Hono } from 'hono'
import type { Hono, Env } from 'hono'
import { defineWebSocketHelper } from 'hono/ws'
import type { UpgradeWebSocket, WSContext } from 'hono/ws'
import type { WebSocket } from 'ws'
import { WebSocketServer } from 'ws'
import { STATUS_CODES } from 'node:http'
import type { IncomingMessage, Server } from 'node:http'
import type { Http2SecureServer, Http2Server } from 'node:http2'
import type { Http2SecureServer, Http2Server, Http2ServerRequest } from 'node:http2'
import type { Duplex } from 'node:stream'
import { CloseEvent } from './events'

Expand All @@ -23,6 +23,7 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app: Hono<any, any, any>
baseUrl?: string | URL
getEnv?: (request: IncomingMessage | Http2ServerRequest) => Env['Bindings']
}

const generateConnectionSymbol = () => Symbol('connection')
Expand Down Expand Up @@ -60,26 +61,28 @@
wss,
injectWebSocket(server) {
server.on('upgrade', async (request, socket: Duplex, head) => {
const url = new URL(request.url ?? '/', init.baseUrl ?? 'http://localhost')

Check failure on line 64 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `string | URL`

Check failure on line 64 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `string | URL`
const headers = new Headers()
for (const key in request.headers) {
const value = request.headers[key]
if (!value) {
continue
}
headers.append(key, Array.isArray(value) ? value[0] : value)

Check failure on line 71 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `string`

Check failure on line 71 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `string`
}

const customEnv = init.getEnv?.(request) ?? {}

Check failure on line 74 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage | Http2ServerRequest`

Check failure on line 74 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage | Http2ServerRequest`
const env: {
incoming: IncomingMessage
outgoing: undefined
[CONNECTION_SYMBOL_KEY]?: symbol
} = {
...customEnv,
incoming: request,
outgoing: undefined,
}
const response = await init.app.request(url, { headers: headers }, env)
const waiter = waiterMap.get(request)

Check failure on line 85 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`

Check failure on line 85 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`

if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
socket.end(
Expand All @@ -88,11 +91,11 @@
'Content-Length: 0\r\n' +
'\r\n'
)
waiterMap.delete(request)

Check failure on line 94 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`

Check failure on line 94 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`
return
}

wss.handleUpgrade(request, socket, head, (ws) => {

Check failure on line 98 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`

Check failure on line 98 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `Buffer<ArrayBufferLike>`

Check failure on line 98 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`
wss.emit('connection', ws, request)
})
})
Expand All @@ -106,7 +109,7 @@
const connectionSymbol = generateConnectionSymbol()
c.env[CONNECTION_SYMBOL_KEY] = connectionSymbol
;(async () => {
const ws = await nodeUpgradeWebSocket(c.env.incoming, connectionSymbol)

Check failure on line 112 in packages/node-ws/src/index.ts

View workflow job for this annotation

GitHub Actions / autofix

Unsafe argument of type `any` assigned to a parameter of type `IncomingMessage`

// buffer messages to handle messages received before the events are set up
const messagesReceivedInStarting: [data: WebSocket.RawData, isBinary: boolean][] = []
Expand Down
Loading