Skip to content
Myr

hono-base.ts

This file

Path

src/hono-base.ts

549 lines 路 16.1 KiB 路 TypeScript

Last changed by

feat(mount): introduce Mount Middleware and deprecate `app.mount` (#5221)Yusuke Wadabefore adoptionae595de

History of this file

Take it

1/**2 * @module3 * This module is the base module for the Hono object.4 */56/* eslint-disable @typescript-eslint/no-explicit-any */7import { compose } from './compose'8import { Context } from './context'9import type { ExecutionContext } from './context'10import type { Router } from './router'11import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'12import type {13  Env,14  ErrorHandler,15  FetchEventLike,16  H,17  HandlerInterface,18  MergePath,19  MergeSchemaPath,20  MiddlewareHandler,21  MiddlewareHandlerInterface,22  Next,23  NotFoundHandler,24  OnHandlerInterface,25  RouterRoute,26  Schema,27} from './types'28import { COMPOSED_HANDLER } from './utils/constants'29import { getPath, getPathNoStrict, mergePath } from './utils/url'3031const notFoundHandler: NotFoundHandler = (c) => {32  return c.text('404 Not Found', 404)33}3435const errorHandler: ErrorHandler = (err, c) => {36  if ('getResponse' in err) {37    const res = err.getResponse()38    return c.newResponse(res.body, res)39  }40  console.error(err)41  return c.text('Internal Server Error', 500)42}4344type GetPath<E extends Env> = (request: Request, options?: { env?: E['Bindings'] }) => string4546export type HonoOptions<E extends Env> = {47  /**48   * `strict` option specifies whether to distinguish whether the last path is a directory or not.49   *50   * @see {@link https://hono.dev/docs/api/hono#strict-mode}51   *52   * @default true53   */54  strict?: boolean55  /**56   * `router` option specifies which router to use.57   *58   * @see {@link https://hono.dev/docs/api/hono#router-option}59   *60   * @example61   * ```ts62   * const app = new Hono({ router: new RegExpRouter() })63   * ```64   */65  router?: Router<[H, RouterRoute]>66  /**67   * `getPath` can handle the host header value.68   *69   * @see {@link https://hono.dev/docs/api/routing#routing-with-host-header-value}70   *71   * @example72   * ```ts73   * const app = new Hono({74   *  getPath: (req) =>75   *   '/' + req.headers.get('host') + req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'),76   * })77   *78   * app.get('/www1.example.com/hello', () => c.text('hello www1'))79   *80   * // A following request will match the route:81   * // new Request('http://www1.example.com/hello', {82   * //  headers: { host: 'www1.example.com' },83   * // })84   * ```85   */86  getPath?: GetPath<E>87}8889type MountOptionHandler = (c: Context) => unknown90type MountReplaceRequest = (originalRequest: Request) => Request91type MountOptions =92  | MountOptionHandler93  | {94      optionHandler?: MountOptionHandler95      replaceRequest?: MountReplaceRequest | false96    }9798class Hono<99  E extends Env = Env,100  S extends Schema = {},101  BasePath extends string = '/',102  CurrentPath extends string = BasePath,103> {104  get!: HandlerInterface<E, 'get', S, BasePath, CurrentPath>105  post!: HandlerInterface<E, 'post', S, BasePath, CurrentPath>106  put!: HandlerInterface<E, 'put', S, BasePath, CurrentPath>107  delete!: HandlerInterface<E, 'delete', S, BasePath, CurrentPath>108  options!: HandlerInterface<E, 'options', S, BasePath, CurrentPath>109  patch!: HandlerInterface<E, 'patch', S, BasePath, CurrentPath>110  query!: HandlerInterface<E, 'query', S, BasePath, CurrentPath>111  all!: HandlerInterface<E, 'all', S, BasePath, CurrentPath>112  on: OnHandlerInterface<E, S, BasePath>113  use: MiddlewareHandlerInterface<E, S, BasePath>114115  /*116    This class is like an abstract class and does not have a router.117    To use it, inherit the class and implement router in the constructor.118  */119  router!: Router<[H, RouterRoute]>120  readonly getPath: GetPath<E>121  // Cannot use `#` because it requires visibility at JavaScript runtime.122  private _basePath: string = '/'123  #path: string = '/'124125  routes: RouterRoute[] = []126127  constructor(options: HonoOptions<E> = {}) {128    // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])129    const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]130    allMethods.forEach((method) => {131      this[method] = (args1: string | H, ...args: H[]) => {132        const methodName = method.toUpperCase()133        if (typeof args1 === 'string') {134          this.#path = args1135        } else {136          this.#addRoute(methodName, this.#path, args1)137        }138        args.forEach((handler) => {139          this.#addRoute(methodName, this.#path, handler)140        })141        return this as any142      }143    })144145    // Implementation of app.on(method, path, ...handlers[])146    this.on = (method: string | string[], path: string | string[], ...handlers: H[]) => {147      for (const p of [path].flat()) {148        this.#path = p149        for (const m of [method].flat()) {150          const methodName = m.toUpperCase()151          for (const handler of handlers) {152            this.#addRoute(methodName, this.#path, handler)153          }154        }155      }156      return this as any157    }158159    // Implementation of app.use(...handlers[]) or app.use(path, ...handlers[])160    this.use = (arg1: string | MiddlewareHandler<any>, ...handlers: MiddlewareHandler<any>[]) => {161      if (typeof arg1 === 'string') {162        this.#path = arg1163      } else {164        this.#path = '*'165        handlers.unshift(arg1)166      }167      handlers.forEach((handler) => {168        this.#addRoute(METHOD_NAME_ALL, this.#path, handler)169      })170      return this as any171    }172173    const { strict, ...optionsWithoutStrict } = options174    Object.assign(this, optionsWithoutStrict)175    this.getPath = (strict ?? true) ? (options.getPath ?? getPath) : getPathNoStrict176  }177178  #clone(): Hono<E, S, BasePath, CurrentPath> {179    const clone = new Hono<E, S, BasePath, CurrentPath>({180      router: this.router,181      getPath: this.getPath,182    })183    clone.errorHandler = this.errorHandler184    clone.#notFoundHandler = this.#notFoundHandler185    clone.routes = this.routes186    return clone187  }188189  #notFoundHandler: NotFoundHandler = notFoundHandler190  // Cannot use `#` because it requires visibility at JavaScript runtime.191  private errorHandler: ErrorHandler = errorHandler192193  /**194   * `.route()` allows grouping other Hono instance in routes.195   *196   * @see {@link https://hono.dev/docs/api/routing#grouping}197   *198   * @param {string} path - base Path199   * @param {Hono} app - other Hono instance200   * @returns {Hono} routed Hono instance201   *202   * @example203   * ```ts204   * const app = new Hono()205   * const app2 = new Hono()206   *207   * app2.get("/user", (c) => c.text("user"))208   * app.route("/api", app2) // GET /api/user209   * ```210   */211  route<212    SubPath extends string,213    SubEnv extends Env,214    SubSchema extends Schema,215    SubBasePath extends string,216    SubCurrentPath extends string,217  >(218    path: SubPath,219    app: Hono<SubEnv, SubSchema, SubBasePath, SubCurrentPath>220  ): Hono<E, MergeSchemaPath<SubSchema, MergePath<BasePath, SubPath>> | S, BasePath, CurrentPath> {221    const subApp = this.basePath(path)222    app.routes.map((r) => {223      let handler224      if (app.errorHandler === errorHandler) {225        handler = r.handler226      } else {227        handler = async (c: Context, next: Next) =>228          (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res229        ;(handler as any)[COMPOSED_HANDLER] = r.handler230      }231232      subApp.#addRoute(r.method, r.path, handler, r.basePath)233    })234    return this235  }236237  /**238   * `.basePath()` allows base paths to be specified.239   *240   * @see {@link https://hono.dev/docs/api/routing#base-path}241   *242   * @param {string} path - base Path243   * @returns {Hono} changed Hono instance244   *245   * @example246   * ```ts247   * const api = new Hono().basePath('/api')248   * ```249   */250  basePath<SubPath extends string>(251    path: SubPath252  ): Hono<E, S, MergePath<BasePath, SubPath>, MergePath<BasePath, SubPath>> {253    const subApp = this.#clone()254    subApp._basePath = mergePath(this._basePath, path)255    return subApp256  }257258  /**259   * `.onError()` handles an error and returns a customized Response.260   *261   * @see {@link https://hono.dev/docs/api/hono#error-handling}262   *263   * @param {ErrorHandler} handler - request Handler for error264   * @returns {Hono} changed Hono instance265   *266   * @example267   * ```ts268   * app.onError((err, c) => {269   *   console.error(`${err}`)270   *   return c.text('Custom Error Message', 500)271   * })272   * ```273   */274  onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath, CurrentPath> => {275    this.errorHandler = handler276    return this277  }278279  /**280   * `.notFound()` allows you to customize a Not Found Response.281   *282   * @see {@link https://hono.dev/docs/api/hono#not-found}283   *284   * @param {NotFoundHandler} handler - request handler for not-found285   * @returns {Hono} changed Hono instance286   *287   * @example288   * ```ts289   * app.notFound((c) => {290   *   return c.text('Custom 404 Message', 404)291   * })292   * ```293   */294  notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath, CurrentPath> => {295    this.#notFoundHandler = handler296    return this297  }298299  /**300   * `.mount()` allows you to mount applications built with other frameworks into your Hono application.301   *302   * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.303   *304   * @see {@link https://hono.dev/docs/api/hono#mount}305   *306   * @param {string} path - base Path307   * @param {Function} applicationHandler - other Request Handler308   * @param {MountOptions} [options] - options of `.mount()`309   * @returns {Hono} mounted Hono instance310   *311   * @example312   * ```ts313   * import { Router as IttyRouter } from 'itty-router'314   * import { Hono } from 'hono'315   * // Create itty-router application316   * const ittyRouter = IttyRouter()317   * // GET /itty-router/hello318   * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))319   *320   * const app = new Hono()321   * app.mount('/itty-router', ittyRouter.handle)322   * ```323   *324   * @example325   * ```ts326   * const app = new Hono()327   * // Send the request to another application without modification.328   * app.mount('/app', anotherApp, {329   *   replaceRequest: (req) => req,330   * })331   * ```332   */333  mount(334    path: string,335    applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,336    options?: MountOptions337  ): Hono<E, S, BasePath, CurrentPath> {338    // handle options339    let replaceRequest: MountReplaceRequest | undefined340    let optionHandler: MountOptionHandler | undefined341    if (options) {342      if (typeof options === 'function') {343        optionHandler = options344      } else {345        optionHandler = options.optionHandler346        if (options.replaceRequest === false) {347          replaceRequest = (request) => request348        } else {349          replaceRequest = options.replaceRequest350        }351      }352    }353354    // prepare handlers for request355    const getOptions: (c: Context) => unknown[] = optionHandler356      ? (c) => {357          const options = optionHandler!(c)358          return Array.isArray(options) ? options : [options]359        }360      : (c) => {361          let executionContext: ExecutionContext | undefined = undefined362          try {363            executionContext = c.executionCtx364          } catch {} // Do nothing365          return [c.env, executionContext]366        }367    replaceRequest ||= (() => {368      const mergedPath = mergePath(this._basePath, path)369      const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length370      return (request) => {371        const url = new URL(request.url)372        url.pathname = this.getPath(request).slice(pathPrefixLength) || '/'373        return new Request(url, request)374      }375    })()376377    const handler: MiddlewareHandler = async (c, next) => {378      const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c))379380      if (res) {381        return res382      }383384      await next()385    }386    this.#addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)387    return this388  }389390  #addRoute(method: string, path: string, handler: H, baseRoutePath?: string): void {391    path = mergePath(this._basePath, path)392    const r: RouterRoute = {393      basePath:394        baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,395      path,396      method,397      handler,398    }399    this.router.add(method, path, [handler, r])400    this.routes.push(r)401  }402403  #handleError(err: unknown, c: Context<E>): Response | Promise<Response> {404    if (err instanceof Error) {405      return this.errorHandler(err, c)406    }407    throw err408  }409410  #dispatch(411    request: Request,412    executionCtx: ExecutionContext | FetchEventLike | undefined,413    env: E['Bindings'],414    method: string415  ): Response | Promise<Response> {416    // Handle HEAD method417    if (method === 'HEAD') {418      return (async () =>419        new Response(null, await this.#dispatch(request, executionCtx, env, 'GET')))()420    }421422    const path = this.getPath(request, { env })423    const matchResult = this.router.match(method, path)424425    const c = new Context(request, {426      path,427      matchResult,428      env,429      executionCtx,430      notFoundHandler: this.#notFoundHandler,431    })432433    // Do not `compose` if it has only one handler434    if (matchResult[0].length === 1) {435      let res: ReturnType<H>436      try {437        res = matchResult[0][0][0][0](c, async () => {438          c.res = await this.#notFoundHandler(c)439        })440      } catch (err) {441        return this.#handleError(err, c)442      }443444      return res instanceof Promise445        ? res446            .then(447              (resolved: Response | undefined) =>448                resolved || (c.finalized ? c.res : this.#notFoundHandler(c))449            )450            .catch((err: Error) => this.#handleError(err, c))451        : (res ?? this.#notFoundHandler(c))452    }453454    const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler)455456    return (async () => {457      try {458        const context = await composed(c)459        if (!context.finalized) {460          throw new Error(461            'Context is not finalized. Did you forget to return a Response object or `await next()`?'462          )463        }464465        return context.res466      } catch (err) {467        return this.#handleError(err, c)468      }469    })()470  }471472  /**473   * `.fetch()` will be entry point of your app.474   *475   * @see {@link https://hono.dev/docs/api/hono#fetch}476   *477   * @param {Request} request - request Object of request478   * @param {Env} env - env Object479   * @param {ExecutionContext} executionCtx - context of execution480   * @returns {Response | Promise<Response>} response of request481   *482   */483  fetch: (484    request: Request,485    env?: E['Bindings'] | {},486    executionCtx?: ExecutionContext487  ) => Response | Promise<Response> = (request, ...rest) => {488    return this.#dispatch(request, rest[1], rest[0], request.method)489  }490491  /**492   * `.request()` is a useful method for testing.493   * You can pass a URL or pathname to send a GET request.494   * app will return a Response object.495   * ```ts496   * test('GET /hello is ok', async () => {497   *   const res = await app.request('/hello')498   *   expect(res.status).toBe(200)499   * })500   * ```501   * @see https://hono.dev/docs/api/hono#request502   */503  request = (504    input: Request | string | URL,505    requestInit?: RequestInit,506    Env?: E['Bindings'] | {},507    executionCtx?: ExecutionContext508  ): Response | Promise<Response> => {509    if (input instanceof Request) {510      return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx)511    }512    input = input.toString()513    return this.fetch(514      new Request(515        /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`,516        requestInit517      ),518      Env,519      executionCtx520    )521  }522523  /**524   * `.fire()` automatically adds a global fetch event listener.525   * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.526   * @deprecated527   * Use `fire` from `hono/service-worker` instead.528   * ```ts529   * import { Hono } from 'hono'530   * import { fire } from 'hono/service-worker'531   *532   * const app = new Hono()533   * // ...534   * fire(app)535   * ```536   * @see https://hono.dev/docs/api/hono#fire537   * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API538   * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/539   */540  fire = (): void => {541    // eslint-disable-next-line @typescript-eslint/ban-ts-comment542    // @ts-ignore543    addEventListener('fetch', (event: FetchEventLike): void => {544      event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method))545    })546  }547}548549export { Hono as HonoBase }