Skip to content

Commit

Permalink
Merge branch 'main' into v4
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Jan 29, 2024
2 parents 5c3a1bf + f616ed9 commit b24f9e3
Show file tree
Hide file tree
Showing 44 changed files with 293 additions and 94 deletions.
2 changes: 2 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ RUN curl -fsSL https://gist.githubusercontent.com/LukeChannings/09d53f5c36439104
# Install Bun
ENV BUN_INSTALL=/usr/local
RUN curl -fsSL https://bun.sh/install | bash

WORKDIR /hono
18 changes: 18 additions & 0 deletions .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
version: '3'

services:
hono:
build: .
container_name: hono
volumes:
- ../:/hono
networks:
- hono
command: bash
stdin_open: true
tty: true
restart: 'no'

networks:
hono:
driver: bridge
Binary file modified bun.lockb
Binary file not shown.
4 changes: 3 additions & 1 deletion deno_dist/adapter/deno/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ export const serveStatic = <E extends Env = Env>(
defaultDocument: DEFAULT_DOCUMENT,
})

if (!path) return await next()
if (!path) {
return await next()
}

path = `./${path}`

Expand Down
8 changes: 6 additions & 2 deletions deno_dist/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './util
const createProxy = (callback: Callback, path: string[]) => {
const proxy: unknown = new Proxy(() => {}, {
get(_obj, key) {
if (typeof key !== 'string' || key === 'then') return undefined
if (typeof key !== 'string' || key === 'then') {
return undefined
}
return createProxy(callback, [...path, key])
},
apply(_1, _2, args) {
Expand Down Expand Up @@ -91,7 +93,9 @@ class ClientRequestImpl {
headerValues['Cookie'] = cookies.join(',')
}

if (this.cType) headerValues['Content-Type'] = this.cType
if (this.cType) {
headerValues['Content-Type'] = this.cType
}

const headers = new Headers(headerValues ?? undefined)
let url = this.url
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/helper/accepts/accepts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {
*/
export const accepts = (c: Context, options: acceptsOptions) => {
const acceptHeader = c.req.header(options.header)
if (!acceptHeader) return options.default
if (!acceptHeader) {
return options.default
}
const accepts = parseAccept(acceptHeader)
const match = options.match || defaultMatch

Expand Down
24 changes: 18 additions & 6 deletions deno_dist/helper/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,24 @@ export const getRuntimeKey = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any

if (global?.Deno !== undefined) return 'deno'
if (global?.Bun !== undefined) return 'bun'
if (typeof global?.WebSocketPair === 'function') return 'workerd'
if (typeof global?.EdgeRuntime === 'string') return 'edge-light'
if (global?.fastly !== undefined) return 'fastly'
if (global?.process?.release?.name === 'node') return 'node'
if (global?.Deno !== undefined) {
return 'deno'
}
if (global?.Bun !== undefined) {
return 'bun'
}
if (typeof global?.WebSocketPair === 'function') {
return 'workerd'
}
if (typeof global?.EdgeRuntime === 'string') {
return 'edge-light'
}
if (global?.fastly !== undefined) {
return 'fastly'
}
if (global?.process?.release?.name === 'node') {
return 'node'
}

return 'other'
}
16 changes: 12 additions & 4 deletions deno_dist/helper/cookie/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ interface GetSignedCookie {
export const getCookie: GetCookie = (c, key?) => {
const cookie = c.req.raw.headers.get('Cookie')
if (typeof key === 'string') {
if (!cookie) return undefined
if (!cookie) {
return undefined
}
const obj = parse(cookie, key)
return obj[key]
}
if (!cookie) return {}
if (!cookie) {
return {}
}
const obj = parse(cookie)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return obj as any
Expand All @@ -28,11 +32,15 @@ export const getCookie: GetCookie = (c, key?) => {
export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {
const cookie = c.req.raw.headers.get('Cookie')
if (typeof key === 'string') {
if (!cookie) return undefined
if (!cookie) {
return undefined
}
const obj = await parseSigned(cookie, secret, key)
return obj[key]
}
if (!cookie) return {}
if (!cookie) {
return {}
}
const obj = await parseSigned(cookie, secret)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return obj as any
Expand Down
16 changes: 12 additions & 4 deletions deno_dist/helper/ssg/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,21 +120,27 @@ export const fetchRoutesContent = async <
const baseURL = 'http://localhost'

for (const route of inspectRoutes(app)) {
if (route.isMiddleware) continue
if (route.isMiddleware) {
continue
}

// GET Route Info
const thisRouteBaseURL = new URL(route.path, baseURL).toString()

let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest
if (beforeRequestHook) {
const maybeRequest = beforeRequestHook(forGetInfoURLRequest)
if (!maybeRequest) continue
if (!maybeRequest) {
continue
}
forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest
}
await app.fetch(forGetInfoURLRequest)

if (!forGetInfoURLRequest.ssgParams) {
if (isDynamicRoute(route.path)) continue
if (isDynamicRoute(route.path)) {
continue
}
forGetInfoURLRequest.ssgParams = [{}]
}

Expand All @@ -143,7 +149,9 @@ export const fetchRoutesContent = async <
let response = await app.request(replacedUrlParam, forGetInfoURLRequest)
if (afterResponseHook) {
const maybeResponse = afterResponseHook(response)
if (!maybeResponse) continue
if (!maybeResponse) {
continue
}
response = maybeResponse
}
const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'
Expand Down
20 changes: 15 additions & 5 deletions deno_dist/hono-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ class Hono<

// Implementation of app.on(method, path, ...handlers[])
this.on = (method: string | string[], path: string | string[], ...handlers: H[]) => {
if (!method) return this
if (!method) {
return this
}
for (const p of [path].flat()) {
this.#path = p
for (const m of [method].flat()) {
Expand Down Expand Up @@ -188,7 +190,9 @@ class Hono<
): Hono<E, MergeSchemaPath<SubSchema, MergePath<BasePath, SubPath>> & S, BasePath> {
const subApp = this.basePath(path)

if (!app) return subApp
if (!app) {
return subApp
}

app.routes.map((r) => {
let handler
Expand Down Expand Up @@ -274,7 +278,9 @@ class Hono<
...optionsArray
)

if (res) return res
if (res) {
return res
}

await next()
}
Expand All @@ -295,7 +301,9 @@ class Hono<
}

private handleError(err: unknown, c: Context<E>) {
if (err instanceof Error) return this.errorHandler(err, c)
if (err instanceof Error) {
return this.errorHandler(err, c)
}
throw err
}

Expand Down Expand Up @@ -325,7 +333,9 @@ class Hono<
let res: ReturnType<H>
try {
res = matchResult[0][0][0][0](c, async () => {})
if (!res) return this.notFoundHandler(c)
if (!res) {
return this.notFoundHandler(c)
}
} catch (err) {
return this.handleError(err, c)
}
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/middleware/jsx-renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export const jsxRenderer = (
): MiddlewareHandler =>
function jsxRenderer(c, next) {
const parentLayout = c.getLayout()
if (!parentLayout && component) c.setLayout(component)
if (!parentLayout && component) {
c.setLayout(component)
}

/* eslint-disable @typescript-eslint/no-explicit-any */
c.setRenderer(createRenderer(c, component, options) as any)
Expand Down
12 changes: 9 additions & 3 deletions deno_dist/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {
header(name: string): string | undefined
header(): Record<string, string>
header(name?: string) {
if (name) return this.raw.headers.get(name.toLowerCase()) ?? undefined
if (name) {
return this.raw.headers.get(name.toLowerCase()) ?? undefined
}

const headerData: Record<string, string | undefined> = {}
this.raw.headers.forEach((value, key) => {
Expand All @@ -181,7 +183,9 @@ export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {
* @see https://hono.dev/api/request#parsebody
*/
async parseBody<T extends BodyData = BodyData>(options?: ParseBodyOptions): Promise<T> {
if (this.bodyCache.parsedBody) return this.bodyCache.parsedBody as T
if (this.bodyCache.parsedBody) {
return this.bodyCache.parsedBody as T
}
const parsedBody = await parseBody<T>(this, options)
this.bodyCache.parsedBody = parsedBody
return parsedBody
Expand All @@ -190,7 +194,9 @@ export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {
private cachedBody = (key: keyof Body) => {
const { bodyCache, raw } = this
const cachedBody = bodyCache[key]
if (cachedBody) return cachedBody
if (cachedBody) {
return cachedBody
}
/**
* If an arrayBuffer cache is exist,
* use it for creating a text, json, and others.
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/router/reg-exp-router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ export class RegExpRouter<T> implements Router<T> {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)
}

if (methodNames.indexOf(method) === -1) methodNames.push(method)
if (methodNames.indexOf(method) === -1) {
methodNames.push(method)
}
if (!middleware[method]) {
;[middleware, routes].forEach((handlerMap) => {
handlerMap[method] = {}
Expand Down
8 changes: 6 additions & 2 deletions deno_dist/router/trie-router/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ export class Node<T> {
parentPatterns.push(...curNode.patterns)
curNode = curNode.children[p]
const pattern = getPattern(p)
if (pattern) possibleKeys.push(pattern[1])
if (pattern) {
possibleKeys.push(pattern[1])
}
continue
}

Expand Down Expand Up @@ -160,7 +162,9 @@ export class Node<T> {
continue
}

if (part === '') continue
if (part === '') {
continue
}

const [key, name, matcher] = pattern

Expand Down
25 changes: 18 additions & 7 deletions deno_dist/utils/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ const verifySignature = async (
try {
const signatureBinStr = atob(base64Signature)
const signature = new Uint8Array(signatureBinStr.length)
for (let i = 0, len = signatureBinStr.length; i < len; i++)
for (let i = 0, len = signatureBinStr.length; i < len; i++) {
signature[i] = signatureBinStr.charCodeAt(i)
}
return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value))
} catch (e) {
return false
Expand All @@ -60,16 +61,22 @@ export const parse = (cookie: string, name?: string): Cookie => {
return pairs.reduce((parsedCookie, pairStr) => {
pairStr = pairStr.trim()
const valueStartPos = pairStr.indexOf('=')
if (valueStartPos === -1) return parsedCookie
if (valueStartPos === -1) {
return parsedCookie
}

const cookieName = pairStr.substring(0, valueStartPos).trim()
if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) return parsedCookie
if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {
return parsedCookie
}

let cookieValue = pairStr.substring(valueStartPos + 1).trim()
if (cookieValue.startsWith('"') && cookieValue.endsWith('"'))
if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
cookieValue = cookieValue.slice(1, -1)
if (validCookieValueRegEx.test(cookieValue))
}
if (validCookieValueRegEx.test(cookieValue)) {
parsedCookie[cookieName] = decodeURIComponent_(cookieValue)
}

return parsedCookie
}, {} as Cookie)
Expand All @@ -85,11 +92,15 @@ export const parseSigned = async (

for (const [key, value] of Object.entries(parse(cookie, name))) {
const signatureStartPos = value.lastIndexOf('.')
if (signatureStartPos < 1) continue
if (signatureStartPos < 1) {
continue
}

const signedValue = value.substring(0, signatureStartPos)
const signature = value.substring(signatureStartPos + 1)
if (signature.length !== 44 || !signature.endsWith('=')) continue
if (signature.length !== 44 || !signature.endsWith('=')) {
continue
}

const isVerified = await verifySignature(signature, signedValue, secretKey)
parsedCookie[key] = isVerified ? signedValue : false
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/utils/filepath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ type FilePathOptions = {

export const getFilePath = (options: FilePathOptions): string | undefined => {
let filename = options.filename
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) return
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
return
}

let root = options.root || ''
const defaultDocument = options.defaultDocument || 'index.html'
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/utils/mime.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const getMimeType = (filename: string): string | undefined => {
const regexp = /\.([a-zA-Z0-9]+?)$/
const match = filename.match(regexp)
if (!match) return
if (!match) {
return
}
let mimeType = mimes[match[1]]
if ((mimeType && mimeType.startsWith('text')) || mimeType === 'application/json') {
mimeType += '; charset=utf-8'
Expand Down
4 changes: 3 additions & 1 deletion deno_dist/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ export const checkOptionalParameter = (path: string): string[] | null => {
in other cases it will return null
*/

if (!path.match(/\:.+\?$/)) return null
if (!path.match(/\:.+\?$/)) {
return null
}

const segments = path.split('/')
const results: string[] = []
Expand Down
Loading

0 comments on commit b24f9e3

Please sign in to comment.