Skip to content
Myr

fix(types): add types to middleware correctly (#521)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent d12a119 · Browse files · 29 files+105 added−104 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

29 files+105 added−104 removed

  • other:+105 added−104 removed

29 files+105 added−104 removed

modified:deno_dist/deno/serve-static.ts+3 added-4 removed
modified:deno_dist/middleware/basic-auth/index.ts+3 added-4 removed
modified:deno_dist/middleware/bearer-auth/index.ts+3 added-4 removed
modified:deno_dist/middleware/cache/index.ts+7 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'24export const cache = (options: { cacheName: string; wait?: boolean; cacheControl?: string }) => {3export const cache = (options: {4 cacheName: string5 wait?: boolean6 cacheControl?: string7}): MiddlewareHandler => {8 if (options.wait === undefined) {9 options.wait = false10 }1112 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }1513 return async (c: Context, next: Next) => {16 return async (c, next) => {17 const key = c.req18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {
13 unmodified lines
modified:deno_dist/middleware/compress/index.ts+3 added-4 removed
modified:deno_dist/middleware/cors/index.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'23type CORSOptions = {4 origin: string5 allowMethods?: string[]
2 unmodified lines
8 credentials?: boolean9 exposeHeaders?: string[]10}1113export const cors = (options?: CORSOptions) => {12export const cors = (options?: CORSOptions): MiddlewareHandler => {13 const defaults: CORSOptions = {14 origin: '*',15 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],16 allowHeaders: [],
3 unmodified lines
20 ...defaults,21 ...options,22 }2325 return async (c: Context, next: Next) => {24 return async (c, next) => {25 await next()2627 function set(key: string, value: string) {28 c.res.headers.append(key, value)
52 unmodified lines
modified:deno_dist/middleware/etag/index.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'2import { sha1 } from '../../utils/crypto.ts'34type ETagOptions = {5 weak: boolean6}79export const etag = (options: ETagOptions = { weak: false }) => {10 return async (c: Context, next: Next) => {8export const etag = (options: ETagOptions = { weak: false }): MiddlewareHandler => {9 return async (c, next) => {10 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')1112 await next()13
19 unmodified lines
modified:deno_dist/middleware/jwt/index.ts+7 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'2import { Jwt } from '../../utils/jwt/index.ts'3import type { AlgorithmTypes } from '../../utils/jwt/types.ts'46export const jwt = (options: { secret: string; cookie?: string; alg?: string }) => {5export const jwt = (options: {6 secret: string7 cookie?: string8 alg?: string9}): MiddlewareHandler => {10 if (!options) {11 throw new Error('JWT auth middleware requires options for "secret')12 }1314 if (!crypto.subtle || !crypto.subtle.importKey) {15 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')16 }1715 return async (ctx: Context, next: Next) => {18 return async (ctx, next) => {19 const credentials = ctx.req.headers.get('Authorization')20 let token21 if (credentials) {22 const parts = credentials.split(/\s+/)
46 unmodified lines
modified:deno_dist/middleware/logger/index.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'2import { getPathFromURL } from '../../utils/url.ts'34enum LogPrefix {5 Outgoing = '-->',
46 unmodified lines
52 : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`53 fn(out)54}5557export const logger = (fn: PrintFunc = console.log) => {58 return async (c: Context, next: Next) => {56export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {58 const { method } = c.req59 const path = getPathFromURL(c.req.url)6061 log(fn, LogPrefix.Incoming, method, path)
8 unmodified lines
modified:deno_dist/middleware/powered-by/index.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'24export const poweredBy = () => {5 return async (c: Context, next: Next) => {3export const poweredBy = (): MiddlewareHandler => {4 return async (c, next) => {5 await next()6 c.res.headers.append('X-Powered-By', 'Hono')7 }8}
modified:deno_dist/middleware/pretty-json/index.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'23type prettyOptions = {4 space: number5}68export const prettyJSON = (options: prettyOptions = { space: 2 }) => {9 return async (c: Context, next: Next) => {7export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8 return async (c, next) => {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 c.pretty(pretty, options.space)11 await next()12 }
1 unmodified line
modified:deno_dist/middleware/serve-static/serve-static.ts+3 added-4 removed
1import type { Context } from '../../context.ts'2import type { Next } from '../../hono.ts'1import type { MiddlewareHandler } from '../../hono.ts'2import { getContentFromKVAsset } from '../../utils/cloudflare.ts'3import { getFilePath } from '../../utils/filepath.ts'4import { getMimeType } from '../../utils/mime.ts'5
6 unmodified lines
1213const DEFAULT_DOCUMENT = 'index.html'1415// This middleware is available only on Cloudflare Workers.17export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {18 return async (c: Context, next: Next): Promise<Response | undefined> => {16export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {17 return async (c, next): Promise<Response | undefined> => {18 // Do nothing if Response is already set19 if (c.finalized) {20 await next()21 }
27 unmodified lines
modified:deno_dist/middleware/validator/middleware.ts+2 added-2 removed
1import type { Context } from '../../context.ts'2import type { Handler } from '../../hono.ts'2import type { MiddlewareHandler } from '../../hono.ts'3import { JSONPathCopy } from '../../utils/json.ts'45type Param =6 | string
46 unmodified lines
53 validator: Validator,54 message: (value: string) => ValidatorMessage,55 context: Context56 ) => Partial<RuleSet>57 ): Handler => {57 ): MiddlewareHandler => {58 return async (c, next) => {59 const validations = validatorFunction(validator, message, c)6061 const result: ResultSet = {
153 unmodified lines
modified:deno_dist/hono.ts+5 added
26 unmodified lines
27 c: Context<RequestParamKeyType, E>,28 next: Next29) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>3031export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(32 c: Context<string, E>,33 next: Next34) => Promise<void> | Promise<Response | undefined>3536export type NotFoundHandler<E extends Partial<Environment> = Environment> = (37 c: Context<string, E>38) => Response | Promise<Response>39
229 unmodified lines
modified:src/deno/serve-static.ts+3 added-4 removed
1import type { Context } from '../context'2import type { Next } from '../hono'1import type { MiddlewareHandler } from '../hono'2import { getFilePath } from '../utils/filepath'3import { getMimeType } from '../utils/mime'45export type ServeStaticOptions = {
2 unmodified lines
8}910const DEFAULT_DOCUMENT = 'index.html'1113export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14 return async (c: Context, next: Next): Promise<Response | undefined> => {12export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {13 return async (c, next): Promise<Response | undefined> => {14 // Do nothing if Response is already set15 if (c.finalized) {16 await next()17 }
25 unmodified lines
modified:src/middleware/basic-auth/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { timingSafeEqual } from '../../utils/buffer'3import { decodeBase64 } from '../../utils/encode'45const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/
16 unmodified lines
2223export const basicAuth = (24 options: { username: string; password: string; realm?: string; hashFunction?: Function },25 ...users: { username: string; password: string }[]27) => {26): MiddlewareHandler => {27 if (!options) {28 throw new Error('basic auth middleware requires options for "username and password"')29 }30
1 unmodified line
32 options.realm = 'Secure Area'33 }34 users.unshift({ username: options.username, password: options.password })3537 return async (ctx: Context, next: Next) => {36 return async (ctx, next) => {37 const requestUser = auth(ctx.req)38 if (requestUser) {39 for (const user of users) {40 const usernameEqual = await timingSafeEqual(
24 unmodified lines
modified:src/middleware/bearer-auth/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { timingSafeEqual } from '../../utils/buffer'34const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'5const PREFIX = 'Bearer'
2 unmodified lines
8 token: string9 realm?: string10 prefix?: string11 hashFunction?: Function13}) => {12}): MiddlewareHandler => {13 if (!options.token) {14 throw new Error('bearer auth middleware requires options for "token"')15 }16 if (!options.realm) {
4 unmodified lines
21 }2223 const realm = options.realm?.replace(/"/g, '\\"')2426 return async (c: Context, next: Next) => {25 return async (c, next) => {26 const headerToken = c.req.headers.get('Authorization')2728 if (!headerToken) {29 // No Authorization header
33 unmodified lines
modified:src/middleware/cache/index.ts+7 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'24export const cache = (options: { cacheName: string; wait?: boolean; cacheControl?: string }) => {3export const cache = (options: {4 cacheName: string5 wait?: boolean6 cacheControl?: string7}): MiddlewareHandler => {8 if (options.wait === undefined) {9 options.wait = false10 }1112 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }1513 return async (c: Context, next: Next) => {16 return async (c, next) => {17 const key = c.req18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {
13 unmodified lines
modified:src/middleware/compress/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'23type EncodingType = 'gzip' | 'deflate'45interface CompressionOptions {6 encoding?: EncodingType7}810export const compress = (options?: CompressionOptions) => {11 return async (ctx: Context, next: Next) => {9export const compress = (options?: CompressionOptions): MiddlewareHandler => {10 return async (ctx, next) => {11 await next()12 const accepted = ctx.req.headers.get('Accept-Encoding')13 const pattern = options?.encoding ?? /gzip|deflate/14 const match = accepted?.match(pattern)
9 unmodified lines
modified:src/middleware/cors/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'23type CORSOptions = {4 origin: string5 allowMethods?: string[]
2 unmodified lines
8 credentials?: boolean9 exposeHeaders?: string[]10}1113export const cors = (options?: CORSOptions) => {12export const cors = (options?: CORSOptions): MiddlewareHandler => {13 const defaults: CORSOptions = {14 origin: '*',15 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],16 allowHeaders: [],
3 unmodified lines
20 ...defaults,21 ...options,22 }2325 return async (c: Context, next: Next) => {24 return async (c, next) => {25 await next()2627 function set(key: string, value: string) {28 c.res.headers.append(key, value)
52 unmodified lines
modified:src/middleware/etag/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { sha1 } from '../../utils/crypto'34type ETagOptions = {5 weak: boolean6}79export const etag = (options: ETagOptions = { weak: false }) => {10 return async (c: Context, next: Next) => {8export const etag = (options: ETagOptions = { weak: false }): MiddlewareHandler => {9 return async (c, next) => {10 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')1112 await next()13
19 unmodified lines
modified:src/middleware/jwt/index.ts+7 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { Jwt } from '../../utils/jwt'3import type { AlgorithmTypes } from '../../utils/jwt/types'46export const jwt = (options: { secret: string; cookie?: string; alg?: string }) => {5export const jwt = (options: {6 secret: string7 cookie?: string8 alg?: string9}): MiddlewareHandler => {10 if (!options) {11 throw new Error('JWT auth middleware requires options for "secret')12 }1314 if (!crypto.subtle || !crypto.subtle.importKey) {15 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')16 }1715 return async (ctx: Context, next: Next) => {18 return async (ctx, next) => {19 const credentials = ctx.req.headers.get('Authorization')20 let token21 if (credentials) {22 const parts = credentials.split(/\s+/)
46 unmodified lines
modified:src/middleware/logger/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { getPathFromURL } from '../../utils/url'34enum LogPrefix {5 Outgoing = '-->',
46 unmodified lines
52 : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`53 fn(out)54}5557export const logger = (fn: PrintFunc = console.log) => {58 return async (c: Context, next: Next) => {56export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {58 const { method } = c.req59 const path = getPathFromURL(c.req.url)6061 log(fn, LogPrefix.Incoming, method, path)
8 unmodified lines
modified:src/middleware/powered-by/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'24export const poweredBy = () => {5 return async (c: Context, next: Next) => {3export const poweredBy = (): MiddlewareHandler => {4 return async (c, next) => {5 await next()6 c.res.headers.append('X-Powered-By', 'Hono')7 }8}
modified:src/middleware/pretty-json/index.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'23type prettyOptions = {4 space: number5}68export const prettyJSON = (options: prettyOptions = { space: 2 }) => {9 return async (c: Context, next: Next) => {7export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8 return async (c, next) => {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 c.pretty(pretty, options.space)11 await next()12 }
1 unmodified line
modified:src/middleware/serve-static/bun.ts+3 added-4 removed
1// @denoify-ignore2/* eslint-disable @typescript-eslint/ban-ts-comment */3import type { Context } from '../../context'4import type { Next } from '../../hono'3import type { MiddlewareHandler } from '../../hono'4import { getFilePath } from '../../utils/filepath'5import { getMimeType } from '../../utils/mime'67// @ts-ignore
5 unmodified lines
13}1415const DEFAULT_DOCUMENT = 'index.html'1618export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {19 return async (c: Context, next: Next): Promise<Response | undefined> => {17export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {18 return async (c, next): Promise<Response | undefined> => {19 // Do nothing if Response is already set20 if (c.res && c.finalized) {21 await next()22 }
25 unmodified lines
modified:src/middleware/serve-static/serve-static.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { getContentFromKVAsset } from '../../utils/cloudflare'3import { getFilePath } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'5
6 unmodified lines
1213const DEFAULT_DOCUMENT = 'index.html'1415// This middleware is available only on Cloudflare Workers.17export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {18 return async (c: Context, next: Next): Promise<Response | undefined> => {16export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {17 return async (c, next): Promise<Response | undefined> => {18 // Do nothing if Response is already set19 if (c.finalized) {20 await next()21 }
27 unmodified lines
modified:src/middleware/validator/middleware.ts+2 added-2 removed
1import type { Context } from '../../context'2import type { Handler } from '../../hono'2import type { MiddlewareHandler } from '../../hono'3import { JSONPathCopy } from '../../utils/json'45type Param =6 | string
46 unmodified lines
53 validator: Validator,54 message: (value: string) => ValidatorMessage,55 context: Context56 ) => Partial<RuleSet>57 ): Handler => {57 ): MiddlewareHandler => {58 return async (c, next) => {59 const validations = validatorFunction(validator, message, c)6061 const result: ResultSet = {
153 unmodified lines
modified:src/hono.ts+5 added
26 unmodified lines
27 c: Context<RequestParamKeyType, E>,28 next: Next29) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>3031export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(32 c: Context<string, E>,33 next: Next34) => Promise<void> | Promise<Response | undefined>3536export type NotFoundHandler<E extends Partial<Environment> = Environment> = (37 c: Context<string, E>38) => Response | Promise<Response>39
229 unmodified lines