Skip to content

Commit

Permalink
exports each helper and middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed May 12, 2024
1 parent 498c4f2 commit 90892be
Show file tree
Hide file tree
Showing 19 changed files with 193 additions and 120 deletions.
75 changes: 61 additions & 14 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hono/do-not-use-this",
"version": "0.0.3",
"version": "0.0.6",
"compilerOptions": {
"lib": [
"dom",
Expand All @@ -12,10 +12,66 @@
"sloppy-imports"
],
"exports": {
".": "./src/mod.ts",
"./middleware": "./src/middleware.ts",
"./helper": "./src/helper.ts",
"./jsx/jsx-runtime": "./src/jsx/jsx-runtime.ts"
".": "./src/index.ts",
"./types": "./src/types.ts",
"./hono-base": "./src/hono-base.ts",
"./tiny": "./src/preset/tiny.ts",
"./quick": "./src/preset/quick.ts",
"./http-exception": "./src/http-exception.ts",
"./basic-auth": "./src/middleware/basic-auth/index.ts",
"./bearer-auth": "./src/middleware/bearer-auth/index.ts",
"./body-limit": "./src/middleware/body-limit/index.ts",
"./cache": "./src/middleware/cache/index.ts",
"./cookie": "./src/helper/cookie/index.ts",
"./accepts": "./src/helper/accepts/index.ts",
"./compress": "./src/middleware/compress/index.ts",
"./cors": "./src/middleware/cors/index.ts",
"./csrf": "./src/middleware/csrf/index.ts",
"./etag": "./src/middleware/etag/index.ts",
"./trailing-slash": "./src/middleware/trailing-slash/index.ts",
"./html": "./src/helper/html/index.ts",
"./css": "./src/helper/css/index.ts",
"./jsx": "./src/jsx/index.ts",
"./jsx/jsx-dev-runtime": "./src/jsx/jsx-dev-runtime.ts",
"./jsx/jsx-runtime": "./src/jsx/jsx-runtime.ts",
"./jsx/streaming": "./src/jsx/streaming.ts",
"./jsx-renderer": "./src/middleware/jsx-renderer/index.ts",
"./jsx/dom": "./src/jsx/dom/index.ts",
"./jsx/dom/jsx-dev-runtime": "./src/jsx/dom/jsx-dev-runtime.ts",
"./jsx/dom/jsx-runtime": "./src/jsx/dom/jsx-runtime.ts",
"./jsx/dom/css": "./src/jsx/dom/css.ts",
"./jwt": "./src/middleware/jwt/jwt.ts",
"./timing": "./src/middleware/timing/timing.ts",
"./logger": "./src/middleware/logger/index.ts",
"./method-override": "./src/middleware/method-override/index.ts",
"./powered-by": "./src/middleware/powered-by/index.ts",
"./pretty-json": "./src/middleware/pretty-json/index.ts",
"./secure-headers": "./src/middleware/secure-headers/secure-headers.ts",
"./ssg": "./src/helper/ssg/index.ts",
"./streaming": "./src/helper/streaming/index.ts",
"./validator": "./src/validator/index.ts",
"./router": "./src/router.ts",
"./router/reg-exp-router": "./src/router/reg-exp-router/index.ts",
"./router/smart-router": "./src/router/smart-router/index.ts",
"./router/trie-router": "./src/router/trie-router/index.ts",
"./router/pattern-router": "./src/router/pattern-router/index.ts",
"./router/linear-router": "./src/router/linear-router/index.ts",
"./utils/jwt": "./src/utils/jwt/index.ts",
"./client": "./src/client/index.ts",
"./adapter": "./src/helper/adapter/index.ts",
"./factory": "./src/helper/factory/index.ts",
"./serve-static": "./src/middleware/serve-static/index.ts",
"./cloudflare-workers": "./src/adapter/cloudflare-workers/index.ts",
"./cloudflare-pages": "./src/adapter/cloudflare-pages/index.ts",
"./deno": "./src/adapter/deno/index.ts",
"./bun": "./src/adapter/bun/index.ts",
"./aws-lambda": "./src/adapter/aws-lambda/index.ts",
"./vercel": "./src/adapter/vercel/index.ts",
"./netlify": "./src/adapter/netlify/index.ts",
"./lambda-edge": "./src/adapter/lambda-edge/index.ts",
"./testing": "./src/helper/testing/index.ts",
"./dev": "./src/helper/dev/index.ts",
"./ws": "./src/helper/websocket/index.ts"
},
"publish": {
"include": [
Expand All @@ -25,15 +81,6 @@
"src/**/*.ts"
],
"exclude": [
"src/index.ts",
"src/adapter/aws-lambda/**/*.ts",
"src/adapter/bun/**/*.ts",
"src/adapter/cloudflare-pages/**/*.ts",
"src/adapter/cloudflare-workers/**/*.ts",
"src/adapter/lambda-edge/**/*.ts",
"src/adapter/netlify/**/*.ts",
"src/adapter/vercel/**/*.ts",
"src/test-utils/**/*.ts",
"src/**/*.test.ts",
"src/**/*.test.tsx"
]
Expand Down
23 changes: 0 additions & 23 deletions src/adapter/aws-lambda/awslambda.d.ts

This file was deleted.

20 changes: 20 additions & 0 deletions src/adapter/aws-lambda/awslambda.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import type { LambdaContext, Handler } from './types'

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace awslambda {
// Note: Anticipated logic for AWS
// https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/blob/main/src/HttpResponseStream.js
export class HttpResponseStream {
// @ts-expect-error it should throw a type error
static from(
underlyingStream: NodeJS.WritableStream,
prelude: Record<string, unknown>
): NodeJS.WritableStream
}
// @ts-expect-error it should throw a type error
export function streamifyResponse(
f: (event: any, responseStream: NodeJS.WritableStream, context: LambdaContext) => Promise<void>
): Handler
}
33 changes: 16 additions & 17 deletions src/adapter/aws-lambda/handler.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import crypto from 'crypto'
import crypto from 'node:crypto'
import type { Hono } from '../../hono'
import type { Env, Schema } from '../../types'

import { encodeBase64 } from '../../utils/encode'
import { decodeBase64, encodeBase64 } from '../../utils/encode'
import { awslambda } from './awslambda'
import type {
ApiGatewayRequestContext,
ApiGatewayRequestContextV2,
ALBRequestContext,
} from './custom-context'
import type { LambdaContext } from './types'
import type { Handler, LambdaContext } from './types'

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down Expand Up @@ -108,7 +108,7 @@ export const streamHandle = <
BasePath extends string = '/'
>(
app: Hono<E, S, BasePath>
) => {
): Handler => {
return awslambda.streamifyResponse(
async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {
const processor = getProcessor(event)
Expand Down Expand Up @@ -151,11 +151,8 @@ export const streamHandle = <
*/
export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(
app: Hono<E, S, BasePath>
) => {
return async (
event: LambdaEvent,
lambdaContext?: LambdaContext
): Promise<APIGatewayProxyResult> => {
): ((event: LambdaEvent, lambdaContext?: LambdaContext) => Promise<APIGatewayProxyResult>) => {
return async (event, lambdaContext?) => {
const processor = getProcessor(event)

const req = processor.createRequest(event)
Expand Down Expand Up @@ -218,7 +215,7 @@ abstract class EventProcessor<E extends LambdaEvent> {
}

if (event.body) {
requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body
requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body
}

return new Request(url, requestInit)
Expand Down Expand Up @@ -261,7 +258,7 @@ abstract class EventProcessor<E extends LambdaEvent> {
}
}

const v2Processor = new (class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {
class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {
protected getPath(event: APIGatewayProxyEventV2): string {
return event.rawPath
}
Expand All @@ -283,11 +280,11 @@ const v2Processor = new (class EventV2Processor extends EventProcessor<APIGatewa
protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {
result.cookies = cookies
}
})()
}

const v1Processor = new (class EventV1Processor extends EventProcessor<
Exclude<LambdaEvent, APIGatewayProxyEventV2>
> {
const v2Processor: EventV2Processor = new EventV2Processor()

class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {
protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {
return event.path
}
Expand Down Expand Up @@ -317,7 +314,9 @@ const v1Processor = new (class EventV1Processor extends EventProcessor<
'set-cookie': cookies,
}
}
})()
}

const v1Processor: EventV1Processor = new EventV1Processor()

export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {
if (isProxyEventV2(event)) {
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/bun/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ interface BunServer {
interface BunWebSocketHandler<T> {
open(ws: BunServerWebSocket<T>): void
close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void
message(ws: BunServerWebSocket<T>, message: string | Buffer): void
message(ws: BunServerWebSocket<T>, message: string | Uint8Array): void
}
interface CreateWebSocket {
(): {
Expand Down
6 changes: 4 additions & 2 deletions src/adapter/cloudflare-workers/serve-static-module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// For ES module mode
import type { Env } from '../../types'
import type { Env, MiddlewareHandler } from '../../types'
import type { ServeStaticOptions } from './serve-static'
import { serveStatic } from './serve-static'

const module = <E extends Env = Env>(options: Omit<ServeStaticOptions<E>, 'namespace'>) => {
const module = <E extends Env = Env>(
options: Omit<ServeStaticOptions<E>, 'namespace'>
): MiddlewareHandler => {
return serveStatic<E>(options)
}

Expand Down
10 changes: 5 additions & 5 deletions src/adapter/cloudflare-workers/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,31 +37,31 @@ export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, ne
if (events.onOpen) {
server.addEventListener(
'open',
(evt) => events.onOpen && events.onOpen(evt as Event, wsContext)
(evt: unknown) => events.onOpen && events.onOpen(evt as Event, wsContext)
)
}
if (events.onClose) {
server.addEventListener(
'close',
(evt) => events.onClose && events.onClose(evt as CloseEvent, wsContext)
(evt: unknown) => events.onClose && events.onClose(evt as CloseEvent, wsContext)
)
}
if (events.onMessage) {
server.addEventListener(
'message',
(evt) => events.onMessage && events.onMessage(evt as MessageEvent, wsContext)
(evt: unknown) => events.onMessage && events.onMessage(evt as MessageEvent, wsContext)
)
}
if (events.onError) {
server.addEventListener(
'error',
(evt) => events.onError && events.onError(evt as ErrorEvent as Event, wsContext)
(evt: unknown) => events.onError && events.onError(evt as ErrorEvent as Event, wsContext)
)
}
server.accept()
return new Response(null, {
status: 101,
// @ts-expect-error Cloudflare Workers API
// @ts-ignore
webSocket: client,
})
}
6 changes: 4 additions & 2 deletions src/adapter/lambda-edge/handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { encodeBase64 } from '../../utils/encode'
import { createBody, isContentTypeBinary } from './handler'

describe('isContentTypeBinary', () => {
Expand All @@ -18,10 +19,11 @@ describe('isContentTypeBinary', () => {

describe('createBody', () => {
it('Should the request be a GET or HEAD, the Request must not include a Body', () => {
const data = Buffer.from('test')
const encoder = new TextEncoder()
const data = encoder.encode('test')
const body = {
action: 'read-only',
data: data.toString('base64'),
data: encodeBase64(data),
encoding: 'base64',
inputTruncated: false,
}
Expand Down
31 changes: 18 additions & 13 deletions src/adapter/lambda-edge/handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import crypto from 'crypto'
import crypto from 'node:crypto'
import type { Hono } from '../../hono'

import { encodeBase64 } from '../../utils/encode'
import { decodeBase64, encodeBase64 } from '../../utils/encode'

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down Expand Up @@ -110,13 +110,15 @@ const convertHeaders = (headers: Headers): CloudFrontHeaders => {
return cfHeaders
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const handle = (app: Hono<any>) => {
return async (
event: CloudFrontEdgeEvent,
context?: CloudFrontContext,
callback?: Callback
): Promise<CloudFrontResult> => {
export const handle = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app: Hono<any>
): ((
event: CloudFrontEdgeEvent,
context?: CloudFrontContext,
callback?: Callback
) => Promise<CloudFrontResult>) => {
return async (event, context?, callback?) => {
const res = await app.fetch(createRequest(event), {
event,
context,
Expand All @@ -143,7 +145,7 @@ const createResult = async (res: Response): Promise<CloudFrontResult> => {
}
}

const createRequest = (event: CloudFrontEdgeEvent) => {
const createRequest = (event: CloudFrontEdgeEvent): Request => {
const queryString = event.Records[0].cf.request.querystring
const urlPath = `https://${event.Records[0].cf.config.distributionDomainName}${event.Records[0].cf.request.uri}`
const url = queryString ? `${urlPath}?${queryString}` : urlPath
Expand All @@ -164,20 +166,23 @@ const createRequest = (event: CloudFrontEdgeEvent) => {
})
}

export const createBody = (method: string, requestBody: CloudFrontRequest['body']) => {
export const createBody = (
method: string,
requestBody: CloudFrontRequest['body']
): string | Uint8Array | undefined => {
if (!requestBody || !requestBody.data) {
return undefined
}
if (method === 'GET' || method === 'HEAD') {
return undefined
}
if (requestBody.encoding === 'base64') {
return Buffer.from(requestBody.data, 'base64')
return decodeBase64(requestBody.data)
}
return requestBody.data
}

export const isContentTypeBinary = (contentType: string) => {
export const isContentTypeBinary = (contentType: string): boolean => {
return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(
contentType
)
Expand Down
17 changes: 5 additions & 12 deletions src/adapter/netlify/handler.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import type { Context } from 'https://edge.netlify.com/'
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Hono } from '../../hono'

export type Env = {
Bindings: {
context: Context
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const handle = (app: Hono<any, any>) => {
return (req: Request, context: Context) => {
export const handle = (
app: Hono<any, any>
): ((req: Request, context: any) => Response | Promise<Response>) => {
return (req: Request, context: any) => {
return app.fetch(req, { context })
}
}
Loading

0 comments on commit 90892be

Please sign in to comment.