Skip to content
Myr

context.ts

This file

Path

src/context.ts

780 lines 路 21.7 KiB 路 TypeScript

Last changed by

fix(context): revert PR #4707 (#4757)Yusuke Wadabefore adoption212c64f

History of this file

Take it

1import { HonoRequest } from './request'2import type { Result } from './router'3import type {4  Env,5  FetchEventLike,6  H,7  Input,8  NotFoundHandler,9  RouterRoute,10  TypedResponse,11} from './types'12import type { ResponseHeader } from './utils/headers'13import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'14import type { ContentfulStatusCode, RedirectStatusCode, StatusCode } from './utils/http-status'15import type { BaseMime } from './utils/mime'16import type { InvalidJSONValue, IsAny, JSONParsed, JSONValue } from './utils/types'1718type HeaderRecord =19  | Record<'Content-Type', BaseMime>20  | Record<ResponseHeader, string | string[]>21  | Record<string, string | string[]>2223/**24 * Data type can be a string, ArrayBuffer, Uint8Array (buffer), or ReadableStream.25 */26export type Data = string | ArrayBuffer | ReadableStream | Uint8Array<ArrayBuffer>2728/**29 * Interface for the execution context in a web worker or similar environment.30 */31export interface ExecutionContext {32  /**33   * Extends the lifetime of the event callback until the promise is settled.34   *35   * @param promise - A promise to wait for.36   */37  waitUntil(promise: Promise<unknown>): void38  /**39   * Allows the event to be passed through to subsequent event listeners.40   */41  passThroughOnException(): void42  /**43   * For compatibility with Wrangler 4.x.44   */45  // eslint-disable-next-line @typescript-eslint/no-explicit-any46  props: any47  /**48   * For compatibility with Wrangler 4.x.49   */50  // eslint-disable-next-line @typescript-eslint/no-explicit-any51  exports?: any52}5354/**55 * Interface for context variable mapping.56 */57export interface ContextVariableMap {}5859/**60 * Interface for context renderer.61 */62export interface ContextRenderer {}6364/**65 * Interface representing a renderer for content.66 *67 * @interface DefaultRenderer68 * @param {string | Promise<string>} content - The content to be rendered, which can be either a string or a Promise resolving to a string.69 * @returns {Response | Promise<Response>} - The response after rendering the content, which can be either a Response or a Promise resolving to a Response.70 */71interface DefaultRenderer {72  (content: string | Promise<string>): Response | Promise<Response>73}7475/**76 * Renderer type which can either be a ContextRenderer or DefaultRenderer.77 */78export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer7980/**81 * Extracts the props for the renderer.82 */83export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]84  ? Props85  : unknown8687// eslint-disable-next-line @typescript-eslint/no-explicit-any88export type Layout<T = Record<string, any>> = (props: T) => any8990/**91 * Interface for getting context variables.92 *93 * @template E - Environment type.94 */95interface Get<E extends Env> {96  <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]97  <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]98}99100/**101 * Interface for setting context variables.102 *103 * @template E - Environment type.104 */105interface Set<E extends Env> {106  <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void107  <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void108}109110/**111 * Interface for creating a new response.112 */113interface NewResponse {114  (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response115  (data: Data | null, init?: ResponseOrInit): Response116}117118/**119 * Interface for responding with a body.120 */121interface BodyRespond {122  // if we return content, only allow the status codes that allow for returning the body123  <T extends Data, U extends ContentfulStatusCode>(124    data: T,125    status?: U,126    headers?: HeaderRecord127  ): Response & TypedResponse<T, U, 'body'>128  <T extends Data, U extends ContentfulStatusCode>(129    data: T,130    init?: ResponseOrInit<U>131  ): Response & TypedResponse<T, U, 'body'>132  <T extends null, U extends StatusCode>(133    data: T,134    status?: U,135    headers?: HeaderRecord136  ): Response & TypedResponse<null, U, 'body'>137  <T extends null, U extends StatusCode>(138    data: T,139    init?: ResponseOrInit<U>140  ): Response & TypedResponse<null, U, 'body'>141}142143/**144 * Interface for responding with text.145 *146 * @interface TextRespond147 * @template T - The type of the text content.148 * @template U - The type of the status code.149 *150 * @param {T} text - The text content to be included in the response.151 * @param {U} [status] - An optional status code for the response.152 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.153 *154 * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types.155 */156interface TextRespond {157  <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(158    text: T,159    status?: U,160    headers?: HeaderRecord161  ): Response & TypedResponse<T, U, 'text'>162  <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(163    text: T,164    init?: ResponseOrInit<U>165  ): Response & TypedResponse<T, U, 'text'>166}167168/**169 * Interface for responding with JSON.170 *171 * @interface JSONRespond172 * @template T - The type of the JSON value or simplified unknown type.173 * @template U - The type of the status code.174 *175 * @param {T} object - The JSON object to be included in the response.176 * @param {U} [status] - An optional status code for the response.177 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.178 *179 * @returns {JSONRespondReturn<T, U>} - The response after rendering the JSON object, typed with the provided object and status code types.180 */181interface JSONRespond {182  <183    T extends JSONValue | {} | InvalidJSONValue,184    U extends ContentfulStatusCode = ContentfulStatusCode,185  >(186    object: T,187    status?: U,188    headers?: HeaderRecord189  ): JSONRespondReturn<T, U>190  <191    T extends JSONValue | {} | InvalidJSONValue,192    U extends ContentfulStatusCode = ContentfulStatusCode,193  >(194    object: T,195    init?: ResponseOrInit<U>196  ): JSONRespondReturn<T, U>197}198199/**200 * @template T - The type of the JSON value or simplified unknown type.201 * @template U - The type of the status code.202 *203 * @returns {Response & TypedResponse<JSONParsed<T>, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.204 */205type JSONRespondReturn<206  T extends JSONValue | {} | InvalidJSONValue,207  U extends ContentfulStatusCode,208> = Response & TypedResponse<JSONParsed<T>, U, 'json'>209210/**211 * Interface representing a function that responds with HTML content.212 *213 * @param html - The HTML content to respond with, which can be a string or a Promise that resolves to a string.214 * @param status - (Optional) The HTTP status code for the response.215 * @param headers - (Optional) A record of headers to include in the response.216 * @param init - (Optional) The response initialization object.217 *218 * @returns A Response object or a Promise that resolves to a Response object.219 */220interface HTMLRespond {221  <T extends string | Promise<string>>(222    html: T,223    status?: ContentfulStatusCode,224    headers?: HeaderRecord225  ): T extends string ? Response : Promise<Response>226  <T extends string | Promise<string>>(227    html: T,228    init?: ResponseOrInit<ContentfulStatusCode>229  ): T extends string ? Response : Promise<Response>230}231232/**233 * Options for configuring the context.234 *235 * @template E - Environment type.236 */237type ContextOptions<E extends Env> = {238  /**239   * Bindings for the environment.240   */241  env: E['Bindings']242  /**243   * Execution context for the request.244   */245  executionCtx?: FetchEventLike | ExecutionContext | undefined246  /**247   * Handler for not found responses.248   */249  notFoundHandler?: NotFoundHandler<E>250  matchResult?: Result<[H, RouterRoute]>251  path?: string252}253254interface SetHeadersOptions {255  append?: boolean256}257258interface SetHeaders {259  (name: 'Content-Type', value?: BaseMime, options?: SetHeadersOptions): void260  (name: ResponseHeader, value?: string, options?: SetHeadersOptions): void261  (name: string, value?: string, options?: SetHeadersOptions): void262}263264type ResponseHeadersInit =265  | [string, string][]266  | Record<'Content-Type', BaseMime>267  | Record<ResponseHeader, string>268  | Record<string, string>269  | Headers270271interface ResponseInit<T extends StatusCode = StatusCode> {272  headers?: ResponseHeadersInit273  status?: T274  statusText?: string275}276277type ResponseOrInit<T extends StatusCode = StatusCode> = ResponseInit<T> | Response278279export const TEXT_PLAIN = 'text/plain; charset=UTF-8'280281const setDefaultContentType = (contentType: string, headers?: HeaderRecord): HeaderRecord => {282  return {283    'Content-Type': contentType,284    ...headers,285  }286}287288const createResponseInstance = (289  body?: BodyInit | null | undefined,290  init?: globalThis.ResponseInit291): Response => new Response(body, init)292293export class Context<294  // eslint-disable-next-line @typescript-eslint/no-explicit-any295  E extends Env = any,296  // eslint-disable-next-line @typescript-eslint/no-explicit-any297  P extends string = any,298  I extends Input = {},299> {300  #rawRequest: Request301  #req: HonoRequest<P, I['out']> | undefined302  /**303   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.304   *305   * @see {@link https://hono.dev/docs/api/context#env}306   *307   * @example308   * ```ts309   * // Environment object for Cloudflare Workers310   * app.get('*', async c => {311   *   const counter = c.env.COUNTER312   * })313   * ```314   */315  env: E['Bindings'] = {}316  #var: Map<unknown, unknown> | undefined317  finalized: boolean = false318  /**319   * `.error` can get the error object from the middleware if the Handler throws an error.320   *321   * @see {@link https://hono.dev/docs/api/context#error}322   *323   * @example324   * ```ts325   * app.use('*', async (c, next) => {326   *   await next()327   *   if (c.error) {328   *     // do something...329   *   }330   * })331   * ```332   */333  error: Error | undefined334335  #status: StatusCode | undefined336  #executionCtx: FetchEventLike | ExecutionContext | undefined337  #res: Response | undefined338  #layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined339  #renderer: Renderer | undefined340  #notFoundHandler: NotFoundHandler<E> | undefined341  #preparedHeaders: Headers | undefined342343  #matchResult: Result<[H, RouterRoute]> | undefined344  #path: string | undefined345346  /**347   * Creates an instance of the Context class.348   *349   * @param req - The Request object.350   * @param options - Optional configuration options for the context.351   */352  constructor(req: Request, options?: ContextOptions<E>) {353    this.#rawRequest = req354    if (options) {355      this.#executionCtx = options.executionCtx356      this.env = options.env357      this.#notFoundHandler = options.notFoundHandler358      this.#path = options.path359      this.#matchResult = options.matchResult360    }361  }362363  /**364   * `.req` is the instance of {@link HonoRequest}.365   */366  get req(): HonoRequest<P, I['out']> {367    this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult)368    return this.#req369  }370371  /**372   * @see {@link https://hono.dev/docs/api/context#event}373   * The FetchEvent associated with the current request.374   *375   * @throws Will throw an error if the context does not have a FetchEvent.376   */377  get event(): FetchEventLike {378    if (this.#executionCtx && 'respondWith' in this.#executionCtx) {379      return this.#executionCtx380    } else {381      throw Error('This context has no FetchEvent')382    }383  }384385  /**386   * @see {@link https://hono.dev/docs/api/context#executionctx}387   * The ExecutionContext associated with the current request.388   *389   * @throws Will throw an error if the context does not have an ExecutionContext.390   */391  get executionCtx(): ExecutionContext {392    if (this.#executionCtx) {393      return this.#executionCtx as ExecutionContext394    } else {395      throw Error('This context has no ExecutionContext')396    }397  }398399  /**400   * @see {@link https://hono.dev/docs/api/context#res}401   * The Response object for the current request.402   */403  get res(): Response {404    return (this.#res ||= createResponseInstance(null, {405      headers: (this.#preparedHeaders ??= new Headers()),406    }))407  }408409  /**410   * Sets the Response object for the current request.411   *412   * @param _res - The Response object to set.413   */414  set res(_res: Response | undefined) {415    if (this.#res && _res) {416      _res = createResponseInstance(_res.body, _res)417      for (const [k, v] of this.#res.headers.entries()) {418        if (k === 'content-type') {419          continue420        }421        if (k === 'set-cookie') {422          const cookies = this.#res.headers.getSetCookie()423          _res.headers.delete('set-cookie')424          for (const cookie of cookies) {425            _res.headers.append('set-cookie', cookie)426          }427        } else {428          _res.headers.set(k, v)429        }430      }431    }432    this.#res = _res433    this.finalized = true434  }435436  /**437   * `.render()` can create a response within a layout.438   *439   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}440   *441   * @example442   * ```ts443   * app.get('/', (c) => {444   *   return c.render('Hello!')445   * })446   * ```447   */448  render: Renderer = (...args) => {449    this.#renderer ??= (content: string | Promise<string>) => this.html(content)450    return this.#renderer(...args)451  }452453  /**454   * Sets the layout for the response.455   *456   * @param layout - The layout to set.457   * @returns The layout function.458   */459  setLayout = (460    layout: Layout<PropsForRenderer & { Layout: Layout }>461  ): Layout<462    PropsForRenderer & {463      Layout: Layout464    }465  > => (this.#layout = layout)466467  /**468   * Gets the current layout for the response.469   *470   * @returns The current layout function.471   */472  getLayout = (): Layout<PropsForRenderer & { Layout: Layout }> | undefined => this.#layout473474  /**475   * `.setRenderer()` can set the layout in the custom middleware.476   *477   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}478   *479   * @example480   * ```tsx481   * app.use('*', async (c, next) => {482   *   c.setRenderer((content) => {483   *     return c.html(484   *       <html>485   *         <body>486   *           <p>{content}</p>487   *         </body>488   *       </html>489   *     )490   *   })491   *   await next()492   * })493   * ```494   */495  setRenderer = (renderer: Renderer): void => {496    this.#renderer = renderer497  }498499  /**500   * `.header()` can set headers.501   *502   * @see {@link https://hono.dev/docs/api/context#header}503   *504   * @example505   * ```ts506   * app.get('/welcome', (c) => {507   *   // Set headers508   *   c.header('X-Message', 'Hello!')509   *   c.header('Content-Type', 'text/plain')510   *511   *   return c.body('Thank you for coming')512   * })513   * ```514   */515  header: SetHeaders = (name, value, options): void => {516    if (this.finalized) {517      this.#res = createResponseInstance((this.#res as Response).body, this.#res)518    }519    const headers = this.#res ? this.#res.headers : (this.#preparedHeaders ??= new Headers())520    if (value === undefined) {521      headers.delete(name)522    } else if (options?.append) {523      headers.append(name, value)524    } else {525      headers.set(name, value)526    }527  }528529  status = (status: StatusCode): void => {530    this.#status = status531  }532533  /**534   * `.set()` can set the value specified by the key.535   *536   * @see {@link https://hono.dev/docs/api/context#set-get}537   *538   * @example539   * ```ts540   * app.use('*', async (c, next) => {541   *   c.set('message', 'Hono is hot!!')542   *   await next()543   * })544   * ```545   */546  set: Set<547    IsAny<E> extends true548      ? {549          // eslint-disable-next-line @typescript-eslint/no-explicit-any550          Variables: ContextVariableMap & Record<string, any>551        }552      : E553  > = (key: string, value: unknown) => {554    this.#var ??= new Map()555    this.#var.set(key, value)556  }557558  /**559   * `.get()` can use the value specified by the key.560   *561   * @see {@link https://hono.dev/docs/api/context#set-get}562   *563   * @example564   * ```ts565   * app.get('/', (c) => {566   *   const message = c.get('message')567   *   return c.text(`The message is "${message}"`)568   * })569   * ```570   */571  get: Get<572    IsAny<E> extends true573      ? {574          // eslint-disable-next-line @typescript-eslint/no-explicit-any575          Variables: ContextVariableMap & Record<string, any>576        }577      : E578  > = (key: string) => {579    return this.#var ? this.#var.get(key) : undefined580  }581582  /**583   * `.var` can access the value of a variable.584   *585   * @see {@link https://hono.dev/docs/api/context#var}586   *587   * @example588   * ```ts589   * const result = c.var.client.oneMethod()590   * ```591   */592  // c.var.propName is a read-only593  get var(): Readonly<594    // eslint-disable-next-line @typescript-eslint/no-explicit-any595    ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])596  > {597    if (!this.#var) {598      // eslint-disable-next-line @typescript-eslint/no-explicit-any599      return {} as any600    }601    return Object.fromEntries(this.#var)602  }603604  #newResponse(605    data: Data | null,606    arg?: StatusCode | ResponseOrInit,607    headers?: HeaderRecord608  ): Response {609    const responseHeaders = this.#res610      ? new Headers(this.#res.headers)611      : (this.#preparedHeaders ?? new Headers())612613    if (typeof arg === 'object' && 'headers' in arg) {614      const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers)615      for (const [key, value] of argHeaders) {616        if (key.toLowerCase() === 'set-cookie') {617          responseHeaders.append(key, value)618        } else {619          responseHeaders.set(key, value)620        }621      }622    }623624    if (headers) {625      for (const [k, v] of Object.entries(headers)) {626        if (typeof v === 'string') {627          responseHeaders.set(k, v)628        } else {629          responseHeaders.delete(k)630          for (const v2 of v) {631            responseHeaders.append(k, v2)632          }633        }634      }635    }636637    const status = typeof arg === 'number' ? arg : (arg?.status ?? this.#status)638    return createResponseInstance(data, { status, headers: responseHeaders })639  }640641  newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))642643  /**644   * `.body()` can return the HTTP response.645   * You can set headers with `.header()` and set HTTP status code with `.status`.646   * This can also be set in `.text()`, `.json()` and so on.647   *648   * @see {@link https://hono.dev/docs/api/context#body}649   *650   * @example651   * ```ts652   * app.get('/welcome', (c) => {653   *   // Set headers654   *   c.header('X-Message', 'Hello!')655   *   c.header('Content-Type', 'text/plain')656   *   // Set HTTP status code657   *   c.status(201)658   *659   *   // Return the response body660   *   return c.body('Thank you for coming')661   * })662   * ```663   */664  body: BodyRespond = (665    data: Data | null,666    arg?: StatusCode | RequestInit,667    headers?: HeaderRecord668  ): ReturnType<BodyRespond> => this.#newResponse(data, arg, headers) as ReturnType<BodyRespond>669670  /**671   * `.text()` can render text as `Content-Type:text/plain`.672   *673   * @see {@link https://hono.dev/docs/api/context#text}674   *675   * @example676   * ```ts677   * app.get('/say', (c) => {678   *   return c.text('Hello!')679   * })680   * ```681   */682  text: TextRespond = (683    text: string,684    arg?: ContentfulStatusCode | ResponseOrInit,685    headers?: HeaderRecord686  ): ReturnType<TextRespond> => {687    return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized688      ? (new Response(text) as ReturnType<TextRespond>)689      : (this.#newResponse(690          text,691          arg,692          setDefaultContentType(TEXT_PLAIN, headers)693        ) as ReturnType<TextRespond>)694  }695696  /**697   * `.json()` can render JSON as `Content-Type:application/json`.698   *699   * @see {@link https://hono.dev/docs/api/context#json}700   *701   * @example702   * ```ts703   * app.get('/api', (c) => {704   *   return c.json({ message: 'Hello!' })705   * })706   * ```707   */708  json: JSONRespond = <709    T extends JSONValue | {} | InvalidJSONValue,710    U extends ContentfulStatusCode = ContentfulStatusCode,711  >(712    object: T,713    arg?: U | ResponseOrInit<U>,714    headers?: HeaderRecord715  ): JSONRespondReturn<T, U> => {716    return this.#newResponse(717      JSON.stringify(object),718      arg,719      setDefaultContentType('application/json', headers)720    ) /* eslint-disable @typescript-eslint/no-explicit-any */ as any721  }722723  html: HTMLRespond = (724    html: string | Promise<string>,725    arg?: ContentfulStatusCode | ResponseOrInit<ContentfulStatusCode>,726    headers?: HeaderRecord727  ): Response | Promise<Response> => {728    const res = (html: string) =>729      this.#newResponse(html, arg, setDefaultContentType('text/html; charset=UTF-8', headers))730    return typeof html === 'object'731      ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res)732      : res(html)733  }734735  /**736   * `.redirect()` can Redirect, default status code is 302.737   *738   * @see {@link https://hono.dev/docs/api/context#redirect}739   *740   * @example741   * ```ts742   * app.get('/redirect', (c) => {743   *   return c.redirect('/')744   * })745   * app.get('/redirect-permanently', (c) => {746   *   return c.redirect('/', 301)747   * })748   * ```749   */750  redirect = <T extends RedirectStatusCode = 302>(751    location: string | URL,752    status?: T753  ): Response & TypedResponse<undefined, T, 'redirect'> => {754    const locationString = String(location)755    this.header(756      'Location',757      // Multibyes should be encoded758      // eslint-disable-next-line no-control-regex759      !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)760    )761    return this.newResponse(null, status ?? 302) as any762  }763764  /**765   * `.notFound()` can return the Not Found Response.766   *767   * @see {@link https://hono.dev/docs/api/context#notfound}768   *769   * @example770   * ```ts771   * app.get('/notfound', (c) => {772   *   return c.notFound()773   * })774   * ```775   */776  notFound = (): ReturnType<NotFoundHandler> => {777    this.#notFoundHandler ??= () => createResponseInstance()778    return this.#notFoundHandler(this)779  }780}