# Hono (narrator proof) # Hono (narrator proof) What this repository is for is not stated in prose this page can quote, so it cannot be established from this repository alone. - **Terms of use** — MIT [package.json:650]. - **Version** — `4.13.1` [package.json:3]. - **Editions** — whether this repository is the whole product or one edition of it cannot be established from this repository alone. - **Running it** — no run path was found in the parsed corpus, so how to start it cannot be established from this repository alone. ## What is in here Each part names what it holds before how much of it there is. The counts are read from the evidence census computed for this snapshot, one per part at most. - [Utils](subsystem-src-utils) — jwt; enums and type aliases. A file to open: `accept.ts` [src/utils/accept.ts:1]. 148 entities under `src/utils` [census]. - [Helper](subsystem-src-helper) — ssg, css, websocket, cookie; type aliases and classes. A file to open: `accepts.ts` [src/helper/accepts/accepts.ts:5]. 109 entities under `src/helper` [census]. - [Jsx](subsystem-src-jsx) — dom, hooks, intrinsic element; type aliases and classes. A file to open: `base.ts` [src/jsx/base.ts:27]. 147 entities under `src/jsx` [census]. - [Middleware](subsystem-src-middleware) — language, timing, cache, compress; HTTP endpoints. A file to open: `index.ts` [src/middleware/basic-auth/index.ts:118]. 110 entities under `src/middleware` [census]. - [Client](subsystem-src-client) — type aliases and class. A file to open: `fetch-result-please.ts` [src/client/fetch-result-please.ts:14]. 25 entities under `src/client` [census]. - [Docs](subsystem-docs) — no symbol kind this page can name. A file to open: `CODE_OF_CONDUCT.md` [docs/CODE_OF_CONDUCT.md:1]. 73 entities under `docs` [census]. - [Adapter](subsystem-src-adapter) — aws lambda, bun, lambda edge, cloudflare workers; type aliases and classes. A file to open: `conninfo.ts` [src/adapter/aws-lambda/conninfo.ts:45]. 71 entities under `src/adapter` [census]. - [Router](subsystem-src-router) — reg exp router, trie router, linear router, pattern router; type aliases and classes. A file to open: `router.ts` [src/router/linear-router/router.ts:11]. 21 entities under `src/router` [census]. - **Repository root and unclaimed files** — validator, .github, preset, request; type aliases and classes. A file to open: `pull_request_template.md` [.github/pull_request_template.md:1]. 110 entities in files no part claims [census]. ## Trust and security, as the code carries it Topics below come from sweeping symbol names and file paths in the parsed corpus. They are not read from a security document: a page that takes its topics from what a document enumerates inherits whatever that document left out. - **Authentication** — `basicAuth` [src/middleware/basic-auth/index.ts:80], `handler` [src/middleware/basic-auth/index.ts:118], `bearerAuth` [src/middleware/bearer-auth/index.ts:104]. - **Authorization** — `PermissionsPolicyDirective` [src/middleware/secure-headers/permissions-policy.ts:3]. - **Secrets and configuration** — `isTokenHeader` [src/utils/jwt/jwt.ts:44], `TokenHeader` [src/utils/jwt/jwt.ts:38], `JwtTokenAudience` [src/utils/jwt/types.ts:106]. - **Transport and browser boundaries** — `deleteCookie` [src/helper/cookie/index.ts:141], `generateCookie` [src/helper/cookie/index.ts:78], `generateSignedCookie` [src/helper/cookie/index.ts:104]. - **Input validation** — `joinPaths` [src/helper/ssg/utils.ts:50], `validateOptions` [src/middleware/language/language.ts:204], `ValidationTargets` [src/types.ts:2683]. - **Cryptography** — `createHash` [src/utils/crypto.ts:33], `sha1` [src/utils/crypto.ts:21], `sha256` [src/utils/crypto.ts:15]. No symbol name or path in the parsed corpus matched rate limiting and abuse and audit and access logging. That is a statement about the names this codebase uses, not a finding about what it does. ## What this repository carries One row per capability lane, scoped to where the evidence for it sits. A lane marked as not found means nothing in the parsed corpus matched it — which is a fact about this parse, and the honest place to start looking rather than the end of the question. | Capability | In this repository | Where | |---|---|---| | Database models | not found | — | | HTTP endpoints | 40 [census] | `src/middleware/basic-auth/index.ts`, `src/middleware/body-limit/index.ts` | | Controllers | not found | — | | Configuration | not found | — | | Automated tests | not found | — | | Written documentation | yes | `.github/pull_request_template.md`, `LICENSE` | | Licence | yes | `LICENSE` | ## Where next Five ways in. Each one names pages that exist in this documentation, or says what the repository holds instead. - **Deploying it** — no deployment descriptor and no deployment page were found; how this is deployed cannot be established from this repository alone. - **Understanding the architecture** — [System Overview](system-overview), [Utils](subsystem-src-utils), [Helper](subsystem-src-helper) and [Jsx](subsystem-src-jsx). - **Contributing a change** — [Documentation health](documentation-health) and [docs/CONTRIBUTING.md:1]. - **Reviewing security** — the topics above, starting at [src/middleware/basic-auth/index.ts:80]. - **Extending it** — [Middleware](subsystem-src-middleware). ## Before you rely on it Each item is something the evidence for this snapshot raises, not a generic release checklist. - 38 of 40 HTTP endpoints [census] declare no guard or middleware [parsed surface] — check that against what the surface is meant to expose. - No test file was found in the parsed corpus — nothing here runs a check before a release. ## How this page was assembled Every count above is read from the evidence census computed for this snapshot; every other claim points at a file and a line you can open. The census covers 814 entities and 430 relationships across 9 parts [census], and it passed its own independent recount [census]. # DetailedError **Kind:** Class **Source:** [`src/client/fetch-result-please.ts`](https://github.com/honojs/hono/blob/main/src/client/fetch-result-please.ts#L46) **Part of:** [Client](subsystem-src-client) **Extends:** `Error` ## Properties | Property | Type | |---|---| | `detail` | `any` | | `code` | `any` | | `log` | `any` | | `statusCode` | `any` | ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `mergePath` — `src/client/utils.ts`:11 # getBunServer **Kind:** Function **Source:** [`src/adapter/bun/server.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/server.ts#L13) **Part of:** [Adapter](subsystem-src-adapter) Get Bun Server Object from Context `getBunServer` reads the Bun `Server` instance from a request context created by the Bun adapter. Use it inside route handlers when server-level Bun APIs are needed alongside normal Hono context methods. ## Signature ```ts function getBunServer(c: Context): T | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | **Returns:** `T | undefined` ## Diagram ```mermaid graph LR BunServer[Bun Server] --> BunAdapter[Bun adapter serve()] BunAdapter --> Context[Hono Context] Context --> GetServer[getBunServer] GetServer --> ServerApi[Bun Server APIs] ``` ## Usage ```ts import { Hono } from 'hono' import { getBunServer, serve } from 'hono/bun' const app = new Hono() app.get('/server', (c) => { const server = getBunServer(c) return c.json({ hostname: server.hostname, port: server.port, }) }) serve({ fetch: app.fetch, }) ``` ## AI Coding Instructions - Call `getBunServer(c)` from handlers that receive a Hono `Context`. - Run the application through the Bun adapter so the active server is available on the context. - Keep Bun-specific server operations in Bun adapter routes or modules. - Do not use this function in handlers shared with non-Bun adapters. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `getConnInfo` — `src/adapter/bun/conninfo.ts`:10 - `BunServerWebSocket` — `src/adapter/bun/websocket.ts`:8 # html **Kind:** Function **Source:** [`src/helper/html/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/html/index.ts#L11) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function html(strings: TemplateStringsArray, values: unknown[]): HtmlEscapedString | Promise ``` ## Parameters | Name | Type | |---|---| | `strings` | `TemplateStringsArray` | | `values` | `unknown[]` | **Returns:** `HtmlEscapedString | Promise` ## Relationships - IMPORTS → `escapeToBuffer` - IMPORTS → `raw` - IMPORTS → `resolveCallbackSync` - IMPORTS → `stringBufferToString` ## Used by 11 references from 9 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (11) - `RequestContext` — `src/middleware/jsx-renderer/index.ts`:14 - `RequestContext` — `src/middleware/jsx-renderer/index.ts`:14 - `createCssContext` — `src/helper/css/index.ts`:72 - `defaultPlugin` — `src/helper/ssg/plugins.ts`:11 - `Props` — `src/jsx/base.ts`:27 - `childrenToString` — `src/jsx/components.ts`:14 - `Context` — `src/jsx/context.ts`:8 - `title` — `src/jsx/intrinsic-element/components.ts`:121 …and 3 more. # HTTPException **Kind:** Class **Source:** [`src/http-exception.ts`](https://github.com/honojs/hono/blob/main/src/http-exception.ts#L46) `HTTPException` must be used when a fatal error such as authentication failure occurs. `HTTPException` represents a fatal HTTP failure, such as an authentication error. Throw it when request handling must stop and an existing `Response` should be returned to the caller. **Extends:** `Error` ## Methods | Method | Signature | Returns | |---|---|---| | `getResponse` | `getResponse()` | `Response` | ## Properties | Property | Type | |---|---| | `res` | `Response` | | `status` | `ContentfulStatusCode` | ## Diagram ```mermaid graph LR A[Request handler] --> B{Fatal HTTP error?} B -- Yes --> C[Create Response] C --> D[Throw HTTPException] D --> E[getResponse] E --> F[Return Response] B -- No --> G[Continue handling] ``` ## Usage ```ts import { HTTPException } from './http-exception' function requireAuthentication(token?: string): void { if (!token) { const response = new Response('Unauthorized', { status: 401, headers: { 'content-type': 'text/plain', }, }) throw new HTTPException(response) } } async function handleRequest(request: Request): Promise { try { requireAuthentication(request.headers.get('authorization') ?? undefined) return new Response('OK') } catch (error) { if (error instanceof HTTPException) { return error.getResponse() } throw error } } ``` ## AI Coding Instructions - Throw `HTTPException` only for fatal request failures that already have a `Response` to return. - Build the response status, headers, and body before creating the exception. - Catch `HTTPException` at the request-handling boundary and return `getResponse()`. - Do not replace unrelated runtime errors with `HTTPException`; allow unexpected errors to follow normal error handling. ## Used by 12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (12) - `handler` — `src/middleware/basic-auth/index.ts`:118 - `bearerAuth` — `src/middleware/bearer-auth/index.ts`:104 - `handler` — `src/middleware/body-limit/index.ts`:72 - `csrf` — `src/middleware/csrf/index.ts`:94 - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 - `headerName` — `src/middleware/jwk/jwk.ts`:81 - `headerName` — `src/middleware/jwt/jwt.ts`:81 - `HTTPExceptionFunction` — `src/middleware/timeout/index.ts`:10 …and 4 more. # match **Kind:** Function **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L10) **Part of:** [Router](subsystem-src-router) ## Signature ```ts function match(this: R, method: string, path: string): Result ``` ## Parameters | Name | Type | |---|---| | `this` | `R` | | `method` | `string` | | `path` | `string` | **Returns:** `Result` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `PreparedRegExpRouter` — `src/router/reg-exp-router/prepared-router.ts`:9 - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 # resolveCallback **Kind:** Function **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L142) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function resolveCallback(str: string | HtmlEscapedString | Promise, phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase], preserveCallbacks: boolean, context: object, buffer: [string]): Promise ``` ## Parameters | Name | Type | |---|---| | `str` | `string | HtmlEscapedString | Promise` | | `phase` | `(typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]` | | `preserveCallbacks` | `boolean` | | `context` | `object` | | `buffer` | `[string]` | **Returns:** `Promise` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `Data` — `src/context.ts`:26 - `SSEMessage` — `src/helper/streaming/sse.ts`:6 - `childrenToString` — `src/jsx/components.ts`:14 - `StreamingContext` — `src/jsx/streaming.ts`:30 # serveStatic **Kind:** Function **Source:** [`src/middleware/serve-static/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/serve-static/index.ts#L35) **Part of:** [Middleware](subsystem-src-middleware) This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun. `serveStatic` contains the shared static-file middleware flow. Runtime adapters wrap it with an environment-specific `getContent()` implementation, such as one backed by Deno or Bun file APIs. ## Signature ```ts function serveStatic(options: ServeStaticOptions & { getContent: (path: string, c: Context) => Promise join?: (...paths: string[]) => string pathResolve?: (path: string) => string isDir?: (path: string) => boolean | undefined | Promise }): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `ServeStaticOptions & { getContent: (path: string, c: Context) => Promise join?: (...paths: string[]) => string pathResolve?: (path: string) => string isDir?: (path: string) => boolean | undefined | Promise }` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[serveStatic middleware] Middleware --> Path[Resolve requested path] Path --> GetContent[getContent callback] GetContent --> Content[File content or response] Content --> Response[HTTP response] ``` ## Usage ```ts import { Hono } from 'hono' import { serveStatic } from 'hono/serve-static' const app = new Hono() app.use( '*', serveStatic({ root: './public', getContent: async (path) => { try { return await Deno.readFile(path) } catch { return null } }, }) ) export default app ``` ## AI Coding Instructions - Keep `serveStatic` runtime-neutral; place Deno, Bun, or other file-system calls in an adapter through `getContent()`. - Return `null` when a requested file does not exist so later middleware or route handling can continue. - Preserve the requested-path and response handling flow when changing static-file behavior. - Use the runtime-specific static middleware wrapper when one exists instead of calling this shared implementation directly. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `serveStatic` — `src/adapter/bun/serve-static.ts`:8 - `ServeStaticOptions` — `src/adapter/cloudflare-workers/serve-static.ts`:6 - `serveStatic` — `src/adapter/deno/serve-static.ts`:8 # Hono (narrator proof) ## Overview Auto-generated technical documentation for **Hono (narrator proof)** — 814 entities (291 functions, 191 types, 102 doc comments, 72 constants). ## Entry Points - `ALL /` → handler - `GET /content-length` → handler - `GET /Cache-Control` → handler - `GET /` → header - `GET /Cache-Control` → handler - `GET /` → directive - `GET /Vary` → handler - `PUT /` → res - `PUT /` → res - `GET /Content-Type` → handler - `GET /Content-Type` → handler - `GET /Content-Length` → handler - `GET /Vary` → handler - `DELETE /Content-Length` → handler - `GET /ETag` → handler - `GET /Cache-Control` → handler - `DELETE /Content-Length` → handler - `DELETE /Content-Type` → handler - `GET /ETag` → handler - `DELETE /` → key - `GET /` → headerName - `GET /` → headerName - `GET /` → handler - `DELETE /Allow` → handler - `DELETE /Content-Length` → handler - `GET /` → methodFormName - `DELETE /` → methodFormName - `DELETE /content-type` → handler - `DELETE /content-length` → handler - `DELETE /` → headerName ## Key Components _The most-referenced entities — start here._ - **HTTPException** (class) — referenced 12× - **html** (function) — referenced 11× - **METHOD_NAME_ALL** (constant) — referenced 10× - **useContext** (function) — referenced 7× - **DOM_RENDERER** (constant) — referenced 6× - **UnsupportedPathError** (class) — referenced 4× - **getCookie** (function) — referenced 4× - **decodeBase64** (function) — referenced 4× - **HtmlEscapedCallbackPhase** (constant) — referenced 4× - **resolveCallback** (function) — referenced 4× ## Subsystems Ordered by how much of the rest of the system depends on them, not by how much code they contain. A small module many things import shapes this codebase more than a large one nothing imports. | Subsystem | Depended on by | Entities | Starts at | |---|---|---|---| | **Utils** | 6 | 148 | `Accept`, `parseAccept` | | **Helper** | 5 | 109 | `Accept`, `acceptsConfig` | | **Jsx** | 2 | 147 | `RenderToStringOptions`, `RenderToReadableStreamOptions` | | **Middleware** | 1 | 110 | `handler`, `handler` | | **Client** | 1 | 25 | `BuildSearchParamsFn`, `ClientRequestOptions` | | **Docs** | 0 | 73 | `Contributor Covenant Code of Conduct`, `Contribution Guide` | | **Adapter** | 0 | 71 | `getConnInfo`, `LambdaEvent` | | **Router** | 0 | 21 | `LinearRouter`, `PatternRouter` | `Client`, `Docs` depend on no other subsystem here — they are the leaves. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `use*` | exported symbols | 23 | `useId`, `useRef`, `useMemo`, `useState` | | `create*` | exported symbols | 17 | `createRef`, `createBody`, `createRoot`, `createPool` | | `jsx*` | exported symbols | 6 | `jsxFn`, `jsxDEV`, `jsxAttr`, `jsxEscape` | | `build*` | exported symbols | 5 | `buildNode`, `buildDataStack`, `buildInitParams`, `buildStyleString` | | `parse*` | exported symbols | 5 | `parseBody`, `parseAccept`, `parseSigned`, `parseResponse` | | `serve*` | exported symbols | 5 | `serveStatic` | # useContext **Kind:** Function **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L259) **Part of:** [Jsx](subsystem-src-jsx) Read the current value of a context created with createContext. Safe to call from async components after `await`. See createContext for the per-runtime isolation guarantees. `useContext` reads the current value from a context created with `createContext`. It can be called in synchronous or asynchronous components, including after an `await`, while keeping context values isolated per runtime. ## Signature ```ts function useContext(context: Context): T ``` ## Parameters | Name | Type | |---|---| | `context` | `Context` | **Returns:** `T` ## Diagram ```mermaid graph LR A[createContext] --> B[Context] B --> C[Context.Provider] C --> D[Component] D --> E[useContext] E --> F[Current context value] ``` ## Usage ```tsx import { createContext, useContext } from 'hono/jsx' const ThemeContext = createContext('light') const ThemeLabel = async () => { await Promise.resolve() const theme = useContext(ThemeContext) return Theme: {theme} } const App = () => ( ) ``` ## AI Coding Instructions - Create contexts with `createContext` before reading them with `useContext`. - Pass the context object returned by `createContext` directly to `useContext`. - Read context inside a component that is rendered below the matching `Context.Provider`. - `useContext` may run after `await` in an async component. ## Used by 7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (7) - `Props` — `src/jsx/base.ts`:27 - `childrenToString` — `src/jsx/components.ts`:14 - `FormContext` — `src/jsx/dom/hooks/index.ts`:24 - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `title` — `src/jsx/intrinsic-element/components.ts`:121 - `StreamingContext` — `src/jsx/streaming.ts`:30 # Utils ## What it is responsible for Utils turns request-facing and low-level values into reusable forms for the rest of the codebase. Its named entry points, `Accept`, `parseAccept`, `Auth`, and `auth`, mark where work enters; related members cover body parsing, cookies, binary-address conversion, MIME/type [helpers](subsystem-src-helper), URI decoding, and terminal-color decisions. `COMPRESSIBLE_CONTENT_TYPE_REGEX` marks a content-type-oriented rule, while `COMPOSED_HANDLER` is explicitly a marker for a composed handler. The subsystem also owns shared type-level shaping: JSON-compatible conversion, flattened editor hints, deep array traversal, and string-literal completion types. ## What it needs, and who needs it Utils needs `Helper`, its only stated dependency. `src/router`, `src/middleware`, `Adapter`, `Helper`, `src/jsx`, and `src/validator` need Utils. Without Utils, those consumers lose access to the named shared entry points and helpers they depend on, including `parseBody`, `Cookie`, and `getColorEnabled`; the supplied evidence does not identify narrower failure modes or Helper’s specific role. ## Notable members `parseBody` is the body-parsing member, paired with `ParseBodyOptions` and `BodyData`. `Cookie`, `SignedCookie`, and `CookieOptions` group parsing and serialization through `parse`, `parseSigned`, and `serialize`. `getColorEnabled` and `getColorEnabledAsync` report whether color change on a terminal is enabled or disabled. Address conversion helpers turn IPv4 and IPv6 values into Uint8Array forms and binary representations back into strings, including detection and extraction for IPv4-mapped IPv6 addresses. 148 entities in `src/utils`. **6 other subsystems depend on it**, which makes it the most depended-upon part of this codebase. ## What it is made of Its 148 entities sit in 27 files under `src/utils`: 60 functions, 57 type aliases, 16 classes, 9 constants and 6 more. `types.ts` holds 19 of them — more than any other file here. `StreamingApi` declares 7 methods, the widest surface here. ## Where work enters - [`Accept`](interface-accept) — `src/utils/accept.ts`:1 - [`parseAccept`](function-parseaccept) — `src/utils/accept.ts`:211 - [`Auth`](type-auth) — `src/utils/basic-auth.ts`:7 - [`auth`](function-auth) — `src/utils/basic-auth.ts`:9 ## How it refuses and fails 1 of its components records a refusal or a failure handler. Its `catch` blocks handle a failure that already happened in 2 places. `StreamingApi` holds 2 of the silent ones — a failure discarded silently leaves no trace for whoever debugs this later. ## Boundaries **6 other subsystems depend on this one** — `Router`, `Middleware`, `Adapter`, `Helper`, `Jsx`, `Validator`. Changing what it exposes changes them. Those 6 hold 65 edges between them, unevenly: `Helper` reaches in across 23 edges, while another holds one. 65 edges arrive against 1 leaving — more of this repository reaches into it than it reaches out to. What they reach is narrower than the folder: 40 of its 148 members carry every inbound edge — `escapeToBuffer` (4), `checkOptionalParameter` (3) and `parseAccept` (3), plus 37 more. It depends on `Helper`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `convert*` | exported symbols | 5 | `convertIPv4ToBinary`, `convertIPv6ToBinary`, `convertIPv4BinaryToString`, `convertIPv6BinaryToString` | # Documentation health 706 symbols have a reference page in this documentation. This page says how each of them came to be described, because "documented" covers four situations a reader should not have to treat alike. ## Where the descriptions come from | | Symbols | What it means for a reader | |---|---:|---| | Written by the author | 129 of 706 | A doc comment in the source. Nothing generated improves on this. | | Generated, with citations | 31 of 706 | Points at specific `file:line` ranges you can open and check. | | Generated, without citations | 38 of 706 | Often right, but nothing anchors it. Treat as a starting point. | | Not described | 508 of 706 | The page shows structure only — signature, members, references. | **160 of 706 descriptions can be checked against source** — 129 because the author wrote them next to the code, 31 because the generator cited the lines it read. The rest are shown, and marked, for what they are. ## Why there is no coverage percentage A percentage counts whether a comment exists, so the cheapest way to raise it is to add empty ones. SonarQube withdrew its comment-density metric over this; studies of "covered" API documentation classify 43–51% of it as carrying no information; and a missing-comment warning has been measured producing 1,774 junk comments in a single codebase. The counts above cannot be moved that way — a doc comment that only restates the symbol name is not counted as one. ## Where the gaps are Undescribed symbols by the part of the system they sit in — worst first, so the next unit of documentation effort has an address. This is the table to bring to planning. | Area | Undescribed | Of | Share | |---|---:|---:|---:| | [`src/jsx`](subsystem-src-jsx) | 131 | 147 | 89% | | [`src/utils`](subsystem-src-utils) | 122 | 148 | 82% | | [`src/helper`](subsystem-src-helper) | 79 | 109 | 72% | | [`src/middleware`](subsystem-src-middleware) | 62 | 110 | 56% | | `src/types.ts` | 37 | 41 | 90% | | [`src/adapter`](subsystem-src-adapter) | 36 | 71 | 51% | | [`src/client`](subsystem-src-client) | 19 | 25 | 76% | | [`src/router`](subsystem-src-router) | 11 | 21 | 52% | | `src/validator` | 4 | 6 | 67% | | `src/context.ts` | 2 | 9 | 22% | | `src/preset` | 2 | 2 | 100% | | `src/router.ts` | 1 | 10 | 10% | | `src/hono-base.ts` | 1 | 1 | 100% | | `src/request` | 1 | 1 | 100% | ## What can be checked A claim on these pages is anchored when it points at something a reader can open: a `file:line` range in the source, or a `[census]` tag naming the arithmetic behind a number. Anything else is prose you would have to take on trust. These counts say which is which. They do not say the anchored claims are right — only that they can be checked. | | Count | What it means | |---|---:|---| | Pages read by this audit | 717 [census] | Every page in the set as it stood before this section was written. This section's own claims are not counted below. | | Pages carrying an anchored claim | 38 of 717 [census] | The page points at source or at a census at least once. | | Anchored claims | 829 [census] | One per `file:line` reference and per census tag. Brackets inside code samples are code, and are not counted. | | … pointing at source | 814 of 829 [census] | A path and a line you can open. | | … pointing at a census | 15 of 829 [census] | A number computed before anything was written. | Whether those citations land in files that exist was NOT CHECKED for this build: the audit was given no way to look a path up. The count above is of citations made, not of citations verified — and reporting them as sound on that basis would be the invention this page exists to catch. Every count in this section and the two below is arithmetic over these pages, redone on each build; `[census]` marks a figure read from that arithmetic rather than written by hand. ## Where the docs and the code disagree One lint reads every page for a single pattern: a sentence stating runtime behaviour — what listens, what validates, what retries — whose only evidence is a prose document. A README saying the server listens on a port is testimony ABOUT the code, not the behaviour itself, and a sentence citing it for the behaviour has quietly turned one into the other. The honest forms either cite the source that listens, or keep the attribution in the sentence. 1 of 717 pages carries a sentence like that, 4 sentences in all [census]. Each is quoted below exactly as written, with the page it is on and the document it leans on. This lint flags innocent sentences and misses guilty ones — it is a list to review, not a list of errors. ```text page: Docs (subsystem-docs) cites: docs/CONTRIBUTING.md claim: [docs/CONTRIBUTING.md:27-31] Dependency setup then runs `bun install --frozen-lockfile`, and the local-development example combines cloning the repository, changing into it, and running that same install command. ``` ```text page: Docs (subsystem-docs) cites: docs/MIGRATION.md claim: [docs/MIGRATION.md:39-49] Other changes in that same upgrade include a changed default for JSX renderer `docType`, the absence of `children` from `FC`, removed MIME types, and type-sensitive route and validator chaining. ``` ```text page: Docs (subsystem-docs) cites: docs/MIGRATION.md claim: [docs/MIGRATION.md:76-103] For Cloudflare Workers, the guide marks `serveStatic` in Service Worker mode obsolete, identifies that mode with `app.fire()`, and recommends Module Worker mode using `export default app`. ``` ```text page: Docs (subsystem-docs) cites: docs/CODE_OF_CONDUCT.md claim: [docs/CODE_OF_CONDUCT.md:39-44] They may remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that do not align with the policy, and they communicate moderation reasons when appropriate. ``` ## What we have not written yet The evidence census lists, for each part of this repository, the reader-topics that part's contents warrant: a part holding database models owes its readers a data model however few models it holds. This section holds that list against the headings the pages for each part actually carry. Every topic the census says this repository warrants — 19 [census] across 9 parts — has a page carrying a heading that answers for it. That is a statement about headings, not about depth: a section can exist and still be thin. A topic counts as written when any page for its part carries a heading naming it — "Fields" answers for a data model, "Endpoint" for an API surface, "Dependencies" for wiring. The match is deliberately loose in that direction: a topic covered under a heading nobody predicted must not be reported as missing, so the error this makes is silence, never a false accusation of absence. 3 pages name no source path [census], so they were matched to no part and can cover no topic above — the pages about this documentation itself are among them. # DOM_RENDERER **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L1) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('RENDERER') ``` ## Value ```ts Symbol('RENDERER') ``` ## Used by 6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (6) - `createCssContext` — `src/helper/css/index.ts`:72 - `Props` — `src/jsx/base.ts`:27 - `childrenToString` — `src/jsx/components.ts`:14 - `Context` — `src/jsx/context.ts`:8 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `StreamingContext` — `src/jsx/streaming.ts`:30 # escapeToBuffer **Kind:** Function **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L90) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function escapeToBuffer(str: string, buffer: StringBuffer): void ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | | `buffer` | `StringBuffer` | **Returns:** `void` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `createCssContext` — `src/helper/css/index.ts`:72 - `html` — `src/helper/html/index.ts`:11 - `Props` — `src/jsx/base.ts`:27 - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 # fetchRP **Kind:** Function **Source:** [`src/client/fetch-result-please.ts`](https://github.com/honojs/hono/blob/main/src/client/fetch-result-please.ts#L14) **Part of:** [Client](subsystem-src-client) Smartly parses and return the consumable result from a fetch `Response`. Throwing a structured error if the response is not `ok`. (DetailedError) `fetchRP` accepts a Fetch API `Response` and parses it into a value callers can consume. If the response is not `ok`, it throws a `DetailedError` so request code can handle failures through a single error path. ## Signature ```ts async function fetchRP(fetchRes: Response | Promise): Promise ``` ## Parameters | Name | Type | |---|---| | `fetchRes` | `Response | Promise` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[fetch request] --> B[Response] B --> C[fetchRP] C --> D{response.ok} D -->|true| E[Parsed result] D -->|false| F[DetailedError] ``` ## Usage ```ts import { fetchRP } from './client/fetch-result-please'; async function loadProfile() { const response = await fetch('/api/profile'); try { const profile = await fetchRP(response); return profile; } catch (error) { console.error('Profile request failed:', error); throw error; } } ``` ## AI Coding Instructions - Pass the original `Response` to `fetchRP` before reading its body with `json()`, `text()`, or similar methods. - Await `fetchRP`, since parsing the response body is asynchronous. - Handle errors around `fetchRP`; non-`ok` responses throw `DetailedError`. - Keep request code focused on making the fetch call and let `fetchRP` decide how to parse the response. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `mergePath` — `src/client/utils.ts`:11 # generateDigest **Kind:** Function **Source:** [`src/middleware/etag/digest.ts`](https://github.com/honojs/hono/blob/main/src/middleware/etag/digest.ts#L18) **Part of:** [Middleware](subsystem-src-middleware) ## Signature ```ts async function generateDigest(stream: ReadableStream> | null, generator: (body: Uint8Array) => ArrayBuffer | Promise): Promise ``` ## Parameters | Name | Type | |---|---| | `stream` | `ReadableStream> | null` | | `generator` | `(body: Uint8Array) => ArrayBuffer | Promise` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `handler` — `src/middleware/etag/index.ts`:97 # getContentFromKVAsset **Kind:** Function **Source:** [`src/adapter/cloudflare-workers/utils.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/utils.ts#L11) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts async function getContentFromKVAsset(path: string, options: KVAssetOptions): Promise ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | | `options` | `KVAssetOptions` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ServeStaticOptions` — `src/adapter/cloudflare-workers/serve-static.ts`:6 # getCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L27) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function getCookie(c, key, prefix: CookiePrefixOptions) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | | `key` | `any` | | `prefix` | `CookiePrefixOptions` | ## Relationships - IMPORTS → `parse` - IMPORTS → `parseSigned` - IMPORTS → `serialize` - IMPORTS → `serializeSigned` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `headerName` — `src/middleware/jwk/jwk.ts`:81 - `headerName` — `src/middleware/jwt/jwt.ts`:81 - `DetectorType` — `src/middleware/language/language.ts`:10 - `ValidationFunction` — `src/validator/validator.ts`:14 # METHOD_NAME_ALL **Kind:** Constant **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L9) ## Definition ```ts 'ALL' as const ``` ## Value ```ts 'ALL' as const ``` ## Used by 10 references from 10 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (10) - `LinearRouter` — `src/router/linear-router/router.ts`:11 - `PatternRouter` — `src/router/pattern-router/router.ts`:8 - `HandlerData` — `src/router/reg-exp-router/matcher.ts`:4 - `PreparedRegExpRouter` — `src/router/reg-exp-router/prepared-router.ts`:9 - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 - `Node` — `src/router/trie-router/node.ts`:25 - `some` — `src/middleware/combine/index.ts`:38 - `handler` — `src/middleware/method-not-allowed/index.ts`:133 …and 2 more. # RegExpRouter **Kind:** Class **Source:** [`src/router/reg-exp-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/router.ts#L47) **Part of:** [Router](subsystem-src-router) `RegExpRouter` stores method and path registrations, then builds regular-expression matchers for route lookup. It is a router implementation used by the application to map incoming request paths to registered handlers. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `#insertPath` | `#insertPath(method: string, path: string)` | `void` | | `add` | `add(method: string, path: string, handler: T)` | `void` | | `buildAllMatchers` | `buildAllMatchers()` | `MatcherMap` | | `#buildMatcher` | `#buildMatcher(method: string)` | `Matcher` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#middleware` | `Record[]>>` | | `#routes` | `Record[]>>` | | `#tries` | `Record` | | `match` | `typeof match, T>` | ## Where it refuses work - `RegExpRouter` stops the work with `Error` when `!middleware || !routes`. ## When something fails - `RegExpRouter` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR App[Application] --> Add[add()] Add --> Insert["#insertPath()"] Insert --> Routes[Route definitions] Routes --> BuildAll["buildAllMatchers()"] BuildAll --> Build["#buildMatcher()"] Build --> Matchers["MatcherMap"] ``` ## Usage ```ts import { Hono } from 'hono' import { RegExpRouter } from 'hono/router/reg-exp-router' const router = new RegExpRouter() const app = new Hono({ router }) app.get('/users/:id', (c) => { return c.json({ id: c.req.param('id'), }) }) app.post('/users', async (c) => { const body = await c.req.json() return c.json(body) }) export default app ``` ## AI Coding Instructions - Register routes through `add()` or the application routing API; do not call private methods such as `#insertPath()` directly. - Keep route method and path patterns consistent, since matcher generation groups routes by HTTP method. - Update `#buildMatcher()` when changing how path parameters or route patterns are translated into regular expressions. - Preserve the `MatcherMap` contract when modifying `buildAllMatchers()`, because request matching depends on its generated matchers. ## Relationships - IMPORTS → `MESSAGE_MATCHER_IS_ALREADY_BUILT` - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `UnsupportedPathError` - IMPORTS → `checkOptionalParameter` - IMPORTS → `match` - IMPORTS → `emptyParam` - IMPORTS → `PATH_ERROR` - IMPORTS → `Trie` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `PreparedRegExpRouter` — `src/router/reg-exp-router/prepared-router.ts`:9 # decodeBase64 **Kind:** Function **Source:** [`src/utils/encode.ts`](https://github.com/honojs/hono/blob/main/src/utils/encode.ts#L25) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function decodeBase64(str: string): Uint8Array ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | **Returns:** `Uint8Array` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `LambdaEvent` — `src/adapter/aws-lambda/handler.ts`:23 - `CloudFrontRequest` — `src/adapter/lambda-edge/handler.ts`:41 - `Auth` — `src/utils/basic-auth.ts`:7 - `HonoJsonWebKey` — `src/utils/jwt/jws.ts`:23 # defaultJoin **Kind:** Function **Source:** [`src/middleware/serve-static/path.ts`](https://github.com/honojs/hono/blob/main/src/middleware/serve-static/path.ts#L5) **Part of:** [Middleware](subsystem-src-middleware) `defaultJoin` does not support Windows paths and always uses `/` separators. If you need Windows path support, please use `join` exported from `node:path` etc. instead. `defaultJoin` combines path segments for the static-file middleware using `/` separators. It is intended for URL-style or POSIX-style paths and does not support Windows path conventions; use `join` from `node:path` when Windows support is needed. ## Signature ```ts function defaultJoin(paths: string[]): string ``` ## Parameters | Name | Type | |---|---| | `paths` | `string[]` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Path segments] --> B[defaultJoin] B --> C[Slash-normalized path] C --> D[Static file lookup] ``` ## Usage ```ts import { defaultJoin } from './path' const filePath = defaultJoin('/public/', '/assets', 'app.js') console.log(filePath) // /public/assets/app.js ``` ## AI Coding Instructions - Keep path segments in URL or POSIX format when calling `defaultJoin`. - Do not use `defaultJoin` for Windows filesystem paths. - Use `join` from `node:path` when the runtime must support platform-specific separators. - Pass the joined result into static-file path resolution rather than manually concatenating segments. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ServeStaticOptions` — `src/middleware/serve-static/index.ts`:13 # emptyParam **Kind:** Constant **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L9) **Part of:** [Router](subsystem-src-router) ## Definition ```ts string[] ``` ## Value ```ts [] ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `PreparedRegExpRouter` — `src/router/reg-exp-router/prepared-router.ts`:9 - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 # EventProcessor **Kind:** Class **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L278) **Part of:** [Adapter](subsystem-src-adapter) `EventProcessor` adapts an AWS Lambda API Gateway event into a standard `Request` and converts the processed response into an `APIGatewayProxyResult`. It reads request path, method, query parameters, headers, cookies, and domain data while applying response headers and cookies to the Lambda result. ## Methods | Method | Signature | Returns | |---|---|---| | `getPath` | `getPath(event: E)` | `string` | | `getMethod` | `getMethod(event: E)` | `string` | | `getQueryString` | `getQueryString(event: E)` | `string` | | `getHeaders` | `getHeaders(event: E)` | `Headers` | | `getCookies` | `getCookies(event: E, headers: Headers)` | `void` | | `setCookiesToResult` | `setCookiesToResult(result: APIGatewayProxyResult, cookies: string[])` | `void` | | `getHeaderValue` | `getHeaderValue(headers: E['headers'], key: string)` | `string | undefined` | | `getDomainName` | `getDomainName(event: E)` | `string | undefined` | | `createRequest` | `createRequest(event: E)` | `Request` | | `createResult` | `createResult(event: E, res: Response, options: Pick)` | `Promise` | | `setCookies` | `setCookies(_event: E, res: Response, result: APIGatewayProxyResult)` | `void` | ## Where it refuses work - `EventProcessor` stops the work with an early return when `event.requestContext && 'domainName' in event.requestContext`. - `EventProcessor` stops the work with an early return when `hostFromHeaders`. ## Diagram ```mermaid graph LR Event[API Gateway event] --> Processor[EventProcessor] Processor --> Request[Request] Request --> Handler[Application handler] Handler --> Response[Response] Response --> Processor Processor --> Result[APIGatewayProxyResult] ``` ## Usage ```ts import { EventProcessor } from "./adapter/aws-lambda/handler"; async function handleInvocation(processor: EventProcessor) { const request = processor.createRequest(); const response = await app.fetch(request); response.headers.forEach((value, name) => { // Apply response headers through the processor integration. processor.getHeaders().set(name, value); }); return processor.createResult(); } ``` ## AI Coding Instructions - Keep AWS event parsing inside `EventProcessor`; pass `createRequest()` output to application code that expects a standard `Request`. - Read request metadata through `getPath()`, `getMethod()`, `getQueryString()`, `getHeaders()`, and `getDomainName()` instead of accessing event fields in downstream handlers. - Preserve cookie handling through `getCookies()` and `setCookiesToResult()` so Lambda response cookies are emitted in the expected result format. - Return the value from `createResult()` at the Lambda boundary, where an `APIGatewayProxyResult` is required. ## How it works `EventProcessor` is an exported abstract base class for translating one of the supported AWS Lambda event shapes into a Web `Request`, and translating a Web `Response` into an `APIGatewayProxyResult`. Its generic event type `E` must extend the `LambdaEvent` union of API Gateway v1, API Gateway v2, ALB, and Lattice v2 events. [src/adapter/aws-lambda/handler.ts:23-27](src/adapter/aws-lambda/handler.ts#L23-L27) [src/adapter/aws-lambda/handler.ts:278-278](src/adapter/aws-lambda/handler.ts#L278) Concrete subclasses must define how to extract a path, HTTP method, query string, headers, cookies, and response cookies for their event shape. [src/adapter/aws-lambda/handler.ts:279-289](src/adapter/aws-lambda/handler.ts#L279-L289) # replaceUrlParam **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L18) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function replaceUrlParam(urlString: string, params: Record) ``` ## Parameters | Name | Type | |---|---| | `urlString` | `string` | | `params` | `Record` | ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # styleObjectForEach **Kind:** Function **Source:** [`src/jsx/utils.ts`](https://github.com/honojs/hono/blob/main/src/jsx/utils.ts#L169) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function styleObjectForEach(style: Record, fn: (key: string, value: string | null) => void): void ``` ## Parameters | Name | Type | |---|---| | `style` | `Record` | | `fn` | `(key: string, value: string | null) => void` | **Returns:** `void` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `Props` — `src/jsx/base.ts`:27 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 # UnsupportedPathError **Kind:** Class **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L103) Error class representing an unsupported path error. `UnsupportedPathError` represents a path that the router cannot handle. It lets routing callers distinguish unsupported-path failures from other errors and return an appropriate response. **Extends:** `Error` ## Diagram ```mermaid graph LR RequestPath[Requested path] --> Router Router -->|Path is unsupported| UnsupportedPathError UnsupportedPathError --> Caller[Route caller or error handler] ``` ## Usage ```ts import { UnsupportedPathError } from "./router"; try { const result = resolveRoute(requestPath); return result; } catch (error) { if (error instanceof UnsupportedPathError) { return { status: 404, message: "The requested path is not supported.", }; } throw error; } ``` ## AI Coding Instructions - Throw `UnsupportedPathError` when router path validation determines that a path cannot be handled. - Check errors with `instanceof UnsupportedPathError` instead of matching error-message text. - Handle this error at the router boundary or request handler where an unsupported path can be mapped to an application response. - Do not replace this error with a generic `Error` when callers need to distinguish routing failures. ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `LinearRouter` — `src/router/linear-router/router.ts`:11 - `PatternRouter` — `src/router/pattern-router/router.ts`:8 - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 - `SmartRouter` — `src/router/smart-router/router.ts`:4 # WSContext **Kind:** Class **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L70) **Part of:** [Helper](subsystem-src-helper) A context for controlling WebSockets `WSContext` is a context object for controlling a WebSocket connection. It exposes methods to send through the connection and close it when the connection should end. ## Methods | Method | Signature | Returns | |---|---|---| | `send` | `send(source: string | ArrayBuffer | Uint8Array, options: SendOptions)` | `void` | | `close` | `close(code: number, reason: string)` | `void` | ## Properties | Property | Type | |---|---| | `#init` | `WSContextInit` | | `raw` | `T` | | `binaryType` | `BinaryType` | | `url` | `URL | null` | | `protocol` | `string | null` | ## Diagram ```mermaid graph LR Handler[WebSocket handler] --> Context[WSContext] Context --> Send[send()] Context --> Close[close()] Send --> Socket[WebSocket connection] Close --> Socket ``` ## Usage ```ts import type { WSContext } from './helper/websocket' function handleWebSocket(context: WSContext) { context.send() // Close the connection when no further messages should be sent. context.close() } ``` ## AI Coding Instructions - Treat `WSContext` as the interface for sending through and closing the active WebSocket connection. - Call `send()` only while the connection is expected to remain open. - Call `close()` when the handler has finished with the connection. - Pass the existing `WSContext` through WebSocket handling code instead of creating alternate connection controls. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `BunServerWebSocket` — `src/adapter/bun/websocket.ts`:8 - `upgradeWebSocket` — `src/adapter/cloudflare-workers/websocket.ts`:5 - `upgradeWebSocket` — `src/adapter/deno/websocket.ts`:4 # ALBProcessor **Kind:** Class **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L503) **Part of:** [Adapter](subsystem-src-adapter) `ALBProcessor` adapts an AWS Application Load Balancer request into request values used by the Lambda handler. It reads headers, path, method, query string, and cookies, then writes response cookies back to the ALB result. **Extends:** `EventProcessor` ## Methods | Method | Signature | Returns | |---|---|---| | `getHeaders` | `getHeaders(event: ALBProxyEvent)` | `Headers` | | `getPath` | `getPath(event: ALBProxyEvent)` | `string` | | `getMethod` | `getMethod(event: ALBProxyEvent)` | `string` | | `getQueryString` | `getQueryString(event: ALBProxyEvent)` | `string` | | `getCookies` | `getCookies(event: ALBProxyEvent, headers: Headers)` | `void` | | `setCookiesToResult` | `setCookiesToResult(result: APIGatewayProxyResult, cookies: string[])` | `void` | ## Diagram ```mermaid graph LR ALB[ALB request event] --> Processor[ALBProcessor] Processor --> Headers[getHeaders()] Processor --> Path[getPath()] Processor --> Method[getMethod()] Processor --> Query[getQueryString()] Processor --> Cookies[getCookies()] Handler[Application handler] --> ResponseCookies[Response cookies] ResponseCookies --> Processor Processor --> Result[ALB response result] Processor --> SetCookies[setCookiesToResult()] ``` ## Usage ```ts import { ALBProcessor } from './adapter/aws-lambda/handler'; export async function handler(event: unknown) { const result = { statusCode: 200, headers: {}, body: '', }; const processor = new ALBProcessor(event, result); const request = { method: processor.getMethod(), path: processor.getPath(), headers: processor.getHeaders(), queryString: processor.getQueryString(), }; processor.getCookies(); result.body = JSON.stringify({ method: request.method, path: request.path, queryString: request.queryString, }); processor.setCookiesToResult(); return result; } ``` ## AI Coding Instructions - Read request metadata through `getHeaders()`, `getPath()`, `getMethod()`, and `getQueryString()` instead of accessing ALB event fields in application code. - Call `getCookies()` before code that depends on request cookies. - Call `setCookiesToResult()` after response cookies have been added and before returning the ALB result. - Keep ALB-specific request and response handling inside this adapter so application handlers remain transport-independent. # ClientResponse **Kind:** Interface **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L128) **Part of:** [Client](subsystem-src-client) `ClientResponse` is the typed response returned by the client layer. It extends the standard response shape with status-aware `ok` values and format-aware body readers such as `json()` and `text()`. ## Properties | Property | Type | |---|---| | `body` | `ReadableStream | null` | | `bodyUsed` | `boolean` | | `ok` | `U extends SuccessStatusCode ? true : U extends Exclude ? false : boolean` | | `redirected` | `boolean` | | `status` | `U` | | `statusText` | `string` | | `type` | `'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'` | | `headers` | `Headers` | | `url` | `string` | ## Diagram ```mermaid graph LR ClientResponse --> Metadata[status, statusText, url, headers] ClientResponse --> Body[body, bodyUsed] ClientResponse --> Status[ok derived from status] ClientResponse --> Readers[json, text, blob, formData, bytes, arrayBuffer] ClientResponse --> ResponseOps[clone, redirect] Readers --> Payload[Typed payload based on response format] ``` ## Usage ```ts type User = { id: string name: string } async function handleUserResponse( response: ClientResponse ) { if (!response.ok) { throw new Error(`Request failed: ${response.status} ${response.statusText}`) } const user = await response.json() console.log(response.url) console.log(user.name) } ``` ## AI Coding Instructions - Preserve the inferred `ClientResponse` type from client route calls so `status`, `ok`, and body reader return types remain specific. - Check `response.ok` or `response.status` before reading a successful payload. - Call `json()` only for JSON response formats; `text()` has separate type behavior for text responses. - A body reader consumes the response body. Use `clone()` before reading when the body must be read again. - Read response metadata from `headers`, `url`, `redirected`, and `statusText` rather than reconstructing it from request state. # defineWebSocketHelper **Kind:** Function **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L111) **Part of:** [Helper](subsystem-src-helper) Create a WebSocket adapter/helper `defineWebSocketHelper` creates the WebSocket adapter used by the helper layer. It centralizes socket connection, message handling, and lifecycle operations behind a shared interface. ## Signature ```ts function defineWebSocketHelper(handler: WebSocketHelperDefineHandler): UpgradeWebSocket ``` ## Parameters | Name | Type | |---|---| | `handler` | `WebSocketHelperDefineHandler` | **Returns:** `UpgradeWebSocket` ## Diagram ```mermaid graph LR App[Application code] --> Helper[defineWebSocketHelper] Helper --> Socket[WebSocket] Socket --> Server[WebSocket server] Server --> Socket Socket --> Helper Helper --> App ``` ## Usage ```ts import { defineWebSocketHelper } from './helper/websocket' const websocket = defineWebSocketHelper({ url: 'wss://example.com/events', }) websocket.connect() websocket.onMessage((message) => { console.log('Received message:', message) }) websocket.send({ type: 'subscribe', channel: 'events', }) window.addEventListener('beforeunload', () => { websocket.close() }) ``` ## AI Coding Instructions - Keep WebSocket-specific behavior inside the helper rather than spreading socket handling across callers. - Close the socket during application teardown to avoid leaving active connections. - Handle connection failures and unexpected close events through the helper’s lifecycle callbacks. - Keep message payload formats aligned with the server protocol before calling `send`. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `BunServerWebSocket` — `src/adapter/bun/websocket.ts`:8 - `upgradeWebSocket` — `src/adapter/cloudflare-workers/websocket.ts`:5 - `upgradeWebSocket` — `src/adapter/deno/websocket.ts`:4 # HonoOptions **Kind:** Type **Source:** [`src/hono-base.ts`](https://github.com/honojs/hono/blob/main/src/hono-base.ts#L46) ## Definition ```ts { strict?: boolean router?: Router<[H, RouterRoute]> getPath?: GetPath } ``` ## Relationships - IMPORTS → `compose` - IMPORTS → `Context` - IMPORTS → `METHODS` - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `METHOD_NAME_ALL_LOWERCASE` - IMPORTS → `COMPOSED_HANDLER` - IMPORTS → `getPath` - IMPORTS → `getPathNoStrict` - IMPORTS → `mergePath` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `Hono` — `src/hono.ts`:16 - `Hono` — `src/preset/quick.ts`:13 - `Hono` — `src/preset/tiny.ts`:11 # HtmlEscapedCallbackPhase **Kind:** Constant **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { Stringify: 1, BeforeStream: 2, Stream: 3, } as const ``` ## Value ```ts { Stringify: 1, BeforeStream: 2, Stream: 3, } as const ``` ## Used by 4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (4) - `Data` — `src/context.ts`:26 - `SSEMessage` — `src/helper/streaming/sse.ts`:6 - `childrenToString` — `src/jsx/components.ts`:14 - `StreamingContext` — `src/jsx/streaming.ts`:30 # Node **Kind:** Class **Source:** [`src/router/trie-router/node.ts`](https://github.com/honojs/hono/blob/main/src/router/trie-router/node.ts#L25) **Part of:** [Router](subsystem-src-router) `Node` is a trie node used by the router to register route handlers and find handlers for an incoming method and path. `insert()` adds handlers along route segments, while `search()` returns matching handler and parameter pairs; `#pushHandlerSets()` maintains the node’s internal handler collections. ## Methods | Method | Signature | Returns | |---|---|---| | `insert` | `insert(method: string, path: string, handler: T)` | `Node` | | `#pushHandlerSets` | `#pushHandlerSets(handlerSets: HandlerParamsSet[], node: Node, method: string, nodeParams: Record, params: Record)` | `void` | | `search` | `search(method: string, path: string)` | `[[T, Params][]]` | ## Properties | Property | Type | |---|---| | `#methods` | `Record>[]` | | `#children` | `Record>` | | `#patterns` | `Pattern[]` | | `#order` | `number` | | `#params` | `Record` | ## Diagram ```mermaid graph LR Registration[Route registration] -->|insert(method, path, handler)| Node[Node] Node --> Literal[Literal child nodes] Node --> Pattern[Parameter or wildcard child nodes] Literal --> HandlerSets[Handler sets] Pattern --> HandlerSets Request[Incoming method and path] -->|search(method, path)| Node HandlerSets --> Matches[Matching handler and params pairs] ``` ## Usage ```ts import { Node } from './src/router/trie-router/node' type Handler = (params: Record) => string const routes = new Node() routes.insert('GET', '/users/:id', (params) => { return `User: ${params.id}` }) const matches = routes.search('GET', '/users/ada') for (const [handler, params] of matches) { console.log(handler(params)) } ``` ## AI Coding Instructions - Keep route registration inside `insert()` so literal, parameter, and wildcard segments are stored consistently. - Use the `Node` generic to keep registered handler types aligned with router dispatch code. - Treat `search()` results as handler and parameter pairs, and handle an empty result when no route matches. - Do not call or expose `#pushHandlerSets()` outside `Node`; it manages internal handler ordering and storage. - Pass route methods and paths in the same format used by the surrounding router integration. ## Relationships - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `getPattern` - IMPORTS → `splitPath` - IMPORTS → `splitRoutingPath` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TrieRouter` — `src/router/trie-router/router.ts`:5 # setMetric **Kind:** Function **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L149) **Part of:** [Middleware](subsystem-src-middleware) Set a metric for the timing middleware. `setMetric` adds a named metric to the timing data associated with the current request context. The timing middleware reads these metrics when producing timing information for the response. ## Signature ```ts function setMetric(c: Context, name: string, valueDescription: number | string | undefined, description: string, precision: number) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `valueDescription` | `number | string | undefined` | | `description` | `string` | | `precision` | `number` | ## Diagram ```mermaid graph LR Request --> TimingMiddleware TimingMiddleware --> Handler Handler --> setMetric setMetric --> RequestMetrics RequestMetrics --> TimingMiddleware TimingMiddleware --> ResponseTiming ``` ## Usage ```ts import { timing, setMetric } from './middleware/timing/timing' app.use('*', timing()) app.get('/reports', async (c) => { const startedAt = performance.now() const report = await loadReport() setMetric(c, 'report_load', performance.now() - startedAt) return c.json(report) }) ``` ## AI Coding Instructions - Register the timing middleware before handlers that call `setMetric`. - Pass the current request context to `setMetric` so the metric is attached to the correct response. - Use stable, descriptive metric names to keep response timing output consistent. - Record metric values in the unit expected by the timing middleware. # useState **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L182) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useState(initialState: T | (() => T)): [T, UpdateStateFunction] ``` ## Parameters | Name | Type | |---|---| | `initialState` | `T | (() => T)` | **Returns:** `[T, UpdateStateFunction]` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `Root` — `src/jsx/dom/client.ts`:11 - `FormContext` — `src/jsx/dom/hooks/index.ts`:24 - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # captureRenderContext **Kind:** Function **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L196) **Part of:** [Jsx](subsystem-src-jsx) Capture the current render store and return a resumer that re-establishes it around a deferred continuation (e.g. a re-render after a suspended promise settles). Shared by every suspension point so none reimplements it. `captureRenderContext` saves the render store that is active when it is called and returns a resumer function. Call the resumer around deferred work, such as a continuation after a suspended promise settles, so that work runs with the original render context. ## Signature ```ts function captureRenderContext(): ((callback: () => T) => T) ``` **Returns:** `((callback: () => T) => T)` ## Diagram ```mermaid graph LR A[Active render store] --> B[captureRenderContext] B --> C[Resumer function] D[Deferred continuation] --> C C --> E[Restore captured render store] E --> F[Run continuation] F --> G[Restore previous render store] ``` ## Usage ```ts import { captureRenderContext } from './context' function continueAfterPromise(promise: Promise, rerender: () => void) { const resume = captureRenderContext() promise.then(() => { resume(() => { rerender() }) }) } ``` ## AI Coding Instructions - Capture the render context before scheduling asynchronous or deferred work. - Invoke deferred continuations through the returned resumer rather than calling them directly. - Preserve the existing render store after the continuation completes; do not assign global render state without restoring it. - Share this helper across suspension paths so promise handlers and retry logic follow the same context-restoration behavior. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `Props` — `src/jsx/base.ts`:27 - `childrenToString` — `src/jsx/components.ts`:14 - `StreamingContext` — `src/jsx/streaming.ts`:30 # Context **Kind:** Class **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L293) `Context` owns an internal response factory through its private `#newResponse()` method. The factory returns a `Response`, keeping response creation inside the context implementation. ## Methods | Method | Signature | Returns | |---|---|---| | `#newResponse` | `#newResponse(data: Data | null, arg: StatusCode | ResponseOrInit, headers: HeaderRecord)` | `Response` | ## Properties | Property | Type | |---|---| | `#rawRequest` | `Request` | | `#req` | `HonoRequest | undefined` | | `env` | `E['Bindings']` | | `#var` | `Map | undefined` | | `finalized` | `boolean` | | `error` | `Error | undefined` | | `#status` | `StatusCode | undefined` | | `#executionCtx` | `FetchEventLike | ExecutionContext | undefined` | | `#res` | `Response | undefined` | | `#layout` | `Layout | undefined` | | `#renderer` | `Renderer | undefined` | | `#notFoundHandler` | `NotFoundHandler | undefined` | | `#preparedHeaders` | `Headers | undefined` | | `#matchResult` | `Result<[H, RouterRoute]> | undefined` | | `#path` | `string | undefined` | | `render` | `Renderer` | | `setLayout` | `any` | | `getLayout` | `any` | | `setRenderer` | `any` | | `header` | `SetHeaders` | | `status` | `any` | | `set` | `Set< IsAny extends true ? { Variables: ContextVariableMap & Record } : E >` | | `get` | `Get< IsAny extends true ? { Variables: ContextVariableMap & Record } : E >` | | `newResponse` | `NewResponse` | | `body` | `BodyRespond` | | `text` | `TextRespond` | | `json` | `JSONRespond` | | `html` | `HTMLRespond` | | `redirect` | `any` | | `notFound` | `any` | ## Where it refuses work - `Context` stops the work with an early return when `!this.#var`. ## Diagram ```mermaid graph LR Context --> Factory["#newResponse()"] Factory --> Response ``` ## Usage ```ts // Pattern for code added inside src/context.ts class Context { #newResponse(): Response { return new Response() } createResponse(): Response { return this.#newResponse() } } ``` ## AI Coding Instructions - Keep response construction behind `#newResponse()`. - Call the private factory with `this.#newResponse()` only from within `Context`. - Return the factory result as a `Response` without exposing the private method. - Treat `Response` as the integration point for code that consumes context output. ## How it works `Context` is the per-request state object used by handlers and middleware. It stores the incoming `Request`, environment bindings, optional execution context, route-match data, response state, a handler error, renderer/layout state, and context variables. Its generic parameters type the environment, route path, and validated request input. [src/context.ts:293-344](src/context.ts#L293-L344) - The constructor requires a `Request`. When options are passed, it stores `executionCtx`, `env`, `notFoundHandler`, `path`, and `matchResult`; without options, `env` remains its initialized empty object. [src/context.ts:315-315](src/context.ts#L315-L315) [src/context.ts:352-361](src/context.ts#L352-L361) - `req` lazily constructs and caches a `HonoRequest` around the original request, path, and match result. `HonoRequest` stores the raw request and path and receives the route-match result for parameter lookup. [src/context.ts:366-369](src/context.ts#L366-L369) [src/request.ts:69-77](src/request.ts#L69-L77) - `env` is a public bindings field, `error` is a public `Error | undefined` field, and `finalized` is a public boolean initialized to `false`. Middleware composition assigns `error` when a handler throws an `Error` and an error handler exists. [src/context.ts:315-317](src/context.ts#L315-L317) [src/context.ts:333-333](src/context.ts#L333) [src/compose.ts:50-59](src/compose.ts#L50-L59) ## Runtime context access - `event` returns the stored execution context only when it exists and has a `respondWith` property; otherwise it throws `Error('This context has no FetchEvent')`. [src/context.ts:377-383](src/context.ts#L377-L383) - `executionCtx` returns the stored execution context cast as `ExecutionContext`; it throws `Error('This context has no ExecutionContext')` when none was supplied. [src/context.ts:391-397](src/context.ts#L391-L397) - The `ExecutionContext` type declares `waitUntil`, `passThroughOnException`, `props`, and optional `exports`. [src/context.ts:31-52](src/context.ts#L31-L52) ## Response state and headers - Reading `res` returns the current response, or creates and caches an empty `Response` with the accumulated prepared headers when no response has been set. [src/context.ts:403-407](src/context.ts#L403-L407) - Assigning `res` marks the context finalized. If a response already exists, the setter clones the incoming response, then copies prior response headers over it except `content-type`; for `set-cookie`, it replaces the incoming cookie headers with all cookies from the prior response. [src/context.ts:414-434](src/context.ts#L414-L434) - During middleware composition, a truthy handler result is assigned to `context.res` when the context is not finalized; an error-handler result is assigned even if it was already finalized. [src/compose.ts:67-70](src/compose.ts#L67-L70) - `header(name, value, { append })` writes to the current response headers or to prepared headers if no response exists. An `undefined` value deletes the header; `append: true` appends it; otherwise it replaces it. If the context is finalized, it first clones the response before changing headers. [src/context.ts:515-527](src/context.ts#L515-L527) - `status(status)` stores a status code for later response construction. [src/context.ts:529-531](src/context.ts#L529-L531) - `newResponse(data, statusOrInit, headers)` creates a `Response`. It starts with current response headers, if any, otherwise prepared headers; merges headers from an init object and explicit headers; preserves multiple `set-cookie` values while merging init headers; and selects a numeric argument’s status, an init object’s status, or the stored status in that order. [src/context.ts:604-654](src/context.ts#L604-L654) ## Response helpers - `body(data, statusOrInit?, headers?)` delegates to `newResponse`. Its overloads statically restrict non-null bodies to contentful status codes, while `null` may use any `StatusCode`. [src/context.ts:122-141](src/context.ts#L122-L141) [src/context.ts:677-681](src/context.ts#L677-L681) - `text(text, statusOrInit?, headers?)` returns text with a default `Content-Type` of `text/plain; charset=UTF-8`. If there are no prepared headers, stored status, arguments beyond text, explicit headers, or finalized response, it directly constructs `new Response(text)` instead. [src/context.ts:279-285](src/context.ts#L279-L285) [src/context.ts:695-707](src/context.ts#L695-L707) - `json(object, statusOrInit?, headers?)` serializes the value with `JSON.stringify` and constructs a response whose default `Content-Type` is `application/json`. [src/context.ts:721-734](src/context.ts#L721-L734) - `html(html, statusOrInit?, headers?)` constructs a response whose default `Content-Type` is `text/html; charset=UTF-8`. For an object input, including a `Promise`, it resolves it through `resolveCallback` and returns a promise of the response; for a string, it returns the response directly. [src/context.ts:220-230](src/context.ts#L220-L230) [src/context.ts:736-746](src/context.ts#L736-L746) - `redirect(location, status?)` sets `Location`, converts the location with `String`, URI-encodes it if it contains characters outside the `\x00`–`\xFF` range, and returns an empty response with the supplied redirect status or `302`. [src/context.ts:763-775](src/context.ts#L763-L775) - `notFound()` invokes the configured not-found handler with this context. If none exists, it caches a handler that returns an empty `Response`. [src/context.ts:789-792](src/context.ts#L789-L792) ## Variables and rendering - `set(key, value)` lazily creates an internal `Map` and stores the value. `get(key)` returns the stored value or `undefined` if no variable map exists or the key is absent. [src/context.ts:546-556](src/context.ts#L546-L556) [src/context.ts:571-580](src/context.ts#L571-L580) - `var` returns `{}` when no variables have been set; otherwise it returns `Object.fromEntries` of the internal map. Its type is read-only, but each access creates a plain object from the current map contents. [src/context.ts:593-602](src/context.ts#L593-L602) - `render` calls the configured renderer. If no renderer has been set, it caches a default renderer that delegates to `html`. `setRenderer` replaces that renderer. [src/context.ts:448-451](src/context.ts#L448-L451) [src/context.ts:495-497](src/context.ts#L495-L497) - `setLayout(layout)` stores and returns the layout function; `getLayout()` returns the stored layout or `undefined`. [src/context.ts:459-465](src/context.ts#L459-L465) [src/context.ts:472-472](src/context.ts#L472) ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `EventContext` — `src/adapter/cloudflare-pages/handler.ts`:12 - `HonoOptions` — `src/hono-base.ts`:46 # cssCommon **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L201) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function cssCommon(strings: TemplateStringsArray, values: CssVariableType[], classNameSlug: ClassNameSlug, onInvalidSlug: OnInvalidSlug): CssClassName ``` ## Parameters | Name | Type | |---|---| | `strings` | `TemplateStringsArray` | | `values` | `CssVariableType[]` | | `classNameSlug` | `ClassNameSlug` | | `onInvalidSlug` | `OnInvalidSlug` | **Returns:** `CssClassName` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # deepMerge **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L66) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function deepMerge(target: T, source: Record): T ``` ## Parameters | Name | Type | |---|---| | `target` | `T` | | `source` | `Record` | **Returns:** `T` # EventV1Processor **Kind:** Class **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L443) **Part of:** [Adapter](subsystem-src-adapter) `EventV1Processor` adapts an AWS Lambda event in the V1 format into request data used by the handler layer. It reads the path, method, query string, cookies, and headers, then writes response cookies back to the Lambda result. **Extends:** `EventProcessor` ## Methods | Method | Signature | Returns | |---|---|---| | `getPath` | `getPath(event: APIGatewayProxyEvent)` | `string` | | `getMethod` | `getMethod(event: APIGatewayProxyEvent)` | `string` | | `getQueryString` | `getQueryString(event: APIGatewayProxyEvent)` | `string` | | `getCookies` | `getCookies(_event: APIGatewayProxyEvent, _headers: Headers)` | `void` | | `getHeaders` | `getHeaders(event: APIGatewayProxyEvent)` | `Headers` | | `setCookiesToResult` | `setCookiesToResult(result: APIGatewayProxyResult, cookies: string[])` | `void` | ## Diagram ```mermaid graph LR Event[AWS Lambda V1 Event] --> Processor[EventV1Processor] Processor --> Path[getPath] Processor --> Method[getMethod] Processor --> Query[getQueryString] Processor --> Headers[getHeaders] Processor --> Cookies[getCookies] Processor --> Result[Lambda Result] Cookies --> SetCookies[setCookiesToResult] SetCookies --> Result ``` ## Usage ```ts import { EventV1Processor } from './adapter/aws-lambda/handler' async function handleLambdaEvent(event: any, result: any) { const processor = new EventV1Processor(event, result) processor.getCookies() const request = new Request( `https://lambda.local${processor.getPath()}${processor.getQueryString()}`, { method: processor.getMethod(), headers: processor.getHeaders(), }, ) const response = await app.fetch(request) result.statusCode = response.status result.body = await response.text() processor.setCookiesToResult() return result } ``` ## AI Coding Instructions - Keep event parsing inside `EventV1Processor`; downstream handlers should work with normalized request values. - Call `getCookies()` before request handling when cookie data must be available through request headers. - Call `setCookiesToResult()` after response processing so response cookies are written to the Lambda result. - Preserve the `Headers` return type from `getHeaders()` rather than converting headers into a plain object unless required by an integration. - Treat query strings and cookies as transport data; avoid rebuilding them in application handlers. # ipRestriction **Kind:** Function **Source:** [`src/middleware/ip-restriction/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/ip-restriction/index.ts#L218) **Part of:** [Middleware](subsystem-src-middleware) IP Restriction Middleware for Hono. `ipRestriction` creates Hono middleware that checks a request’s client IP address against configured allow and deny lists. Attach it to an application or route to reject requests from disallowed addresses before route handlers run. ## Signature ```ts function ipRestriction(getIP: GetIPAddr, { denyList = [], allowList = [] }: IPRestrictionRules, onError: ( remote: { addr: string; type: AddressType }, c: Context ) => Response | Promise): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `getIP` | `GetIPAddr` | | `{ denyList = [], allowList = [] }` | `IPRestrictionRules` | | `onError` | `( remote: { addr: string; type: AddressType }, c: Context ) => Response | Promise` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[ipRestriction middleware] Middleware --> IP[Read client IP] IP --> Lists[Check allowList and denyList] Lists -->|Allowed| Handler[Route handler] Lists -->|Denied| Forbidden[Forbidden response] ``` ## Usage ```ts import { Hono } from 'hono' import { ipRestriction } from 'hono/ip-restriction' const app = new Hono() app.use( '*', ipRestriction({ allowList: ['192.168.0.2', '10.0.0.0/24'], denyList: ['192.168.0.10'], }) ) app.get('/', (c) => c.text('Access granted')) export default app ``` ## AI Coding Instructions - Register `ipRestriction` with `app.use()` before routes that require IP checks. - Keep IP addresses and CIDR ranges in `allowList` and `denyList` aligned with the deployment network. - Test requests from both allowed and denied addresses when changing list rules. - Account for proxies and platform networking when determining the client IP visible to Hono. # Node **Kind:** Class **Source:** [`src/router/reg-exp-router/node.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/node.ts#L45) **Part of:** [Router](subsystem-src-router) `Node` stores route data for the regular-expression router and builds the regular-expression source used for matching. It accepts route entries through `insert()` and produces a matcher pattern through `buildRegExpStr()`. ## Methods | Method | Signature | Returns | |---|---|---| | `insert` | `insert(tokens: readonly string[], index: number, paramMap: ParamAssocArray, context: Context, isStatic: boolean)` | `void` | | `buildRegExpStr` | `buildRegExpStr()` | `string` | ## Properties | Property | Type | |---|---| | `#index` | `number` | | `#varIndex` | `number` | | `#children` | `Record` | ## Where it refuses work - `Node` stops the work with an early return when `regexpStr === '.*'`. - `Node` stops the work with an early return when `/\((?!\?:)/.test(regexpStr)`. - `Node` stops the work with an early return when `regexpStr.length === 1 && regExpMetaChars.has(regexpStr)`. - `Node` stops the work with an early return when `(regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_W…`. - `Node` stops the work with an early return when `k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR`. - `Node` stops the work with an early return when `node.#index !== undefined`. ## Diagram ```mermaid graph LR Route[Route definition] --> Insert[Node.insert] Insert --> Tree[Node route structure] Tree --> Build[Node.buildRegExpStr] Build --> Pattern[Regular expression source] Pattern --> Matcher[Route matcher] ``` ## Usage ```ts import { Node } from './node' const handler = () => new Response('User route matched') // A router creates and owns the root Node instance. function compileRoutes(node: Node) { node.insert('GET', '/users/:id', handler) const patternSource = node.buildRegExpStr() return new RegExp(patternSource) } ``` ## AI Coding Instructions - Treat `Node` as router-internal state; register routes through the router when that public API is available. - Call `insert()` before `buildRegExpStr()`, since the generated pattern reflects the routes stored in the node. - Keep route parameter syntax consistent with the regular-expression router's parser. - Preserve route insertion behavior when changing node traversal or pattern generation, as matcher output depends on stored route structure. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ReplacementMap` — `src/router/reg-exp-router/trie.ts`:4 # stringBufferToString **Kind:** Function **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L53) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function stringBufferToString(buffer: StringBuffer, callbacks: HtmlEscapedCallback[] | undefined): Promise ``` ## Parameters | Name | Type | |---|---| | `buffer` | `StringBuffer` | | `callbacks` | `HtmlEscapedCallback[] | undefined` | **Returns:** `Promise` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `html` — `src/helper/html/index.ts`:11 - `Props` — `src/jsx/base.ts`:27 - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 # checkOptionalParameter **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L171) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function checkOptionalParameter(path: string): string[] | null ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string[] | null` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `LinearRouter` — `src/router/linear-router/router.ts`:11 - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 - `TrieRouter` — `src/router/trie-router/router.ts`:5 # compose **Kind:** Function **Source:** [`src/compose.ts`](https://github.com/honojs/hono/blob/main/src/compose.ts#L15) Compose middleware functions into a single function based on `koa-compose` package. `compose` combines middleware functions into one middleware handler using the dispatch pattern from `koa-compose`. Each middleware can run logic before and after `await next()`, allowing request handling, state changes, and cleanup to flow through the chain. ## Signature ```ts function compose(middleware: [[Function, unknown], unknown][] | [[Function]][], onError: ErrorHandler, onNotFound: NotFoundHandler): ((context: Context, next?: Next) => Promise) ``` ## Parameters | Name | Type | |---|---| | `middleware` | `[[Function, unknown], unknown][] | [[Function]][]` | | `onError` | `ErrorHandler` | | `onNotFound` | `NotFoundHandler` | **Returns:** `((context: Context, next?: Next) => Promise)` ## Diagram ```mermaid graph LR A[Composed middleware] --> B[Middleware A] B --> C[Middleware B] C --> D[Middleware C] D --> E[Final next handler] E --> D D --> C C --> B B --> A ``` ## Usage ```ts import { compose } from './compose' type Context = { requestId?: string logs: string[] } const middleware = compose([ async (context, next) => { context.logs.push('before request') await next() context.logs.push('after request') }, async (context, next) => { context.requestId = crypto.randomUUID() await next() }, ]) const context: Context = { logs: [] } await middleware(context, async () => { context.logs.push(`handling ${context.requestId}`) }) console.log(context.logs) ``` ## AI Coding Instructions - Keep middleware signatures compatible with the composed handler: `(context, next) => Promise`. - Call and `await next()` when downstream middleware must run before post-processing logic. - Do not call `next()` more than once from the same middleware invocation. - Preserve middleware order when adding handlers; earlier middleware wraps later middleware. - Pass a final `next` handler when composition must continue into code outside the middleware list. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `some` — `src/middleware/combine/index.ts`:38 - `HonoOptions` — `src/hono-base.ts`:46 # DOM_ERROR_HANDLER **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L2) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('ERROR_HANDLER') ``` ## Value ```ts Symbol('ERROR_HANDLER') ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `ErrorBoundary` — `src/jsx/dom/components.ts`:7 - `createContextProviderFunction` — `src/jsx/dom/context.ts`:7 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # EventV2Processor **Kind:** Class **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L404) **Part of:** [Adapter](subsystem-src-adapter) This class adapts AWS Lambda HTTP request data into the request values consumed by the handler layer. It exposes path, method, query string, headers, and cookie handling while writing response cookies back to the Lambda result. **Extends:** `EventProcessor` ## Methods | Method | Signature | Returns | |---|---|---| | `getPath` | `getPath(event: APIGatewayProxyEventV2)` | `string` | | `getMethod` | `getMethod(event: APIGatewayProxyEventV2)` | `string` | | `getQueryString` | `getQueryString(event: APIGatewayProxyEventV2)` | `string` | | `getCookies` | `getCookies(event: APIGatewayProxyEventV2, headers: Headers)` | `void` | | `setCookiesToResult` | `setCookiesToResult(result: APIGatewayProxyResult, cookies: string[])` | `void` | | `getHeaders` | `getHeaders(event: APIGatewayProxyEventV2)` | `Headers` | ## Diagram ```mermaid graph LR Event["EventV2Processor [census]"] --> Request["Request accessors"] Event --> Cookies["Cookie handling"] Request --> Path["getPath"] Request --> Method["getMethod"] Request --> Query["getQueryString"] Request --> Headers["getHeaders"] Cookies --> ReadCookies["getCookies"] Cookies --> WriteCookies["setCookiesToResult"] ``` ## Usage ```ts declare const processor: EventV2Processor; // [census] const requestDetails = { path: processor.getPath(), method: processor.getMethod(), queryString: processor.getQueryString(), contentType: processor.getHeaders().get("content-type"), }; processor.getCookies(); // Handle the request and prepare response cookies. processor.setCookiesToResult(); ``` ## AI Coding Instructions - Keep AWS Lambda event-specific parsing inside this adapter layer. - Read cookies before handler code depends on them, then write response cookies before returning the Lambda result. - Treat `getHeaders()` as the source for request header access rather than reading the Lambda event directly. - Preserve the existing path, method, and query string mapping behavior when changing request handling. ## How it works `EventV2Processor` is an exported concrete `EventProcessor` subclass for `APIGatewayProxyEventV2` events. It supplies the v2-specific path, method, query, header, and cookie mappings used by the inherited request/result conversion methods. [src/adapter/aws-lambda/handler.ts:404-439](src/adapter/aws-lambda/handler.ts#L404-L439) - `getProcessor()` selects the module-level `EventV2Processor` instance when an event has both `rawPath` and `requestContext.http`, after checking whether it is an ALB event. [src/adapter/aws-lambda/handler.ts:625-637](src/adapter/aws-lambda/handler.ts#L625-L637) [src/adapter/aws-lambda/handler.ts:646-651](src/adapter/aws-lambda/handler.ts#L646-L651) - For a v2 event, it takes the request path from `rawPath`, the HTTP method from `requestContext.http.method`, and the query string directly from `rawQueryString`. [src/adapter/aws-lambda/handler.ts:405-415](src/adapter/aws-lambda/handler.ts#L405-L415) - Its header conversion starts with a new `Headers` object. If `event.cookies` is an array, it writes one `Cookie` header whose value joins the entries with `; `. It then copies each truthy entry from `event.headers` with `Headers.set()`. [src/adapter/aws-lambda/handler.ts:417-438](src/adapter/aws-lambda/handler.ts#L417-L438) - Through `EventProcessor.createRequest()`, the processor constructs a URL as `https://${domainName}${rawPath}`, appending `?${rawQueryString}` only when that string is non-empty. The domain comes first from `event.requestContext.domainName`; otherwise the shared logic checks `host` in `headers`, then `multiValueHeaders`. [src/adapter/aws-lambda/handler.ts:301-323](src/adapter/aws-lambda/handler.ts#L301-L323) - When `event.body` is truthy, the inherited request conversion decodes it from base64 if `isBase64Encoded` is true; otherwise it UTF-8 encodes the string. It assigns that byte sequence as the `Request` body and sets `content-length` to its byte length. [src/adapter/aws-lambda/handler.ts:327-341](src/adapter/aws-lambda/handler.ts#L327-L341) - The inherited result conversion marks a response body as base64-encoded when the configured binary-content predicate, or the default predicate, classifies its `content-type` as binary. If it is not already marked binary, a non-`identity` `content-encoding` also marks it binary. Binary bodies are read as an `ArrayBuffer` and base64 encoded; other bodies are read as text. [src/adapter/aws-lambda/handler.ts:344-360](src/adapter/aws-lambda/handler.ts#L344-L360) [src/adapter/aws-lambda/handler.ts:666-674](src/adapter/aws-lambda/handler.ts#L666-L674) - For response cookies, this subclass writes extracted `Set-Cookie` values to the result’s `cookies` array. The shared logic removes `set-cookie` from the response headers before copying remaining headers into the Lambda result. [src/adapter/aws-lambda/handler.ts:388-400](src/adapter/aws-lambda/handler.ts#L388-L400) [src/adapter/aws-lambda/handler.ts:423-425](src/adapter/aws-lambda/handler.ts#L423-L425) - In the standard `handle()` path, exceptions while creating the request or reading its request context are logged. A `TypeError` becomes a `400` result with body `Invalid request`; other caught errors become a `500` result with body `Internal Server Error`. [src/adapter/aws-lambda/handler.ts:252-266](src/adapter/aws-lambda/handler.ts#L252-L266) An invalid v2 header name is covered by a test that expects this `400` result. [src/adapter/aws-lambda/handler.test.ts:441-467](src/adapter/aws-lambda/handler.test.ts#L441-L467) # getSignedCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L50) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts async function getSignedCookie(c, secret, key, prefix: CookiePrefixOptions) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | | `secret` | `any` | | `key` | `any` | | `prefix` | `CookiePrefixOptions` | ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `headerName` — `src/middleware/jwk/jwk.ts`:81 - `headerName` — `src/middleware/jwt/jwt.ts`:81 # parseResponse **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L92) **Part of:** [Client](subsystem-src-client) Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference. Smartly parse the response data, throwing a structured error if the response is not `ok`. (DetailedError) `parseResponse` accepts an `hc` fetch response and returns its parsed, consumable data with the response type inferred from the client call. It checks `response.ok` before parsing and throws a `DetailedError` when the request fails. ## Signature ```ts async function parseResponse(fetchRes: T | Promise): Promise< FilterClientResponseByStatusCode< T, Exclude > extends never ? undefined : FilterClientResponseByStatusCode< T, Exclude > extends ClientResponse ? RF extends 'json' ? RT : RT extends string ? RT : string : undefined > ``` ## Parameters | Name | Type | |---|---| | `fetchRes` | `T | Promise` | **Returns:** `Promise< FilterClientResponseByStatusCode< T, Exclude > extends never ? undefined : FilterClientResponseByStatusCode< T, Exclude > extends ClientResponse ? RF extends 'json' ? RT : RT extends string ? RT : string : undefined >` ## Diagram ```mermaid graph LR A[hc client call] --> B[parseResponse] B --> C{response.ok} C -->|true| D[Parsed typed data] C -->|false| E[DetailedError] ``` ## Usage ```ts import { hc, parseResponse } from 'hono/client' import type { AppType } from './server' const client = hc('/api') const user = await parseResponse( client.users[':id'].$get({ param: { id: 'user-id' }, }) ) console.log(user) ``` ## AI Coding Instructions - Pass the `hc` client call directly to `parseResponse` to preserve inferred response types. - Handle `DetailedError` where request failures need status or response error details. - Do not call `response.json()`, `response.text()`, or another body reader before `parseResponse`; response bodies can only be consumed once. - Use `parseResponse` at client-call boundaries so callers receive parsed data rather than raw `Response` objects. # Trie **Kind:** Class **Source:** [`src/router/reg-exp-router/trie.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/trie.ts#L6) **Part of:** [Router](subsystem-src-router) `Trie` stores route definitions in a prefix tree for the regular-expression router. It accepts routes through `insert()` and compiles the stored tree into a `RegExp` with replacement maps through `buildRegExp()`. ## Methods | Method | Signature | Returns | |---|---|---| | `insert` | `insert(path: string, isStatic: boolean)` | `void` | | `buildRegExp` | `buildRegExp()` | `[RegExp, ReplacementMap, ReplacementMap]` | ## Properties | Property | Type | |---|---| | `#context` | `Context` | | `#root` | `Node` | | `#index` | `number` | | `paths` | `Record` | ## Where it refuses work - `Trie` stops the work with an early return when `regexp === ''`. ## Diagram ```mermaid graph LR Route["Route definition"] --> Insert["Trie.insert()"] Insert --> Tree["Trie node tree"] Tree --> Build["Trie.buildRegExp()"] Build --> Pattern["RegExp"] Build --> Params["Parameter replacement map"] Build --> Routes["Route replacement map"] ``` ## Usage ```ts import { Trie } from './src/router/reg-exp-router/trie' const trie = new Trie() trie.insert('GET', '/users/:id', (c) => { return c.text(`User: ${c.req.param('id')}`) }) trie.insert('GET', '/health', (c) => { return c.text('ok') }) const [pattern, paramReplacements, routeReplacements] = trie.buildRegExp() const match = pattern.exec('/users/42') if (match) { // Router code reads captures through the replacement maps console.log(match) console.log(paramReplacements) console.log(routeReplacements) } ``` ## AI Coding Instructions - Add routes through `insert()` before calling `buildRegExp()` so the compiled expression includes every route. - Keep the `RegExp` and both replacement maps together; capture groups are interpreted through those maps. - Preserve route parameter syntax when inserting paths, since parameter names are resolved during expression construction. - Treat `Trie` as router infrastructure; route dispatch code should consume the output of `buildRegExp()` rather than inspect trie nodes directly. ## How it works `Trie` is an internal route-pattern tree used by `RegExpRouter` to collect dynamic paths and compile them into one regular expression plus capture-index lookup tables. It owns a shared `Node` root, a variable-index context, and a sequential dynamic-handler index. [src/router/reg-exp-router/trie.ts:6-11] ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 # wrapTime **Kind:** Function **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L244) **Part of:** [Middleware](subsystem-src-middleware) Wrap a Promise to capture its duration. `wrapTime` wraps a Promise and records how long the asynchronous operation takes to settle. It is used by timing middleware to collect duration data without changing the operation’s normal resolution or rejection flow. ## Signature ```ts async function wrapTime(c: Context, name: string, callable: Promise, description: string, precision: number): Promise ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `callable` | `Promise` | | `description` | `string` | | `precision` | `number` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Async operation Promise] --> B[wrapTime] B --> C[Record start time] C --> D[Wait for Promise settlement] D --> E[Capture duration] E --> F[Timing middleware data] ``` ## Usage ```ts import { wrapTime } from "./middleware/timing/timing"; async function loadUser() { const response = await wrapTime(fetch("/api/users/current")); if (!response.ok) { throw new Error("Unable to load user"); } return response.json(); } ``` ## AI Coding Instructions - Pass the original Promise to `wrapTime`; do not await the operation before wrapping it. - Await or return the wrapped Promise so callers keep the original async control flow. - Apply `wrapTime` at middleware or request boundaries where duration data is collected. - Preserve existing error handling; rejected Promises should continue through the normal error path. # basicAuth **Kind:** Function **Source:** [`src/middleware/basic-auth/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/basic-auth/index.ts#L80) **Part of:** [Middleware](subsystem-src-middleware) Basic Auth Middleware for Hono. `basicAuth` creates Hono middleware that checks HTTP Basic Authentication credentials before allowing a request to continue. Apply it to a route or route group to return an unauthorized response when the supplied username or password does not match the configured values. ## Signature ```ts function basicAuth(options: BasicAuthOptions, users: { username: string; password: string }[]): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `BasicAuthOptions` | | `users` | `{ username: string; password: string }[]` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[basicAuth middleware] Middleware --> Credentials[Read Authorization header] Credentials --> Valid{Credentials match?} Valid -->|Yes| Handler[Route handler] Valid -->|No| Unauthorized[Unauthorized response] ``` ## Usage ```ts import { Hono } from 'hono' import { basicAuth } from 'hono/basic-auth' const app = new Hono() app.use( '/admin/*', basicAuth({ username: 'admin', password: 'secret', }) ) app.get('/admin/dashboard', (c) => { return c.text('Admin dashboard') }) export default app ``` ## AI Coding Instructions - Apply `basicAuth` with `app.use()` before the routes that require authentication. - Scope the middleware path carefully so public routes do not require credentials. - Keep usernames and passwords outside source code by reading them from environment configuration. - Send credentials through the standard `Authorization: Basic ...` request header rather than custom headers. # DOM_STASH **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L3) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('STASH') ``` ## Value ```ts Symbol('STASH') ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `STASH_EFFECT` — `src/jsx/hooks/index.ts`:9 - `StreamingContext` — `src/jsx/streaming.ts`:30 # HonoRequest **Kind:** Class **Source:** [`src/request.ts`](https://github.com/honojs/hono/blob/main/src/request.ts#L34) `HonoRequest` represents the incoming request exposed through Hono's context. It reads decoded route parameters with `param()` and URL query values with `query()`, while keeping request parsing behavior inside the framework. ## Methods | Method | Signature | Returns | |---|---|---| | `param` | `param(key: string extends P ? never : P2 extends `${infer _}?` ? never : P2)` | `string` | | `param` | `param(key: P2)` | `string | undefined` | | `param` | `param(key: string)` | `string | undefined` | | `param` | `param()` | `Simplify>>>` | | `param` | `param(key: string)` | `unknown` | | `#getDecodedParam` | `#getDecodedParam(key: string)` | `string | undefined` | | `#getAllDecodedParams` | `#getAllDecodedParams()` | `Record` | | `#getParamValue` | `#getParamValue(paramKey: any)` | `string | undefined` | | `query` | `query(key: string)` | `string | undefined` | | `query` | `query()` | `Record` | | `query` | `query(key: string)` | `void` | | `queries` | `queries(key: string)` | `string[] | undefined` | | `queries` | `queries()` | `Record` | | `queries` | `queries(key: string)` | `void` | | `header` | `header(name: RequestHeader)` | `string | undefined` | | `header` | `header(name: string)` | `string | undefined` | | `header` | `header()` | `Record` | | `header` | `header(name: string)` | `void` | | `parseBody` | `parseBody(options: Options)` | `Promise` | | `parseBody` | `parseBody(options: Partial)` | `Promise` | | `parseBody` | `parseBody(options: Partial)` | `void` | | `json` | `json()` | `Promise` | | `text` | `text()` | `Promise` | | `arrayBuffer` | `arrayBuffer()` | `Promise` | | `bytes` | `bytes()` | `Promise` | | `blob` | `blob()` | `Promise` | | `formData` | `formData()` | `Promise` | | `addValidatedData` | `addValidatedData(target: keyof ValidationTargets, data: {})` | `void` | | `valid` | `valid(target: T)` | `InputToDataByTarget` | | `valid` | `valid(target: keyof ValidationTargets)` | `void` | ## Properties | Property | Type | |---|---| | `raw` | `Request` | | `#validatedData` | `{ [K in keyof ValidationTargets]?: {} } | undefined` | | `#matchResult` | `Result<[unknown, RouterRoute]>` | | `routeIndex` | `number` | | `path` | `string` | | `bodyCache` | `BodyCache` | | `#cachedBody` | `any` | ## Where it refuses work - `HonoRequest` stops the work with an early return when `name`. - `HonoRequest` stops the work with an early return when `cachedBody`. ## Diagram ```mermaid graph LR Request[Incoming Request] --> HonoRequest Route[Matched Route] --> HonoRequest HonoRequest --> Param[param()] HonoRequest --> Query[query()] Param --> Handler[Route Handler] Query --> Handler ``` ## Usage ```ts import { Hono } from 'hono' const app = new Hono() app.get('/users/:id', (c) => { const id = c.req.param('id') const filter = c.req.query('filter') const query = c.req.query() return c.json({ id, filter, query, }) }) export default app ``` ## AI Coding Instructions - Access `HonoRequest` through `c.req` in route handlers rather than constructing it directly. - Use `param('name')` when reading a matched route parameter; account for `undefined` when the parameter may not exist. - Use `param()` without an argument when the route's typed parameter record is needed. - Use `query('name')` for a single query value and `query()` for the full query record. - Keep parameter decoding in the request class; do not call private `#getDecodedParam`, `#getAllDecodedParams`, or `#getParamValue` outside this class. ## Relationships - IMPORTS → `HTTPException` - IMPORTS → `GET_MATCH_RESULT` - IMPORTS → `parseBody` - IMPORTS → `getQueryParam` - IMPORTS → `getQueryParams` - IMPORTS → `tryDecodeURIComponent` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Data` — `src/context.ts`:26 # keyframesCommon **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L260) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function keyframesCommon(strings: TemplateStringsArray, values: CssVariableType[], classNameSlug: ClassNameSlug, onInvalidSlug: OnInvalidSlug): CssClassName ``` ## Parameters | Name | Type | |---|---| | `strings` | `TemplateStringsArray` | | `values` | `CssVariableType[]` | | `classNameSlug` | `ClassNameSlug` | | `onInvalidSlug` | `OnInvalidSlug` | **Returns:** `CssClassName` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # LatticeV2Processor **Kind:** Class **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L584) **Part of:** [Adapter](subsystem-src-adapter) `LatticeV2Processor` adapts an AWS VPC Lattice event into request data consumed by the Lambda handler. It reads the request path, method, query string, headers, and cookies, then writes response cookies back to the Lambda result. **Extends:** `EventProcessor` ## Methods | Method | Signature | Returns | |---|---|---| | `getPath` | `getPath(event: LatticeProxyEventV2)` | `string` | | `getMethod` | `getMethod(event: LatticeProxyEventV2)` | `string` | | `getQueryString` | `getQueryString()` | `string` | | `getHeaders` | `getHeaders(event: LatticeProxyEventV2)` | `Headers` | | `getCookies` | `getCookies()` | `void` | | `setCookiesToResult` | `setCookiesToResult(result: APIGatewayProxyResult, cookies: string[])` | `void` | ## Diagram ```mermaid graph LR Event[AWS VPC Lattice event] --> Processor[LatticeV2Processor] Processor --> Path[getPath()] Processor --> Method[getMethod()] Processor --> Query[getQueryString()] Processor --> Headers[getHeaders()] Processor --> Cookies[getCookies()] Processor --> Result[Lambda response] Cookies --> SetCookies[setCookiesToResult()] SetCookies --> Result ``` ## Usage ```ts import { LatticeV2Processor } from './handler' function inspectRequest(processor: LatticeV2Processor) { const path = processor.getPath() const method = processor.getMethod() const queryString = processor.getQueryString() const headers = processor.getHeaders() processor.getCookies() console.log({ path, method, queryString, contentType: headers.get('content-type'), }) processor.setCookiesToResult() } ``` ## AI Coding Instructions - Keep request access behind `LatticeV2Processor` methods instead of reading the VPC Lattice event directly in handler logic. - Treat `getHeaders()` as the source for request header lookups and use the `Headers` API for case-insensitive access. - Call `getCookies()` before code that depends on request cookies. - Call `setCookiesToResult()` after response cookies are prepared so they are included in the Lambda result. - Keep VPC Lattice-specific event handling in `src/adapter/aws-lambda/handler.ts`. ## How it works `LatticeV2Processor` is the exported `EventProcessor` specialization for Lambda events whose request context has a `serviceArn` property. `getProcessor()` selects its shared instance after excluding ALB and API Gateway v2 event shapes. [src/adapter/aws-lambda/handler.ts:584-623](src/adapter/aws-lambda/handler.ts#L584-L623) [src/adapter/aws-lambda/handler.ts:625-657](src/adapter/aws-lambda/handler.ts#L625-L657) Its event type requires a path, HTTP method, array-valued headers and query-string parameters, nullable body, base64 flag, and a Lattice v2 request context. That context includes `serviceArn`, `serviceNetworkArn`, `targetGroupArn`, region, timestamp, and identity fields. [src/adapter/aws-lambda/handler.ts:29-38](src/adapter/aws-lambda/handler.ts#L29-L38) [src/adapter/aws-lambda/types.ts:155-173](src/adapter/aws-lambda/types.ts#L155-L173) # parseAccept **Kind:** Function **Source:** [`src/utils/accept.ts`](https://github.com/honojs/hono/blob/main/src/utils/accept.ts#L211) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function parseAccept(acceptHeader: string): Accept[] ``` ## Parameters | Name | Type | |---|---| | `acceptHeader` | `string` | **Returns:** `Accept[]` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `handler` — `src/middleware/compress/index.ts`:139 - `DetectorType` — `src/middleware/language/language.ts`:10 - `Accept` — `src/helper/accepts/accepts.ts`:5 # PATH_ERROR **Kind:** Constant **Source:** [`src/router/reg-exp-router/node.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/node.ts#L4) **Part of:** [Router](subsystem-src-router) ## Definition ```ts Symbol() ``` ## Value ```ts Symbol() ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 # replaceUrlProtocol **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L46) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function replaceUrlProtocol(urlString: string, protocol: 'ws' | 'http') ``` ## Parameters | Name | Type | |---|---| | `urlString` | `string` | | `protocol` | `'ws' | 'http'` | # buildSearchParams **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L26) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function buildSearchParams(query: Record) ``` ## Parameters | Name | Type | |---|---| | `query` | `Record` | # cache **Kind:** Function **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L183) **Part of:** [Middleware](subsystem-src-middleware) Cache Middleware for Hono. `cache` creates Hono middleware that checks a named Cache API store before running a route handler. For cache misses, it runs the handler, sets the configured `Cache-Control` header, and stores the response for later matching requests. ## Signature ```ts function cache(options: { cacheName: string | ((c: Context) => Promise | string) wait?: boolean cacheControl?: string vary?: string | string[] keyGenerator?: (c: Context) => Promise | string maxQueryBodySize?: number cacheableStatusCodes?: StatusCode[] onCacheNotAvailable?: ((reason: string) => void) | false }): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `{ cacheName: string | ((c: Context) => Promise | string) wait?: boolean cacheControl?: string vary?: string | string[] keyGenerator?: (c: Context) => Promise | string maxQueryBodySize?: number cacheableStatusCodes?: StatusCode[] onCacheNotAvailable?: ((reason: string) => void) | false }` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[cache middleware] Middleware --> CacheStore[Named Cache API store] CacheStore -->|Cache hit| CachedResponse[Cached response] CacheStore -->|Cache miss| Handler[Route handler] Handler --> Response[Response with Cache-Control] Response --> CacheStore Response --> Client[Client] CachedResponse --> Client ``` ## Usage ```ts import { Hono } from 'hono' import { cache } from 'hono/cache' const app = new Hono() app.get( '/articles/:id', cache({ cacheName: 'articles', cacheControl: 'max-age=3600', wait: true, }), async (c) => { const article = await getArticle(c.req.param('id')) return c.json(article) } ) export default app ``` ## AI Coding Instructions - Apply `cache` before the route handler whose response should be stored. - Set `cacheName` to separate cached responses for different application areas. - Set `cacheControl` to match the intended client and edge caching policy. - Use `wait: true` when cache writes should run through the execution context rather than delay the response. - Ensure cached routes return responses that are safe to reuse for matching requests. # cxCommon **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L240) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function cxCommon(args: (string | boolean | null | undefined | CssClassName)[]): (string | boolean | null | undefined | CssClassName)[] ``` ## Parameters | Name | Type | |---|---| | `args` | `(string | boolean | null | undefined | CssClassName)[]` | **Returns:** `(string | boolean | null | undefined | CssClassName)[]` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # encodeBase64 **Kind:** Function **Source:** [`src/utils/encode.ts`](https://github.com/honojs/hono/blob/main/src/utils/encode.ts#L15) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function encodeBase64(buf: ArrayBufferLike): string ``` ## Parameters | Name | Type | |---|---| | `buf` | `ArrayBufferLike` | **Returns:** `string` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `key` — `src/middleware/secure-headers/secure-headers.ts`:139 - `LambdaEvent` — `src/adapter/aws-lambda/handler.ts`:23 - `CloudFrontRequest` — `src/adapter/lambda-edge/handler.ts`:41 # globalContexts **Kind:** Constant **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L13) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Context[] ``` ## Value ```ts [] ``` ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `Props` — `src/jsx/base.ts`:27 - `createContextProviderFunction` — `src/jsx/dom/context.ts`:7 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # handle **Kind:** Function **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L239) **Part of:** [Adapter](subsystem-src-adapter) Converts a Hono application to an AWS Lambda handler. Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB), and Lambda Function URLs. `handle` converts a Hono application into an AWS Lambda handler. It adapts requests from API Gateway v1 and v2, Application Load Balancers, and Lambda Function URLs into Hono requests, then returns the Hono response in the Lambda-compatible format. ## Signature ```ts function handle(app: Hono, { isContentTypeBinary }: HandleOptions): (( event: L, lambdaContext?: LambdaContext ) => Promise< APIGatewayProxyResult & (L extends { multiValueHeaders: Record } ? WithMultiValueHeaders : WithHeaders) >) ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | | `{ isContentTypeBinary }` | `HandleOptions` | **Returns:** `(( event: L, lambdaContext?: LambdaContext ) => Promise< APIGatewayProxyResult & (L extends { multiValueHeaders: Record } ? WithMultiValueHeaders : WithHeaders) >)` ## Diagram ```mermaid graph LR Event[API Gateway / ALB / Lambda Function URL] --> Handler[handle] Handler --> Hono[Hono application] Hono --> Response[Lambda response] ``` ## Usage ```ts import { Hono } from 'hono' import { handle } from 'hono/aws-lambda' const app = new Hono() app.get('/', (c) => { return c.text('Hello from Hono') }) export const handler = handle(app) ``` ## AI Coding Instructions - Pass the configured Hono application directly to `handle` when exporting the Lambda handler. - Keep route definitions and middleware on the Hono application before creating the Lambda handler. - Use this adapter for API Gateway v1, API Gateway v2, ALB, and Lambda Function URL events. - Do not write separate event parsing logic for supported AWS event sources unless application-specific behavior requires it. # MESSAGE_MATCHER_IS_ALREADY_BUILT **Kind:** Constant **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L21) Error message indicating that a route cannot be added because the matcher is already built. `MESSAGE_MATCHER_IS_ALREADY_BUILT` stores the error message used when code attempts to add a route after its matcher has been built. It keeps this validation message consistent within `src/router.ts` when route configuration occurs in the wrong order. ## Definition ```ts 'Can not add a route since the matcher is already built.' ``` ## Value ```ts 'Can not add a route since the matcher is already built.' ``` ## Diagram ```mermaid graph LR A[Add route] --> B{Matcher built?} B -- No --> C[Register route] B -- Yes --> D[MESSAGE_MATCHER_IS_ALREADY_BUILT] D --> E[Throw error] ``` ## Usage ```ts import { MESSAGE_MATCHER_IS_ALREADY_BUILT } from "./router"; function addRoute(matcherBuilt: boolean) { if (matcherBuilt) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); } // Register the route before building the matcher. } ``` ## AI Coding Instructions - Use `MESSAGE_MATCHER_IS_ALREADY_BUILT` instead of duplicating the matcher-built error text. - Check matcher build state before registering a new route. - Add routes before the router builds its matcher. - Keep errors related to route registration in `src/router.ts` aligned with this constant. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RegExpRouter` — `src/router/reg-exp-router/router.ts`:47 - `SmartRouter` — `src/router/smart-router/router.ts`:4 # PreparedRegExpRouter **Kind:** Class **Source:** [`src/router/reg-exp-router/prepared-router.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/prepared-router.ts#L9) **Part of:** [Router](subsystem-src-router) `PreparedRegExpRouter` collects route definitions and prepares regular-expression matchers for the routing layer. It separates path and wildcard handling while producing a `MatcherMap` through `buildAllMatchers()`. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `#addWildcard` | `#addWildcard(method: string, handlerData: [T, ParamIndexMap])` | `void` | | `#addPath` | `#addPath(method: string, path: string, handler: T, indexes: (number | string)[], map: ParamIndexMap | undefined)` | `void` | | `add` | `add(method: string, path: string, handler: T)` | `void` | | `buildAllMatchers` | `buildAllMatchers()` | `MatcherMap` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#matchers` | `MatcherMap` | | `#relocateMap` | `RelocateMap` | | `match` | `typeof match, T>` | ## Where it refuses work - `PreparedRegExpRouter` stops the work with `Error` when `!data`. ## Diagram ```mermaid graph LR A[add method path handler] --> B{Route pattern} B -->|Path| C[#addPath] B -->|Wildcard| D[#addWildcard] C --> E[Prepared route data] D --> E E --> F[buildAllMatchers] F --> G[MatcherMap] ``` ## Usage ```ts import { PreparedRegExpRouter } from './src/router/reg-exp-router/prepared-router' type Handler = (request: Request) => Response const router = new PreparedRegExpRouter() router.add('GET', '/articles/:slug', (request) => { return new Response(`Article request: ${request.url}`) }) router.add('GET', '/assets/*', () => { return new Response('Asset request') }) const matchers = router.buildAllMatchers() // Pass `matchers` to the router component that resolves requests. ``` ## AI Coding Instructions - Register routes through `add()`; keep `#addPath()` and `#addWildcard()` as internal preparation details. - Preserve the generic `T` consistently between registered handlers and the resulting `MatcherMap`. - Handle wildcard paths through the existing wildcard flow rather than adding separate matcher logic at call sites. - Build matchers after route registration and pass the resulting map to the request-matching layer. ## How it works - `PreparedRegExpRouter` is a `Router` implementation whose `name` is `"PreparedRegExpRouter"`. Its constructor accepts a prebuilt `MatcherMap` and a relocation map, then stores both in private fields. [src/router/reg-exp-router/prepared-router.ts:9-17] - It expects its initialization data to describe the paths that may later be registered. `buildInitParams({ paths })` builds that data by adding every path to a temporary `RegExpRouter` under the `ALL` method, exporting its compiled matchers, recording where each path’s handlers and parameter-index map belong, and clearing those handler slots before returning `[matchers, relocateMap]`. [src/router/reg-exp-router/prepared-router.ts:95-153] - `add(method, path, handler)` registers a handler into the already prepared matcher data. If the specified method has no matcher entry, it creates one by copying the `ALL` matcher’s regular expression, handler lists, and static-route handler lists. [src/router/reg-exp-router/prepared-router.ts:47-59] - For `'*'` and `'/*'`, `add` creates `[handler, {}]`; for a specific method it appends that pair to every existing dynamic and static handler list for that method. For `ALL`, it does the same for every matcher currently present. [src/router/reg-exp-router/prepared-router.ts:19-23] [src/router/reg-exp-router/prepared-router.ts:61-70] - For every non-wildcard path, `add` requires an entry in the relocation map. If none exists, it throws `Error("Path is not registered")`. [src/router/reg-exp-router/prepared-router.ts:73-76] The relocation data determines whether the handler is appended to a static-path list or one or more dynamic handler lists, and associates the handler with the recorded `ParamIndexMap`. [src/router/reg-exp-router/prepared-router.ts:25-45] With method `ALL`, this insertion is repeated for each current matcher; otherwise it is done only for the selected method. [src/router/reg-exp-router/prepared-router.ts:77-85] - `match(method, path)` is the shared regular-expression matcher. It selects the matcher for `method`, falling back to the `ALL` matcher; it first checks an exact static-path entry, then tests the path against the matcher regular expression. [src/router/reg-exp-router/matcher.ts:10-24] A non-match returns `[[], emptyParam]`; a dynamic match selects a handler list from the first empty capture after index 0 and returns that list with the regular-expression match array. [src/router/reg-exp-router/matcher.ts:22-29] On its first call, this function replaces the instance’s `match` property with the bound matching closure. [src/router/reg-exp-router/matcher.ts:10-12] [src/router/reg-exp-router/matcher.ts:31-32] `PreparedRegExpRouter` assigns this function as its `match` member. [src/router/reg-exp-router/prepared-router.ts:92] - A match result contains handler and parameter-index-map pairs plus a parameter stash, as represented by `Result`; static routes use an empty parameter stash. [src/router.ts:67-98] [src/router/reg-exp-router/matcher.ts:17-20] Parameter-index maps are records from parameter names to numeric capture positions. [src/router.ts:54-58] - `buildInitParams` omits wildcard paths from the relocation map, because wildcard registration is handled directly by `add`. [src/router/reg-exp-router/prepared-router.ts:61-70] [src/router/reg-exp-router/prepared-router.ts:111-115] It also merges parameter maps and records distinct dynamic or static handler locations for each non-wildcard path. [src/router/reg-exp-router/prepared-router.ts:116-143] - `serializeInitParams` converts constructor parameters to a JavaScript array-expression string. It serializes `RegExp` values through `toString()`, removes the marker quoting, adjusts doubled backslashes, and appends JSON for the relocation map. [src/router/reg-exp-router/prepared-router.ts:156-165] ## Relationships - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `match` - IMPORTS → `emptyParam` - IMPORTS → `RegExpRouter` # GET_MATCH_RESULT **Kind:** Constant **Source:** [`src/request/constants.ts`](https://github.com/honojs/hono/blob/main/src/request/constants.ts#L1) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `matchedRoutes` — `src/helper/route/index.ts`:32 - `HonoRequest` — `src/request.ts`:34 # handle **Kind:** Function **Source:** [`src/adapter/service-worker/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/service-worker/handler.ts#L18) **Part of:** [Adapter](subsystem-src-adapter) Adapter for Service Worker `handle` adapts Service Worker fetch events to the application's request handler. It receives an incoming request, runs it through the adapter flow, and returns the response used by the Service Worker. ## Signature ```ts function handle(app: Hono, opts: HandleOptions): Handler ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | | `opts` | `HandleOptions` | **Returns:** `Handler` ## Diagram ```mermaid graph LR FetchEvent[Service Worker fetch event] --> Request[Request] Request --> Handle[handle] Handle --> App[Application handler] App --> Response[Response] Response --> FetchEvent ``` ## Usage ```ts import { handle } from './handler' self.addEventListener('fetch', (event) => { event.respondWith(handle(event.request)) }) ``` ## AI Coding Instructions - Keep the Service Worker adapter focused on converting incoming requests into application handler calls. - Return the handler response directly so `fetch` events receive a valid `Response`. - Register `handle` through `event.respondWith(...)` when wiring Service Worker fetch events. - Do not add browser window APIs to this module; Service Worker code runs in a worker context. # JSXNode **Kind:** Class **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L171) **Part of:** [Jsx](subsystem-src-jsx) `JSXNode` represents a JSX node and exposes conversion methods for rendering its contents. Call `toString()` to obtain rendered text, or call `toStringToBuffer()` when integrating with buffer-oriented output handling. **Implements:** `HtmlEscaped` ## Methods | Method | Signature | Returns | |---|---|---| | `toString` | `toString()` | `string | Promise` | | `toStringToBuffer` | `toStringToBuffer(buffer: StringBufferWithCallbacks)` | `void` | ## Properties | Property | Type | |---|---| | `tag` | `string | Function` | | `props` | `Props` | | `key` | `string` | | `children` | `Child[]` | | `isEscaped` | `true` | ## Where it refuses work - `JSXNode` stops the work with `Error` when `typeof tag !== 'function' && !isValidTagName(tag)`. - `JSXNode` stops the work with `Error` when `children.length > 0` — “Can only set one of `children` or `props.dangerouslySetInnerHTML`.”. - `JSXNode` stops the work with `Error` when `!key.startsWith('on') && key !== 'ref'`. ## Diagram ```mermaid graph LR JSXNode --> ToString["toString(): string | Promise"] JSXNode --> ToBuffer["toStringToBuffer(): void"] ToString --> Text["Rendered string"] ToBuffer --> BufferOutput["Buffer-oriented output"] ``` ## Usage ```ts import { JSXNode } from "./jsx/base"; async function renderNode(node: JSXNode): Promise { return await node.toString(); } function writeNodeToBuffer(node: JSXNode): void { node.toStringToBuffer(); } ``` ## AI Coding Instructions - Handle `toString()` as potentially asynchronous; use `await` when consuming its result. - Keep string rendering and buffer-oriented output separate by calling the method that matches the caller's output path. - Do not assume `toStringToBuffer()` returns rendered content; its return type is `void`. - Pass `JSXNode` instances through rendering boundaries rather than converting them early when later output handling may differ. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `title` — `src/jsx/intrinsic-element/components.ts`:121 - `StreamingContext` — `src/jsx/streaming.ts`:30 # LinearRouter **Kind:** Class **Source:** [`src/router/linear-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/linear-router/router.ts#L11) **Part of:** [Router](subsystem-src-router) `LinearRouter` registers route entries through `add()` and resolves matching entries through `match()`. It stores handlers of type `T` and returns a `Result` for each match attempt. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `add` | `add(method: string, path: string, handler: T)` | `void` | | `match` | `match(method: string, path: string)` | `Result` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#routes` | `[string, string, T][]` | ## Where it refuses work - `LinearRouter` stops the work with `UnsupportedPathError` when `hasLabel && hasStar`. ## Diagram ```mermaid graph LR RouteDefinition --> add["LinearRouter.add()"] add --> RouteTable Request --> match["LinearRouter.match()"] RouteTable --> match match --> Result["Result"] ``` ## Usage ```ts import { LinearRouter } from "./src/router/linear-router/router"; type Handler = () => string; const router = new LinearRouter(); router.add("GET", "/users/:id", () => "User route matched"); router.add("GET", "/health", () => "Service is available"); const result = router.match("GET", "/users/ada"); console.log(result); ``` ## AI Coding Instructions - Keep the handler type `T` consistent for every route registered on the same router instance. - Register routes with `add()` before attempting to resolve them with `match()`. - Treat the value returned by `match()` as a `Result`; handle both matching and non-matching outcomes according to its defined shape. - Preserve route registration order when changing route setup, since a linear router evaluates stored route entries during matching. ## Relationships - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `UnsupportedPathError` - IMPORTS → `checkOptionalParameter` # mergePath **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L11) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function mergePath(base: string, path: string) ``` ## Parameters | Name | Type | |---|---| | `base` | `string` | | `path` | `string` | ## Relationships - IMPORTS → `fetchRP` - IMPORTS → `DetailedError` # normalizeLanguage **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L84) **Part of:** [Middleware](subsystem-src-middleware) Validate and normalize language codes `normalizeLanguage` validates an incoming language code and converts it to the format expected by the language middleware. It acts as a boundary between external request values and the normalized language value used by the application. ## Signature ```ts function normalizeLanguage(lang: string | null | undefined, options: DetectorOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `lang` | `string | null | undefined` | | `options` | `DetectorOptions` | **Returns:** `string | undefined` ## Diagram ```mermaid graph LR A[Incoming language code] --> B[normalizeLanguage] B --> C{Valid code?} C -->|Yes| D[Normalized language code] C -->|No| E[Fallback or validation result] ``` ## Usage ```ts import { normalizeLanguage } from './middleware/language/language'; const requestedLanguage = 'EN-us'; const language = normalizeLanguage(requestedLanguage); console.log(language); ``` ## AI Coding Instructions - Pass request-derived language values through `normalizeLanguage` before using them for locale selection or translations. - Keep language-code formatting rules in this function rather than duplicating case conversion or validation in middleware callers. - Preserve the function’s handling of invalid or missing values when changing language middleware behavior. - Update callers and tests together if supported language codes or fallback behavior changes. # rawCssString **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L32) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function rawCssString(value: string): CssEscapedString ``` ## Parameters | Name | Type | |---|---| | `value` | `string` | **Returns:** `CssEscapedString` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # StreamingApi **Kind:** Class **Source:** [`src/utils/stream.ts`](https://github.com/honojs/hono/blob/main/src/utils/stream.ts#L6) **Part of:** [Utils](subsystem-src-utils) `StreamingApi` coordinates streamed output, delayed work, piping, and cancellation in `src/utils/stream.ts`. It exposes async write methods alongside abort handling so callers can stop work when the stream is no longer active. ## Methods | Method | Signature | Returns | |---|---|---| | `write` | `write(input: Uint8Array | string)` | `Promise` | | `writeln` | `writeln(input: string)` | `Promise` | | `sleep` | `sleep(ms: number)` | `Promise` | | `close` | `close()` | `void` | | `pipe` | `pipe(body: ReadableStream)` | `void` | | `onAbort` | `onAbort(listener: () => void | Promise)` | `void` | | `abort` | `abort()` | `void` | ## Properties | Property | Type | |---|---| | `responseReadable` | `ReadableStream` | | `aborted` | `boolean` | | `closed` | `boolean` | ## When something fails - `StreamingApi` handles failure in 2 places: it discards it silently in all 2. ## Diagram ```mermaid graph LR Caller --> StreamingApi StreamingApi --> Write[write / writeln] StreamingApi --> Delay[sleep] StreamingApi --> Pipe[pipe] StreamingApi --> Abort[onAbort / abort] StreamingApi --> Close[close] ``` ## Usage ```ts import type { StreamingApi } from "./utils/stream"; async function handleStream(stream: StreamingApi) { stream.onAbort(() => { console.log("Stream aborted"); }); await stream.write(); await stream.writeln(); await stream.sleep(); stream.close(); } ``` ## AI Coding Instructions - Await `write()` and `writeln()` before dependent streamed work. - Register `onAbort()` handlers before starting long-running work. - Stop pending work when an abort handler runs; do not continue writing after cancellation. - Call `close()` when streaming is complete. - Keep stream lifecycle handling in the caller that owns the request or response. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `SSEMessage` — `src/helper/streaming/sse.ts`:6 - `stream` — `src/helper/streaming/stream.ts`:7 # bearerAuth **Kind:** Function **Source:** [`src/middleware/bearer-auth/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/bearer-auth/index.ts#L104) **Part of:** [Middleware](subsystem-src-middleware) Bearer Auth Middleware for Hono. `bearerAuth` is Hono middleware that validates the Bearer token from an incoming request’s `Authorization` header. Apply it to routes or an app to reject requests with missing or invalid tokens before the route handler runs. ## Signature ```ts function bearerAuth(options: BearerAuthOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `BearerAuthOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[bearerAuth middleware] Middleware --> Header[Authorization header] Header --> Token[Bearer token validation] Token -->|Valid| Handler[Route handler] Token -->|Missing or invalid| Unauthorized[Unauthorized response] ``` ## Usage ```ts import { Hono } from 'hono' import { bearerAuth } from 'hono/bearer-auth' const app = new Hono() app.use( '/api/*', bearerAuth({ token: 'my-secret-token', }) ) app.get('/api/profile', (c) => { return c.json({ message: 'Authenticated request' }) }) export default app ``` ## AI Coding Instructions - Apply `bearerAuth` before handlers that require authenticated requests. - Pass the expected token with the `token` option, or provide token verification logic when authentication rules need custom validation. - Send credentials through the `Authorization: Bearer ` request header. - Scope middleware to protected route prefixes when public routes must remain accessible. ## Relationships - IMPORTS → `HTTPException` - IMPORTS → `timingSafeEqual` # ClientRequest **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L67) **Part of:** [Client](subsystem-src-client) ## Definition ```ts { [M in keyof ExpandAllMethod]: ExpandAllMethod[M] extends Endpoint & { input: infer R } ? R extends object ? HasRequiredKeys extends true ? ( args: R, options?: ClientRequestOptions ) => Promise[M]>> : ( args?: R, options?: ClientRequestOptions ) => Promise[M]>> : never : never } & { $url: < const Arg extends | (S[keyof S] extends { input: infer R } ? R extends { param: infer P } ? R extends { query: infer Q } ? { param: P; query: Q } : { param: P } : R extends { query: infer Q } ? { query: Q } : {} : {}) | undefined = undefined, >( arg?: Arg ) => HonoURL $path: < const Arg extends | (S[keyof S] extends { input: infer R } ? R extends { param: infer P } ? R extends { query: infer Q } ? { param: P; query: Q } : { param: P } : R extends { query: infer Q } ? { query: Q } : {} : {}) | undefined = undefined, >( arg?: Arg ) => BuildPath } & (S['$get'] extends { outputFormat: 'ws' } ? S['$get'] extends { input: infer I } ? { $ws: (args?: I) => WebSocket } : {} : {}) ``` # cloneRawRequest **Kind:** Function **Source:** [`src/request.ts`](https://github.com/honojs/hono/blob/main/src/request.ts#L472) Clones a HonoRequest's underlying raw Request object. This utility handles both consumed and unconsumed request bodies: - If the request body hasn't been consumed, it uses the native `clone()` method - If the request body has been consumed, it reconstructs a new Request using cached body data This is particularly useful when you need to: - Process the same request body multiple times - Pass requests to external services after validation `cloneRawRequest` creates a new native `Request` from a `HonoRequest` without losing access to its body. It calls `Request.clone()` when the body is unconsumed and rebuilds the request from Hono's cached body data when the body has already been read. ## Signature ```ts async function cloneRawRequest(req: HonoRequest): Promise ``` ## Parameters | Name | Type | |---|---| | `req` | `HonoRequest` | **Returns:** `Promise` ## Diagram ```mermaid graph LR A[HonoRequest] --> B{Raw body consumed?} B -->|No| C[raw.clone()] B -->|Yes| D[Read cached body data] D --> E[Create new Request] C --> F[Cloned Request] E --> F ``` ## Usage ```ts import { Hono } from 'hono' import { cloneRawRequest } from './request' const app = new Hono() app.post('/validate-and-forward', async (c) => { const payload = await c.req.json() if (!payload.email) { return c.json({ error: 'email is required' }, 400) } const requestToForward = cloneRawRequest(c.req) const response = await fetch('https://api.example.com/submit', { method: requestToForward.method, headers: requestToForward.headers, body: requestToForward.body, duplex: 'half', }) return new Response(response.body, response) }) ``` ## AI Coding Instructions - Pass the `HonoRequest` instance to `cloneRawRequest`, not only its `raw` property, so cached body data remains available. - Use this function before forwarding a request when middleware or validation may have already read the body. - Treat the returned value as a native `Request` and pass it to APIs such as `fetch`. - Do not assume `request.raw.clone()` works after the request body has been consumed; use `cloneRawRequest` for that case. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `handler` — `src/middleware/cache/index.ts`:310 # handleMiddleware **Kind:** Function **Source:** [`src/adapter/cloudflare-pages/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-pages/handler.ts#L49) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function handleMiddleware(middleware: MiddlewareHandler< E & { Bindings: { eventContext: EventContext } }, P, I >): PagesFunction ``` ## Parameters | Name | Type | |---|---| | `middleware` | `MiddlewareHandler< E & { Bindings: { eventContext: EventContext } }, P, I >` | **Returns:** `PagesFunction` # renderToReadableStream **Kind:** Function **Source:** [`src/jsx/streaming.ts`](https://github.com/honojs/hono/blob/main/src/jsx/streaming.ts#L146) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function renderToReadableStream(content: HtmlEscapedString | JSXNode | Promise, onError: (e: unknown) => string | void): ReadableStream ``` ## Parameters | Name | Type | |---|---| | `content` | `HtmlEscapedString | JSXNode | Promise` | | `onError` | `(e: unknown) => string | void` | **Returns:** `ReadableStream` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `RenderToStringOptions` — `src/jsx/dom/server.ts`:11 - `RequestContext` — `src/middleware/jsx-renderer/index.ts`:14 # SmartRouter **Kind:** Class **Source:** [`src/router/smart-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/smart-router/router.ts#L4) **Part of:** [Router](subsystem-src-router) `SmartRouter` registers routes with `add()` and resolves incoming paths with `match()`, which returns a `Result`. It acts as the routing layer between route definitions and code that needs to select a matching handler or value. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `add` | `add(method: string, path: string, handler: T)` | `void` | | `match` | `match(method: string, path: string)` | `Result` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#routers` | `Router[]` | | `#routes` | `[string, string, T][]` | ## Where it refuses work - `SmartRouter` stops the work with `Error` when `!this.#routes`. - `SmartRouter` stops the work with `Error` when `!this.#routes` — “Fatal error”. - `SmartRouter` stops the work with `Error` when `i === len` — “Fatal error”. - `SmartRouter` stops the work with `Error` when `this.#routes || this.#routers.length !== 1` — “No active router has been determined yet.”. ## When something fails - `SmartRouter` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR Routes[Route definitions] -->|add()| Router[SmartRouter] Request[Incoming path] -->|match()| Router Router --> Result[Result<T>] ``` ## Usage ```ts import { SmartRouter } from './src/router/smart-router/router'; const router = new SmartRouter(); router.add('/users/:id', { handler: 'getUser', }); const result = router.match('/users/ada'); // Handle the returned Result according to its success or failure shape. console.log(result); ``` ## AI Coding Instructions - Register route patterns through `add()` before attempting to resolve paths with `match()`. - Keep values passed to `add()` consistent so callers can handle the `Result` returned by `match()`. - Preserve route-pattern parsing and matching behavior when changing router internals. - Handle both match and non-match outcomes from `match()` rather than assuming every path resolves. ## How it works `SmartRouter` is a `Router` implementation that receives an ordered array of candidate routers and initially stores added routes locally rather than adding them to those candidates immediately. Its initial `name` is `"SmartRouter"`. [src/router/smart-router/router.ts:4-10] A `Router` has a mutable `name`, an `add(method, path, handler)` method, and a `match(method, path)` method returning `Result`. [src/router.ts:29-52] ## Construction and route registration - The constructor requires `{ routers: Router[] }` and stores that array as its candidate-router list. It does not validate that the list is non-empty. [src/router/smart-router/router.ts:9-11] - Before router selection, `add()` appends `[method, path, handler]` tuples to its private route list. [src/router/smart-router/router.ts:13-19] - After selection, the private route list is set to `undefined`; any later `add()` call throws `Error` with `MESSAGE_MATCHER_IS_ALREADY_BUILT`, whose text is `"Can not add a route since the matcher is already built."`. [src/router/smart-router/router.ts:14-16] [src/router/smart-router/router.ts:46-48] [src/router.ts:19-22] ## First match and candidate selection The first call to `match(method, path)` selects one candidate router: 1. It iterates through candidate routers in their configured order. [src/router/smart-router/router.ts:26-35] 2. For each candidate, it calls that candidate’s `add()` once for every locally stored route, then calls the candidate’s `match(method, path)`. [src/router/smart-router/router.ts:35-38] 3. If this work throws `UnsupportedPathError`, it skips that candidate and tries the next one. Any other thrown value is rethrown. [src/router/smart-router/router.ts:39-44] 4. The first candidate that completes these operations is selected, even if its match result contains no handlers; selection is based on the absence of an `UnsupportedPathError`, not on match-result contents. [src/router/smart-router/router.ts:38-49] 5. It replaces its own `match` method with the selected router’s bound `match` method, retains only that router, clears the buffered routes, changes `name` to `"SmartRouter + "`, and returns the first match result. [src/router/smart-router/router.ts:46-60] For example, the default `Hono` constructor creates a `SmartRouter` with `RegExpRouter` first and `TrieRouter` second, unless `options.router` is supplied. [src/hono.ts:26-33] `RegExpRouter` can throw `UnsupportedPathError` when insertion encounters its internal `PATH_ERROR`, which is the error type `SmartRouter` catches for candidate fallback. [src/router/reg-exp-router/router.ts:59-64] [src/router/smart-router/router.ts:39-42] ## Errors and state restrictions - Calling the original `match()` after route buffering has already been cleared would throw `Error('Fatal error')`; under normal selection, that method is replaced before subsequent calls. [src/router/smart-router/router.ts:21-24] [src/router/smart-router/router.ts:46-48] - If every candidate throws `UnsupportedPathError`, `match()` throws `Error('Fatal error')`. [src/router/smart-router/router.ts:40-42] [src/router/smart-router/router.ts:52-55] - If a candidate throws anything other than `UnsupportedPathError` while routes are being added or while matching, that value is rethrown. [src/router/smart-router/router.ts:34-44] - Candidate routers that fail with `UnsupportedPathError` may already have received some buffered routes, because routes are added one at a time before the error is caught; `SmartRouter` does not reset such a candidate. [src/router/smart-router/router.ts:35-42] ## Active router `activeRouter` returns the selected router only after selection has reduced the candidate list to one router and cleared the buffered route list. Otherwise it throws `Error('No active router has been determined yet.')`. [src/router/smart-router/router.ts:63-69] ## Application lifecycle In `HonoBase`, route registration calls `this.router.add(method, path, [handler, routeMetadata])`, and dispatch calls `this.router.match(method, path)`. Thus, for the default router, route buffering ends when dispatch first performs a match. [src/hono-base.ts:386-397] [src/hono-base.ts:419-428] ## Relationships - IMPORTS → `MESSAGE_MATCHER_IS_ALREADY_BUILT` - IMPORTS → `UnsupportedPathError` # timingSafeEqual **Kind:** Function **Source:** [`src/utils/buffer.ts`](https://github.com/honojs/hono/blob/main/src/utils/buffer.ts#L76) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function timingSafeEqual(a, b, hashFunction: Function): Promise ``` ## Parameters | Name | Type | |---|---| | `a` | `any` | | `b` | `any` | | `hashFunction` | `Function` | **Returns:** `Promise` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `handler` — `src/middleware/basic-auth/index.ts`:118 - `bearerAuth` — `src/middleware/bearer-auth/index.ts`:104 # viewTransitionCommon **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L302) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts ViewTransitionType ``` ## Value ```ts (( strings: TemplateStringsArray | CssClassName | undefined, values: CssVariableType[], classNameSlug?: ClassNameSlug, onInvalidSlug?: OnInvalidSlug ): CssClassName => { if (!strings) { // eslint-disable-next-line @typescript-eslint/no-explicit-any strings = [`/* h-v-t ${viewTransitionNameIndex++} */`] as any } const content = Array.isArray(strings) ? cssCommon(strings as… ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # endTime **Kind:** Function **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L208) **Part of:** [Middleware](subsystem-src-middleware) End a timer for the timing middleware. `endTime` stops the timer managed by the timing middleware when request processing finishes. It pairs with the middleware’s timer start logic to calculate and record timing data for the completed request. ## Signature ```ts function endTime(c: Context, name: string, precision: number) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `precision` | `number` | ## Diagram ```mermaid graph LR Request[Incoming request] --> Start[Start timing middleware] Start --> Handler[Request handler] Handler --> End[endTime] End --> Timing[Elapsed timing data] Timing --> Response[Completed response] ``` ## Usage ```ts import { endTime } from './middleware/timing/timing'; // Call after the request handler has completed and the timer state exists. function onRequestComplete(request: Request, response: Response) { endTime(request, response); } ``` ## AI Coding Instructions - Call `endTime` only after the timing middleware has initialized timer state for the request. - Keep timer start and end handling within the same request lifecycle. - Preserve any request or response fields used to store timing data. - Invoke the function from response completion or middleware flow rather than before handler work has finished. # getPattern **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L51) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getPattern(label: string, next: string): Pattern | null ``` ## Parameters | Name | Type | |---|---| | `label` | `string` | | `next` | `string` | **Returns:** `Pattern | null` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Node` — `src/router/trie-router/node.ts`:25 - `matchedRoutes` — `src/helper/route/index.ts`:32 # Hono **Kind:** Class **Source:** [`src/hono.ts`](https://github.com/honojs/hono/blob/main/src/hono.ts#L16) The Hono class extends the functionality of the HonoBase class. It sets up routing and allows for custom options to be passed. `Hono` extends `HonoBase` and creates an application instance with routing support. Use it to register request handlers, configure application options, and route incoming requests to matching handlers. **Extends:** `HonoBase` ## Diagram ```mermaid graph LR Request[Incoming Request] --> Hono[Hono] Hono --> HonoBase[HonoBase] Hono --> Router[Router] Router --> Handler[Route Handler] Handler --> Response[Response] ``` ## Usage ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => { return c.text('Hello from Hono') }) export default app ``` ## AI Coding Instructions - Create application instances with `new Hono()` before registering routes or middleware. - Register routes through the `Hono` instance so requests pass through its configured router. - Pass supported options to the constructor when application-level routing behavior must be configured. - Keep route handlers focused on creating responses through the request context. - Preserve the `HonoBase` inheritance path when changing application setup behavior. ## Relationships - IMPORTS → `HonoOptions` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `CreateHandlersInterface` — `src/helper/factory/index.ts`:20 # isDynamicRoute **Kind:** Function **Source:** [`src/helper/ssg/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/utils.ts#L73) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function isDynamicRoute(path: string): boolean ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `boolean` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `SSG_CONTEXT` — `src/helper/ssg/middleware.ts`:5 - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # jsxDEV **Kind:** Function **Source:** [`src/jsx/jsx-dev-runtime.ts`](https://github.com/honojs/hono/blob/main/src/jsx/jsx-dev-runtime.ts#L12) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function jsxDEV(tag: string | Function, props: Record, key: string): JSXNode ``` ## Parameters | Name | Type | |---|---| | `tag` | `string | Function` | | `props` | `Record` | | `key` | `string` | **Returns:** `JSXNode` ## Relationships - IMPORTS → `jsxFn` - IMPORTS → `Fragment` ## Used by 2 references from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 # PatternRouter **Kind:** Class **Source:** [`src/router/pattern-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/pattern-router/router.ts#L8) **Part of:** [Router](subsystem-src-router) `PatternRouter` stores handlers or values under path patterns and resolves an incoming path against those patterns. Call `add()` to register a pattern, then call `match()` to receive a `Result` for the matching route. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `add` | `add(method: string, path: string, handler: T)` | `void` | | `match` | `match(method: string, path: string)` | `Result` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#routes` | `Route[]` | ## When something fails - `PatternRouter` handles failure in 1 place: it lets it reach the caller in all 1. ## Diagram ```mermaid graph LR A[Pattern and value] --> B[PatternRouter.add] C[Incoming path] --> D[PatternRouter.match] B --> E[Registered patterns] E --> D D --> F[Result] ``` ## Usage ```ts import { PatternRouter } from './router'; const router = new PatternRouter(); router.add('/users/:id', 'user-detail'); router.add('/posts/:slug', 'post-detail'); const result = router.match('/users/42'); console.log(result); ``` ## AI Coding Instructions - Register patterns through `add()` before attempting to resolve paths with `match()`. - Keep the value type consistent with the router generic, such as `PatternRouter` or `PatternRouter`. - Treat the return value from `match()` as a `Result` and handle both matching and non-matching outcomes. - Keep pattern syntax consistent across registrations so route parameters are parsed predictably. ## Relationships - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `UnsupportedPathError` # removeIndexString **Kind:** Function **Source:** [`src/client/utils.ts`](https://github.com/honojs/hono/blob/main/src/client/utils.ts#L55) **Part of:** [Client](subsystem-src-client) ## Signature ```ts function removeIndexString(urlString: string) ``` ## Parameters | Name | Type | |---|---| | `urlString` | `string` | # streamHandle **Kind:** Function **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L138) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function streamHandle(app: Hono): Handler ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | **Returns:** `Handler` # ClientRequestOptions **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L32) **Part of:** [Client](subsystem-src-client) ## Definition ```ts { fetch?: typeof fetch | HonoRequest webSocket?: (...args: ConstructorParameters) => WebSocket init?: RequestInit buildSearchParams?: BuildSearchParamsFn } & (keyof T extends never ? { headers?: | Record | (() => Record | Promise>) } : { headers: T | (() => T | Promise) }) ``` # createBody **Kind:** Function **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L198) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function createBody(method: string, requestBody: CloudFrontRequest['body']): string | Uint8Array | undefined ``` ## Parameters | Name | Type | |---|---| | `method` | `string` | | `requestBody` | `CloudFrontRequest['body']` | **Returns:** `string | Uint8Array | undefined` # isOldBunVersion **Kind:** Function **Source:** [`src/helper/streaming/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/utils.ts#L1) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function isOldBunVersion(): boolean ``` **Returns:** `boolean` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `SSEMessage` — `src/helper/streaming/sse.ts`:6 - `stream` — `src/helper/streaming/stream.ts`:7 # jwt **Kind:** Function **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L54) **Part of:** [Middleware](subsystem-src-middleware) JWT Auth Middleware for Hono. `jwt` creates Hono middleware that reads a JWT from the request, verifies it with the configured options, and stores the decoded payload in the request context. Routes protected by this middleware can read the payload from `c.get('jwtPayload')`. ## Signature ```ts function jwt(options: { secret: SignatureKey cookie?: | string | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions } alg: SignatureAlgorithm headerName?: string realm?: string verification?: VerifyOptions }): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `{ secret: SignatureKey cookie?: | string | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions } alg: SignatureAlgorithm headerName?: string realm?: string verification?: VerifyOptions }` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[jwt middleware] Middleware --> Token[Read JWT] Token --> Verify[Verify signature and claims] Verify -->|Valid| Context[Store jwtPayload in context] Context --> Handler[Route handler] Verify -->|Invalid or missing| Unauthorized[Unauthorized response] ``` ## Usage ```ts import { Hono } from 'hono' import { jwt } from 'hono/jwt' const app = new Hono() app.use( '/api/*', jwt({ secret: 'my-secret-key', }) ) app.get('/api/profile', (c) => { const payload = c.get('jwtPayload') return c.json({ userId: payload.sub, }) }) export default app ``` ## AI Coding Instructions - Register `jwt` before route handlers that read `c.get('jwtPayload')`. - Pass the same secret or public-key configuration used when signing tokens. - Scope the middleware to protected route paths instead of applying it to public endpoints. - Read claims from `jwtPayload` in handlers and validate application-specific fields before granting access. - Return tokens through the expected authorization header format when calling protected routes. # METHOD_NAME_ALL_LOWERCASE **Kind:** Constant **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L13) Constant representing all HTTP methods in lowercase. `METHOD_NAME_ALL_LOWERCASE` stores the lowercase method token for routes that match all HTTP methods. Router code can pass or compare this token when registering method-agnostic routes. ## Definition ```ts 'all' as const ``` ## Value ```ts 'all' as const ``` ## Diagram ```mermaid graph LR A[Route registration] --> B[METHOD_NAME_ALL_LOWERCASE] B --> C[all] C --> D[Router method matching] ``` ## Usage ```ts import { METHOD_NAME_ALL_LOWERCASE } from './router' router.add(METHOD_NAME_ALL_LOWERCASE, '/health', (context) => { return context.text('OK') }) ``` ## AI Coding Instructions - Use `METHOD_NAME_ALL_LOWERCASE` instead of hardcoding the `all` method token. - Pass this constant to router registration code when a route should match any HTTP method. - Keep lowercase and uppercase method tokens distinct when comparing router method values. - Check router matching behavior before changing how all-method routes are registered. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoOptions` — `src/hono-base.ts`:46 # parseBody **Kind:** Function **Source:** [`src/utils/body.ts`](https://github.com/honojs/hono/blob/main/src/utils/body.ts#L97) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function parseBody(request: HonoRequest | Request, options) ``` ## Parameters | Name | Type | |---|---| | `request` | `HonoRequest | Request` | | `options` | `any` | ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `methodFormName` — `src/middleware/method-override/index.ts`:79 - `HonoRequest` — `src/request.ts`:34 # TrieRouter **Kind:** Class **Source:** [`src/router/trie-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/trie-router/router.ts#L5) **Part of:** [Router](subsystem-src-router) `TrieRouter` stores route patterns and their handlers in a trie-based route tree. Use `add()` to register a method and path, then call `match()` to resolve an incoming method and path to a `Result`. **Implements:** `Router` ## Methods | Method | Signature | Returns | |---|---|---| | `add` | `add(method: string, path: string, handler: T)` | `void` | | `match` | `match(method: string, path: string)` | `Result` | ## Properties | Property | Type | |---|---| | `name` | `string` | | `#node` | `Node` | ## Diagram ```mermaid graph LR Route[Route registration] --> Add[add()] Add --> Trie[Trie route tree] Request[Incoming method and path] --> Match[match()] Match --> Trie Trie --> Result[Result] ``` ## Usage ```ts const router = new TrieRouter() router.add('GET', '/articles/:slug', 'getArticle') router.add('POST', '/articles', 'createArticle') const result = router.match('GET', '/articles/intro') // Pass result to the request dispatcher. console.log(result) ``` ## AI Coding Instructions - Keep the handler type consistent for every route registered in the same `TrieRouter` instance. - Register routes through `add()` before matching requests through `match()`. - Pass the HTTP method and request path to `match()` using the same format used during registration. - Handle the returned `Result` in the caller that dispatches matched handlers and processes route parameters. ## How it works - `TrieRouter` is an exported generic router class implementing `Router`. Its public `name` field is `"TrieRouter"`, and each instance initializes one private `Node` as its route storage and matcher. [`src/router/trie-router/router.ts:5-11`](src/router/trie-router/router.ts#L5-L11) - `add(method, path, handler)` registers `handler` for the supplied method and path by inserting it into that private node structure. This mutates the router’s stored routes and has no returned value. [`src/router/trie-router/router.ts:13-23`](src/router/trie-router/router.ts#L13-L23) The underlying insertion splits routing paths into segments, creates child nodes as needed, and appends a method/handler entry at the terminal node. [`src/router/trie-router/node.ts:44-84`](src/router/trie-router/node.ts#L44-L84) - Before insertion, `add` checks for an optional named parameter. When `path` ends in `?` and contains `:`, the helper returns expanded path variants; `TrieRouter` inserts the same handler for every variant. [`src/router/trie-router/router.ts:13-20`](src/router/trie-router/router.ts#L13-L20) For example, `/api/animals/:type?` expands to `/api/animals` and `/api/animals/:type`; a root optional parameter expands to `/` and its parameterized form. [`src/utils/url.ts:171-205`](src/utils/url.ts#L171-L205) [`src/utils/url.test.ts:235-255`](src/utils/url.test.ts#L235-L255) - `match(method, path)` delegates directly to the node search and returns `Result`, whose concrete form here is a one-element tuple containing an array of `[handler, params]` pairs. [`src/router/trie-router/router.ts:25-27`](src/router/trie-router/router.ts#L25-L27) [`src/router/trie-router/node.ts:114-115`](src/router/trie-router/node.ts#L114-L115) [`src/router/trie-router/node.ts:237-244`](src/router/trie-router/node.ts#L237-L244) A non-match returns that same shape with an empty handler array. [`src/router/trie-router/node.test.ts:14-20`](src/router/trie-router/node.test.ts#L14-L20) - Paths support literal segments, named segments such as `:id`, wildcard segments (`*`), and named segments constrained by a regular expression such as `:id{[0-9]+}`. Pattern recognition is performed while adding routes. [`src/utils/url.ts:50-77`](src/utils/url.ts#L50-L77) Named and constrained captures are returned in the parameter record. [`src/router/trie-router/node.ts:165-229`](src/router/trie-router/node.ts#L165-L229) [`src/router/trie-router/node.test.ts:74-108`](src/router/trie-router/node.test.ts#L74-L108) [`src/router/trie-router/node.test.ts:216-234`](src/router/trie-router/node.test.ts#L216-L234) - A registered method is matched exactly; if no exact method entry exists at a matched route node, an entry registered as `ALL` is selected. [`src/router/trie-router/node.ts:94-110`](src/router/trie-router/node.ts#L94-L110) [`src/router.ts:6-13`](src/router.ts#L6-L13) Wildcards can match the remainder of a path and also match when no further segment follows, such as `/hello/*` matching `/hello`. [`src/router/trie-router/node.ts:136-146`](src/router/trie-router/node.ts#L136-L146) [`src/router/trie-router/node.ts:153-163`](src/router/trie-router/node.ts#L153-L163) - Matching can return more than one handler when multiple registered routes match. Returned matches are sorted by their route insertion score, which is incremented for each insertion. [`src/router/trie-router/node.ts:44-46`](src/router/trie-router/node.ts#L44-L46) [`src/router/trie-router/node.ts:237-244`](src/router/trie-router/node.ts#L237-L244) For example, a literal route and a wildcard route can both be returned. [`src/router/trie-router/node.test.ts:125-134`](src/router/trie-router/node.test.ts#L125-L134) - `TrieRouter` itself contains no explicit argument validation or explicit error handling. [`src/router/trie-router/router.ts:9-27`](src/router/trie-router/router.ts#L9-L27) Route patterns with `{...}` are passed to `new RegExp(...)` during insertion, without a catch in the shown code. [`src/utils/url.ts:60-74`](src/utils/url.ts#L60-L74) ## Relationships - IMPORTS → `checkOptionalParameter` - IMPORTS → `Node` # useCallback **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L299) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useCallback(callback: T, deps: readonly unknown[]): T ``` ## Parameters | Name | Type | |---|---| | `callback` | `T` | | `deps` | `readonly unknown[]` | **Returns:** `T` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `FormContext` — `src/jsx/dom/hooks/index.ts`:24 - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # bufferToFormData **Kind:** Function **Source:** [`src/utils/buffer.ts`](https://github.com/honojs/hono/blob/main/src/utils/buffer.ts#L106) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function bufferToFormData(arrayBuffer: ArrayBuffer, contentType: string): Promise ``` ## Parameters | Name | Type | |---|---| | `arrayBuffer` | `ArrayBuffer` | | `contentType` | `string` | **Returns:** `Promise` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `BodyData` — `src/utils/body.ts`:39 - `ValidationFunction` — `src/validator/validator.ts`:14 # buildInitParams **Kind:** Function **Source:** [`src/router/reg-exp-router/prepared-router.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/prepared-router.ts#L95) **Part of:** [Router](subsystem-src-router) ## Signature ```ts function buildInitParams({ paths }) ``` ## Parameters | Name | Type | |---|---| | `{ paths }` | `any` | # BunWebSocketHandler **Kind:** Interface **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L15) **Part of:** [Adapter](subsystem-src-adapter) `BunWebSocketHandler` defines lifecycle callbacks for WebSocket activity in the Bun adapter. Implement `open`, `close`, and `message` to handle connection events and incoming WebSocket messages. ## Diagram ```mermaid graph LR Socket[Bun WebSocket] --> Handler[BunWebSocketHandler] Handler --> Open[open()] Handler --> Message[message()] Handler --> Close[close()] ``` ## Usage ```ts import type { BunWebSocketHandler } from "./websocket"; const websocketHandler: BunWebSocketHandler = { open() { console.log("WebSocket connection opened"); }, message() { console.log("WebSocket message received"); }, close() { console.log("WebSocket connection closed"); }, }; // Provide websocketHandler where the Bun adapter expects a WebSocket handler. ``` ## AI Coding Instructions - Implement all handler methods required by `BunWebSocketHandler`. - Keep connection setup in `open` and cleanup logic in `close`. - Handle incoming WebSocket activity in `message`. - Do not add parameters or return values unless the interface definition is updated. # CLASS_NAME **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L7) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # cors **Kind:** Function **Source:** [`src/middleware/cors/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cors/index.ts#L63) **Part of:** [Middleware](subsystem-src-middleware) CORS Middleware for Hono. `cors` creates Hono middleware that adds Cross-Origin Resource Sharing headers to responses and handles browser preflight requests. Configure it at the app or route scope to control allowed origins, methods, request headers, exposed headers, and credentials. ## Signature ```ts function cors(options: CORSOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `CORSOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[cors options] Middleware --> Check{Preflight request?} Check -->|Yes| Preflight[Return CORS response headers] Check -->|No| Next[Run downstream Hono handler] Next --> Response[Add CORS response headers] ``` ## Usage ```ts import { Hono } from 'hono' import { cors } from 'hono/cors' const app = new Hono() app.use( '/api/*', cors({ origin: 'https://example.com', allowMethods: ['GET', 'POST'], allowHeaders: ['Content-Type', 'Authorization'], credentials: true, }) ) app.get('/api/users', (c) => { return c.json({ users: [] }) }) export default app ``` ## AI Coding Instructions - Register `cors` before the routes that need CORS headers, using `app.use()` with an appropriate path scope. - Set a specific `origin` when `credentials` is enabled; browsers reject credentialed responses with a wildcard origin. - Configure `allowMethods` and `allowHeaders` to match the methods and headers sent by browser clients. - Do not add separate `OPTIONS` handlers for routes covered by this middleware unless custom preflight behavior is required. # createContext **Kind:** Function **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L213) **Part of:** [Jsx](subsystem-src-jsx) Create a context whose value can be provided with `` and read with useContext. Server-side renders are isolated per request, so a provided value never leaks into a concurrent request — even across `await` in an async component, when `AsyncLocalStorage` is available (Node.js >= 20.16, Deno, Bun, Cloudflare Workers with `nodejs_compat`). Without it, reading context after `await` returns the default value; synchronous components and `use()`-based suspension are unaffected. `createContext` creates a context object with a default value, a `` component, and a value that `useContext` can read. During server rendering, context state is isolated by request; reading context after `await` in an async component depends on `AsyncLocalStorage` availability. ## Signature ```ts function createContext(defaultValue: T): Context ``` ## Parameters | Name | Type | |---|---| | `defaultValue` | `T` | **Returns:** `Context` ## Diagram ```mermaid graph LR Default[Default value] --> Context[createContext] Context --> Provider[Context.Provider] Provider --> Tree[Component tree] Tree --> Consumer[useContext] Consumer --> Value[Current context value] ``` ## Usage ```tsx import { createContext, useContext } from "./jsx"; const ThemeContext = createContext("light"); function ThemeLabel() { const theme = useContext(ThemeContext); return Theme: {theme}; } export function App() { return ( ); } ``` ## AI Coding Instructions - Create contexts outside component render functions so consumers reference the same context object. - Wrap consumers with `` when they need a value other than the default. - Use `useContext(Context)` only inside a component render or supported hook execution path. - In async server components, avoid relying on context reads after `await` when `AsyncLocalStorage` is unavailable. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Props` — `src/jsx/base.ts`:27 - `StreamingContext` — `src/jsx/streaming.ts`:30 # METHODS **Kind:** Constant **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L17) Array of supported HTTP methods. `METHODS` is an array of HTTP methods supported by the router. It acts as the method allowlist used when routing incoming requests and validating method-specific behavior. ## Definition ```ts ['get', 'post', 'put', 'delete', 'options', 'patch', 'query'] as const ``` ## Value ```ts ['get', 'post', 'put', 'delete', 'options', 'patch', 'query'] as const ``` ## Diagram ```mermaid graph LR Request[Incoming request] --> Method[HTTP method] Method --> Methods[METHODS] Methods --> Router[Router handling] ``` ## Usage ```ts import { METHODS } from "./router"; function supportsMethod(method: string): boolean { return METHODS.includes(method); } if (supportsMethod(request.method)) { // Route the request } ``` ## AI Coding Instructions - Keep `METHODS` aligned with the HTTP methods handled by the router. - Check request methods against `METHODS` before dispatching route handlers. - Update method-specific routing logic when adding or removing entries from `METHODS`. - Preserve the constant as the shared source of truth for supported methods. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoOptions` — `src/hono-base.ts`:46 # TypedURL **Kind:** Interface **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L215) **Part of:** [Client](subsystem-src-client) `TypedURL` represents a URL as typed component fields, including protocol, host details, path, search string, origin, and full href. It keeps derived fields such as `host`, `origin`, and `href` aligned with the protocol, hostname, port, pathname, and search values. ## Properties | Property | Type | |---|---| | `protocol` | `Protocol` | | `hostname` | `Hostname` | | `port` | `Port` | | `host` | `Port extends '' ? Hostname : `${Hostname}:${Port}`` | | `origin` | ``${Protocol}` | | `pathname` | `Pathname` | | `search` | `Search` | | `href` | ``${Protocol}` | ## Diagram ```mermaid graph LR Protocol[protocol] --> Origin[origin] Hostname[hostname] --> Host[host] Port[port] --> Host Host --> Origin Origin --> Href[href] Pathname[pathname] --> Href Search[search] --> Href ``` ## Usage ```ts function request(url: TypedURL) { return fetch(url.href); } const apiUrl: TypedURL = { protocol: "https:", hostname: "api.example.com", port: "", host: "api.example.com", origin: "https://api.example.com", pathname: "/users", search: "?active=true", href: "https://api.example.com/users?active=true", }; request(apiUrl); ``` ## AI Coding Instructions - Keep `host` consistent with `hostname` and `port`; omit the colon when `port` is an empty string. - Build `origin` from the protocol and host rather than accepting unrelated values. - Build `href` from the origin, pathname, and search fields. - Preserve literal string types when constructing values so derived template-literal types remain valid. # Client **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L311) **Part of:** [Client](subsystem-src-client) ## Definition ```ts T extends HonoBase ? S extends Record ? K extends string ? PathToChain : never : never : never ``` # compress **Kind:** Function **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L72) **Part of:** [Middleware](subsystem-src-middleware) Compress Middleware for Hono. `compress` creates Hono middleware that compresses eligible HTTP responses based on the client’s `Accept-Encoding` header. Apply it to routes or the application to reduce response body size while preserving the response flow. ## Signature ```ts function compress(options: CompressionOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `CompressionOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR A[Client Request] --> B[Hono App] B --> C[Route Handler] C --> D[Response] D --> E{Accept-Encoding supports compression?} E -->|Yes| F[compress middleware] E -->|No| G[Uncompressed Response] F --> H[Compressed Response] ``` ## Usage ```ts import { Hono } from 'hono' import { compress } from 'hono/compress' const app = new Hono() app.use('*', compress()) app.get('/data', (c) => { return c.json({ message: 'This response can be compressed when supported by the client.', }) }) export default app ``` ## AI Coding Instructions - Register `compress()` before route handlers when responses from those routes should be compressed. - Keep response headers and bodies valid before middleware returns the final response. - Test requests with different `Accept-Encoding` headers when changing compression behavior. - Apply the middleware to a route pattern when only part of the application should return compressed responses. # DEFAULT_STYLE_ID **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L4) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts 'hono-css' ``` ## Value ```ts 'hono-css' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # getConnInfo **Kind:** Function **Source:** [`src/adapter/bun/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/conninfo.ts#L10) **Part of:** [Adapter](subsystem-src-adapter) Get ConnInfo with Bun `getConnInfo` reads connection details for the current request when running on Bun. It is intended for handlers that need access to request connection metadata through the Bun adapter. ## Signature ```ts function getConnInfo(c: Context) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | ## Diagram ```mermaid graph LR Request --> Context Context --> getConnInfo getConnInfo --> BunServer BunServer --> ConnInfo ConnInfo --> Handler ``` ## Usage ```ts import { Hono } from 'hono' import { getConnInfo } from 'hono/bun' const app = new Hono() app.get('/connection', (c) => { const connInfo = getConnInfo(c) return c.json(connInfo) }) export default app ``` ## AI Coding Instructions - Call `getConnInfo` from a request handler with the active Hono context. - Use this Bun-specific helper only when the application is running with the Bun adapter. - Keep connection metadata handling separate from request parsing and response creation. - Handle missing or unavailable connection details before relying on them for application logic. ## Relationships - IMPORTS → `getBunServer` # isValidAttributeName **Kind:** Function **Source:** [`src/jsx/utils.ts`](https://github.com/honojs/hono/blob/main/src/jsx/utils.ts#L49) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function isValidAttributeName(name: string): boolean ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | **Returns:** `boolean` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Props` — `src/jsx/base.ts`:27 - `jsxAttr` — `src/jsx/jsx-runtime.ts`:16 # resolveCallbackSync **Kind:** Function **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L129) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function resolveCallbackSync(str: string | HtmlEscapedString): string ``` ## Parameters | Name | Type | |---|---| | `str` | `string | HtmlEscapedString` | **Returns:** `string` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `html` — `src/helper/html/index.ts`:11 - `Props` — `src/jsx/base.ts`:27 # serializeInitParams **Kind:** Function **Source:** [`src/router/reg-exp-router/prepared-router.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/prepared-router.ts#L156) **Part of:** [Router](subsystem-src-router) ## Signature ```ts function serializeInitParams([matchers, relocateMap]) ``` ## Parameters | Name | Type | |---|---| | `[matchers, relocateMap]` | `any` | # TEXT_PLAIN **Kind:** Constant **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L279) ## Definition ```ts 'text/plain; charset=UTF-8' ``` ## Value ```ts 'text/plain; charset=UTF-8' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `streamText` — `src/helper/streaming/text.ts`:6 # Context **Kind:** Interface **Source:** [`src/router/reg-exp-router/node.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/node.ts#L7) **Part of:** [Router](subsystem-src-router) `Context` stores the current variable index while regular-expression route nodes are created. It is passed through route-node insertion so parameter captures can keep consistent positions within generated patterns. ## Properties | Property | Type | |---|---| | `varIndex` | `number` | ## Diagram ```mermaid graph LR Context --> varIndex Context --> RouteNodeInsertion RouteNodeInsertion --> RegExpPattern ``` ## Usage ```ts const context: Context = { varIndex: currentVariableIndex, } function addRouteVariable(context: Context): number { const variableIndex = context.varIndex context.varIndex = getNextVariableIndex(variableIndex) return variableIndex } ``` ## AI Coding Instructions - Keep `varIndex` as a numeric value representing the current route-variable position. - Pass the same `Context` object through related route-node insertion calls when variable positions must remain aligned. - Update `varIndex` only when adding a route segment that introduces a variable capture. - Do not reset `varIndex` during nested node insertion unless starting a separate route-building context. ## How it works `Context` is an exported TypeScript interface used as mutable insertion state by the regular-expression router’s trie. It contains exactly one numeric field, `varIndex`. [src/router/reg-exp-router/node.ts:7-9] - `Node.insert()` requires a `Context` argument. [src/router/reg-exp-router/node.ts:51-57] - Each `Trie` creates one context with `varIndex: 0` and passes that same instance to every root-node insertion. [src/router/reg-exp-router/trie.ts:6-9] [src/router/reg-exp-router/trie.ts:13-17] [src/router/reg-exp-router/trie.ts:54-55] - When inserting a named dynamic path token, `Node.insert()` assigns the current `context.varIndex` to the target node only if that node has no prior variable index, then increments `context.varIndex`; it also appends the parameter name and assigned index to `paramMap`. [src/router/reg-exp-router/node.ts:74-77] [src/router/reg-exp-router/node.ts:108-110] - Wildcard patterns have an empty captured name, so they do not take a `varIndex` or add a parameter association. [src/router/reg-exp-router/node.ts:64-70] [src/router/reg-exp-router/node.ts:108-110] - The assigned index is emitted as an `@` marker while building the trie’s regular-expression string. [src/router/reg-exp-router/node.ts:137-151] `Trie.buildRegExp()` converts those markers into entries in a parameter replacement map, associating each variable index with a regular-expression capture index. [src/router/reg-exp-router/trie.ts:64-81] `Context` itself has no runtime validation or declared errors; its visible side effect is mutation of `varIndex` during named-parameter insertion. [src/router/reg-exp-router/node.ts:7-9] [src/router/reg-exp-router/node.ts:108-110] # except **Kind:** Function **Source:** [`src/middleware/combine/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/combine/index.ts#L141) **Part of:** [Middleware](subsystem-src-middleware) Create a composed middleware that runs all middleware except when the condition is met. `except` creates a middleware handler that evaluates a condition before running the middleware passed to it. When the condition matches, it skips the composed middleware and continues to the next handler; otherwise, it runs the composed middleware. ## Signature ```ts function except(condition: string | Condition | (string | Condition)[], middleware: MiddlewareHandler[]): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `condition` | `string | Condition | (string | Condition)[]` | | `middleware` | `MiddlewareHandler[]` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Request] --> Condition{Condition matches?} Condition -->|Yes| Next[Next handler] Condition -->|No| Compose[Compose middleware] Compose --> Middleware[Middleware handlers] Middleware --> Next ``` ## Usage ```ts import { Hono } from 'hono' import { except } from 'hono/combine' import { bearerAuth } from 'hono/bearer-auth' const app = new Hono() app.use( '/api/*', except( (c) => c.req.path === '/api/health', bearerAuth({ token: 'secret-token' }) ) ) app.get('/api/health', (c) => c.text('ok')) app.get('/api/profile', (c) => { return c.json({ id: 'user' }) }) ``` ## AI Coding Instructions - Return `true` from the condition when the middleware should be skipped. - Keep condition checks limited to request data available on the context. - Pass middleware handlers after the condition; they run only when the condition does not match. - Ensure skipped requests can be handled by a later route or middleware handler. # FilterClientResponseByStatusCode **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L284) **Part of:** [Client](subsystem-src-client) Filter a ClientResponse type so it only includes responses of specific status codes. `FilterClientResponseByStatusCode` filters a `ClientResponse` union by its status-code type. It returns only the response members whose `status` matches the requested status-code type, which lets handlers work with the matching response shape. ## Definition ```ts T extends ClientResponse ? RC extends U ? ClientResponse : never : never ``` ## Diagram ```mermaid graph LR A[ClientResponse union] --> C[FilterClientResponseByStatusCode] B[Requested status-code type] --> C C --> D[Matching response members] ``` ## Usage ```ts import type { ClientResponse, FilterClientResponseByStatusCode, } from "./types"; type StatusHandler< TResponse extends ClientResponse, TStatusCode extends number, > = ( response: FilterClientResponseByStatusCode, ) => void; // Use this type when a handler accepts only responses for TStatusCode. const handleResponse = < TResponse extends ClientResponse, TStatusCode extends number, >( response: FilterClientResponseByStatusCode, ) => { return response.status; }; ``` ## AI Coding Instructions - Pass the full `ClientResponse` union as the response type argument. - Pass a status-code type or status-code union that matches the client response definitions. - Keep filtering at the type level; this type does not validate a runtime response. - Handle the filtered result as a narrowed response shape, including its matching data or error fields. # findTargetHandler **Kind:** Function **Source:** [`src/utils/handler.ts`](https://github.com/honojs/hono/blob/main/src/utils/handler.ts#L9) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function findTargetHandler(handler: Function): Function ``` ## Parameters | Name | Type | |---|---| | `handler` | `Function` | **Returns:** `Function` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `inspectRoutes` — `src/helper/dev/index.ts`:27 - `dirname` — `src/helper/ssg/utils.ts`:11 # getConnInfo **Kind:** Function **Source:** [`src/adapter/aws-lambda/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/conninfo.ts#L45) **Part of:** [Adapter](subsystem-src-adapter) Get connection information from AWS Lambda Extracts client IP from various Lambda event sources: - API Gateway v1 (REST API): requestContext.identity.sourceIp - API Gateway v2 (HTTP API/Function URLs): requestContext.http.sourceIp - ALB: Falls back to x-forwarded-for header `getConnInfo` reads AWS Lambda event data to determine client connection information, including the client IP address. It supports API Gateway REST API events, HTTP API or Function URL events, and ALB events through the `x-forwarded-for` header. ## Signature ```ts function getConnInfo(c: Context) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | ## Diagram ```mermaid graph LR Event[AWS Lambda event] --> Context[requestContext] Context --> V1[identity.sourceIp
API Gateway v1] Context --> V2[http.sourceIp
API Gateway v2 / Function URL] Event --> Headers[headers] Headers --> ALB[x-forwarded-for
ALB fallback] V1 --> ConnInfo[getConnInfo result] V2 --> ConnInfo ALB --> ConnInfo ``` ## Usage ```ts import { getConnInfo } from './src/adapter/aws-lambda/conninfo'; export async function handler(event: unknown) { const connInfo = getConnInfo(event); console.log('Connection information:', connInfo); return { statusCode: 200, body: JSON.stringify({ ok: true }), }; } ``` ## AI Coding Instructions - Pass the original Lambda event to `getConnInfo` so it can inspect `requestContext` and headers. - Keep support for both `requestContext.identity.sourceIp` and `requestContext.http.sourceIp` when changing event handling. - Treat `x-forwarded-for` as the fallback source for ALB events, and account for missing or differently cased headers. - Avoid assuming every Lambda event has the same `requestContext` shape. # PSEUDO_GLOBAL_SELECTOR **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L2) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts ':-hono-global' ``` ## Value ```ts ':-hono-global' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # shouldDeDupeByKey **Kind:** Function **Source:** [`src/jsx/intrinsic-element/common.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/common.ts#L18) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function shouldDeDupeByKey(tagName: string, supportSort: boolean): boolean ``` ## Parameters | Name | Type | |---|---| | `tagName` | `string` | | `supportSort` | `boolean` | **Returns:** `boolean` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # validator **Kind:** Function **Source:** [`src/validator/validator.ts`](https://github.com/honojs/hono/blob/main/src/validator/validator.ts#L46) ## Signature ```ts function validator(target: U, validationFunc: VF): MiddlewareHandler> ``` ## Parameters | Name | Type | |---|---| | `target` | `U` | | `validationFunc` | `VF` | **Returns:** `MiddlewareHandler>` # ApplyGlobalResponse **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L358) **Part of:** [Client](subsystem-src-client) ## Definition ```ts App extends HonoBase ? ModSchema, Def> extends infer S extends Schema ? Hono : never : never ``` # FetchEventLike **Kind:** Class **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2773) `FetchEventLike` represents the event object handled during a fetch request. It coordinates response handling, exception pass-through behavior, and asynchronous work tied to the request lifecycle. ## Methods | Method | Signature | Returns | |---|---|---| | `respondWith` | `respondWith(promise: Response | Promise)` | `void` | | `passThroughOnException` | `passThroughOnException()` | `void` | | `waitUntil` | `waitUntil(promise: Promise)` | `void` | ## Properties | Property | Type | |---|---| | `request` | `Request` | ## Diagram ```mermaid graph LR Handler[Fetch handler] --> Event[FetchEventLike] Event --> Response[respondWith()] Event --> Exceptions[passThroughOnException()] Event --> Background[waitUntil()] ``` ## Usage ```ts function handleFetch(event: FetchEventLike): void { event.passThroughOnException(); event.waitUntil(); event.respondWith(); } ``` ## AI Coding Instructions - Pass `FetchEventLike` into fetch handler code instead of depending on a platform-specific event type. - Call `respondWith()` when the handler should control the request response. - Call `passThroughOnException()` before work that may fail when fallback request behavior is desired. - Register request-related asynchronous work with `waitUntil()` so it remains associated with the event. ## How it works `FetchEventLike` is an exported abstract TypeScript class that describes the FetchEvent-shaped execution context used by Hono. It declares, but does not implement, four members: a read-only `Request`, `respondWith`, `passThroughOnException`, and `waitUntil`. [src/types.ts:2773-2778] - `request` must be a read-only `Request`. [src/types.ts:2774] - `respondWith` accepts either a `Response` or `Promise` and returns `void`. [src/types.ts:2775] - `passThroughOnException` takes no arguments and returns `void`. [src/types.ts:2776] - `waitUntil` accepts `Promise` and returns `void`. [src/types.ts:2777] Hono stores this type as one possible request execution context, alongside `ExecutionContext`, when constructing a `Context`. [src/context.ts:237-252] During request dispatch, `HonoBase` passes its received execution context into that `Context`. [src/hono-base.ts:407-428] `Context.event` exposes the stored value as `FetchEventLike` only when the value exists and has a `respondWith` property. Otherwise, it throws `Error('This context has no FetchEvent')`. [src/context.ts:377-382] This is the visible runtime validation for access through `c.event`; the check does not verify the declared `request`, `passThroughOnException`, or `waitUntil` members. [src/context.ts:377-382] The service-worker adapter passes its incoming event to `app.fetch` as the execution context and calls that event’s `respondWith` with the app response promise. [src/adapter/service-worker/handler.ts:25-35] Its local service-worker `FetchEvent` declaration has a read-only request, `respondWith`, and `waitUntil`; its `respondWith` also accepts `PromiseLike`. [src/adapter/service-worker/types.ts:1-14] `FetchEventLike` contains no method bodies, validation logic, error handling, or direct side effects of its own; those depend on the concrete event object. [src/types.ts:2773-2778] # Fragment **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L421) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function Fragment({ children, }: { key?: string children?: Child | HtmlEscapedString }): HtmlEscapedString ``` ## Parameters | Name | Type | |---|---| | `{ children, }` | `{ key?: string children?: Child | HtmlEscapedString }` | **Returns:** `HtmlEscapedString` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `childrenToString` — `src/jsx/components.ts`:14 - `jsxDEV` — `src/jsx/jsx-dev-runtime.ts`:12 # handle **Kind:** Function **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L116) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function handle(app: Hono): (( event: CloudFrontEdgeEvent, context?: CloudFrontContext, callback?: Callback ) => Promise) ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | **Returns:** `(( event: CloudFrontEdgeEvent, context?: CloudFrontContext, callback?: Callback ) => Promise)` # HandlerData **Kind:** Type **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L4) **Part of:** [Router](subsystem-src-router) ## Definition ```ts [T, ParamIndexMap][] ``` ## Relationships - IMPORTS → `METHOD_NAME_ALL` # methodNotAllowed **Kind:** Function **Source:** [`src/middleware/method-not-allowed/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-not-allowed/index.ts#L59) **Part of:** [Middleware](subsystem-src-middleware) Method Not Allowed Middleware for Hono. Returns a `405 Method Not Allowed` response with an `Allow` header when the request path matches a registered route but the request method is not supported. `methodNotAllowed` creates Hono middleware that returns a Method Not Allowed response when a request matches a registered path but uses an unsupported HTTP method. It adds an `Allow` header containing the methods registered for that path. ## Signature ```ts function methodNotAllowed(options: MethodNotAllowedOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `MethodNotAllowedOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request --> Router Router -->|Path and method match| RouteHandler Router -->|Path matches, method does not| MethodNotAllowed MethodNotAllowed --> AllowHeader AllowHeader --> Response ``` ## Usage ```ts import { Hono } from 'hono' import { methodNotAllowed } from 'hono/method-not-allowed' const app = new Hono() app.use(methodNotAllowed()) app.post('/entries', (c) => { return c.json({ created: true }) }) export default app ``` ## AI Coding Instructions - Register `methodNotAllowed()` before route definitions so it can inspect routing results after downstream handlers run. - Keep route methods explicit with `app.get`, `app.post`, and related route APIs so the middleware can produce the correct `Allow` header. - Do not replace the Method Not Allowed response or remove its `Allow` header in later middleware. - Use this middleware for applications that need to distinguish an unknown path from a known path with an unsupported method. # SELECTOR **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L6) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # splitRoutingPath **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L16) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function splitRoutingPath(routePath: string): string[] ``` ## Parameters | Name | Type | |---|---| | `routePath` | `string` | **Returns:** `string[]` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Node` — `src/router/trie-router/node.ts`:25 - `matchedRoutes` — `src/helper/route/index.ts`:32 # createContext **Kind:** Function **Source:** [`src/jsx/dom/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/context.ts#L45) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createContext(defaultValue: T): Context ``` ## Parameters | Name | Type | |---|---| | `defaultValue` | `T` | **Returns:** `Context` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `FormContext` — `src/jsx/dom/hooks/index.ts`:24 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # InferRequestOptionsType **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L273) **Part of:** [Client](subsystem-src-client) ## Definition ```ts T extends ( args: any, options: infer R ) => Promise> ? NonNullable : never ``` # Matcher **Kind:** Type **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L6) **Part of:** [Router](subsystem-src-router) ## Definition ```ts [RegExp, HandlerData[], StaticMap] ``` # methodOverride **Kind:** Function **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L60) **Part of:** [Middleware](subsystem-src-middleware) Method Override Middleware for Hono. `methodOverride` is Hono middleware that changes the request method before route handling. It reads an override method from the request and dispatches the request through the supplied Hono app, allowing clients that can only send `POST` requests to reach routes such as `DELETE` or `PATCH`. ## Signature ```ts function methodOverride(options: MethodOverrideOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `MethodOverrideOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Client[Client POST request] --> Middleware[methodOverride middleware] Middleware --> Override[Read method override] Override --> App[Hono app] App --> Route[Route matching overridden method] Route --> Response[Response] ``` ## Usage ```ts import { Hono } from 'hono' import { methodOverride } from 'hono/method-override' const app = new Hono() app.use('/posts/*', methodOverride({ app })) app.delete('/posts/:id', (c) => { return c.text(`Deleted post ${c.req.param('id')}`) }) // Send a POST request to: // /posts/123?_method=DELETE export default app ``` ## AI Coding Instructions - Pass the same `Hono` app instance to `methodOverride({ app })`. - Mount the middleware on paths that need method override handling. - Keep the target route declared with its actual HTTP method, such as `DELETE` or `PATCH`. - Send an override value that matches the method expected by the target route. - Test both the original request method and the overridden route behavior when changing middleware order. # Router **Kind:** Interface **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L29) Interface representing a router. `Router` defines the contract for registering routes and matching incoming values against them. Implementations expose a `name`, add route definitions through `add()`, and return a typed `Result` from `match()`. ## Properties | Property | Type | |---|---| | `name` | `string` | ## Diagram ```mermaid graph LR Consumer --> Router Router -->|add()| RouteDefinitions Consumer -->|match()| Router Router -->|Result| MatchResult ``` ## Usage ```ts import type { Router } from "./router"; const router: Router = createRouter({ name: "api", }); router.add("/users/:id"); const result = router.match("/users/42"); if (result) { console.log(result); } ``` ## AI Coding Instructions - Keep `name` as a stable string identifier for the router instance. - Call `add()` before matching paths that depend on registered routes. - Preserve the generic `Result` type returned by `match()` when implementing or wrapping a router. - Keep route registration and match behavior aligned with the `Router` interface contract. # SELECTORS **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L9) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # serveStatic **Kind:** Function **Source:** [`src/adapter/deno/serve-static.ts`](https://github.com/honojs/hono/blob/main/src/adapter/deno/serve-static.ts#L8) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function serveStatic(options: ServeStaticOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `ServeStaticOptions` | **Returns:** `MiddlewareHandler` ## Relationships - IMPORTS → `serveStatic` # sha256 **Kind:** Function **Source:** [`src/utils/crypto.ts`](https://github.com/honojs/hono/blob/main/src/utils/crypto.ts#L15) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function sha256(data: Data): Promise ``` ## Parameters | Name | Type | |---|---| | `data` | `Data` | **Returns:** `Promise` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `handler` — `src/middleware/cache/index.ts`:310 - `equal` — `src/utils/buffer.ts`:8 # bodyLimit **Kind:** Function **Source:** [`src/middleware/body-limit/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/body-limit/index.ts#L50) **Part of:** [Middleware](subsystem-src-middleware) Body Limit Middleware for Hono. `bodyLimit` creates Hono middleware that checks incoming request bodies against a configured maximum size. Requests that exceed the limit are handled by the middleware error path, while allowed requests continue to the next middleware or route handler. ## Signature ```ts function bodyLimit(options: BodyLimitOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `BodyLimitOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Client[Client] --> Request[Incoming request] Request --> Limit[bodyLimit middleware] Limit -->|Within configured size| Next[Next middleware or route] Limit -->|Exceeds configured size| Error[Error handler] ``` ## Usage ```ts import { Hono } from 'hono' import { bodyLimit } from 'hono/body-limit' const app = new Hono() const maxBodySize = Number(process.env.MAX_BODY_SIZE) app.use( '/uploads/*', bodyLimit({ maxSize: maxBodySize, }) ) app.post('/uploads', async (c) => { const body = await c.req.arrayBuffer() return c.json({ receivedBytes: body.byteLength, }) }) ``` ## AI Coding Instructions - Register `bodyLimit` before routes or middleware that read the request body. - Set `maxSize` from validated application configuration in bytes. - Do not rely only on the `Content-Length` header; streamed request data is also checked. - Use the `onError` option when the application needs a custom response for oversized bodies. # ExecutionContext **Kind:** Interface **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L31) Interface for the execution context in a web worker or similar environment. `ExecutionContext` carries request-scoped state and worker lifecycle controls. It exposes `props` and `exports` for integration data, while `waitUntil()` and `passThroughOnException()` control asynchronous work and error handling. ## Properties | Property | Type | |---|---| | `props` | `any` | | `exports` | `any` | ## Diagram ```mermaid graph LR Handler[Request Handler] --> Context[ExecutionContext] Context --> Props[props] Context --> Exports[exports] Context --> Wait[waitUntil()] Context --> PassThrough[passThroughOnException()] Wait --> AsyncWork[Background async work] PassThrough --> Upstream[Upstream request handling] ``` ## Usage ```ts function handleRequest(request: Request, ctx: ExecutionContext) { ctx.passThroughOnException(); ctx.waitUntil( Promise.resolve().then(() => { console.log("Request completed:", request.url); }), ); const config = ctx.props; const handlers = ctx.exports; return new Response(JSON.stringify({ config, handlers })); } ``` ## AI Coding Instructions - Treat `ExecutionContext` as request-scoped state; do not retain it outside the request lifecycle. - Use `waitUntil()` for asynchronous work that may continue after the response is returned. - Call `passThroughOnException()` only when failed worker handling should fall back to upstream request handling. - Access `props` and `exports` defensively because their shapes are typed as `any`. # InferRequestType **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L265) **Part of:** [Client](subsystem-src-client) ## Definition ```ts T extends ( args: infer R, options: any | undefined ) => Promise> ? NonNullable : never ``` # isStylesheetLinkWithPrecedence **Kind:** Function **Source:** [`src/jsx/intrinsic-element/common.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/common.ts#L15) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function isStylesheetLinkWithPrecedence(props: Props): boolean ``` ## Parameters | Name | Type | |---|---| | `props` | `Props` | **Returns:** `boolean` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # MatcherMap **Kind:** Type **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L7) **Part of:** [Router](subsystem-src-router) ## Definition ```ts Record | null> ``` # serveStatic **Kind:** Function **Source:** [`src/adapter/bun/serve-static.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/serve-static.ts#L8) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function serveStatic(options: ServeStaticOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `ServeStaticOptions` | **Returns:** `MiddlewareHandler` ## Relationships - IMPORTS → `serveStatic` # STYLE_STRING **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L8) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `createCssContext` — `src/helper/css/index.ts`:72 - `createCssJsxDomObjects` — `src/jsx/dom/css.ts`:77 # tryDecodeURIComponent **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L208) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function tryDecodeURIComponent(str: string): string ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | **Returns:** `string` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `HonoRequest` — `src/request.ts`:34 - `Cookie` — `src/utils/cookie.ts`:8 # basePath **Kind:** Function **Source:** [`src/helper/route/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/route/index.ts#L107) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function basePath(c: Context, index: number): string ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `index` | `number` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `handler` — `src/middleware/method-not-allowed/index.ts`:133 # BunServerWebSocket **Kind:** Interface **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L8) **Part of:** [Adapter](subsystem-src-adapter) `BunServerWebSocket` represents a WebSocket connection in the Bun adapter. It exposes connection-scoped `data`, the current `readyState`, and methods for sending through or closing the connection. ## Properties | Property | Type | |---|---| | `data` | `T` | | `readyState` | `0 | 1 | 2 | 3` | ## Diagram ```mermaid graph LR App[Application handler] --> Socket[BunServerWebSocket] Socket --> Data[data: T] Socket --> State[readyState] Socket --> Send[send()] Socket --> Close[close()] ``` ## Usage ```ts import type { BunServerWebSocket } from "./websocket"; type SessionData = { userId: string; }; function handleSocket(socket: BunServerWebSocket) { if (socket.readyState === 1) { socket.send(); } console.log(`Connected user: ${socket.data.userId}`); socket.close(); } ``` ## AI Coding Instructions - Treat `data` as typed, connection-scoped state supplied by the Bun adapter. - Check `readyState` before calling `send()` when connection state matters. - Do not pass a payload to `send()`; this interface declares no parameters. - Call `close()` when the application is finished with the connection. - Keep Bun-specific WebSocket handling behind the adapter boundary. ## Relationships - IMPORTS → `createWSMessageEvent` - IMPORTS → `defineWebSocketHelper` - IMPORTS → `WSContext` - IMPORTS → `getBunServer` # csrf **Kind:** Function **Source:** [`src/middleware/csrf/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/csrf/index.ts#L94) **Part of:** [Middleware](subsystem-src-middleware) CSRF Protection Middleware for Hono. Protects against Cross-Site Request Forgery attacks by validating request origins and sec-fetch-site headers. The request is allowed if either validation passes. `csrf` creates Hono middleware that checks request origin and `Sec-Fetch-Site` headers to help prevent Cross-Site Request Forgery attacks. Requests proceed when either validation passes; otherwise, the middleware rejects the request before it reaches route handlers. ## Signature ```ts function csrf(options: CSRFOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `CSRFOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> CSRF[csrf middleware] CSRF --> Origin[Validate Origin header] CSRF --> FetchSite[Validate Sec-Fetch-Site header] Origin --> Allowed[Continue to route handler] FetchSite --> Allowed Origin --> Rejected[Reject request] FetchSite --> Rejected ``` ## Usage ```ts import { Hono } from 'hono' import { csrf } from 'hono/csrf' const app = new Hono() app.use( csrf({ origin: 'https://app.example.com', }) ) app.post('/account/email', (c) => { return c.json({ updated: true }) }) export default app ``` ## AI Coding Instructions - Register `csrf()` before routes that handle state-changing requests. - Configure `origin` when the application accepts requests from a known external origin. - Keep browser clients sending standard `Origin` and `Sec-Fetch-Site` headers. - Do not bypass this middleware for protected routes unless another CSRF validation mechanism is in place. ## Relationships - IMPORTS → `HTTPException` # HandlerInterface **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L127) # isMiddleware **Kind:** Function **Source:** [`src/utils/handler.ts`](https://github.com/honojs/hono/blob/main/src/utils/handler.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function isMiddleware(handler: Function) ``` ## Parameters | Name | Type | |---|---| | `handler` | `Function` | ## Relationships - IMPORTS → `COMPOSED_HANDLER` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `inspectRoutes` — `src/helper/dev/index.ts`:27 - `dirname` — `src/helper/ssg/utils.ts`:11 # normalizeIntrinsicElementKey **Kind:** Function **Source:** [`src/jsx/utils.ts`](https://github.com/honojs/hono/blob/main/src/jsx/utils.ts#L11) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function normalizeIntrinsicElementKey(key: string): string ``` ## Parameters | Name | Type | |---|---| | `key` | `string` | **Returns:** `string` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Props` — `src/jsx/base.ts`:27 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # ParamAssocArray **Kind:** Type **Source:** [`src/router/reg-exp-router/node.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/node.ts#L6) **Part of:** [Router](subsystem-src-router) ## Definition ```ts [string, number][] ``` # PickResponseByStatusCode **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L388) **Part of:** [Client](subsystem-src-client) Keep only specific status code responses from all routes of an app. Useful when error responses are handled centrally (e.g., via custom fetch) and you want the client to only expose success response types. `PickResponseByStatusCode` filters an app's route response definitions to keep only responses matching the supplied status-code type. Use it when a shared HTTP layer handles certain responses and client-facing route types should expose only the remaining responses. ## Definition ```ts App extends HonoBase ? PickSchema, U> extends infer S extends Schema ? Hono : never : never ``` ## Diagram ```mermaid graph LR A[App route contract] --> C[PickResponseByStatusCode] B[Allowed status-code type] --> C C --> D[Filtered route response definitions] D --> E[Client-facing route types] ``` ## Usage ```ts import type { PickResponseByStatusCode } from '@ts-rest/core'; import { contract } from './contract'; import type { SuccessStatusCode } from './http-status'; type ClientRoutes = PickResponseByStatusCode< typeof contract, SuccessStatusCode >; // Use ClientRoutes when building a client whose shared fetch layer // handles excluded responses before they reach application code. ``` ## AI Coding Instructions - Pass the full app contract type as the first generic argument and the allowed status-code union as the second. - Define shared status-code unions near the HTTP or fetch integration when multiple clients need the same filtering behavior. - Keep centrally handled responses out of the selected status-code union so they do not appear in client response types. - Apply this type to contract definitions before deriving client types that should only expose selected responses. # COMPRESSIBLE_CONTENT_TYPE_REGEX **Kind:** Constant **Source:** [`src/utils/compress.ts`](https://github.com/honojs/hono/blob/main/src/utils/compress.ts#L9) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-… ``` ## Value ```ts /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-… ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `handler` — `src/middleware/compress/index.ts`:139 - `ServeStaticOptions` — `src/middleware/serve-static/index.ts`:13 # detectFromHeader **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L153) **Part of:** [Middleware](subsystem-src-middleware) Detects language from Accept-Language header `detectFromHeader` reads the `Accept-Language` header and determines the requested language. It is used by language middleware to select a language before handling a request. ## Signature ```ts function detectFromHeader(c: Context, options: DetectorOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `options` | `DetectorOptions` | **Returns:** `string | undefined` ## Diagram ```mermaid graph LR Request[Incoming request] --> Header[Accept-Language header] Header --> Detect[detectFromHeader] Detect --> Language[Detected language] Language --> Middleware[Language middleware] ``` ## Usage ```ts import { detectFromHeader } from './middleware/language/language'; const language = detectFromHeader('fr-CA,fr,en'); if (language) { console.log(`Detected language: ${language}`); } ``` ## AI Coding Instructions - Pass the raw `Accept-Language` header value to `detectFromHeader`. - Handle an absent or unmatched language result before setting request language state. - Keep header parsing in this function rather than duplicating parsing logic in middleware handlers. # Fetch **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L234) **Part of:** [Client](subsystem-src-client) ## Definition ```ts ( args?: InferRequestType, opt?: ClientRequestOptions ) => Promise>> ``` # MiddlewareHandlerInterface **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L1080) # ReplacementMap **Kind:** Type **Source:** [`src/router/reg-exp-router/trie.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/trie.ts#L4) **Part of:** [Router](subsystem-src-router) ## Definition ```ts number[] ``` ## Relationships - IMPORTS → `Node` # serveStatic **Kind:** Function **Source:** [`src/adapter/cloudflare-workers/serve-static.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/serve-static.ts#L21) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function serveStatic(options: ServeStaticOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `ServeStaticOptions` | **Returns:** `MiddlewareHandler` # setCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L99) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function setCookie(c: Context, name: string, value: string, opt: CookieOptions): void ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `value` | `string` | | `opt` | `CookieOptions` | **Returns:** `void` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DetectorType` — `src/middleware/language/language.ts`:10 # toArray **Kind:** Function **Source:** [`src/jsx/children.ts`](https://github.com/honojs/hono/blob/main/src/jsx/children.ts#L3) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function toArray(children: Child): Child[] ``` ## Parameters | Name | Type | |---|---| | `children` | `Child` | **Returns:** `Child[]` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # COMPOSED_HANDLER **Kind:** Constant **Source:** [`src/utils/constants.ts`](https://github.com/honojs/hono/blob/main/src/utils/constants.ts#L4) **Part of:** [Utils](subsystem-src-utils) Constant used to mark a composed handler. `COMPOSED_HANDLER` is a shared marker for handlers created through composition. Code that creates or inspects composed handlers can use this constant to apply and detect the same marker consistently. ## Definition ```ts '__COMPOSED_HANDLER' ``` ## Value ```ts '__COMPOSED_HANDLER' ``` ## Diagram ```mermaid graph LR A[Handler composition] --> B[Composed handler] B --> C[COMPOSED_HANDLER marker] C --> D[Handler detection logic] ``` ## Usage ```ts import { COMPOSED_HANDLER } from './utils/constants'; function isComposedHandler(handler: object): boolean { return COMPOSED_HANDLER in handler; } // A handler created by composition is marked with COMPOSED_HANDLER. if (isComposedHandler(handler)) { // Apply composed-handler behavior. } ``` ## AI Coding Instructions - Import `COMPOSED_HANDLER` from `src/utils/constants.ts` instead of duplicating its marker value. - Apply the marker where handlers are composed, not where ordinary handlers are created. - Check for the marker before running behavior that is specific to composed handlers. - Keep marker creation and marker detection aligned so both paths use `COMPOSED_HANDLER`. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `HonoOptions` — `src/hono-base.ts`:46 - `isMiddleware` — `src/utils/handler.ts`:8 # createWSContext **Kind:** Function **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L33) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function createWSContext(ws: BunServerWebSocket): WSContext ``` ## Parameters | Name | Type | |---|---| | `ws` | `BunServerWebSocket` | **Returns:** `WSContext` # deDupeKeyMap **Kind:** Constant **Source:** [`src/jsx/intrinsic-element/common.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/common.ts#L3) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Record ``` ## Value ```ts { title: [], script: ['src'], style: ['data-href'], link: ['href'], meta: ['name', 'httpEquiv', 'charset', 'itemProp'], } ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # ensureWithinOutDir **Kind:** Function **Source:** [`src/helper/ssg/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/utils.ts#L77) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function ensureWithinOutDir(outDir: string, filePath: string): void ``` ## Parameters | Name | Type | |---|---| | `outDir` | `string` | | `filePath` | `string` | **Returns:** `void` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # etag **Kind:** Function **Source:** [`src/middleware/etag/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/etag/index.ts#L79) **Part of:** [Middleware](subsystem-src-middleware) ETag Middleware for Hono. `etag` creates an `ETag` header from a response body after downstream handlers run. When the request includes a matching `If-None-Match` header, it replaces the response with a Not Modified response. ## Signature ```ts function etag(options: ETagOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `ETagOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request --> ETagMiddleware ETagMiddleware --> Handler Handler --> Response Response --> ETagMiddleware ETagMiddleware -->|Sets ETag header| Client ETagMiddleware -->|Matching If-None-Match| NotModifiedResponse ``` ## Usage ```ts import { Hono } from 'hono' import { etag } from 'hono/etag' const app = new Hono() app.use(etag()) app.get('/profile', (c) => { return c.json({ name: 'Ada' }) }) export default app ``` ## AI Coding Instructions - Register `etag()` before routes whose responses should include an `ETag` header. - Allow downstream handlers to create the response before adding logic that depends on response content. - Preserve an `ETag` header set explicitly by a route or another middleware. - Test conditional requests with an `If-None-Match` header that matches the response `ETag`. # InferResponseType **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L251) **Part of:** [Client](subsystem-src-client) ## Definition ```ts InferResponseTypeFromEndpoint< InferEndpointType, U > ``` # OnHandlerInterface **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L1457) # StaticMap **Kind:** Type **Source:** [`src/router/reg-exp-router/matcher.ts`](https://github.com/honojs/hono/blob/main/src/router/reg-exp-router/matcher.ts#L5) **Part of:** [Router](subsystem-src-router) ## Definition ```ts Record> ``` # buildDataStack **Kind:** Constant **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L106) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts [Context, Node][] ``` ## Value ```ts [] ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `STASH_EFFECT` — `src/jsx/hooks/index.ts`:9 - `StreamingContext` — `src/jsx/streaming.ts`:30 # filterStaticGenerateRoutes **Kind:** Function **Source:** [`src/helper/ssg/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/utils.ts#L61) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function filterStaticGenerateRoutes(hono: Hono): FilterStaticGenerateRouteData[] ``` ## Parameters | Name | Type | |---|---| | `hono` | `Hono` | **Returns:** `FilterStaticGenerateRouteData[]` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # getProcessor **Kind:** Function **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L625) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function getProcessor(event: LambdaEvent): EventProcessor ``` ## Parameters | Name | Type | |---|---| | `event` | `LambdaEvent` | **Returns:** `EventProcessor` # Jwt **Kind:** Constant **Source:** [`src/utils/jwt/index.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/index.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { sign, verify, decode, verifyWithJwks } ``` ## Value ```ts { sign, verify, decode, verifyWithJwks } ``` ## Relationships - IMPORTS → `decode` - IMPORTS → `sign` - IMPORTS → `verify` - IMPORTS → `verifyWithJwks` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `headerName` — `src/middleware/jwk/jwk.ts`:81 - `headerName` — `src/middleware/jwt/jwt.ts`:81 # ObjectType **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L328) **Part of:** [Client](subsystem-src-client) ## Definition ```ts { [key: string]: T } ``` # secureHeaders **Kind:** Function **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L179) **Part of:** [Middleware](subsystem-src-middleware) Secure Headers Middleware for Hono. `secureHeaders` creates Hono middleware that adds security-related HTTP response headers. Register it on an application or route so matching responses include the configured header policies. ## Signature ```ts function secureHeaders(customOptions: SecureHeadersOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `customOptions` | `SecureHeadersOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Client --> HonoApp HonoApp --> SecureHeaders[secureHeaders middleware] SecureHeaders --> Handler[Route handler] Handler --> Response SecureHeaders --> ResponseHeaders[Security response headers] ResponseHeaders --> Client ``` ## Usage ```ts import { Hono } from 'hono' import { secureHeaders } from './middleware/secure-headers/secure-headers' const app = new Hono() app.use('*', secureHeaders()) app.get('/', (c) => { return c.text('Hello') }) export default app ``` ## AI Coding Instructions - Register `secureHeaders()` before route handlers so headers are applied to route responses. - Apply the middleware globally with `app.use()` or scope it to routes that need the header policy. - Keep header configuration close to application middleware setup to make policy changes easy to review. - Check interactions with other middleware that sets response headers, since later middleware may replace header values. # ToSchema **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2500) ## Definition ```ts IsAny extends true ? { [K in P]: { [K2 in M as AddDollar]: { input: AddParam, P> output: {} outputFormat: ResponseFormat status: StatusCode } } } : [RorO] extends [never] ? {} : [RorO] extends [Promise] ? {} : { [K in P]: { [K2 in M as AddDollar]: Simplify< { input: AddParam, P> } & ToSchemaOutput > } } ``` # BuildSearchParamsFn **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L30) **Part of:** [Client](subsystem-src-client) ## Definition ```ts (query: Record) => URLSearchParams ``` # createWSMessageEvent **Kind:** Function **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L95) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function createWSMessageEvent(source: WSMessageReceive): MessageEvent ``` ## Parameters | Name | Type | |---|---| | `source` | `WSMessageReceive` | **Returns:** `MessageEvent` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `BunServerWebSocket` — `src/adapter/bun/websocket.ts`:8 # dataPrecedenceAttr **Kind:** Constant **Source:** [`src/jsx/intrinsic-element/common.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/common.ts#L13) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts 'data-precedence' ``` ## Value ```ts 'data-precedence' ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # ExtractValidationResponse **Kind:** Type **Source:** [`src/validator/validator.ts`](https://github.com/honojs/hono/blob/main/src/validator/validator.ts#L28) ## Definition ```ts VF extends (value: any, c: any) => infer R ? R extends Promise ? PR extends TypedResponse ? TypedResponse : PR extends Response ? PR : PR extends undefined ? never : never : R extends TypedResponse ? TypedResponse : R extends Response ? R : R extends undefined ? never : never : never ``` # handle **Kind:** Function **Source:** [`src/adapter/cloudflare-pages/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-pages/handler.ts#L32) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function handle(app: Hono): PagesFunction ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | **Returns:** `PagesFunction` # startTime **Kind:** Function **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L187) **Part of:** [Middleware](subsystem-src-middleware) Start a timer for the timing middleware. `startTime` starts the timer used by the timing middleware. Call it when request handling begins, then retain the returned value so later middleware code can calculate elapsed time. ## Signature ```ts function startTime(c: Context, name: string, description: string) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `description` | `string` | ## Diagram ```mermaid graph LR Request[Incoming request] --> Start[startTime] Start --> Timer[Stored timer value] Timer --> Handler[Request handler] Handler --> End[Timing middleware records elapsed time] ``` ## Usage ```ts import { startTime } from "./src/middleware/timing/timing"; function timingMiddleware(request: Request) { const timer = startTime(); return handleRequest(request).finally(() => { recordTiming(timer); }); } ``` ## AI Coding Instructions - Call `startTime` at the beginning of the middleware execution path. - Keep the returned timer value available until elapsed time is recorded. - Use the same timer value for all timing calculations associated with a request. - Keep timer creation separate from response logging or metric submission. # utf8Encoder **Kind:** Constant **Source:** [`src/utils/jwt/utf8.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/utf8.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts TextEncoder ``` ## Value ```ts new TextEncoder() ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `HonoJsonWebKey` — `src/utils/jwt/jws.ts`:23 - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # Callback **Kind:** Type **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L320) **Part of:** [Client](subsystem-src-client) ## Definition ```ts (opts: CallbackOptions) => unknown ``` # DOM_INTERNAL_TAG **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L4) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('INTERNAL') ``` ## Value ```ts Symbol('INTERNAL') ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 - `setInternalTagFlag` — `src/jsx/dom/utils.ts`:3 # getRuntimeKey **Kind:** Function **Source:** [`src/helper/adapter/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/adapter/index.ts#L50) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function getRuntimeKey(): Runtime ``` **Returns:** `Runtime` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoJsonWebKey` — `src/utils/jwt/jws.ts`:23 # LambdaContext **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L35) **Part of:** [Adapter](subsystem-src-adapter) Handler context parameter. See ://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html AWS documentation. `LambdaContext` models the context parameter passed to an AWS Lambda handler. It contains invocation metadata, runtime settings, optional Cognito identity and client context data, and a method for checking the remaining execution time. ## Properties | Property | Type | |---|---| | `callbackWaitsForEmptyEventLoop` | `boolean` | | `functionName` | `string` | | `functionVersion` | `string` | | `invokedFunctionArn` | `string` | | `memoryLimitInMB` | `string` | | `awsRequestId` | `string` | | `logGroupName` | `string` | | `logStreamName` | `string` | | `identity` | `CognitoIdentity | undefined` | | `clientContext` | `ClientContext | undefined` | ## Diagram ```mermaid graph LR Handler["Lambda handler"] --> Context["LambdaContext"] Context --> Invocation["Invocation metadata"] Context --> Runtime["Runtime settings"] Context --> Identity["CognitoIdentity | undefined"] Context --> Client["ClientContext | undefined"] Context --> Remaining["getRemainingTimeInMillis()"] ``` ## Usage ```ts import type { LambdaContext } from './types'; export async function handler( event: { action?: string }, context: LambdaContext, ) { console.log({ requestId: context.awsRequestId, functionName: context.functionName, invokedFunctionArn: context.invokedFunctionArn, remainingTime: context.getRemainingTimeInMillis(), }); if (context.getRemainingTimeInMillis() <= 0) { throw new Error('Lambda execution time has expired.'); } context.callbackWaitsForEmptyEventLoop = false; return { requestId: context.awsRequestId, action: event.action, }; } ``` ## AI Coding Instructions - Accept `LambdaContext` as the handler context parameter when adapter code needs AWS Lambda invocation metadata. - Call `getRemainingTimeInMillis()` before work that may exceed the Lambda execution limit. - Treat `identity` and `clientContext` as optional values and check for `undefined` before reading their properties. - Set `callbackWaitsForEmptyEventLoop` only when the handler should return before the Node.js event loop is empty. - Keep AWS-specific context handling inside the Lambda adapter boundary. # MergePath **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2610) ## Definition ```ts B extends '' ? MergePath : A extends '' ? B : A extends '/' ? B : A extends `${infer P}/` ? B extends `/${infer Q}` ? `${P}/${Q}` : `${P}/${B}` : B extends `/${infer Q}` ? Q extends '' ? A : `${A}/${Q}` : `${A}/${B}` ``` # timeout **Kind:** Function **Source:** [`src/middleware/timeout/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timeout/index.ts#L38) **Part of:** [Middleware](subsystem-src-middleware) Timeout Middleware for Hono. `timeout` creates Hono middleware that limits how long downstream request handling may run. Apply it to an app or route path to return a timeout response when the configured duration expires before the next handler finishes. ## Signature ```ts function timeout(duration: number, exception: HTTPExceptionFunction | HTTPException): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `duration` | `number` | | `exception` | `HTTPExceptionFunction | HTTPException` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[timeout middleware] Middleware --> Next[Downstream middleware or handler] Middleware --> Timer[Timeout timer] Next --> Race[Wait for completion] Timer --> Race Race -->|Handler completes| Response[Normal response] Race -->|Duration expires| TimeoutResponse[Timeout response] ``` ## Usage ```ts import { Hono } from 'hono' import { timeout } from 'hono/timeout' const app = new Hono() const requestTimeout = Number(process.env.REQUEST_TIMEOUT_MS) app.use('/api/*', timeout(requestTimeout)) app.get('/api/data', async (c) => { const response = await fetch('https://example.com/data') return c.json(await response.json()) }) export default app ``` ## AI Coding Instructions - Apply `timeout` before the middleware and handlers whose execution time it should limit. - Pass a duration in milliseconds from configuration rather than hard-coding route-specific values. - Keep downstream handlers compatible with early timeout responses; a timed-out client request does not stop external work already started by the handler. - Scope the middleware with a route pattern when only selected endpoints need timeout handling. # verify **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L96) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function verify(token: string, publicKey: SignatureKey, algOrOptions: SignatureAlgorithm | VerifyOptionsWithAlg): Promise ``` ## Parameters | Name | Type | |---|---| | `token` | `string` | | `publicKey` | `SignatureKey` | | `algOrOptions` | `SignatureAlgorithm | VerifyOptionsWithAlg` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Jwt` — `src/utils/jwt/index.ts`:7 # DOM_MEMO **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L5) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('MEMO') ``` ## Value ```ts Symbol('MEMO') ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Props` — `src/jsx/base.ts`:27 - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # getConnInfo **Kind:** Function **Source:** [`src/adapter/deno/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/deno/conninfo.ts#L8) **Part of:** [Adapter](subsystem-src-adapter) Get conninfo with Deno `getConnInfo` reads connection details from the Deno request environment for a Hono context. It returns the remote and local address information associated with the current request, allowing handlers to inspect client and server connection data. ## Signature ```ts function getConnInfo(c) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | ## Diagram ```mermaid graph LR Request[Deno request] --> Context[Hono context] Context --> Environment[Deno connection environment] Environment --> getConnInfo[getConnInfo] getConnInfo --> ConnInfo[Remote and local connection info] ``` ## Usage ```ts import { Hono } from 'hono' import { getConnInfo } from 'hono/conninfo' const app = new Hono() app.get('/connection', (c) => { const connInfo = getConnInfo(c) return c.json({ remote: connInfo.remote, local: connInfo.local, }) }) Deno.serve(app.fetch) ``` ## AI Coding Instructions - Call `getConnInfo` with the current Hono `Context` inside a request handler. - Treat connection addresses as request metadata and account for missing address fields where deployment environments do not expose them. - Keep Deno-specific connection handling within the Deno adapter rather than reading adapter environment values directly in shared application code. - Import the connection helper from `hono/conninfo` so the matching runtime implementation is selected. # joinPaths **Kind:** Function **Source:** [`src/helper/ssg/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/utils.ts#L50) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function joinPaths(paths: string[]): string ``` ## Parameters | Name | Type | |---|---| | `paths` | `string[]` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # Response **Kind:** Interface **Source:** [`src/client/types.ts`](https://github.com/honojs/hono/blob/main/src/client/types.ts#L232) **Part of:** [Client](subsystem-src-client) # timing **Kind:** Function **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L76) **Part of:** [Middleware](subsystem-src-middleware) Server-Timing Middleware for Hono. `timing` creates Hono middleware that measures request timing and writes timing data to the `Server-Timing` response header. It also makes a metrics collector available through the request context so handlers can record named operations. ## Signature ```ts function timing(config: TimingOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `config` | `TimingOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request --> Timing["timing() middleware"] Timing --> Metrics["Context metrics collector"] Metrics --> Handler["Route handler"] Handler --> Response["Response"] Timing --> Header["Server-Timing header"] Header --> Response ``` ## Usage ```ts import { Hono } from 'hono' import { timing } from 'hono/timing' const app = new Hono() app.use('*', timing()) app.get('/reports', async (c) => { const metrics = c.get('metrics') metrics.start('database') const report = await loadReport() metrics.end('database') return c.json(report) }) async function loadReport() { return { status: 'ok' } } export default app ``` ## AI Coding Instructions - Register `timing()` before route handlers so it can measure the full request lifecycle. - Access custom timing metrics with `c.get('metrics')` inside handlers or downstream middleware. - Call `metrics.start(name)` and `metrics.end(name)` with the same metric name. - Preserve `Server-Timing` headers when adding response headers manually. - Enable cross-origin timing settings only when browser clients need access to timing data. # TypedResponse **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2635) ## Definition ```ts { _data: T _status: U _format: F } ``` # verifyWithJwks **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L197) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function verifyWithJwks(token: string, options: { keys?: HonoJsonWebKey[] jwks_uri?: string verification?: VerifyOptions allowedAlgorithms: readonly AsymmetricAlgorithm[] }, init: RequestInit): Promise ``` ## Parameters | Name | Type | |---|---| | `token` | `string` | | `options` | `{ keys?: HonoJsonWebKey[] jwks_uri?: string verification?: VerifyOptions allowedAlgorithms: readonly AsymmetricAlgorithm[] }` | | `init` | `RequestInit` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Jwt` — `src/utils/jwt/index.ts`:7 # dirname **Kind:** Function **Source:** [`src/helper/ssg/utils.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/utils.ts#L11) **Part of:** [Helper](subsystem-src-helper) Get dirname `dirname` gets the directory portion of a file or path string. It supports static-site-generation helpers that need to locate a file's parent directory before resolving related paths or writing output. ## Signature ```ts function dirname(path: string): string ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Path string] --> B[dirname] B --> C[Directory path] ``` ## Usage ```ts import { dirname } from '../src/helper/ssg/utils' const filePath = 'content/guides/setup.mdx' const directory = dirname(filePath) console.log(directory) ``` ## AI Coding Instructions - Pass a path string representing a file or nested resource. - Use the returned directory path when resolving files relative to the current resource. - Keep path-format handling consistent with other SSG utilities. - Check callers that may pass root-level paths or paths without directory segments. ## Relationships - IMPORTS → `METHOD_NAME_ALL` - IMPORTS → `findTargetHandler` - IMPORTS → `isMiddleware` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # domRenderers **Kind:** Constant **Source:** [`src/jsx/intrinsic-element/common.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/common.ts#L11) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Record ``` ## Value ```ts {} ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Props` — `src/jsx/base.ts`:27 - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # ExtractHandlerResponse **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2750) ## Definition ```ts T extends (c: any, next: any) => Promise ? Exclude extends never ? never : Exclude extends Response | TypedResponse ? Exclude : never : T extends (c: any, next: any) => infer R ? R extends Response | TypedResponse ? R : never : never ``` # FetchEvent **Kind:** Interface **Source:** [`src/adapter/service-worker/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/service-worker/types.ts#L6) **Part of:** [Adapter](subsystem-src-adapter) `FetchEvent` represents a fetch handled by the service worker adapter. It carries the incoming `Request`, client identifiers, preload state, and a completion promise, while `respondWith()` marks the event as handled by the adapter. ## Properties | Property | Type | |---|---| | `clientId` | `string` | | `handled` | `Promise` | | `preloadResponse` | `Promise` | | `request` | `Request` | | `resultingClientId` | `string` | ## Diagram ```mermaid graph LR Client[Client] --> Request[Request] Request --> Event[FetchEvent] Event --> ClientId[clientId] Event --> ResultingClientId[resultingClientId] Event --> Preload[preloadResponse] Event --> Handled[handled] Event --> RespondWith[respondWith()] ``` ## Usage ```ts function handleFetch(event: FetchEvent): void { const request = event.request; void event.preloadResponse.then((preloaded) => { console.log("Preloaded response:", preloaded); }); void event.handled.then(() => { console.log("Fetch handling completed for:", request.url); }); console.log("Client:", event.clientId); console.log("Resulting client:", event.resultingClientId); event.respondWith(); } ``` ## AI Coding Instructions - Read `event.request` for the incoming URL, method, headers, and request body. - Call `respondWith()` according to the adapter event contract. - Treat `handled` as a signal that fetch processing has completed. - Do not assume `preloadResponse` resolves to a `Response`; its type is `any`. - Use `clientId` and `resultingClientId` when request handling depends on client navigation state. ## How it works `FetchEvent` is an exported TypeScript interface for the event accepted by the service-worker adapter’s handler. It extends `ExtendableEvent`, which itself extends `Event`. [src/adapter/service-worker/types.ts:1-6] The adapter defines its handler as a function that takes this interface and returns `void`. [src/adapter/service-worker/handler.ts:10] It declares these members: - `request`: a read-only `Request` representing the request passed to the application. [src/adapter/service-worker/types.ts:11] - `respondWith(r)`: a method accepting either a `Response` or a thenable that resolves to a `Response`. [src/adapter/service-worker/types.ts:13] - `clientId` and `resultingClientId`: read-only strings. [src/adapter/service-worker/types.ts:7,12] - `handled`: a read-only `Promise`. [src/adapter/service-worker/types.ts:8] - `preloadResponse`: a read-only `Promise`. [src/adapter/service-worker/types.ts:9-10] - `waitUntil(f)`, inherited from `ExtendableEvent`, which accepts a `Promise` and returns `void`. [src/adapter/service-worker/types.ts:1-4] When `handle(app, opts)` receives a `FetchEvent`, it calls `evt.respondWith(...)` with an async operation. That operation calls `app.fetch(evt.request, {}, evt)`, passing the event as the third argument. [src/adapter/service-worker/handler.ts:25-35] Consequently, application code can read event members through its execution context; the adapter test reads `c.executionCtx.clientId` and receives the event’s mocked `clientId`. [src/adapter/service-worker/handler.test.ts:95-119] If the application response has status `404` and `opts.fetch` is defined, the handler calls `opts.fetch(evt.request)` and passes that result to `respondWith`; otherwise, it passes the application response. [src/adapter/service-worker/handler.ts:29-35] The default option binds `globalThis.fetch` to `globalThis`. [src/adapter/service-worker/handler.ts:20-23] `FetchEvent` itself contains only type declarations: it has no implementation, runtime validation, thrown errors, or direct side effects in `types.ts`. [src/adapter/service-worker/types.ts:1-14] # jsxRenderer **Kind:** Function **Source:** [`src/middleware/jsx-renderer/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jsx-renderer/index.ts#L114) **Part of:** [Middleware](subsystem-src-middleware) JSX Renderer Middleware for hono. `jsxRenderer` creates Hono middleware that registers a JSX renderer for the current request. Routes can call `c.render()` with page content, and the renderer wraps that content in the supplied JSX component before returning an HTML response. ## Signature ```ts function jsxRenderer(component: ComponentWithChildren, options: RendererOptions | ((c: Context) => RendererOptions)): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `component` | `ComponentWithChildren` | | `options` | `RendererOptions | ((c: Context) => RendererOptions)` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR A[Request] --> B[jsxRenderer middleware] B --> C[Register renderer on context] C --> D[Route handler] D --> E[c.render JSX content] E --> F[Renderer component] F --> G[HTML response] ``` ## Usage ```tsx import { Hono } from 'hono' import { jsxRenderer } from 'hono/jsx-renderer' const app = new Hono() app.use( '*', jsxRenderer(({ children }) => ( My Hono App
Site Header
{children} )) ) app.get('/', (c) => { return c.render(

Hello from Hono

) }) export default app ``` ## AI Coding Instructions - Register `jsxRenderer` before routes that call `c.render()`. - Keep `{children}` in the renderer component so route content is included in the response. - Use `c.render()` for pages that should pass through the JSX renderer; use other response methods only when bypassing the page wrapper is intended. - Keep shared document structure, such as ``, ``, and navigation, in the renderer component rather than duplicating it in route handlers. # parseSigned **Kind:** Function **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L146) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function parseSigned(cookie: string, secret: string | BufferSource, name: string): Promise ``` ## Parameters | Name | Type | |---|---| | `cookie` | `string` | | `secret` | `string | BufferSource` | | `name` | `string` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `getCookie` — `src/helper/cookie/index.ts`:27 # appendTrailingSlash **Kind:** Function **Source:** [`src/middleware/trailing-slash/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/trailing-slash/index.ts#L128) **Part of:** [Middleware](subsystem-src-middleware) Append trailing slash middleware for Hono. Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`. `appendTrailingSlash` creates Hono middleware that redirects requests whose path does not end with `/`. It runs before route handling so canonical slash-terminated URLs reach the matching route. ## Signature ```ts function appendTrailingSlash(options: AppendTrailingSlashOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `AppendTrailingSlashOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[appendTrailingSlash middleware] Middleware --> Check{Path ends with slash?} Check -- No --> Redirect[Redirect to path with slash] Check -- Yes --> Next[Continue to next middleware or route] ``` ## Usage ```ts import { Hono } from 'hono' import { appendTrailingSlash } from 'hono/trailing-slash' const app = new Hono() app.use(appendTrailingSlash()) app.get('/docs/', (c) => { return c.text('Documentation') }) export default app ``` ## AI Coding Instructions - Register `appendTrailingSlash()` before routes that expect slash-terminated paths. - Apply the middleware at the app level when all routes should use trailing slashes, or mount it on a route prefix for narrower behavior. - Do not add separate redirect logic inside route handlers when this middleware already handles path normalization. - Test requests with and without a trailing slash, including paths that include query parameters. # convertIPv6ToBinary **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L157) **Part of:** [Utils](subsystem-src-utils) Convert IPv6 to Uint8Array `convertIPv6ToBinary` accepts an IPv6 address string and converts it into a `Uint8Array`. It belongs to the IP address utility layer, where callers can use the byte representation for address processing and comparisons. ## Signature ```ts function convertIPv6ToBinary(ipv6: string): bigint ``` ## Parameters | Name | Type | |---|---| | `ipv6` | `string` | **Returns:** `bigint` ## Diagram ```mermaid graph LR Address[IPv6 address string] --> Convert[convertIPv6ToBinary] Convert --> Bytes[Uint8Array] ``` ## Usage ```ts import { convertIPv6ToBinary } from './utils/ipaddr'; const address = 'fe80::abcd'; const bytes = convertIPv6ToBinary(address); console.log(bytes); ``` ## AI Coding Instructions - Pass IPv6 address strings to `convertIPv6ToBinary`; do not use it for IPv4 addresses. - Treat the returned value as binary address data rather than a formatted address string. - Keep address parsing and conversion logic in `src/utils/ipaddr.ts`. - Match existing caller behavior for invalid or malformed IPv6 input. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # ExtractValidatorOutput **Kind:** Type **Source:** [`src/validator/validator.ts`](https://github.com/honojs/hono/blob/main/src/validator/validator.ts#L175) ## Definition ```ts VF extends (value: any, c: any) => infer R ? R extends Promise ? PR extends Response | TypedResponse ? never : PR : R extends Response | TypedResponse ? never : R : never ``` # matchedRoutes **Kind:** Function **Source:** [`src/helper/route/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/route/index.ts#L32) **Part of:** [Helper](subsystem-src-helper) Get matched routes in the handler `matchedRoutes` gets the routes that match a handler. Use it when route-aware code needs to inspect the handler’s current route matches before performing follow-up work. ## Signature ```ts function matchedRoutes(c: Context): RouterRoute[] ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | **Returns:** `RouterRoute[]` ## Diagram ```mermaid graph LR Handler[Handler] --> MatchedRoutes[matchedRoutes] MatchedRoutes --> Routes[Matched routes] Routes --> Consumer[Route-aware logic] ``` ## Usage ```ts import { matchedRoutes } from './helper/route' const routes = matchedRoutes(handler) for (const route of routes) { console.log(route) } ``` ## AI Coding Instructions - Pass the handler instance associated with the current request or execution context. - Treat the returned routes as inspection data for route-aware behavior. - Keep route matching logic centralized through `matchedRoutes` rather than duplicating handler traversal. - Check the route shape before reading route-specific properties in downstream code. ## Relationships - IMPORTS → `GET_MATCH_RESULT` - IMPORTS → `getPattern` - IMPORTS → `splitRoutingPath` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `handler` — `src/middleware/method-not-allowed/index.ts`:133 # PERMALINK **Kind:** Constant **Source:** [`src/jsx/constants.ts`](https://github.com/honojs/hono/blob/main/src/jsx/constants.ts#L6) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Symbol('PERMALINK') ``` ## Value ```ts Symbol('PERMALINK') ``` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `FormContext` — `src/jsx/dom/hooks/index.ts`:24 - `title` — `src/jsx/intrinsic-element/components.ts`:121 # toSSG **Kind:** Function **Source:** [`src/adapter/bun/ssg.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/ssg.ts#L25) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts async function toSSG(app, options) ``` ## Parameters | Name | Type | |---|---| | `app` | `any` | | `options` | `any` | # defaultPlugin **Kind:** Function **Source:** [`src/helper/ssg/plugins.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/plugins.ts#L11) **Part of:** [Helper](subsystem-src-helper) The default plugin that defines the recommended behavior. `defaultPlugin` creates the plugin that applies the project's recommended static-site-generation behavior. Add it to the SSG plugin list so its hooks participate in the build lifecycle. ## Signature ```ts function defaultPlugin(): SSGPlugin ``` **Returns:** `SSGPlugin` ## Diagram ```mermaid graph LR Config[SSG configuration] --> PluginFactory[defaultPlugin()] PluginFactory --> Plugin[Default plugin] Plugin --> Build[SSG build lifecycle] Build --> Output[Generated site output] ``` ## Usage ```ts import { defaultPlugin } from './src/helper/ssg/plugins'; const plugins = [ defaultPlugin(), ]; export { plugins }; ``` ## AI Coding Instructions - Keep `defaultPlugin()` in the SSG plugin configuration so the default build behavior remains active. - Follow the plugin hook and return-value conventions already used in `src/helper/ssg/plugins.ts`. - Avoid duplicating behavior implemented by the default plugin in custom plugins. - When changing plugin behavior, verify how the change affects generated static output and build-time hooks. ## Relationships - IMPORTS → `html` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # Hono **Kind:** Class **Source:** [`src/preset/quick.ts`](https://github.com/honojs/hono/blob/main/src/preset/quick.ts#L13) **Extends:** `HonoBase` ## Relationships - IMPORTS → `HonoOptions` # jsxFn **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L342) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function jsxFn(tag: string | Function, props: Props, children: Child[]): JSXNode ``` ## Parameters | Name | Type | |---|---| | `tag` | `string | Function` | | `props` | `Props` | | `children` | `Child[]` | **Returns:** `JSXNode` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `jsxDEV` — `src/jsx/jsx-dev-runtime.ts`:12 # serializeSigned **Kind:** Function **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L270) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function serializeSigned(name: string, value: string, secret: string | BufferSource, opt: CookieOptions): Promise ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `value` | `string` | | `secret` | `string | BufferSource` | | `opt` | `CookieOptions` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `getCookie` — `src/helper/cookie/index.ts`:27 # some **Kind:** Function **Source:** [`src/middleware/combine/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/combine/index.ts#L38) **Part of:** [Middleware](subsystem-src-middleware) Create a composed middleware that runs the first middleware that returns true. `some` creates a middleware composition that evaluates child middleware in order. It stops when a middleware returns `true`, allowing matching middleware to handle the current context without continuing to later handlers. ## Signature ```ts function some(middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `middleware` | `(MiddlewareHandler | Condition)[]` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Context[Context] --> First[First middleware] First -->|false| Next[Next middleware] First -->|true| Handled[Stop composition] Next -->|false| Remaining[Remaining middleware] Next -->|true| Handled Remaining -->|true| Handled Remaining -->|false| Unhandled[No middleware handled the context] ``` ## Usage ```ts import { some } from "./middleware/combine"; type RequestContext = { path: string; response?: string; }; const handleHealthCheck = async (ctx: RequestContext) => { if (ctx.path !== "/health") return false; ctx.response = "ok"; return true; }; const handleNotFound = async (ctx: RequestContext) => { ctx.response = "not found"; return true; }; const handleRequest = some(handleHealthCheck, handleNotFound); const ctx: RequestContext = { path: "/health" }; await handleRequest(ctx); console.log(ctx.response); // "ok" ``` ## AI Coding Instructions - Keep middleware ordered from the most specific match to the fallback handler. - Return `true` only when the middleware has handled the context and later middleware should not run. - Return `false` when the middleware does not match so `some` can continue evaluating handlers. - Add fallback middleware last when unmatched contexts need a default response. ## Relationships - IMPORTS → `compose` - IMPORTS → `METHOD_NAME_ALL` # toSSG **Kind:** Function **Source:** [`src/adapter/deno/ssg.ts`](https://github.com/honojs/hono/blob/main/src/adapter/deno/ssg.ts#L25) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts async function toSSG(app, options) ``` ## Parameters | Name | Type | |---|---| | `app` | `any` | | `options` | `any` | # Hono **Kind:** Class **Source:** [`src/preset/tiny.ts`](https://github.com/honojs/hono/blob/main/src/preset/tiny.ts#L11) **Extends:** `HonoBase` ## Relationships - IMPORTS → `HonoOptions` # sign **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L56) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function sign(payload: JWTPayload, privateKey: SignatureKey, alg: SignatureAlgorithm): Promise ``` ## Parameters | Name | Type | |---|---| | `payload` | `JWTPayload` | | `privateKey` | `SignatureKey` | | `alg` | `SignatureAlgorithm` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Jwt` — `src/utils/jwt/index.ts`:7 # SSG_CONTEXT **Kind:** Constant **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L5) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts 'HONO_SSG_CONTEXT' ``` ## Value ```ts 'HONO_SSG_CONTEXT' ``` ## Relationships - IMPORTS → `isDynamicRoute` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # trimTrailingSlash **Kind:** Function **Source:** [`src/middleware/trailing-slash/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/trailing-slash/index.ts#L44) **Part of:** [Middleware](subsystem-src-middleware) Trailing Slash Middleware for Hono. `trimTrailingSlash` creates Hono middleware that redirects requests whose path ends with a trailing slash to the equivalent path without it. It keeps route URLs consistent before the request continues through the application middleware and route handlers. ## Signature ```ts function trimTrailingSlash(options: TrimTrailingSlashOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `TrimTrailingSlashOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[trimTrailingSlash middleware] Middleware --> Check{Path has trailing slash?} Check -->|Yes| Redirect[Redirect to trimmed path] Check -->|No| Next[Continue to next middleware or route] ``` ## Usage ```ts import { Hono } from 'hono' import { trimTrailingSlash } from 'hono/trailing-slash' const app = new Hono() app.use(trimTrailingSlash()) app.get('/users', (c) => { return c.text('User list') }) export default app ``` ## AI Coding Instructions - Register `trimTrailingSlash()` before routes that should use normalized paths. - Import the middleware from `hono/trailing-slash`. - Keep route definitions without trailing slashes when this middleware is enabled. - Do not add separate trailing-slash route variants unless they require different behavior. # update **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L740) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts async function update(context: Context, node: NodeObject): Promise ``` ## Parameters | Name | Type | |---|---| | `context` | `Context` | | `node` | `NodeObject` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `STASH_EFFECT` — `src/jsx/hooks/index.ts`:9 # upgradeWebSocket **Kind:** Constant **Source:** [`src/adapter/cloudflare-workers/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/websocket.ts#L5) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts UpgradeWebSocket< WebSocket, any, Omit, 'onOpen'> > ``` ## Value ```ts defineWebSocketHelper(async (c, events) => { const upgradeHeader = c.req.header('Upgrade') if (upgradeHeader !== 'websocket') { return } // @ts-expect-error WebSocketPair is not typed const webSocketPair = new WebSocketPair() const client: WebSocket = webSocketPair[0] const server: WebSocket = webSocketPair[1] const wsContext = new WSContext({ close: (code, rea… ``` ## Relationships - IMPORTS → `WSContext` - IMPORTS → `defineWebSocketHelper` # detectFromPath **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L176) **Part of:** [Middleware](subsystem-src-middleware) Detects language from URL path `detectFromPath` reads a URL path and determines the language encoded in that path. It is used by the language middleware to select the request language before downstream handlers process the request. ## Signature ```ts function detectFromPath(c: Context, options: DetectorOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `options` | `DetectorOptions` | **Returns:** `string | undefined` ## Diagram ```mermaid graph LR A[Request URL path] --> B[detectFromPath] B --> C[Detected language] C --> D[Language middleware] D --> E[Request handling] ``` ## Usage ```ts import { detectFromPath } from './middleware/language/language'; const language = detectFromPath('/en/docs/getting-started'); if (language) { console.log(`Detected language: ${language}`); } ``` ## AI Coding Instructions - Pass the URL pathname rather than the full URL when calling `detectFromPath`. - Keep path parsing rules consistent with the language prefixes supported by the middleware. - Handle cases where no language is detected before selecting localized content. - Update related routing and middleware behavior when changing language path formats. # getConnInfo **Kind:** Function **Source:** [`src/adapter/vercel/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/vercel/conninfo.ts#L3) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function getConnInfo(c) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | # InferInput **Kind:** Type **Source:** [`src/validator/utils.ts`](https://github.com/honojs/hono/blob/main/src/validator/utils.ts#L59) Utility type to infer input types for validation targets. Preserves literal union types (e.g., 'asc' | 'desc') while using the default ValidationTargets type for other values. `InferInput` derives the input type accepted by a validation target. It preserves literal unions such as `'asc' | 'desc'` and falls back to `ValidationTargets` for other target values. ## Definition ```ts [Exclude] extends [never] ? {} : [Exclude] extends [object] ? undefined extends Output ? SimplifyDeep, Target, T>> | undefined : SimplifyDeep> : {} ``` ## Diagram ```mermaid graph LR A[Validation target type] --> B[InferInput] B --> C[Literal union preserved] B --> D[Other values use ValidationTargets] ``` ## Usage ```ts import type { InferInput } from './validator/utils'; type SortDirection = InferInput<'asc' | 'desc'>; const direction: SortDirection = 'asc'; // const invalidDirection: SortDirection = 'up'; // Type error ``` ## AI Coding Instructions - Keep literal union types intact when passing them through `InferInput`. - Use `InferInput` for validator-facing input types rather than widening values to `string`. - Treat `ValidationTargets` as the fallback type for inputs that are not preserved literal unions. - Update related validator type definitions if supported validation target shapes change. # parse **Kind:** Function **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L109) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function parse(cookie: string, name: string): Cookie ``` ## Parameters | Name | Type | |---|---| | `cookie` | `string` | | `name` | `string` | **Returns:** `Cookie` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `getCookie` — `src/helper/cookie/index.ts`:27 # runWithRenderContext **Kind:** Function **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L161) **Part of:** [Jsx](subsystem-src-jsx) Establish the request-scoped context store for a render. `resumeStore` continues a suspended subtree in the same store on the fallback path (ignored when `AsyncLocalStorage` is available, where isolation is automatic). Without `AsyncLocalStorage` a render can't be followed across `await`, so the store lives in `fallbackStore` only during synchronous work (mirroring React's request storage). Reading context after `await` then finds no store and falls back to the default value — never another request's value. `runWithRenderContext` creates the request-scoped context store used while rendering a JSX tree. When `AsyncLocalStorage` is available, the store remains isolated across asynchronous work; otherwise, the fallback store exists only for synchronous rendering and context reads after `await` return their default values. ## Signature ```ts function runWithRenderContext(callback: () => T, resumeStore: RenderStore): T ``` ## Parameters | Name | Type | |---|---| | `callback` | `() => T` | | `resumeStore` | `RenderStore` | **Returns:** `T` ## Diagram ```mermaid graph LR Render[Render callback] --> Run[runWithRenderContext] Run --> ALS{AsyncLocalStorage available?} ALS -->|Yes| RequestStore[Request-scoped async store] ALS -->|No| FallbackStore[Temporary fallback store] RequestStore --> ContextRead[Context reads] FallbackStore --> ContextRead FallbackStore --> Cleanup[Restore previous fallback store] ``` ## Usage ```tsx import { runWithRenderContext } from './jsx/context'; import { renderPage } from './render'; const html = runWithRenderContext(() => { return renderPage(); }); // Context reads performed during renderPage use this render's store. return new Response(html, { headers: { 'content-type': 'text/html' }, }); ``` ## AI Coding Instructions - Wrap each top-level render entry point with `runWithRenderContext` so context values are scoped to that render. - Keep fallback-mode context-dependent rendering synchronous; context reads after `await` use the context default value when `AsyncLocalStorage` is unavailable. - Pass `resumeStore` only when resuming a suspended subtree that must continue with its prior context values. - Restore the previous fallback store after callback execution so one render cannot expose context values to another render. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Props` — `src/jsx/base.ts`:27 # X_HONO_DISABLE_SSG_HEADER_KEY **Kind:** Constant **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L6) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts 'x-hono-disable-ssg' ``` ## Value ```ts 'x-hono-disable-ssg' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # createCssJsxDomObjects **Kind:** Function **Source:** [`src/jsx/dom/css.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/css.ts#L77) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createCssJsxDomObjects({ id }) ``` ## Parameters | Name | Type | |---|---| | `{ id }` | `any` | ## Relationships - IMPORTS → `CLASS_NAME` - IMPORTS → `DEFAULT_STYLE_ID` - IMPORTS → `PSEUDO_GLOBAL_SELECTOR` - IMPORTS → `SELECTOR` - IMPORTS → `SELECTORS` - IMPORTS → `STYLE_STRING` - IMPORTS → `cssCommon` - IMPORTS → `cxCommon` - IMPORTS → `keyframesCommon` - IMPORTS → `viewTransitionCommon` - IMPORTS → `rawCssString` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `createCssContext` — `src/helper/css/index.ts`:72 # every **Kind:** Function **Source:** [`src/middleware/combine/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/combine/index.ts#L99) **Part of:** [Middleware](subsystem-src-middleware) Create a composed middleware that runs all middleware and throws an error if any of them fail. `every` creates a single middleware from multiple middleware functions. It runs each middleware and propagates an error when any middleware fails, allowing the caller to handle the failure through the normal middleware error path. ## Signature ```ts function every(middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `middleware` | `(MiddlewareHandler | Condition)[]` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR A[Request context] --> B[every middleware] B --> C[Middleware A] B --> D[Middleware B] B --> E[Middleware C] C --> F{Any middleware fails?} D --> F E --> F F -->|Yes| G[Throw error] F -->|No| H[Continue request flow] ``` ## Usage ```ts import { every } from "./middleware/combine"; const requireUser = async (context: RequestContext) => { if (!context.user) { throw new Error("Authentication required"); } }; const requireProject = async (context: RequestContext) => { if (!context.params.projectId) { throw new Error("Project ID is required"); } }; const validateRequest = every(requireUser, requireProject); await validateRequest(context); ``` ## AI Coding Instructions - Pass middleware that follows the project's middleware function signature. - Let middleware throw errors for failed checks; `every` propagates those errors. - Keep each middleware focused on one request concern, such as authentication or input validation. - Add shared middleware through `every` where a route or handler requires all checks to pass. # ExtractSchemaForStatusCode **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2741) ## Definition ```ts { [Path in keyof ExtractSchema]: { [Method in keyof ExtractSchema[Path]]: Extract< ExtractSchema[Path][Method], { status: Status } > } } ``` # fetchRoutesContent **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L205) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function fetchRoutesContent(app: Hono, beforeRequestHook: BeforeRequestHook, afterResponseHook: AfterResponseHook, concurrency: number): Generator< Promise< | Generator< Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined> > | undefined > > ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | | `beforeRequestHook` | `BeforeRequestHook` | | `afterResponseHook` | `AfterResponseHook` | | `concurrency` | `number` | **Returns:** `Generator< Promise< | Generator< Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined> > | undefined > >` # handle **Kind:** Function **Source:** [`src/adapter/netlify/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/netlify/handler.ts#L4) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function handle(app: Hono): ((req: Request, context: any) => Response | Promise) ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | **Returns:** `((req: Request, context: any) => Response | Promise)` # verifying **Kind:** Function **Source:** [`src/utils/jwt/jws.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jws.ts#L39) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function verifying(publicKey: SignatureKey, alg: SignatureAlgorithm, signature: BufferSource, data: BufferSource): Promise ``` ## Parameters | Name | Type | |---|---| | `publicKey` | `SignatureKey` | | `alg` | `SignatureAlgorithm` | | `signature` | `BufferSource` | | `data` | `BufferSource` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # createPortal **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L815) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createPortal(children: Child, container: HTMLElement, key: string): Child ``` ## Parameters | Name | Type | |---|---| | `children` | `Child` | | `container` | `HTMLElement` | | `key` | `string` | **Returns:** `Child` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # defaultIsContentTypeBinary **Kind:** Function **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L666) **Part of:** [Adapter](subsystem-src-adapter) Check if the given content type is binary. This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler(). `defaultIsContentTypeBinary` checks a response `Content-Type` and returns whether AWS Lambda should treat the response body as binary data. It is the default predicate used by `handler()`, which can be replaced through the `isContentTypeBinary` handler option. ## Signature ```ts function defaultIsContentTypeBinary(contentType: string): boolean ``` ## Parameters | Name | Type | |---|---| | `contentType` | `string` | **Returns:** `boolean` ## Diagram ```mermaid graph LR Response[Response Content-Type] --> Check[defaultIsContentTypeBinary] Check -->|binary| Encode[Base64 encode body] Check -->|text| Body[Return body as text] Override[isContentTypeBinary option] --> Check ``` ## Usage ```ts import { handler } from 'hono/aws-lambda' import { Hono } from 'hono' const app = new Hono() app.get('/report', (c) => { return c.body(new Uint8Array([1, 2, 3]), { headers: { 'Content-Type': 'application/pdf', }, }) }) export const lambdaHandler = handler(app, { isContentTypeBinary: (contentType) => contentType.startsWith('application/pdf') || contentType.startsWith('image/'), }) ``` ## AI Coding Instructions - Keep the predicate input limited to the response `Content-Type` string. - Return a boolean that determines whether the Lambda response body is Base64 encoded. - Pass custom binary-type rules through `handler()` using `isContentTypeBinary`. - Include custom media types when an endpoint returns non-text response bodies. # InputToDataByTarget **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2720) ## Definition ```ts T extends { [K in Target]: infer R } ? R : never ``` # languageDetector **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L292) **Part of:** [Middleware](subsystem-src-middleware) Language detector middleware factory `languageDetector` creates middleware that determines the language for an incoming request. Register it early in the middleware pipeline so downstream handlers can use the detected language context. ## Signature ```ts function languageDetector(userOptions: Partial): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `userOptions` | `Partial` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Detector[languageDetector middleware] Detector --> Language[Detected language context] Language --> Handler[Downstream handler] ``` ## Usage ```ts import { languageDetector } from './middleware/language/language'; const app = createApp(); app.use(languageDetector()); // Routes registered after the detector can access language-aware context. app.get('/content', contentHandler); ``` ## AI Coding Instructions - Register `languageDetector()` before routes or middleware that depend on request language context. - Keep language lookup behavior aligned with the application's translation and locale handling. - Do not create detector middleware inside individual route handlers. - Test requests with missing or unsupported language inputs alongside supported language inputs. # mergePath **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L158) **Part of:** [Utils](subsystem-src-utils) Merge paths. `mergePath` combines path values into a single URL path. Use it when building route, endpoint, or asset paths so callers do not need to concatenate path strings manually. ## Signature ```ts function mergePath(base: string | undefined, sub: string | undefined, rest: string[]): string ``` ## Parameters | Name | Type | |---|---| | `base` | `string | undefined` | | `sub` | `string | undefined` | | `rest` | `string[]` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Base path] --> C[mergePath] B[Path segment] --> C C --> D[Merged path] ``` ## Usage ```ts import { mergePath } from './utils/url'; const usersPath = mergePath('/api/', '/users'); console.log(usersPath); // /api/users ``` ## AI Coding Instructions - Pass path segments to `mergePath` instead of concatenating strings with `/`. - Keep path inputs consistent with existing callers, especially leading and trailing slashes. - Use this helper when constructing routes, API endpoints, or asset paths in shared URL-building code. - Do not assume it handles full URLs, query parameters, or hash fragments unless its implementation supports them. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoOptions` — `src/hono-base.ts`:46 # toSSG **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L368) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts async function toSSG(app, fs, options) ``` ## Parameters | Name | Type | |---|---| | `app` | `any` | | `fs` | `any` | | `options` | `any` | # Factory **Kind:** Class **Source:** [`src/helper/factory/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/factory/index.ts#L332) **Part of:** [Helper](subsystem-src-helper) ## Properties | Property | Type | |---|---| | `#defaultAppOptions` | `HonoOptions` | | `createApp` | `any` | | `createMiddleware` | `any` | | `createHandlers` | `CreateHandlersInterface` | # getConnInfo **Kind:** Function **Source:** [`src/adapter/cloudflare-pages/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-pages/conninfo.ts#L22) **Part of:** [Adapter](subsystem-src-adapter) Get connection information from Cloudflare Pages `getConnInfo` reads connection details from a Cloudflare Pages request. It maps Cloudflare-specific request metadata into the connection information shape used by the adapter layer. ## Signature ```ts function getConnInfo(c) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | ## Diagram ```mermaid graph LR A[Cloudflare Pages Request] --> B[getConnInfo] B --> C[Connection Information] C --> D[Adapter Request Handling] ``` ## Usage ```ts import { getConnInfo } from "./conninfo" export const onRequest: PagesFunction = async ({ request }) => { const connInfo = getConnInfo(request) console.log(connInfo) return new Response("OK") } ``` ## AI Coding Instructions - Pass the Cloudflare Pages `Request` object to `getConnInfo`. - Keep Cloudflare-specific header and request metadata handling inside this adapter module. - Return connection data in the shared shape expected by the rest of the adapter system. - Account for connection fields that may be absent in local development or test environments. # requestId **Kind:** Function **Source:** [`src/middleware/request-id/request-id.ts`](https://github.com/honojs/hono/blob/main/src/middleware/request-id/request-id.ts#L41) **Part of:** [Middleware](subsystem-src-middleware) Request ID Middleware for Hono. `requestId` is Hono middleware that assigns an identifier to each incoming request. It makes the identifier available through the request context and returns it in the response header so logs, handlers, and clients can reference the same request. ## Signature ```ts function requestId({ limitLength = 255, headerName = 'X-Request-Id', generator = () => crypto.randomUUID(), }: RequestIdOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `{ limitLength = 255, headerName = 'X-Request-Id', generator = () => crypto.randomUUID(), }` | `RequestIdOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Client[Client Request] --> Middleware[requestId Middleware] Middleware --> Context[Hono Context: requestId] Middleware --> Handler[Route Handler] Handler --> Response[Response with Request ID Header] ``` ## Usage ```ts import { Hono } from 'hono' import { requestId } from 'hono/request-id' const app = new Hono() app.use('*', requestId()) app.get('/status', (c) => { const id = c.get('requestId') return c.json({ requestId: id, status: 'ok', }) }) export default app ``` ## AI Coding Instructions - Register `requestId()` before route handlers that need access to `c.get('requestId')`. - Use the request ID when writing logs or reporting errors so related events can be correlated. - Preserve the response request ID header when adding middleware that creates or replaces responses. - Avoid generating separate request IDs inside handlers; read the value already stored on the Hono context. # signing **Kind:** Function **Source:** [`src/utils/jwt/jws.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jws.ts#L29) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function signing(privateKey: SignatureKey, alg: SignatureAlgorithm, data: BufferSource): Promise ``` ## Parameters | Name | Type | |---|---| | `privateKey` | `SignatureKey` | | `alg` | `SignatureAlgorithm` | | `data` | `BufferSource` | **Returns:** `Promise` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # useMemo **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L352) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useMemo(factory: () => T, deps: readonly unknown[]): T ``` ## Parameters | Name | Type | |---|---| | `factory` | `() => T` | | `deps` | `readonly unknown[]` | **Returns:** `T` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # ValidationFunction **Kind:** Type **Source:** [`src/validator/validator.ts`](https://github.com/honojs/hono/blob/main/src/validator/validator.ts#L14) ## Definition ```ts ( value: InputType, c: Context ) => OutputType | TypedResponse | Promise | Promise ``` ## Relationships - IMPORTS → `getCookie` - IMPORTS → `HTTPException` - IMPORTS → `bufferToFormData` # buildNode **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L667) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function buildNode(node: Child): Node | undefined ``` ## Parameters | Name | Type | |---|---| | `node` | `Child` | **Returns:** `Node | undefined` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Root` — `src/jsx/dom/client.ts`:11 # convertIPv6BinaryToString **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L327) **Part of:** [Utils](subsystem-src-utils) Convert a binary representation of an IPv6 address to a string. `convertIPv6BinaryToString` converts an IPv6 address from its binary representation into a string. Use it at boundaries where binary address data must be displayed, logged, or passed to code that expects an IPv6 string. ## Signature ```ts function convertIPv6BinaryToString(ipV6: bigint): string ``` ## Parameters | Name | Type | |---|---| | `ipV6` | `bigint` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Binary IPv6 value] --> B[convertIPv6BinaryToString] B --> C[IPv6 string] ``` ## Usage ```ts import { convertIPv6BinaryToString } from "./utils/ipaddr"; // Obtain the binary IPv6 value from a network, parser, or storage layer. declare const binaryIPv6: string; const ipv6Address = convertIPv6BinaryToString(binaryIPv6); console.log(ipv6Address); ``` ## AI Coding Instructions - Pass the binary IPv6 value to this function, not an already formatted IPv6 string. - Keep binary-to-string conversion at input or output boundaries rather than spreading address formatting logic across callers. - Preserve the binary value unchanged before conversion; changing its order changes the resulting address. - Use the returned string for display, logging, serialization, or APIs that accept textual IPv6 addresses. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # generateSignedCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L104) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts async function generateSignedCookie(name: string, value: string, secret: string | BufferSource, opt: CookieOptions): Promise ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `value` | `string` | | `secret` | `string | BufferSource` | | `opt` | `CookieOptions` | **Returns:** `Promise` # getConnInfo **Kind:** Function **Source:** [`src/adapter/cloudflare-workers/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/conninfo.ts#L3) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function getConnInfo(c) ``` ## Parameters | Name | Type | |---|---| | `c` | `any` | # logger **Kind:** Function **Source:** [`src/middleware/logger/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/logger/index.ts#L81) **Part of:** [Middleware](subsystem-src-middleware) Logger Middleware for Hono. `logger` creates Hono middleware that writes request and response log entries during request handling. It records the request method and path before execution, then logs the response status and elapsed time after downstream middleware completes. ## Signature ```ts function logger(fn: PrintFunc): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `fn` | `PrintFunc` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Logger[logger middleware] Logger --> StartLog[Write request log] StartLog --> Next[Run downstream handler] Next --> ResponseLog[Write response log] ResponseLog --> Response[Send response] ``` ## Usage ```ts import { Hono } from 'hono' import { logger } from 'hono/logger' const app = new Hono() app.use('*', logger()) app.get('/', (c) => { return c.text('Hello from Hono') }) export default app ``` ## AI Coding Instructions - Register `logger()` with `app.use()` so it runs before the routes or middleware you want to observe. - Place the logger early in the middleware chain to include downstream handler execution time in its output. - Keep downstream middleware calling `await next()` so the logger can record the final response status. - Pass a custom print function to `logger` when logs need to be sent to an application-specific logging destination. ## Relationships - IMPORTS → `getColorEnabledAsync` # ValidationTargets **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2683) ## Definition ```ts { json: any form: Record query: Record param: Record header: Record cookie: Record } ``` # AddParam **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2601) ## Definition ```ts ParamKeys

extends never ? I : I extends { param: infer _ } ? I : I & { param: UnionToIntersection>> } ``` # createContextProviderFunction **Kind:** Function **Source:** [`src/jsx/dom/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/context.ts#L7) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createContextProviderFunction(values: T[]): Function ``` ## Parameters | Name | Type | |---|---| | `values` | `T[]` | **Returns:** `Function` ## Relationships - IMPORTS → `DOM_ERROR_HANDLER` - IMPORTS → `globalContexts` - IMPORTS → `setInternalTagFlag` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Context` — `src/jsx/context.ts`:8 # createPool **Kind:** Function **Source:** [`src/utils/concurrent.ts`](https://github.com/honojs/hono/blob/main/src/utils/concurrent.ts#L12) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function createPool({ concurrency, interval, }: { concurrency?: number interval?: number }): Pool ``` ## Parameters | Name | Type | |---|---| | `{ concurrency, interval, }` | `{ concurrency?: number interval?: number }` | **Returns:** `Pool` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # getConnInfo **Kind:** Function **Source:** [`src/adapter/lambda-edge/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/conninfo.ts#L11) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function getConnInfo(c: Context) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | # saveContentToFile **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L310) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts async function saveContentToFile(data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>, fsModule: FileSystemModule, outDir: string, extensionMap: Record): Promise ``` ## Parameters | Name | Type | |---|---| | `data` | `Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>` | | `fsModule` | `FileSystemModule` | | `outDir` | `string` | | `extensionMap` | `Record` | **Returns:** `Promise` # validateOptions **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L204) **Part of:** [Middleware](subsystem-src-middleware) Validate detector options `validateOptions` validates detector options before they are used by the language middleware. It checks that the supplied configuration matches the detector's expected option structure. Call it during middleware setup to reject invalid configuration early. ## Signature ```ts function validateOptions(options: DetectorOptions): void ``` ## Parameters | Name | Type | |---|---| | `options` | `DetectorOptions` | **Returns:** `void` ## Diagram ```mermaid graph LR A[Detector options] --> B[validateOptions] B --> C[Valid options] B --> D[Invalid option error] C --> E[Language middleware] ``` ## Usage ```ts import { validateOptions } from './src/middleware/language/language'; const detectorOptions = { supportedLanguages: ['en', 'fr'], fallbackLanguage: 'en', }; validateOptions(detectorOptions); // Pass validated options to language middleware setup. ``` ## AI Coding Instructions - Validate detector configuration before creating or invoking the language middleware. - Keep option names and value types aligned with the language detector configuration contract. - Do not bypass validation when options come from environment variables or external configuration files. - Update validation rules when adding detector options so invalid values fail at setup time. # detectFromCookie **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L145) **Part of:** [Middleware](subsystem-src-middleware) Detects language from cookie `detectFromCookie` reads the language preference stored in a cookie and returns the detected language value. It is used by the language middleware to select a request language before applying language-dependent behavior. ## Signature ```ts function detectFromCookie(c: Context, options: DetectorOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `options` | `DetectorOptions` | **Returns:** `string | undefined` ## Diagram ```mermaid graph LR Request[Incoming request] --> Cookie[Cookie header] Cookie --> Detect[detectFromCookie] Detect --> Language[Detected language] Language --> Middleware[Language middleware] ``` ## Usage ```ts import { detectFromCookie } from './middleware/language/language'; const cookieHeader = request.headers.get('cookie') ?? undefined; const language = detectFromCookie(cookieHeader); if (language) { request.language = language; } ``` ## AI Coding Instructions - Keep cookie parsing and language detection within `detectFromCookie`; callers should pass the request cookie value rather than parse it themselves. - Handle missing, malformed, or unsupported cookie values without throwing during request processing. - Keep detected language values aligned with the languages supported by the language middleware. - Apply the detected value before fallback language selection so explicit user preferences take precedence. # Endpoint **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2546) ## Definition ```ts { input: any output: any outputFormat: ResponseFormat status: StatusCode } ``` # getConnInfo **Kind:** Function **Source:** [`src/adapter/netlify/conninfo.ts`](https://github.com/honojs/hono/blob/main/src/adapter/netlify/conninfo.ts#L53) **Part of:** [Adapter](subsystem-src-adapter) Get connection information from Netlify `getConnInfo` retrieves connection information from the Netlify adapter. It acts as the Netlify-specific source for connection data used by the surrounding adapter flow. ## Signature ```ts function getConnInfo(c: Context) ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | ## Diagram ```mermaid graph LR A[Application] --> B[getConnInfo] B --> C[Netlify adapter] C --> D[Connection information] D --> A ``` ## Usage ```ts import { getConnInfo } from './adapter/netlify/conninfo'; const connectionInfo = await getConnInfo(); console.log(connectionInfo); ``` ## AI Coding Instructions - Keep Netlify-specific connection lookup logic inside the Netlify adapter. - Treat the return value as adapter data; avoid duplicating Netlify environment handling in callers. - Handle missing or invalid connection data at the integration boundary. - Update callers when the connection information shape changes. # renderNode **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L783) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function renderNode(node: NodeObject, container: Container): void ``` ## Parameters | Name | Type | |---|---| | `node` | `NodeObject` | | `container` | `Container` | **Returns:** `void` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Root` — `src/jsx/dom/client.ts`:11 # serialize **Kind:** Function **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L261) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function serialize(name: Name, value: string, opt: CookieConstraint): string ``` ## Parameters | Name | Type | |---|---| | `name` | `Name` | | `value` | `string` | | `opt` | `CookieConstraint` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `getCookie` — `src/helper/cookie/index.ts`:27 # stream **Kind:** Function **Source:** [`src/helper/streaming/stream.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/stream.ts#L7) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function stream(c: Context, cb: (stream: StreamingApi) => Promise, onError: (e: Error, stream: StreamingApi) => Promise): Response ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `cb` | `(stream: StreamingApi) => Promise` | | `onError` | `(e: Error, stream: StreamingApi) => Promise` | **Returns:** `Response` ## Relationships - IMPORTS → `StreamingApi` - IMPORTS → `isOldBunVersion` # buildStyleString **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L139) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function buildStyleString(strings: TemplateStringsArray, values: CssVariableType[]): [string, string, CssClassName[], string[]] ``` ## Parameters | Name | Type | |---|---| | `strings` | `TemplateStringsArray` | | `values` | `CssVariableType[]` | **Returns:** `[string, string, CssClassName[], string[]]` # childrenToString **Kind:** Function **Source:** [`src/jsx/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/components.ts#L14) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts async function childrenToString(children: Child[]): Promise ``` ## Parameters | Name | Type | |---|---| | `children` | `Child[]` | **Returns:** `Promise` ## Relationships - IMPORTS → `html` - IMPORTS → `HtmlEscapedCallbackPhase` - IMPORTS → `resolveCallback` - IMPORTS → `Fragment` - IMPORTS → `DOM_RENDERER` - IMPORTS → `captureRenderContext` - IMPORTS → `useContext` - IMPORTS → `ErrorBoundary` - IMPORTS → `StreamingContext` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `StreamingContext` — `src/jsx/streaming.ts`:30 # detectFromQuery **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L137) **Part of:** [Middleware](subsystem-src-middleware) Detects language from query parameter `detectFromQuery` reads the language value from the incoming request query parameters. It is used by the language middleware to select the request language before downstream handlers process the request. ## Signature ```ts function detectFromQuery(c: Context, options: DetectorOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `options` | `DetectorOptions` | **Returns:** `string | undefined` ## Diagram ```mermaid graph LR Request[Incoming request] --> Query[Query parameters] Query --> Detect[detectFromQuery] Detect --> Language[Detected language] Language --> Middleware[Language middleware] Middleware --> Handler[Request handler] ``` ## Usage ```ts import { detectFromQuery } from './language'; app.use((req, res, next) => { const language = detectFromQuery(req); if (language) { req.language = language; } next(); }); ``` ## AI Coding Instructions - Pass the incoming request object to `detectFromQuery` rather than reading query parameters in multiple middleware layers. - Keep query parameter parsing inside this function so language detection has one code path. - Handle an absent or invalid detected language in the calling middleware. - Keep the detected language available on the request for downstream handlers when the middleware contract supports it. # getMimeType **Kind:** Function **Source:** [`src/utils/mime.ts`](https://github.com/honojs/hono/blob/main/src/utils/mime.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getMimeType(filename: string, mimes: Record): string | undefined ``` ## Parameters | Name | Type | |---|---| | `filename` | `string` | | `mimes` | `Record` | **Returns:** `string | undefined` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ServeStaticOptions` — `src/middleware/serve-static/index.ts`:13 # handle **Kind:** Function **Source:** [`src/adapter/vercel/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/vercel/handler.ts#L4) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function handle(app: Hono) ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | # Handler **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L76) ## Definition ```ts (c: Context, next: Next) => R ``` # createCssContext **Kind:** Function **Source:** [`src/helper/css/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/index.ts#L72) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function createCssContext({ id, classNameSlug, onInvalidSlug, }: { id: Readonly classNameSlug?: ClassNameSlug onInvalidSlug?: OnInvalidSlug }): DefaultContextType ``` ## Parameters | Name | Type | |---|---| | `{ id, classNameSlug, onInvalidSlug, }` | `{ id: Readonly classNameSlug?: ClassNameSlug onInvalidSlug?: OnInvalidSlug }` | **Returns:** `DefaultContextType` ## Relationships - IMPORTS → `html` - IMPORTS → `DOM_RENDERER` - IMPORTS → `createCssJsxDomObjects` - IMPORTS → `escapeToBuffer` - IMPORTS → `CLASS_NAME` - IMPORTS → `DEFAULT_STYLE_ID` - IMPORTS → `PSEUDO_GLOBAL_SELECTOR` - IMPORTS → `SELECTOR` - IMPORTS → `SELECTORS` - IMPORTS → `STYLE_STRING` - IMPORTS → `cssCommon` - IMPORTS → `cxCommon` - IMPORTS → `keyframesCommon` - IMPORTS → `viewTransitionCommon` - IMPORTS → `rawCssString` # getPath **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L106) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getPath(request: Request): string ``` ## Parameters | Name | Type | |---|---| | `request` | `Request` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoOptions` — `src/hono-base.ts`:46 # isContentTypeBinary **Kind:** Function **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L214) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function isContentTypeBinary(contentType: string): boolean ``` ## Parameters | Name | Type | |---|---| | `contentType` | `string` | **Returns:** `boolean` # isValidTagName **Kind:** Function **Source:** [`src/jsx/utils.ts`](https://github.com/honojs/hono/blob/main/src/jsx/utils.ts#L32) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function isValidTagName(name: unknown): name is string ``` ## Parameters | Name | Type | |---|---| | `name` | `unknown` | **Returns:** `name is string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Props` — `src/jsx/base.ts`:27 # MergeSchemaPath **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2563) ## Definition ```ts { [P in keyof OrigSchema as MergePath]: [OrigSchema[P]] extends [ Record, ] ? { [M in keyof OrigSchema[P]]: MergeEndpointParamsWithPath } : never } ``` # prettyJSON **Kind:** Function **Source:** [`src/middleware/pretty-json/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/pretty-json/index.ts#L46) **Part of:** [Middleware](subsystem-src-middleware) Pretty JSON Middleware for Hono. `prettyJSON` creates Hono middleware that formats JSON response bodies with indentation when the request asks for pretty output. Register it before route handlers so it can inspect downstream JSON responses and replace them with formatted JSON when appropriate. ## Signature ```ts function prettyJSON(options: PrettyOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `PrettyOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[prettyJSON middleware] Middleware --> Route[Route handler] Route --> Response[JSON response] Response --> Middleware Middleware --> Formatted[Formatted JSON response] ``` ## Usage ```ts import { Hono } from 'hono' import { prettyJSON } from 'hono/pretty-json' const app = new Hono() app.use('*', prettyJSON()) app.get('/users', (c) => { return c.json({ users: [{ id: 'user-a', name: 'Ada' }], }) }) export default app ``` Request the route with `?pretty` to receive formatted JSON. ## AI Coding Instructions - Register `prettyJSON()` before routes whose JSON responses should support formatted output. - Return JSON through Hono response helpers such as `c.json()` so the response has a JSON content type. - Preserve the middleware order: `prettyJSON` must wrap downstream route handling to format the completed response. - Avoid applying assumptions about non-JSON response bodies; the middleware should only reformat valid JSON responses. # MiddlewareHandler **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L83) ## Definition ```ts (c: Context, next: Next) => Promise ``` # NONCE **Kind:** Function **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L137) **Part of:** [Middleware](subsystem-src-middleware) ## Signature ```ts function NONCE(ctx) ``` ## Parameters | Name | Type | |---|---| | `ctx` | `any` | # raw **Kind:** Function **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L40) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function raw(value: unknown, callbacks: HtmlEscapedCallback[]): HtmlEscapedString ``` ## Parameters | Name | Type | |---|---| | `value` | `unknown` | | `callbacks` | `HtmlEscapedCallback[]` | **Returns:** `HtmlEscapedString` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `html` — `src/helper/html/index.ts`:11 # setSignedCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L130) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts async function setSignedCookie(c: Context, name: string, value: string, secret: string | BufferSource, opt: CookieOptions): Promise ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `value` | `string` | | `secret` | `string | BufferSource` | | `opt` | `CookieOptions` | **Returns:** `Promise` # title **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L121) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function title({ children, ...props }) ``` ## Parameters | Name | Type | |---|---| | `{ children, ...props }` | `any` | ## Relationships - IMPORTS → `html` - IMPORTS → `JSXNode` - IMPORTS → `getNameSpaceContext` - IMPORTS → `toArray` - IMPORTS → `PERMALINK` - IMPORTS → `useContext` - IMPORTS → `dataPrecedenceAttr` - IMPORTS → `deDupeKeyMap` - IMPORTS → `isStylesheetLinkWithPrecedence` - IMPORTS → `shouldDeDupeByKey` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Props` — `src/jsx/base.ts`:27 # upgradeWebSocket **Kind:** Constant **Source:** [`src/adapter/deno/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/deno/websocket.ts#L4) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts UpgradeWebSocket ``` ## Value ```ts defineWebSocketHelper(async (c, events, options) => { if (c.req.header('upgrade') !== 'websocket') { return } // Echo the negotiated subprotocol back to the client. Browsers (e.g. Chrome) // reject the connection when a subprotocol was requested but the response is // missing the `Sec-WebSocket-Protocol` header. const subprotocol = c.req.header('sec-websocket-protoco… ``` ## Relationships - IMPORTS → `WSContext` - IMPORTS → `defineWebSocketHelper` # auth **Kind:** Function **Source:** [`src/utils/basic-auth.ts`](https://github.com/honojs/hono/blob/main/src/utils/basic-auth.ts#L9) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function auth(req: Request) ``` ## Parameters | Name | Type | |---|---| | `req` | `Request` | ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `handler` — `src/middleware/basic-auth/index.ts`:118 # poweredBy **Kind:** Function **Source:** [`src/middleware/powered-by/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/powered-by/index.ts#L30) **Part of:** [Middleware](subsystem-src-middleware) Powered By Middleware for Hono. `poweredBy` creates Hono middleware that adds an `X-Powered-By` response header. It runs after downstream middleware and handlers, allowing the header value to be configured with `serverName`. ## Signature ```ts function poweredBy(options: PoweredByOptions): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `options` | `PoweredByOptions` | **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR A[Incoming request] --> B[poweredBy middleware] B --> C[Downstream middleware and route handler] C --> D[Set X-Powered-By response header] D --> E[Response] ``` ## Usage ```ts import { Hono } from 'hono' import { poweredBy } from 'hono/powered-by' const app = new Hono() app.use('*', poweredBy({ serverName: 'My API' })) app.get('/', (c) => { return c.text('Hello') }) export default app ``` ## AI Coding Instructions - Register `poweredBy()` with `app.use()` so it applies to the intended routes. - Pass `serverName` when the default `Hono` header value should be replaced. - Keep `await next()` in the middleware flow so downstream handlers run before the response header is set. - Check for other middleware that sets `X-Powered-By`, since later header writes can replace earlier values. # RouterRoute **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L57) `RouterRoute` describes a route registered with a router. It stores the route's base path, path, HTTP method, and handler so the router can match requests and invoke the associated handler. ## Properties | Property | Type | |---|---| | `basePath` | `string` | | `path` | `string` | | `method` | `string` | | `handler` | `H` | ## Diagram ```mermaid graph LR Router[Router] --> Route[RouterRoute] Route --> BasePath[basePath: string] Route --> Path[path: string] Route --> Method[method: string] Route --> Handler[handler: H] Request[Incoming request] --> Router Router --> Handler ``` ## Usage ```ts interface RouterRoute { basePath: string; path: string; method: string; handler: H; } type RequestHandler = (request: Request) => Response; const getUserRoute: RouterRoute = { basePath: "/api", path: "/users/:id", method: "GET", handler: (request) => { return new Response(`Requested: ${request.url}`); }, }; ``` ## AI Coding Instructions - Keep `basePath` and `path` separate so the router can compose the final route path. - Match `method` values to the format expected by the router, such as `"GET"` or `"POST"`. - Type `handler` with the handler signature used by the router implementation. - Preserve the generic `H` type when passing routes through registration or matching code. # streamSSE **Kind:** Function **Source:** [`src/helper/streaming/sse.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/sse.ts#L73) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function streamSSE(c: Context, cb: (stream: SSEStreamingApi) => Promise, onError: (e: Error, stream: SSEStreamingApi) => Promise): Response ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `cb` | `(stream: SSEStreamingApi) => Promise` | | `onError` | `(e: Error, stream: SSEStreamingApi) => Promise` | **Returns:** `Response` # use **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L336) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function use(promise: Promise): T ``` ## Parameters | Name | Type | |---|---| | `promise` | `Promise` | **Returns:** `T` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # websocket **Kind:** Constant **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L76) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts BunWebSocketHandler ``` ## Value ```ts { open(ws) { const websocketListeners = ws.data.events if (websocketListeners.onOpen) { websocketListeners.onOpen(new Event('open'), createWSContext(ws)) } }, close(ws, code, reason) { const websocketListeners = ws.data.events if (websocketListeners.onClose) { websocketListeners.onClose( new CloseEvent('close', { code, reason, … ``` # decode **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L264) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function decode(token: string): { header: TokenHeader; payload: JWTPayload } ``` ## Parameters | Name | Type | |---|---| | `token` | `string` | **Returns:** `{ header: TokenHeader; payload: JWTPayload }` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Jwt` — `src/utils/jwt/index.ts`:7 # DetectorOptions **Kind:** Interface **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L13) **Part of:** [Middleware](subsystem-src-middleware) `DetectorOptions` configures how language middleware detects, validates, and stores the active language. It defines detection sources, cache behavior, cookie settings, matching rules, fallback behavior, and the languages accepted by the application. ## Properties | Property | Type | |---|---| | `order` | `DetectorType[]` | | `lookupQueryString` | `string` | | `lookupCookie` | `string` | | `lookupFromPathIndex` | `number` | | `lookupFromHeaderKey` | `string` | | `caches` | `CacheType[] | false` | | `cookieOptions` | `{ domain?: string path?: string sameSite?: 'Strict' | 'Lax' | 'None' secure?: boolean maxAge?: number httpOnly?: boolean }` | | `ignoreCase` | `boolean` | | `fallbackLanguage` | `string` | | `supportedLanguages` | `string[]` | | `convertDetectedLanguage` | `(lang: string) => string` | | `debug` | `boolean` | ## Diagram ```mermaid graph LR Request[Incoming request] --> Order[Detection order] Order --> Query[Query string] Order --> Cookie[Cookie] Order --> Path[URL path] Order --> Header[Request header] Query --> Language[Detected language] Cookie --> Language Path --> Language Header --> Language Language --> Supported[Supported languages] Supported -->|match| Active[Active language] Supported -->|no match| Fallback[Fallback language] Active --> Cache[Configured caches] Cache --> CookieOptions[Cookie options] ``` ## Usage ```ts import type { CacheType, DetectorOptions, DetectorType, } from './src/middleware/language/language' function createDetectorOptions( lookupFromPathIndex: number, ): DetectorOptions { const order: DetectorType[] = ['querystring', 'cookie', 'path', 'header'] const caches: CacheType[] = ['cookie'] return { order, lookupQueryString: 'lang', lookupCookie: 'language', lookupFromPathIndex, lookupFromHeaderKey: 'accept-language', caches, cookieOptions: { path: '/', sameSite: 'Lax', httpOnly: true, secure: true, }, ignoreCase: true, fallbackLanguage: 'en', supportedLanguages: ['en', 'fr', 'de'], } } ``` ## AI Coding Instructions - Keep `order` aligned with the request sources supported by the language middleware. - Use `supportedLanguages` to limit accepted detected values, and set `fallbackLanguage` to a supported value. - Set `caches` to `false` when detected languages must not be persisted between requests. - Match `lookupQueryString`, `lookupCookie`, and `lookupFromHeaderKey` with the names used by application routes and clients. - Configure `cookieOptions` for the deployment environment, including `secure`, `sameSite`, and cookie scope. ## How it works `DetectorOptions` is the exported TypeScript interface that defines the complete configuration shape used by language detection functions and by `languageDetector`. Its required fields select detection sources, configure their lookups, define language matching, caching, and fallback behavior; `cookieOptions`, `convertDetectedLanguage`, and `debug` are optional. [src/middleware/language/language.ts:13-45](src/middleware/language/language.ts#L13-L45) - `order` is an array of detector names: `'path'`, `'querystring'`, `'cookie'`, or `'header'`. The middleware tries these in array order and stops at the first detector that returns a language. [src/middleware/language/language.ts:10-10](src/middleware/language/language.ts#L10) [src/middleware/language/language.ts:241-258](src/middleware/language/language.ts#L241-L258) - `lookupQueryString` names the query parameter read by the query-string detector. [src/middleware/language/language.ts:16-17](src/middleware/language/language.ts#L16-L17) [src/middleware/language/language.ts:137-140](src/middleware/language/language.ts#L137-L140) - `lookupCookie` names both the request cookie read by the cookie detector and the response cookie written when cookie caching is active. [src/middleware/language/language.ts:18-19](src/middleware/language/language.ts#L18-L19) [src/middleware/language/language.ts:145-148](src/middleware/language/language.ts#L145-L148) [src/middleware/language/language.ts:221-228](src/middleware/language/language.ts#L221-L228) - `lookupFromPathIndex` selects the zero-based non-empty URL path segment examined by the path detector. [src/middleware/language/language.ts:20-21](src/middleware/language/language.ts#L20-L21) [src/middleware/language/language.ts:176-180](src/middleware/language/language.ts#L176-L180) - `lookupFromHeaderKey` names the request header passed to the Accept-header parser by the header detector. [src/middleware/language/language.ts:22-23](src/middleware/language/language.ts#L22-L23) [src/middleware/language/language.ts:153-166](src/middleware/language/language.ts#L153-L166) - `caches` is either `false` or an array whose declared member type is `'cookie'`. Cookie caching writes only when the value is an array containing `'cookie'`; the cookie helper appends a `Set-Cookie` response header. [src/middleware/language/language.ts:11-11](src/middleware/language/language.ts#L11) [src/middleware/language/language.ts:25-25](src/middleware/language/language.ts#L25) [src/middleware/language/language.ts:221-228](src/middleware/language/language.ts#L221-L228) [src/helper/cookie/index.ts:99-102](src/helper/cookie/index.ts#L99-L102) - `cookieOptions` can set `domain`, `path`, `sameSite`, `secure`, `maxAge`, and `httpOnly` for that cache cookie. The middleware merges a supplied object with the default cookie options before use. [src/middleware/language/language.ts:26-34](src/middleware/language/language.ts#L26-L34) [src/middleware/language/language.ts:292-300](src/middleware/language/language.ts#L292-L300) - `ignoreCase` controls whether detected and supported codes are compared in lowercase or unchanged. A successful match returns the original configured entry from `supportedLanguages`, not the normalized input. [src/middleware/language/language.ts:35-36](src/middleware/language/language.ts#L35-L36) [src/middleware/language/language.ts:98-106](src/middleware/language/language.ts#L98-L106) - `supportedLanguages` is the accepted language-code list, and `fallbackLanguage` is returned when no configured detector yields an accepted language. [src/middleware/language/language.ts:37-40](src/middleware/language/language.ts#L37-L40) [src/middleware/language/language.ts:260-266](src/middleware/language/language.ts#L260-L266) - `convertDetectedLanguage`, when present, receives the trimmed detected value before case handling and supported-language matching. Errors during normalization result in that candidate being rejected. [src/middleware/language/language.ts:41-42](src/middleware/language/language.ts#L41-L42) [src/middleware/language/language.ts:92-131](src/middleware/language/language.ts#L92-L131) - `debug` causes successful detections and detector or cookie-cache exceptions to be sent to `console.log` or `console.error`; it does not alter the selected language. [src/middleware/language/language.ts:43-44](src/middleware/language/language.ts#L43-L44) [src/middleware/language/language.ts:227-232](src/middleware/language/language.ts#L227-L232) [src/middleware/language/language.ts:244-256](src/middleware/language/language.ts#L244-L256) Language candidates are trimmed, optionally converted, then checked first for an exact configured match. If that fails, a longer detected tag may match the longest configured prefix immediately followed by `-`; otherwise it is rejected. [src/middleware/language/language.ts:92-131](src/middleware/language/language.ts#L92-L131) For header detection, parsed `Accept-Language` entries are examined in parser order, which is sorted by descending quality only when the parser observes a later entry with a higher quality value. [src/middleware/language/language.ts:153-167](src/middleware/language/language.ts#L153-L167) [src/utils/accept.ts:211-237](src/utils/accept.ts#L211-L237) `languageDetector` accepts `Partial`, overlays it on `DEFAULT_OPTIONS`, and separately merges nested cookie settings. The defaults check query string `lang`, cookie `language`, then header `accept-language`; accept `en`; fall back to `en`; cache in a cookie; ignore case; and set cache-cookie defaults of `SameSite=Strict`, `Secure`, one-year `maxAge`, and `HttpOnly`. [src/middleware/language/language.ts:51-68](src/middleware/language/language.ts#L51-L68) [src/middleware/language/language.ts:292-300](src/middleware/language/language.ts#L292-L300) Before returning middleware, construction throws `Error` when the fallback is absent from `supportedLanguages`, the path index is negative, or `order` contains a name outside the detector map. [src/middleware/language/language.ts:204-216](src/middleware/language/language.ts#L204-L216) On each request, the resulting language is stored as `ctx` variable `language` before downstream middleware runs. [src/middleware/language/language.ts:304-308](src/middleware/language/language.ts#L304-L308) # ExtractInput **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L37) ## Definition ```ts I extends Input ? unknown extends I['in'] ? {} : I['in'] : I ``` # generateCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L78) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function generateCookie(name: string, value: string, opt: CookieOptions): string ``` ## Parameters | Name | Type | |---|---| | `name` | `string` | | `value` | `string` | | `opt` | `CookieOptions` | **Returns:** `string` # JSXFragmentNode **Kind:** Class **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L321) **Part of:** [Jsx](subsystem-src-jsx) `JSXFragmentNode` represents a JSX fragment node within the JSX node model. Its `toStringToBuffer()` method writes the fragment’s string form to the active output buffer instead of returning a string. **Extends:** `JSXNode` ## Methods | Method | Signature | Returns | |---|---|---| | `toStringToBuffer` | `toStringToBuffer(buffer: StringBufferWithCallbacks)` | `void` | ## Diagram ```mermaid graph LR Fragment[JSXFragmentNode] --> Writer[toStringToBuffer()] Writer --> Buffer[Output Buffer] ``` ## Usage ```ts import { JSXFragmentNode } from "./jsx/base"; function writeFragment(fragment: JSXFragmentNode): void { fragment.toStringToBuffer(); } ``` ## AI Coding Instructions - Call `toStringToBuffer()` when rendering a fragment through the buffer-based output path. - Do not expect `toStringToBuffer()` to return rendered content; it returns `void`. - Keep fragment rendering consistent with other JSX node types in `src/jsx/base.ts`. - Pass `JSXFragmentNode` instances through code that manages the active output buffer. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Context` — `src/jsx/context.ts`:8 # upgradeWebSocket **Kind:** Constant **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L48) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts UpgradeWebSocket ``` ## Value ```ts defineWebSocketHelper((c, events) => { const server = getBunServer<{ upgrade( req: Request, options?: { data: T } ): boolean }>(c) if (!server) { throw new TypeError('env has to include the 2nd argument of fetch.') } const upgradeResult = server.upgrade(c.req.raw, { data: { events, url: new URL(c.req.url), … ``` # APIGatewayProxyEvent **Kind:** Interface **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L64) **Part of:** [Adapter](subsystem-src-adapter) `APIGatewayProxyEvent` describes the request payload passed from Amazon API Gateway to an AWS Lambda handler. It contains HTTP request data, headers, query parameters, body encoding details, route information, and API Gateway request context. ## Properties | Property | Type | |---|---| | `version` | `string` | | `httpMethod` | `string` | | `headers` | `Record` | | `multiValueHeaders` | `{ [headerKey: string]: string[] }` | | `path` | `string` | | `body` | `string | null` | | `isBase64Encoded` | `boolean` | | `queryStringParameters` | `Record` | | `requestContext` | `ApiGatewayRequestContext` | | `resource` | `string` | | `multiValueQueryStringParameters` | `{ [parameterKey: string]: string[] }` | | `pathParameters` | `Record` | | `stageVariables` | `Record` | ## Diagram ```mermaid graph LR APIGateway[API Gateway] --> Event[APIGatewayProxyEvent] Event --> Method[httpMethod] Event --> Route[path and resource] Event --> Headers[headers and multiValueHeaders] Event --> Query[queryStringParameters] Event --> Body[body and isBase64Encoded] Event --> Context[requestContext] Event --> Lambda[AWS Lambda Handler] ``` ## Usage ```ts import type { APIGatewayProxyEvent } from "./adapter/aws-lambda/handler"; export function readRequest(event: APIGatewayProxyEvent) { const body = event.body === null ? undefined : event.isBase64Encoded ? Buffer.from(event.body, "base64").toString("utf8") : event.body; return { method: event.httpMethod, path: event.path, contentType: event.headers["content-type"], query: event.queryStringParameters, body, requestContext: event.requestContext, }; } ``` ## AI Coding Instructions - Treat `body` as nullable and check `isBase64Encoded` before reading or parsing its contents. - Read single-value headers from `headers`; preserve repeated header values from `multiValueHeaders`. - Handle missing query string and header values because their record values may be `undefined`. - Pass `requestContext` through to logging, tracing, or authorization code without assuming fields not defined by `ApiGatewayRequestContext`. # DEFAULT_OPTIONS **Kind:** Constant **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L51) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts DetectorOptions ``` ## Value ```ts { order: ['querystring', 'cookie', 'header'], lookupQueryString: 'lang', lookupCookie: 'language', lookupFromHeaderKey: 'accept-language', lookupFromPathIndex: 0, caches: ['cookie'], ignoreCase: true, fallbackLanguage: 'en', supportedLanguages: ['en'], cookieOptions: { sameSite: 'Strict', secure: true, maxAge: 365 * 24 * 60 * 60, httpOnly: true, }, debug: fa… ``` # getQueryParams **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L310) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getQueryParams(url: string, key: string): string[] | undefined | Record ``` ## Parameters | Name | Type | |---|---| | `url` | `string` | | `key` | `string` | **Returns:** `string[] | undefined | Record` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoRequest` — `src/request.ts`:34 # HandlerResponse **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L70) ## Definition ```ts | Response | TypedResponse | Promise> | Promise ``` # proxy **Kind:** Function **Source:** [`src/helper/proxy/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/proxy/index.ts#L160) **Part of:** [Helper](subsystem-src-helper) Fetch API wrapper for proxy. The parameters and return value are the same as for `fetch` (except for the proxy-specific options). The “Accept-Encoding” header is replaced with an encoding that the current runtime can handle. Unnecessary response headers are deleted and a Response object is returned that can be returned as is as a response from the handler. `proxy` wraps the Fetch API for forwarding requests through a handler. It adjusts the `Accept-Encoding` header to match the current runtime, removes response headers that should not be forwarded, and returns a `Response` that can be returned directly from the handler. ## Signature ```ts async function proxy(input, proxyInit) ``` ## Parameters | Name | Type | |---|---| | `input` | `any` | | `proxyInit` | `any` | ## Diagram ```mermaid graph LR A[Incoming handler request] --> B[proxy] B --> C[Adjust Accept-Encoding] C --> D[Fetch upstream resource] D --> E[Remove response headers] E --> F[Return Response from handler] ``` ## Usage ```ts import { proxy } from "./helper/proxy"; export async function handleRequest(request: Request): Promise { const url = new URL(request.url); const upstreamUrl = `https://api.example.com${url.pathname}`; return proxy(upstreamUrl, { method: request.method, headers: request.headers, body: request.body, }); } ``` ## AI Coding Instructions - Treat `proxy` as a Fetch-compatible wrapper; pass standard fetch inputs unless proxy-specific options are needed. - Return the resulting `Response` directly from the request handler rather than rebuilding its body or headers. - Do not manually set `Accept-Encoding` before calling `proxy`; the wrapper selects an encoding supported by the current runtime. - Preserve the incoming method, headers, and body when forwarding a request unless the handler intentionally changes them. ## Relationships - IMPORTS → `HTTPException` # setInternalTagFlag **Kind:** Function **Source:** [`src/jsx/dom/utils.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/utils.ts#L3) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function setInternalTagFlag(fn: Function): Function ``` ## Parameters | Name | Type | |---|---| | `fn` | `Function` | **Returns:** `Function` ## Relationships - IMPORTS → `DOM_INTERNAL_TAG` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `createContextProviderFunction` — `src/jsx/dom/context.ts`:7 # APIGatewayProxyEventV2 **Kind:** Interface **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L41) **Part of:** [Adapter](subsystem-src-adapter) `APIGatewayProxyEventV2` represents an API Gateway HTTP API request received by the AWS Lambda adapter. It carries route details, headers, cookies, request body data, encoding state, and API Gateway request context for request conversion and handling. ## Properties | Property | Type | |---|---| | `version` | `string` | | `routeKey` | `string` | | `headers` | `Record` | | `multiValueHeaders` | `undefined` | | `cookies` | `string[]` | | `rawPath` | `string` | | `rawQueryString` | `string` | | `body` | `string | null` | | `isBase64Encoded` | `boolean` | | `requestContext` | `ApiGatewayRequestContextV2` | | `queryStringParameters` | `{ [name: string]: string | undefined }` | | `pathParameters` | `{ [name: string]: string | undefined }` | | `stageVariables` | `{ [name: string]: string | undefined }` | ## Diagram ```mermaid graph LR Gateway[API Gateway Request] --> Event[Proxy Event] Event --> Route[Route and Path] Event --> Headers[Headers and Cookies] Event --> Payload[Body and Encoding] Event --> Context[Request Context] Event --> Adapter[AWS Lambda Adapter] ``` ## Usage ```ts import type { APIGatewayProxyEventV2 } from "./handler"; function readRequest(event: APIGatewayProxyEventV2) { const body = event.isBase64Encoded ? Buffer.from(event.body ?? "", "base64") : event.body; return { path: event.rawPath, query: event.rawQueryString, headers: event.headers, cookies: event.cookies, body, context: event.requestContext, }; } ``` ## AI Coding Instructions - Treat `body` as nullable before parsing or decoding it. - Decode `body` only when `isBase64Encoded` is true. - Read header values defensively because each header value may be undefined. - Keep `multiValueHeaders` undefined when creating events for this adapter. - Pass `requestContext` through when request metadata is needed downstream. ## How it works `APIGatewayProxyEventV2` is an exported TypeScript interface for the v2 Lambda event variant handled by this AWS Lambda adapter. It is included in the `LambdaEvent` union, alongside API Gateway v1, ALB, and Lattice event shapes. [`src/adapter/aws-lambda/handler.ts:23-27`](src/adapter/aws-lambda/handler.ts#L23-L27) Its declared fields are: - Required event metadata: `version`, `routeKey`, `rawPath`, `rawQueryString`, `body`, and `isBase64Encoded`. [`src/adapter/aws-lambda/handler.ts:41-50`](src/adapter/aws-lambda/handler.ts#L41-L50) - `headers` as a map whose values can be strings or `undefined`; it explicitly declares `multiValueHeaders?: undefined`. [`src/adapter/aws-lambda/handler.ts:44-45`](src/adapter/aws-lambda/handler.ts#L44-L45) - Optional `cookies`, query parameters, path parameters, and stage variables. [`src/adapter/aws-lambda/handler.ts:46-60`](src/adapter/aws-lambda/handler.ts#L46-L60) - A required `requestContext` of type `ApiGatewayRequestContextV2`. [`src/adapter/aws-lambda/handler.ts:51-51`](src/adapter/aws-lambda/handler.ts#L51-L51) That context includes a required `domainName` and an `http` object containing the request method, path, protocol, source IP, and user agent. [`src/adapter/aws-lambda/types.ts:128-147`](src/adapter/aws-lambda/types.ts#L128-L147) At runtime, the adapter classifies an event as this type only when it has both a top-level `rawPath` property and an `http` property in `requestContext`; the code notes that `rawPath` alone can also occur on v1 events behind a custom-domain base-path mapping. [`src/adapter/aws-lambda/handler.ts:646-651`](src/adapter/aws-lambda/handler.ts#L646-L651) For an event selected this way, `EventV2Processor` converts it to a Fetch `Request`: - It takes the path from `rawPath`, the query string from `rawQueryString`, and the HTTP method from `requestContext.http.method`. [`src/adapter/aws-lambda/handler.ts:404-415`](src/adapter/aws-lambda/handler.ts#L404-L415) - It constructs the request URL with the event’s `requestContext.domainName`; if the raw query string is nonempty, it appends it after `?`. [`src/adapter/aws-lambda/handler.ts:318-324`](src/adapter/aws-lambda/handler.ts#L318-L324) - It joins a `cookies` array with `"; "` into a `Cookie` request header when the field is an array. [`src/adapter/aws-lambda/handler.ts:417-421`](src/adapter/aws-lambda/handler.ts#L417-L421) - It copies only truthy entries from `headers` into a `Headers` object. [`src/adapter/aws-lambda/handler.ts:427-438`](src/adapter/aws-lambda/handler.ts#L427-L438) - When `body` is truthy, it decodes it as base64 if `isBase64Encoded` is true; otherwise it UTF-8 encodes the string. It assigns that byte sequence as the request body and sets `content-length` to its byte length. [`src/adapter/aws-lambda/handler.ts:333-339`](src/adapter/aws-lambda/handler.ts#L333-L339) `handle()` obtains the matching processor, builds this request, passes it to `app.fetch()` with the original event, request context, and optional Lambda context, then converts the Fetch response back to a Lambda result. [`src/adapter/aws-lambda/handler.ts:252-274`](src/adapter/aws-lambda/handler.ts#L252-L274) If request construction throws a `TypeError`, it logs the error and returns a 400 `"Invalid request"` result; other construction errors produce a logged 500 `"Internal Server Error"` result. [`src/adapter/aws-lambda/handler.ts:255-266`](src/adapter/aws-lambda/handler.ts#L255-L266) For this event variant, response `Set-Cookie` values are emitted in the result’s `cookies` array rather than response headers. [`src/adapter/aws-lambda/handler.ts:388-400`](src/adapter/aws-lambda/handler.ts#L388-L400) [`src/adapter/aws-lambda/handler.ts:423-425`](src/adapter/aws-lambda/handler.ts#L423-L425) # distinctRemoteAddr **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L59) **Part of:** [Utils](subsystem-src-utils) Distinct Remote Addr `distinctRemoteAddr` derives a distinct remote-address value from the address data passed to it. It belongs to the IP-address utility layer and centralizes remote-address handling for callers that need a consistent value. ## Signature ```ts function distinctRemoteAddr(remoteAddr: string): AddressType ``` ## Parameters | Name | Type | |---|---| | `remoteAddr` | `string` | **Returns:** `AddressType` ## Diagram ```mermaid graph LR Input[Remote address data] --> Function[distinctRemoteAddr] Function --> Output[Distinct remote address] ``` ## Usage ```ts import { distinctRemoteAddr } from "./utils/ipaddr"; const remoteAddress = request.socket.remoteAddress; const address = distinctRemoteAddr(remoteAddress); if (address) { auditLog({ remoteAddress: address }); } ``` ## AI Coding Instructions - Keep remote-address parsing and normalization inside `src/utils/ipaddr.ts`. - Pass the address value in the format expected by `distinctRemoteAddr`. - Check the returned value before using it in logs, access checks, or storage. - Do not duplicate remote-address handling logic at call sites. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # Input **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L42) ## Definition ```ts { in?: {} out?: {} outputFormat?: ResponseFormat } ``` # parseAcceptLanguage **Kind:** Function **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L74) **Part of:** [Middleware](subsystem-src-middleware) Parse Accept-Language header values with quality scores `parseAcceptLanguage` parses an `Accept-Language` header into language preferences and accounts for quality-score parameters. It is used by language middleware to determine the client’s preferred language order before locale selection. ## Signature ```ts function parseAcceptLanguage(header: string): Array<{ lang: string; q: number }> ``` ## Parameters | Name | Type | |---|---| | `header` | `string` | **Returns:** `Array<{ lang: string; q: number }>` ## Diagram ```mermaid graph LR Header[Accept-Language header] --> Parse[parseAcceptLanguage] Parse --> Entries[Language entries with quality scores] Entries --> Ordered[Preferred language order] Ordered --> Middleware[Language middleware] ``` ## Usage ```ts import { parseAcceptLanguage } from "./middleware/language/language"; const header = request.headers.get("accept-language") ?? ""; const preferredLanguages = parseAcceptLanguage(header); // Pass the parsed preferences to locale-selection logic. const locale = selectSupportedLocale(preferredLanguages); ``` ## AI Coding Instructions - Keep parsing aligned with the `Accept-Language` header format: comma-separated language ranges with optional quality parameters. - Preserve quality-score ordering when changing parsing logic, since downstream locale selection depends on preference order. - Handle missing or empty header values before calling the function when integrating with request middleware. - Keep locale matching separate from header parsing; this function should only interpret client preferences. # registerAction **Kind:** Function **Source:** [`src/jsx/dom/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/hooks/index.ts#L32) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function registerAction(action: Promise) ``` ## Parameters | Name | Type | |---|---| | `action` | `Promise` | ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # testClient **Kind:** Function **Source:** [`src/helper/testing/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/testing/index.ts#L16) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function testClient(app: T, Env: ExtractEnv['Bindings'] | {}, executionCtx: ExecutionContext, options: Omit): UnionToIntersection['Bindings'] | {}` | | `executionCtx` | `ExecutionContext` | | `options` | `Omit` | **Returns:** `UnionToIntersection # ApiGatewayRequestContext **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L85) **Part of:** [Adapter](subsystem-src-adapter) `ApiGatewayRequestContext` describes API Gateway metadata attached to an AWS Lambda request. It carries account, API, domain, HTTP, authorization, identity, and request-path details used by the Lambda adapter. ## Properties | Property | Type | |---|---| | `accountId` | `string` | | `apiId` | `string` | | `authorizer` | `{ claims?: unknown scopes?: unknown }` | | `domainName` | `string` | | `domainPrefix` | `string` | | `extendedRequestId` | `string` | | `httpMethod` | `string` | | `identity` | `Identity` | | `path` | `string` | | `protocol` | `string` | | `requestId` | `string` | | `requestTime` | `string` | | `requestTimeEpoch` | `number` | | `resourceId` | `string` | | `resourcePath` | `string` | | `stage` | `string` | ## Diagram ```mermaid graph LR Request[API Gateway Request] --> Context[ApiGatewayRequestContext] Context --> Account[accountId / apiId] Context --> Domain[domainName / domainPrefix] Context --> Http[httpMethod / path / protocol] Context --> Auth[authorizer claims and scopes] Context --> Identity[identity: Identity] Context --> RequestId[extendedRequestId] ``` ## Usage ```ts import type { ApiGatewayRequestContext } from './types'; function getRequestDetails(context: ApiGatewayRequestContext) { return { requestId: context.extendedRequestId, method: context.httpMethod, path: context.path, host: context.domainName, claims: context.authorizer.claims, identity: context.identity, }; } ``` ## AI Coding Instructions - Treat `authorizer.claims` and `authorizer.scopes` as `unknown`; validate or narrow their types before reading values. - Read `identity` through the imported `Identity` type rather than duplicating its fields. - Use `httpMethod`, `path`, and `protocol` when building request URLs or routing adapter inputs. - Preserve `extendedRequestId` when logging request-specific errors or diagnostics. - Do not assume `authorizer` contains claims or scopes; both fields are optional. ## How it works `ApiGatewayRequestContext` is an exported TypeScript interface representing the `requestContext` field of the adapter’s API Gateway v1 proxy event (`APIGatewayProxyEvent`). That event type contains HTTP method, headers, path, body, query parameters, and this context object. [src/adapter/aws-lambda/handler.ts:63-82] The interface requires API/account and request metadata: `accountId`, `apiId`, `domainName`, `domainPrefix`, `extendedRequestId`, `httpMethod`, `path`, `protocol`, `requestId`, `requestTime`, `requestTimeEpoch`, `resourcePath`, and `stage`. `resourceId` is optional. [src/adapter/aws-lambda/types.ts:85-105] It also requires: - `authorizer`, whose only declared fields are optional `claims` and `scopes`, each typed as `unknown`. [src/adapter/aws-lambda/types.ts:88-91] - `identity`, containing required `sourceIp` and `userAgent`, plus optional AWS, Cognito, caller, organization, user, and client-certificate fields. [src/adapter/aws-lambda/types.ts:69-83] A client certificate, when present, includes PEM, subject/issuer distinguished names, serial number, and `notBefore`/`notAfter` validity strings. [src/adapter/aws-lambda/types.ts:58-67] The Lambda adapter treats an event as API Gateway v1 when it is not identified as an ALB event, API Gateway v2 event, or Lattice v2 event; it then selects the v1 processor. [src/adapter/aws-lambda/handler.ts:625-637] The v1 event’s HTTP request is built from top-level event fields such as `path` and `httpMethod`, rather than from this context’s `path` or `httpMethod`. [src/adapter/aws-lambda/handler.ts:443-450] When handling an event, `handle()` obtains `event.requestContext` without transforming it and passes it to `app.fetch()` as `requestContext`, alongside the original event and optional Lambda context. [src/adapter/aws-lambda/handler.ts:116-124] [src/adapter/aws-lambda/handler.ts:252-274] The streaming handler follows the same pattern. [src/adapter/aws-lambda/handler.ts:147-157] `getConnInfo()` accepts this interface as one member of its Lambda request-context union. [src/adapter/aws-lambda/conninfo.ts:9-18] If the context has an `identity` property and `identity.sourceIp` is truthy, it returns that value as `remote.address`. [src/adapter/aws-lambda/conninfo.ts:45-53] The included test constructs a v1-shaped context and verifies that `identity.sourceIp` becomes the returned remote address. [src/adapter/aws-lambda/conninfo.test.ts:5-35] This file declares only the interface shape; it contains no runtime validation, conversion, error handling, or side effects for `ApiGatewayRequestContext`. [src/adapter/aws-lambda/types.ts:85-105] The adapter’s public AWS Lambda entry point re-exports the interface as a type. [src/adapter/aws-lambda/index.ts:6-14] # combineAfterGenerateHooks **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L160) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function combineAfterGenerateHooks(hooks: AfterGenerateHook | AfterGenerateHook[], fsModule: FileSystemModule, options: ToSSGOptions): AfterGenerateHook ``` ## Parameters | Name | Type | |---|---| | `hooks` | `AfterGenerateHook | AfterGenerateHook[]` | | `fsModule` | `FileSystemModule` | | `options` | `ToSSGOptions` | **Returns:** `AfterGenerateHook` # ErrorBoundary **Kind:** Constant **Source:** [`src/jsx/dom/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/components.ts#L7) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts FC< PropsWithChildren<{ fallback?: Child fallbackRender?: FallbackRender onError?: ErrorHandler }> > ``` ## Value ```ts (({ children, fallback, fallbackRender, onError }: any) => { const res = Fragment({ children }) ;(res as any)[DOM_ERROR_HANDLER] = (err: any) => { if (err instanceof Promise) { throw err } onError?.(err) return fallbackRender?.(err) || fallback } return res }) as any ``` ## Relationships - IMPORTS → `DOM_ERROR_HANDLER` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `childrenToString` — `src/jsx/components.ts`:14 # getExtension **Kind:** Function **Source:** [`src/utils/mime.ts`](https://github.com/honojs/hono/blob/main/src/utils/mime.ts#L18) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getExtension(mimeType: string): string | undefined ``` ## Parameters | Name | Type | |---|---| | `mimeType` | `string` | **Returns:** `string | undefined` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `DEFAULT_OUTPUT_DIR` — `src/helper/ssg/ssg.ts`:27 # IsLiteralUnion **Kind:** Type **Source:** [`src/validator/utils.ts`](https://github.com/honojs/hono/blob/main/src/validator/utils.ts#L9) Checks if T is a literal union type (e.g., 'asc' | 'desc') that should be preserved in input types. Returns true for union literals, false for single literals or wide types. `IsLiteralUnion` evaluates whether `T` is a union of literal values, such as `'asc' | 'desc'`. Validator input-type logic uses this result to preserve literal unions while treating single literals and widened types differently. ## Definition ```ts [Exclude] extends [Base] ? [Exclude] extends [UnionToIntersection>] ? false : true : false ``` ## Diagram ```mermaid graph LR T[Input type T] --> Check{Is T a literal union?} Check -->|Yes| True[true: preserve input type] Check -->|No| False[false: handle as non-union or wide type] ``` ## Usage ```ts import type { IsLiteralUnion } from './validator/utils' type SortDirection = 'asc' | 'desc' type SingleDirection = 'asc' type WideString = string type IsSortDirection = IsLiteralUnion // true type IsSingleDirection = IsLiteralUnion // false type IsWideString = IsLiteralUnion // false ``` ## AI Coding Instructions - Use `IsLiteralUnion` only in type-level conditional logic; it has no runtime value. - Preserve unions of literal strings or numbers when this type evaluates to `true`. - Do not treat a single literal, such as `'asc'`, as a literal union. - Check widened types such as `string`, `number`, and `boolean` separately when changing validator input-type behavior. # useRequestContext **Kind:** Function **Source:** [`src/middleware/jsx-renderer/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jsx-renderer/index.ts#L153) **Part of:** [Middleware](subsystem-src-middleware) useRequestContext for Hono. `useRequestContext` returns the current Hono request context inside a JSX component rendered by the JSX renderer middleware. Use it to read request data, headers, parameters, and environment bindings while generating JSX output. ## Signature ```ts function useRequestContext(): Context ``` **Returns:** `Context` ## Diagram ```mermaid graph LR Request[Incoming request] --> Renderer[JSX renderer middleware] Renderer --> Component[JSX component] Component --> Hook[useRequestContext] Hook --> Context[Hono Context] ``` ## Usage ```tsx import { Hono } from 'hono' import { jsxRenderer, useRequestContext } from 'hono/jsx-renderer' const app = new Hono() const RequestInfo = () => { const c = useRequestContext() return (

{c.req.method} {c.req.path}

Request ID: {c.req.header('x-request-id') ?? 'not provided'}

) } app.get( '*', jsxRenderer(({ children }) => ( {children} )) ) app.get('/', (c) => c.render()) ``` ## AI Coding Instructions - Call `useRequestContext` only while rendering a JSX component under `jsxRenderer`. - Read request values through the returned Hono context, such as `c.req.path`, `c.req.param()`, and `c.req.header()`. - Do not pass the request context through component props when the component can access it with this hook. - Keep request-dependent rendering inside components that run during the current request. # ApiGatewayRequestContextV2 **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L128) **Part of:** [Adapter](subsystem-src-adapter) `ApiGatewayRequestContextV2` describes request metadata received from an API Gateway HTTP API event in the AWS Lambda adapter. It carries API, domain, route, stage, authorization, and client connection details for request handling and logging. ## Properties | Property | Type | |---|---| | `accountId` | `string` | | `apiId` | `string` | | `authentication` | `null` | | `authorizer` | `Authorizer` | | `domainName` | `string` | | `domainPrefix` | `string` | | `http` | `{ method: string path: string protocol: string sourceIp: string userAgent: string }` | | `requestId` | `string` | | `routeKey` | `string` | | `stage` | `string` | | `time` | `string` | | `timeEpoch` | `number` | ## Diagram ```mermaid graph LR Request[API Gateway request] --> Context[ApiGatewayRequestContextV2] Context --> Api[accountId and apiId] Context --> Domain[domainName and domainPrefix] Context --> Route[routeKey and stage] Context --> Auth[authentication and authorizer] Context --> Http[http method path protocol sourceIp userAgent] Context --> RequestId[requestId] ``` ## Usage ```ts import type { ApiGatewayRequestContextV2 } from './types' function getRequestDetails(context: ApiGatewayRequestContextV2) { return { requestId: context.requestId, method: context.http.method, path: context.http.path, clientAddress: context.http.sourceIp, route: context.routeKey, stage: context.stage, } } ``` ## AI Coding Instructions - Read request method, path, protocol, source IP, and user agent from `context.http`. - Treat `authentication` as `null`; read authorization data from `context.authorizer`. - Keep `requestId` attached to logs and error reports for request tracing. - Use `domainName`, `domainPrefix`, `routeKey`, and `stage` when routing or building request-specific metadata. ## How it works `ApiGatewayRequestContextV2` is an exported TypeScript interface describing the `requestContext` field of an `APIGatewayProxyEventV2`. That event shape is used by the AWS Lambda adapter for HTTP API and direct Lambda Function URL invocations. [`src/adapter/aws-lambda/types.ts:128-147`](src/adapter/aws-lambda/types.ts#L128-L147) [`src/adapter/aws-lambda/handler.ts:40-61`](src/adapter/aws-lambda/handler.ts#L40-L61) It is re-exported from the AWS Lambda adapter entry point as a type. [`src/adapter/aws-lambda/index.ts:8-14`](src/adapter/aws-lambda/index.ts#L8-L14) # env **Kind:** Function **Source:** [`src/helper/adapter/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/adapter/index.ts#L10) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function env(c: T extends Record ? Context : C, runtime: Runtime): T & C['env'] ``` ## Parameters | Name | Type | |---|---| | `c` | `T extends Record ? Context : C` | | `runtime` | `Runtime` | **Returns:** `T & C['env']` # NotFoundHandler **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L107) ## Definition ```ts ( c: Context ) => NotFoundResponse extends Response ? NotFoundResponse | Promise : Response | Promise ``` # RETAINED_304_HEADERS **Kind:** Constant **Source:** [`src/middleware/etag/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/etag/index.ts#L21) **Part of:** [Middleware](subsystem-src-middleware) Default headers to pass through on 304 responses. From the spec: > The response must not contain a body and must include the headers that > would have been sent in an equivalent 200 OK response: Cache-Control, > Content-Location, Date, ETag, Expires, and Vary. `RETAINED_304_HEADERS` [census] lists the headers copied from a representation response to a not-modified response. The ETag middleware uses this list to preserve cache and representation metadata while omitting the response body. ## Definition ```ts [ 'cache-control', 'content-location', 'date', 'etag', 'expires', 'vary', ] ``` ## Value ```ts [ 'cache-control', 'content-location', 'date', 'etag', 'expires', 'vary', ] ``` ## Diagram ```mermaid graph LR A[Representation response headers] --> B[Retained-header list] B --> C[ETag middleware] C --> D[Not-modified response headers] ``` ## Usage ```ts import { RETAINED_304_HEADERS as retainedHeaders, // [census] } from './middleware/etag' function copyRetainedHeaders(source: Headers): Headers { const responseHeaders = new Headers() for (const name of retainedHeaders) { const value = source.get(name) if (value !== null) { responseHeaders.set(name, value) } } return responseHeaders } ``` ## AI Coding Instructions - Copy only headers named by `RETAINED_304_HEADERS` [census] when building a not-modified response. - Read header values from the equivalent representation response, not from request headers. - Do not attach a response body when the ETag middleware selects the not-modified path. - Keep ETag comparison and retained-header copying in the ETag middleware flow. # splitPath **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function splitPath(path: string): string[] ``` ## Parameters | Name | Type | |---|---| | `path` | `string` | **Returns:** `string[]` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Node` — `src/router/trie-router/node.ts`:25 # Suspense **Kind:** Constant **Source:** [`src/jsx/dom/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/components.ts#L25) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts FC> ``` ## Value ```ts (({ children, fallback, }: any) => { const res = Fragment({ children }) ;(res as any)[DOM_ERROR_HANDLER] = (err: any, retry: () => void) => { if (!(err instanceof Promise)) { throw err } err.finally(retry) return fallback } return res }) as any ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `StreamingContext` — `src/jsx/streaming.ts`:30 # FormContext **Kind:** Constant **Source:** [`src/jsx/dom/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/hooks/index.ts#L24) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Context ``` ## Value ```ts createContext({ pending: false, data: null, method: null, action: null, }) ``` ## Relationships - IMPORTS → `PERMALINK` - IMPORTS → `useContext` - IMPORTS → `useCallback` - IMPORTS → `useState` - IMPORTS → `createContext` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # getPathNoStrict **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L141) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getPathNoStrict(request: Request): string ``` ## Parameters | Name | Type | |---|---| | `request` | `Request` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoOptions` — `src/hono-base.ts`:46 # isContentEncodingBinary **Kind:** Function **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L672) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function isContentEncodingBinary(contentEncoding: string | null) ``` ## Parameters | Name | Type | |---|---| | `contentEncoding` | `string | null` | # Schema **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2531) ## Definition ```ts { [Path: string]: { [Method: `$${Lowercase}`]: Endpoint } } ``` # ServeStaticOptions **Kind:** Type **Source:** [`src/middleware/serve-static/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/serve-static/index.ts#L13) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { root?: string path?: string precompressed?: boolean mimes?: Record rewriteRequestPath?: (path: string) => string onFound?: (path: string, c: Context) => void | Promise onNotFound?: (path: string, c: Context) => void | Promise } ``` ## Relationships - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` - IMPORTS → `getMimeType` - IMPORTS → `tryDecodeURI` - IMPORTS → `defaultJoin` # showRoutes **Kind:** Function **Source:** [`src/helper/dev/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/dev/index.ts#L39) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function showRoutes(hono: Hono, opts: ShowRoutesOptions): void ``` ## Parameters | Name | Type | |---|---| | `hono` | `Hono` | | `opts` | `ShowRoutesOptions` | **Returns:** `void` # clearCache **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L18) **Part of:** [Jsx](subsystem-src-jsx) ## Relationships - IMPORTS → `useContext` - IMPORTS → `use` - IMPORTS → `useCallback` - IMPORTS → `useMemo` - IMPORTS → `useState` - IMPORTS → `dataPrecedenceAttr` - IMPORTS → `deDupeKeyMap` - IMPORTS → `domRenderers` - IMPORTS → `isStylesheetLinkWithPrecedence` - IMPORTS → `shouldDeDupeByKey` - IMPORTS → `FormContext` - IMPORTS → `registerAction` - IMPORTS → `createPortal` - IMPORTS → `getNameSpaceContext` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `jsxDEV` — `src/jsx/dom/jsx-dev-runtime.ts`:10 # convertIPv4ToBinary **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L148) **Part of:** [Utils](subsystem-src-utils) Convert IPv4 to Uint8Array Converts an IPv4 address string into a `Uint8Array` representation. It supports code in `src/utils/ipaddr.ts` that needs address data in byte form. ## Signature ```ts function convertIPv4ToBinary(ipv4: string): bigint ``` ## Parameters | Name | Type | |---|---| | `ipv4` | `string` | **Returns:** `bigint` ## Diagram ```mermaid graph LR Input[IPv4 address string] --> Convert[convertIPv4ToBinary] Convert --> Output[Uint8Array] ``` ## Usage ```ts import { convertIPv4ToBinary } from './utils/ipaddr'; declare const ipv4Address: string; const addressBytes = convertIPv4ToBinary(ipv4Address); console.log(addressBytes); ``` ## AI Coding Instructions - Pass a valid IPv4 address string to this function. - Keep the returned value as a `Uint8Array` when passing address data to byte-oriented APIs. - Handle invalid address input at the caller when the surrounding flow requires user-facing errors. - Import the helper from `src/utils/ipaddr.ts` rather than duplicating address-to-byte conversion logic. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # detectors **Kind:** Constant **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L186) **Part of:** [Middleware](subsystem-src-middleware) Collection of all language detection strategies `detectors` is the collection of language detection strategies used by the language middleware. The middleware checks these strategies to determine the language for an incoming request and apply the selected language to downstream processing. ## Definition ```ts { querystring: detectFromQuery, cookie: detectFromCookie, header: detectFromHeader, path: detectFromPath, } as const ``` ## Value ```ts { querystring: detectFromQuery, cookie: detectFromCookie, header: detectFromHeader, path: detectFromPath, } as const ``` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[Language middleware] Middleware --> Detectors[detectors] Detectors --> Strategy[Language detection strategy] Strategy --> Language[Detected language] Language --> Context[Request language context] ``` ## Usage ```ts import { detectors } from './middleware/language/language'; // Inspect the detection strategies registered with the language middleware. for (const detector of detectors) { console.log(detector); } ``` ## AI Coding Instructions - Keep each entry in `detectors` compatible with the language middleware's expected detector contract. - Add new language detection strategies to this collection so the middleware can evaluate them. - Preserve detector ordering when precedence affects which language source is selected. - Update related middleware tests when adding, removing, or changing a detector. - Avoid placing request-specific state in the shared `detectors` collection. # Env **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L30) ## Definition ```ts { Bindings?: Bindings Variables?: Variables } ``` # LatticeRequestContextV2 **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L155) **Part of:** [Adapter](subsystem-src-adapter) `LatticeRequestContextV2` represents request metadata added by AWS VPC Lattice in the Lambda adapter. It contains service and target identifiers, the request region and timestamp, plus optional caller identity attributes. ## Properties | Property | Type | |---|---| | `serviceNetworkArn` | `string` | | `serviceArn` | `string` | | `targetGroupArn` | `string` | | `region` | `string` | | `timeEpoch` | `string` | | `identity` | `{ sourceVpcArn?: string type?: string principal?: string principalOrgID?: string sessionName?: string x509IssuerOu?: string x509SanDns?: string x509SanNameCn?: string x509SanUri?: string x509SubjectCn?: string }` | ## Diagram ```mermaid graph LR Request[VPC Lattice request] --> Context[LatticeRequestContextV2] Context --> Service[serviceNetworkArn] Context --> ServiceArn[serviceArn] Context --> Target[targetGroupArn] Context --> Metadata[region and timeEpoch] Context --> Identity[identity] Identity --> Caller[optional caller attributes] ``` ## Usage ```ts import type { LatticeRequestContextV2 } from './types'; function logLatticeRequest(context: LatticeRequestContextV2): void { console.log({ serviceNetworkArn: context.serviceNetworkArn, serviceArn: context.serviceArn, targetGroupArn: context.targetGroupArn, region: context.region, principal: context.identity.principal, sourceVpcArn: context.identity.sourceVpcArn, }); } ``` ## AI Coding Instructions - Treat `identity` fields as optional and check for `undefined` before reading or forwarding them. - Keep ARN fields as strings; do not parse them unless the calling code needs a specific ARN component. - Use `timeEpoch` as the request timestamp value received from the Lattice event. - Pass this context through adapter boundaries when handlers need Lattice service, target group, or caller identity metadata. # streamText **Kind:** Function **Source:** [`src/helper/streaming/text.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/text.ts#L6) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function streamText(c: Context, cb: (stream: StreamingApi) => Promise, onError: (e: Error, stream: StreamingApi) => Promise): Response ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `cb` | `(stream: StreamingApi) => Promise` | | `onError` | `(e: Error, stream: StreamingApi) => Promise` | **Returns:** `Response` ## Relationships - IMPORTS → `TEXT_PLAIN` # accepts **Kind:** Function **Source:** [`src/helper/accepts/accepts.ts`](https://github.com/honojs/hono/blob/main/src/helper/accepts/accepts.ts#L40) **Part of:** [Helper](subsystem-src-helper) Match the accept header with the given options. `accepts` checks the request `Accept` header against the media types passed to it. It returns the matching option so route handlers can select an appropriate response representation. ## Signature ```ts function accepts(c: Context, options: acceptsOptions): string ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `options` | `acceptsOptions` | **Returns:** `string` ## Diagram ```mermaid graph LR Request[Incoming request] --> Context[Context] Context --> Accepts[accepts] Options[Supported media types] --> Accepts Accepts --> Match[Matching media type] Match --> Response[Route response] ``` ## Usage ```ts import { Hono } from 'hono' import { accepts } from 'hono/accepts' const app = new Hono() app.get('/profile', (c) => { const type = accepts(c, 'application/json', 'text/html') if (type === 'text/html') { return c.html('

Profile

') } if (type === 'application/json') { return c.json({ name: 'Ada' }) } return c.text('Not Acceptable', 406) }) ``` ## AI Coding Instructions - Pass the Hono context as the first argument, followed by the media types the handler can return. - Check the returned value before sending a representation, since no supplied type may match the request header. - Keep media type strings aligned with the response methods used by the route. - Return an appropriate unsupported-media response when no acceptable type is selected. # ALBProxyEvent **Kind:** Interface **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L85) **Part of:** [Adapter](subsystem-src-adapter) `ALBProxyEvent` represents the request data passed from an Application Load Balancer to the Lambda handler. It carries HTTP method, path, headers, query parameters, body content, encoding state, and ALB request context for adapter-level request handling. ## Properties | Property | Type | |---|---| | `httpMethod` | `string` | | `headers` | `Record` | | `multiValueHeaders` | `Record` | | `path` | `string` | | `body` | `string | null` | | `isBase64Encoded` | `boolean` | | `queryStringParameters` | `Record` | | `multiValueQueryStringParameters` | `{ [parameterKey: string]: string[] }` | | `requestContext` | `ALBRequestContext` | ## Diagram ```mermaid graph LR ALB[Application Load Balancer] --> Event[ALBProxyEvent] Event --> Method[httpMethod] Event --> Path[path] Event --> Headers[headers and multiValueHeaders] Event --> Query[queryStringParameters and multiValueQueryStringParameters] Event --> Body[body and isBase64Encoded] Event --> Context[requestContext] Event --> Handler[Lambda handler] ``` ## Usage ```ts import type { ALBProxyEvent } from "./handler"; function readRequest(event: ALBProxyEvent) { const contentType = event.headers["content-type"]; const tags = event.multiValueQueryStringParameters.tags ?? []; const body = event.body ?? ""; return { method: event.httpMethod, path: event.path, contentType, tags, body, isEncoded: event.isBase64Encoded, }; } ``` ## AI Coding Instructions - Treat `body` as nullable and handle the absence of a request body before parsing it. - Check `isBase64Encoded` before interpreting body content. - Preserve both single-value and multi-value header and query parameter maps when adapting the event to another request format. - Do not assume header names use a specific letter case; read the keys provided by the ALB event. - Pass `requestContext` through when downstream code needs ALB request metadata. ## How it works `ALBProxyEvent` is an exported TypeScript interface for the Lambda event shape handled as an Application Load Balancer (ALB) request. It is one member of the `LambdaEvent` union. [src/adapter/aws-lambda/handler.ts:23-27](src/adapter/aws-lambda/handler.ts#L23-L27) [src/adapter/aws-lambda/handler.ts:84-97](src/adapter/aws-lambda/handler.ts#L84-L97) Its required fields are: - `httpMethod: string` and `path: string`, used as the method and path of the constructed `Request`. [src/adapter/aws-lambda/handler.ts:86-89](src/adapter/aws-lambda/handler.ts#L86-L89) [src/adapter/aws-lambda/handler.ts:526-532](src/adapter/aws-lambda/handler.ts#L526-L532) - `body: string | null` and `isBase64Encoded: boolean`; a truthy body is Base64-decoded when `isBase64Encoded` is true, otherwise UTF-8 encoded, then assigned as the request body and used to set `content-length`. [src/adapter/aws-lambda/handler.ts:90-91](src/adapter/aws-lambda/handler.ts#L90-L91) [src/adapter/aws-lambda/handler.ts:333-339](src/adapter/aws-lambda/handler.ts#L333-L339) - `requestContext: ALBRequestContext`, whose declared shape contains `elb.targetGroupArn: string`. [src/adapter/aws-lambda/handler.ts:96](src/adapter/aws-lambda/handler.ts#L96) [src/adapter/aws-lambda/types.ts:149-153](src/adapter/aws-lambda/types.ts#L149-L153) It can also contain optional single-value or multi-value headers and query-string parameter maps. [src/adapter/aws-lambda/handler.ts:87-95](src/adapter/aws-lambda/handler.ts#L87-L95) At runtime, an event is treated as an `ALBProxyEvent` when `requestContext` has its own `elb` property; this ALB test runs before the API Gateway v2 and Lattice tests. [src/adapter/aws-lambda/handler.ts:625-644](src/adapter/aws-lambda/handler.ts#L625-L644) For an ALB event, request-header conversion gives `multiValueHeaders` precedence over `headers`. Multi-value entries are joined with `; ` and assigned as one header value; otherwise truthy values from `headers` are assigned. Header values containing non-ASCII characters are percent-encoded before assignment. [src/adapter/aws-lambda/handler.ts:13-21](src/adapter/aws-lambda/handler.ts#L13-L21) [src/adapter/aws-lambda/handler.ts:503-524](src/adapter/aws-lambda/handler.ts#L503-L524) The query string prefers `multiValueQueryStringParameters` when present. Each multi-value entry is rendered as repeated `key=value` pairs, while the single-value map is rendered as one `key=value` pair per truthy entry; these keys and values are not encoded by the ALB processor. [src/adapter/aws-lambda/handler.ts:534-558](src/adapter/aws-lambda/handler.ts#L534-L558) Request creation derives the domain from `requestContext.domainName` when available, then the `host` single-value header, then the `host` multi-value header; it constructs an HTTPS URL from that domain, the ALB path, and the generated query string. `ALBRequestContext` itself declares only `elb.targetGroupArn`, so the header fallback is the declared ALB-event route to a domain value. [src/adapter/aws-lambda/handler.ts:301-342](src/adapter/aws-lambda/handler.ts#L301-L342) [src/adapter/aws-lambda/types.ts:149-153](src/adapter/aws-lambda/types.ts#L149-L153) When `handle()` processes such an event, it passes the converted request, the original event, its request context, and the optional Lambda context to `app.fetch()`. [src/adapter/aws-lambda/handler.ts:251-274](src/adapter/aws-lambda/handler.ts#L251-L274) If request creation throws, it logs the error and returns an ALB-formatted result with a `400` response for `TypeError`, or a `500` response otherwise. [src/adapter/aws-lambda/handler.ts:255-266](src/adapter/aws-lambda/handler.ts#L255-L266) Response formatting chooses `multiValueHeaders` when the incoming event has a truthy `multiValueHeaders`; otherwise it chooses `headers`. Response bodies are Base64-encoded for binary content types or non-`identity` content encodings, and are text otherwise. [src/adapter/aws-lambda/handler.ts:344-385](src/adapter/aws-lambda/handler.ts#L344-L385) For `set-cookie`, ALB output stores all cookies in `multiValueHeaders['set-cookie']` in multi-value mode, but stores only the first cookie in `headers['set-cookie']` otherwise. [src/adapter/aws-lambda/handler.ts:388-400](src/adapter/aws-lambda/handler.ts#L388-L400) [src/adapter/aws-lambda/handler.ts:572-578](src/adapter/aws-lambda/handler.ts#L572-L578) # decodeBase64Url **Kind:** Function **Source:** [`src/utils/encode.ts`](https://github.com/honojs/hono/blob/main/src/utils/encode.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function decodeBase64Url(str: string): Uint8Array ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | **Returns:** `Uint8Array` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # ErrorHandler **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L116) ## Definition ```ts ( err: Error | HTTPResponseError, c: Context ) => Response | Promise ``` # getContext **Kind:** Function **Source:** [`src/middleware/context-storage/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/context-storage/index.ts#L53) **Part of:** [Middleware](subsystem-src-middleware) ## Signature ```ts function getContext(): Context ``` **Returns:** `Context` # StreamingContext **Kind:** Constant **Source:** [`src/jsx/streaming.ts`](https://github.com/honojs/hono/blob/main/src/jsx/streaming.ts#L30) **Part of:** [Jsx](subsystem-src-jsx) Used to specify nonce for scripts generated by `Suspense` and `ErrorBoundary`. `StreamingContext` carries a CSP nonce for inline scripts emitted by `Suspense` and `ErrorBoundary` during JSX streaming. Wrap streamed JSX with its provider so generated scripts receive the same nonce allowed by the response's Content Security Policy. ## Definition ```ts JSXContext<{ scriptNonce: string } | null> ``` ## Value ```ts createContext<{ scriptNonce: string } | null>(null) ``` ## Diagram ```mermaid graph LR A[StreamingContext.Provider] --> B[Streaming JSX render] B --> C[Suspense] B --> D[ErrorBoundary] C --> E[Generated script with nonce] D --> E ``` ## Usage ```tsx import { StreamingContext } from 'hono/jsx/streaming' const nonce = 'request-csp-nonce' const app = ( Loading…

}>
) ``` ## AI Coding Instructions - Set the nonce from the request's Content Security Policy configuration. - Wrap the streamed JSX tree with `StreamingContext.Provider` before rendering. - Keep the nonce consistent with the nonce sent in the `Content-Security-Policy` response header. - Use this context when `Suspense` or `ErrorBoundary` can emit inline streaming scripts. ## Relationships - IMPORTS → `html` - IMPORTS → `HtmlEscapedCallbackPhase` - IMPORTS → `resolveCallback` - IMPORTS → `JSXNode` - IMPORTS → `childrenToString` - IMPORTS → `DOM_RENDERER` - IMPORTS → `DOM_STASH` - IMPORTS → `captureRenderContext` - IMPORTS → `createContext` - IMPORTS → `useContext` - IMPORTS → `Suspense` - IMPORTS → `buildDataStack` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `childrenToString` — `src/jsx/components.ts`:14 # CloudFrontRequest **Kind:** Interface **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L41) **Part of:** [Adapter](subsystem-src-adapter) `CloudFrontRequest` represents an incoming request handled by the Lambda@Edge adapter. It carries request routing data, headers, body metadata, client IP information, and origin details for request processing. ## Properties | Property | Type | |---|---| | `clientIp` | `string` | | `headers` | `CloudFrontHeaders` | | `method` | `string` | | `querystring` | `string` | | `uri` | `string` | | `body` | `{ inputTruncated: boolean action: string encoding: string data: string }` | | `origin` | `CloudFrontOrigin` | ## Diagram ```mermaid graph LR Request[CloudFrontRequest] Request --> ClientIp[clientIp: string] Request --> Headers[headers: CloudFrontHeaders] Request --> Method[method: string] Request --> Query[querystring: string] Request --> Uri[uri: string] Request --> Body[body] Request --> Origin[origin: CloudFrontOrigin] Body --> Truncated[inputTruncated] Body --> Action[action] Body --> Encoding[encoding] Body --> Data[data] ``` ## Usage ```ts import type { CloudFrontRequest } from "./handler"; function inspectRequest(request: CloudFrontRequest): CloudFrontRequest { const path = request.querystring ? `${request.uri}?${request.querystring}` : request.uri; console.log({ method: request.method, path, clientIp: request.clientIp, }); if (request.body.inputTruncated) { console.warn("Request body was truncated by CloudFront"); } return request; } ``` ## AI Coding Instructions - Keep `uri` and `querystring` separate when reading or rewriting request paths. - Preserve the `body` fields together when forwarding or transforming request content. - Check `body.inputTruncated` before assuming `body.data` contains the full request body. - Treat `headers` and `origin` as CloudFront-shaped values when integrating with Lambda@Edge handlers. ## How it works `CloudFrontRequest` is an exported TypeScript interface for the `cf.request` object within each Lambda@Edge event record. `CloudFrontEvent.cf.request` is typed as `CloudFrontRequest`, and `CloudFrontEdgeEvent` contains an array of those records. [src/adapter/lambda-edge/handler.ts:41-54](src/adapter/lambda-edge/handler.ts#L41-L54) [src/adapter/lambda-edge/handler.ts:69-79](src/adapter/lambda-edge/handler.ts#L69-L79) - It requires `clientIp`, `headers`, `method`, `querystring`, and `uri`, all as strings except `headers`. [src/adapter/lambda-edge/handler.ts:41-46](src/adapter/lambda-edge/handler.ts#L41-L46) - `headers` maps header names to arrays of `{ key, value }` string pairs, allowing multiple values for one header name. [src/adapter/lambda-edge/handler.ts:10-17](src/adapter/lambda-edge/handler.ts#L10-L17) - Its optional `body` has `inputTruncated`, `action`, `encoding`, and `data` fields. [src/adapter/lambda-edge/handler.ts:47-52](src/adapter/lambda-edge/handler.ts#L47-L52) - Its optional `origin` is either an S3 origin or a custom origin. The S3 form includes authentication method, headers, domain, path, and region; the custom form includes headers, domain, timeouts, path, port, protocol, and SSL protocols. The union excludes having both forms at once. [src/adapter/lambda-edge/handler.ts:19-39](src/adapter/lambda-edge/handler.ts#L19-L39) [src/adapter/lambda-edge/handler.ts:53](src/adapter/lambda-edge/handler.ts#L53) The Lambda@Edge adapter reads only the first record’s request when constructing the Fetch API `Request`. It selects the host from the first `host` header value, falling back to the distribution domain name, combines it with `uri` and a nonempty `querystring`, then creates an HTTPS URL. [src/adapter/lambda-edge/handler.ts:164-170](src/adapter/lambda-edge/handler.ts#L164-L170) For headers, the adapter iterates every request-header entry and appends every array element’s value to a `Headers` object. [src/adapter/lambda-edge/handler.ts:172-175](src/adapter/lambda-edge/handler.ts#L172-L175) A test demonstrates that three `x-forwarded-for` values become the comma-separated value observed through the Hono request header API. [src/adapter/lambda-edge/handler.test.ts:93-121](src/adapter/lambda-edge/handler.test.ts#L93-L121) For the body, the adapter omits it when `body` is absent, when `body.data` is falsy, or when `method` is exactly `GET` or `HEAD`. [src/adapter/lambda-edge/handler.ts:198-207](src/adapter/lambda-edge/handler.ts#L198-L207) When `body.encoding` is exactly `base64`, it decodes `body.data` into a `Uint8Array`; otherwise, it passes `data` through as a string. [src/adapter/lambda-edge/handler.ts:208-211](src/adapter/lambda-edge/handler.ts#L208-L211) For a retained body, it calculates the byte length and overwrites the request’s `content-length` header with that length. [src/adapter/lambda-edge/handler.ts:181-195](src/adapter/lambda-edge/handler.ts#L181-L195) The original `CloudFrontRequest` is also passed to `app.fetch()` as the `request` binding, without copying or transforming it. [src/adapter/lambda-edge/handler.ts:128-141](src/adapter/lambda-edge/handler.ts#L128-L141) A callback may return that request object as the handler result; the handler returns the first callback result, and throws the first callback error. [src/adapter/lambda-edge/handler.ts:126-145](src/adapter/lambda-edge/handler.ts#L126-L145) [src/adapter/lambda-edge/handler.test.ts:226-241](src/adapter/lambda-edge/handler.test.ts#L226-L241) The adapter contains no explicit validation of `CloudFrontRequest` fields before directly accessing the first record, its request headers, method, URI, and query string. [src/adapter/lambda-edge/handler.ts:124-145](src/adapter/lambda-edge/handler.ts#L124-L145) [src/adapter/lambda-edge/handler.ts:164-179](src/adapter/lambda-edge/handler.ts#L164-L179) ## Relationships - IMPORTS → `decodeBase64` - IMPORTS → `encodeBase64` # CreateHandlersInterface **Kind:** Interface **Source:** [`src/helper/factory/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/factory/index.ts#L20) **Part of:** [Helper](subsystem-src-helper) ## Relationships - IMPORTS → `Hono` # ExtractSchema **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2737) ## Definition ```ts UnionToIntersection< T extends HonoBase ? S : never > ``` # getColorEnabledAsync **Kind:** Function **Source:** [`src/utils/color.ts`](https://github.com/honojs/hono/blob/main/src/utils/color.ts#L36) **Part of:** [Utils](subsystem-src-utils) Get whether color change on terminal is enabled or disabled. If `NO_COLOR` environment variable is set, this function returns `false`. `getColorEnabledAsync` asynchronously determines whether terminal color changes are enabled. When the `NO_COLOR` environment variable is set, it returns `false` so callers can avoid emitting color formatting. ## Signature ```ts async function getColorEnabledAsync(): Promise ``` **Returns:** `Promise` ## Diagram ```mermaid graph LR A[Caller] --> B[getColorEnabledAsync] B --> C{NO_COLOR set?} C -->|Yes| D[Return false] C -->|No| E[Return color-enabled status] ``` ## Usage ```ts import { getColorEnabledAsync } from './utils/color'; const colorEnabled = await getColorEnabledAsync(); if (colorEnabled) { console.log('\u001b[32mSuccess\u001b[0m'); } else { console.log('Success'); } ``` ## AI Coding Instructions - Always `await` `getColorEnabledAsync` before deciding whether to write terminal color escape sequences. - Respect a `false` result and emit plain text when color changes are disabled. - Do not override the `NO_COLOR` environment variable behavior in calling code. - Keep terminal output formatting decisions close to the code that writes to the terminal. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `logger` — `src/middleware/logger/index.ts`:81 # getNameSpaceContext **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L56) **Part of:** [Jsx](subsystem-src-jsx) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `title` — `src/jsx/intrinsic-element/components.ts`:121 # TimingVariables **Kind:** Type **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L10) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { metric?: { headers: string[] timers: Map } } ``` # AlgorithmTypes **Kind:** Enum **Source:** [`src/utils/jwt/jwa.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwa.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Values - `HS256` - `HS384` - `HS512` - `RS256` - `RS384` - `RS512` - `PS256` - `PS384` - `PS512` - `ES256` - `ES384` - `ES512` - `EdDSA` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # contextStorage **Kind:** Function **Source:** [`src/middleware/context-storage/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/context-storage/index.ts#L43) **Part of:** [Middleware](subsystem-src-middleware) Context Storage Middleware for Hono. `contextStorage` creates middleware that stores the active Hono `Context` for the lifetime of a request. Code running within that request can access the same context through `getContext()` without passing `c` through each function call. ## Signature ```ts function contextStorage(): MiddlewareHandler ``` **Returns:** `MiddlewareHandler` ## Diagram ```mermaid graph LR Request[Incoming request] --> Middleware[contextStorage middleware] Middleware --> Handler[Route handler] Handler --> Service[Application code] Service --> GetContext[getContext()] GetContext --> Context[Active Hono Context] ``` ## Usage ```ts import { Hono } from 'hono' import { contextStorage, getContext } from 'hono/context-storage' const app = new Hono() app.use(contextStorage()) function getRequestPath() { return getContext().req.path } app.get('/status', (c) => { return c.json({ path: getRequestPath(), }) }) export default app ``` ## AI Coding Instructions - Register `contextStorage()` before routes or middleware that call `getContext()`. - Call `getContext()` only while handling an active request; do not retain the returned context for later work. - Prefer the route handler’s `c` parameter when it is already available; use context storage for code paths where passing `c` is impractical. - Keep request-specific values on the Hono context so concurrent requests remain isolated. # deleteCookie **Kind:** Function **Source:** [`src/helper/cookie/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts#L141) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function deleteCookie(c: Context, name: string, opt: CookieOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `name` | `string` | | `opt` | `CookieOptions` | **Returns:** `string | undefined` # denoFileSystemModule **Kind:** Constant **Source:** [`src/adapter/deno/ssg.ts`](https://github.com/honojs/hono/blob/main/src/adapter/deno/ssg.ts#L9) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts FileSystemModule ``` ## Value ```ts { writeFile: async (path, data) => { const uint8Data = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data) await Deno.writeFile(path, uint8Data) }, mkdir: async (path, options) => { return Deno.mkdir(path, { recursive: options?.recursive ?? false }) }, } ``` # getNameSpaceContext **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L111) **Part of:** [Jsx](subsystem-src-jsx) ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `clearCache` — `src/jsx/dom/intrinsic-element/components.ts`:18 # HTTPResponseError **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L113) `HTTPResponseError` describes an error object that exposes a `Response` through `getResponse()`. Error-handling code can detect this interface and return the associated response instead of creating a new error response. ## Properties | Property | Type | |---|---| | `getResponse` | `() => Response` | ## Diagram ```mermaid graph LR Error[Thrown error] --> Check{Has getResponse?} Check -->|Yes| HTTPResponseError[HTTPResponseError] HTTPResponseError --> Response[getResponse returns Response] Check -->|No| Fallback[Default error handling] ``` ## Usage ```ts interface HTTPResponseError { getResponse: () => Response } const isHTTPResponseError = (error: unknown): error is HTTPResponseError => { return ( typeof error === 'object' && error !== null && 'getResponse' in error && typeof error.getResponse === 'function' ) } try { throw { getResponse: () => new Response('Access denied'), } } catch (error) { if (isHTTPResponseError(error)) { return error.getResponse() } return new Response('Unexpected error') } ``` ## AI Coding Instructions - Implement `getResponse` as a function that returns a `Response` instance. - Check unknown thrown values before calling `getResponse`. - Return the response from `getResponse` directly when handling this error type. - Keep response construction inside the error when the error defines its own HTTP output. ## How it works `HTTPResponseError` is an exported TypeScript interface for an `Error` that also has a `getResponse()` method returning a web `Response`. It has no constructor or runtime implementation in `src/types.ts`; it only describes this structural shape. [`src/types.ts:113-115`](src/types.ts#L113-L115) An `ErrorHandler` receives either `Error` or `HTTPResponseError` plus a `Context`, and must return a `Response` or a promise of one. [`src/types.ts:116-119`](src/types.ts#L116-L119) # EventContext **Kind:** Type **Source:** [`src/adapter/cloudflare-pages/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-pages/handler.ts#L12) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts { request: Request functionPath: string waitUntil: (promise: Promise) => void passThroughOnException: () => void props: any next: (input?: Request | string, init?: RequestInit) => Promise env: Env & { ASSETS: { fetch: typeof fetch } } params: Params

data: Data } ``` ## Relationships - IMPORTS → `Context` - IMPORTS → `HTTPException` # getColorEnabled **Kind:** Function **Source:** [`src/utils/color.ts`](https://github.com/honojs/hono/blob/main/src/utils/color.ts#L14) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getColorEnabled(): boolean ``` **Returns:** `boolean` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `inspectRoutes` — `src/helper/dev/index.ts`:27 # IntersectNonAnyTypes **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2763) ## Definition ```ts T extends [infer Head, ...infer Rest] ? ProcessHead & IntersectNonAnyTypes : {} ``` # RequestIdOptions **Kind:** Type **Source:** [`src/middleware/request-id/request-id.ts`](https://github.com/honojs/hono/blob/main/src/middleware/request-id/request-id.ts#L13) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { limitLength?: number headerName?: string generator?: (c: Context) => string } ``` # SSEStreamingApi **Kind:** Class **Source:** [`src/helper/streaming/sse.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/sse.ts#L13) **Part of:** [Helper](subsystem-src-helper) `SSEStreamingApi` provides the Server-Sent Events streaming helper for the application. Its `writeSSE()` method writes data through the SSE response flow so connected clients can receive streamed updates. **Extends:** `StreamingApi` ## Methods | Method | Signature | Returns | |---|---|---| | `writeSSE` | `writeSSE(message: SSEMessage)` | `void` | ## Where it refuses work - `SSEStreamingApi` stops the work with `Error` when `value && /[\r\n]/.test(value)`. ## Diagram ```mermaid graph LR A[Application event] --> B[SSEStreamingApi] B --> C[writeSSE()] C --> D[SSE response stream] D --> E[Connected client] ``` ## Usage ```ts import { SSEStreamingApi } from './helper/streaming/sse'; const sseStreamingApi = new SSEStreamingApi(); sseStreamingApi.writeSSE(); ``` ## AI Coding Instructions - Keep SSE-specific output handling inside `SSEStreamingApi`. - Call `writeSSE()` from code that already owns the active SSE response flow. - Preserve the event formatting expected by connected SSE clients when changing `writeSSE()`. - Handle closed or unavailable response streams at the integration point. # STASH_EFFECT **Kind:** Constant **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L9) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts 1 ``` ## Value ```ts 1 ``` ## Relationships - IMPORTS → `DOM_STASH` - IMPORTS → `buildDataStack` - IMPORTS → `update` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HasRenderToDom` — `src/jsx/dom/render.ts`:30 # build **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L497) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function build(context: Context, node: NodeObject, children: Child[]): void ``` ## Parameters | Name | Type | |---|---| | `context` | `Context` | | `node` | `NodeObject` | | `children` | `Child[]` | **Returns:** `void` # encodeBase64Url **Kind:** Function **Source:** [`src/utils/encode.ts`](https://github.com/honojs/hono/blob/main/src/utils/encode.ts#L10) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function encodeBase64Url(buf: ArrayBufferLike): string ``` ## Parameters | Name | Type | |---|---| | `buf` | `ArrayBufferLike` | **Returns:** `string` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # handler **Kind:** API Endpoint **Source:** [`src/middleware/basic-auth/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/basic-auth/index.ts#L118) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `ALL /` ## Relationships - IMPORTS → `HTTPException` - IMPORTS → `auth` - IMPORTS → `timingSafeEqual` # LatticeProxyEventV2 **Kind:** Interface **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L29) **Part of:** [Adapter](subsystem-src-adapter) `LatticeProxyEventV2` represents an incoming request passed from AWS VPC Lattice to the Lambda adapter. It stores request metadata, multi-value headers and query parameters, an optional body, encoding state, and the associated Lattice request context. ## Properties | Property | Type | |---|---| | `version` | `string` | | `path` | `string` | | `method` | `string` | | `headers` | `Record` | | `queryStringParameters` | `Record` | | `body` | `string | null` | | `isBase64Encoded` | `boolean` | | `requestContext` | `LatticeRequestContextV2` | ## Diagram ```mermaid graph LR Request[AWS VPC Lattice request] --> Event[LatticeProxyEventV2] Event --> Route[path and method] Event --> Metadata[headers and query parameters] Event --> Payload[body and isBase64Encoded] Event --> Context[requestContext] Event --> Handler[Lambda handler] ``` ## Usage ```ts import type { LatticeProxyEventV2 } from "./handler"; export function readRequest(event: LatticeProxyEventV2) { const contentType = event.headers["content-type"]?.find(Boolean); const requestId = event.requestContext.requestId; const body = event.body ? event.isBase64Encoded ? Buffer.from(event.body, "base64").toString("utf8") : event.body : null; return { requestId, method: event.method, path: event.path, contentType, query: event.queryStringParameters, body, }; } ``` ## AI Coding Instructions - Preserve header and query parameter values as string arrays because a request can include repeated values. - Check for a `null` body before reading or parsing it. - Decode `body` as base64 only when `isBase64Encoded` is `true`. - Pass `requestContext` through to logging, tracing, and authorization code rather than rebuilding request metadata. ## How it works `LatticeProxyEventV2` is an exported TypeScript interface for one AWS Lambda event variant. It is included in the `LambdaEvent` union used by the AWS Lambda adapter. [src/adapter/aws-lambda/handler.ts:23-38] Its declared fields are: - `version`, `path`, and `method` strings. [src/adapter/aws-lambda/handler.ts:29-32] - `headers` and `queryStringParameters` maps whose values are `string[]` or `undefined`. [src/adapter/aws-lambda/handler.ts:33-34] - A nullable string `body`, an `isBase64Encoded` flag, and a `requestContext` of type `LatticeRequestContextV2`. [src/adapter/aws-lambda/handler.ts:35-37] - The referenced request context contains service-network, service, and target-group ARNs; region and epoch time strings; plus an `identity` object with optional source-VPC, principal, session, and X.509-related properties. [src/adapter/aws-lambda/types.ts:155-173] When `getProcessor` receives an event whose `requestContext` has its own `serviceArn` property, it selects `LatticeV2Processor` for that event. ALB and API Gateway v2 detection run before this check. [src/adapter/aws-lambda/handler.ts:625-637] [src/adapter/aws-lambda/handler.ts:639-657] Through that processor, the adapter converts the event into a Fetch `Request` as follows: - The request path comes from `event.path`, and the HTTP method comes from `event.method`. [src/adapter/aws-lambda/handler.ts:584-591] - The processor returns an empty query string; therefore, `queryStringParameters` is not read when constructing the request URL. [src/adapter/aws-lambda/handler.ts:593-595] [src/adapter/aws-lambda/handler.ts:318-324] - Each defined header array is appended to a `Headers` object once per value. Header values containing non-ASCII characters are URI-encoded before being appended. [src/adapter/aws-lambda/handler.ts:597-609] [src/adapter/aws-lambda/handler.ts:13-21] - The request domain is taken from `requestContext.domainName` when that property exists; otherwise the adapter reads the first `host` value from `headers` and, if needed, from `multiValueHeaders`. The declared Lattice context has no `domainName` field, and `LatticeProxyEventV2` has no `multiValueHeaders` field. [src/adapter/aws-lambda/handler.ts:301-316] [src/adapter/aws-lambda/handler.ts:29-38] [src/adapter/aws-lambda/types.ts:155-173] - If `body` is truthy, it is base64-decoded when `isBase64Encoded` is true; otherwise it is UTF-8 encoded. The adapter sets `content-length` to the resulting byte length. [src/adapter/aws-lambda/handler.ts:333-339] - A `null` or empty-string body is not assigned to the constructed request because the body branch tests `if (event.body)`. [src/adapter/aws-lambda/handler.ts:333-339] `handle()` passes the constructed request, the original event, its request context, and the optional Lambda context to `app.fetch`. [src/adapter/aws-lambda/handler.ts:252-274] If request construction throws a `TypeError`, it logs the error and returns a 400 `"Invalid request"` response; other thrown errors produce a logged 500 `"Internal Server Error"` response. [src/adapter/aws-lambda/handler.ts:255-266] For this event type, response conversion starts with a single-value `headers` object rather than `multiValueHeaders`, because `LatticeProxyEventV2` does not declare `multiValueHeaders`. [src/adapter/aws-lambda/handler.ts:361-372] Response bodies are base64-encoded when the configured or default content-type test marks the response binary, or when `content-encoding` is present and is not `identity`; otherwise the body is returned as text. [src/adapter/aws-lambda/handler.ts:349-360] [src/adapter/aws-lambda/handler.ts:666-674] Response headers are copied into that result header object. [src/adapter/aws-lambda/handler.ts:374-385] If the response has `set-cookie` headers, this processor writes the extracted cookie array to `result.headers['set-cookie']` and removes `set-cookie` from the response headers before the remaining headers are copied. [src/adapter/aws-lambda/handler.ts:388-400] [src/adapter/aws-lambda/handler.ts:615-620] The interface itself contains no runtime validation; runtime classification only checks for `requestContext.serviceArn`, while later request construction reads the declared fields directly. [src/adapter/aws-lambda/handler.ts:29-38] [src/adapter/aws-lambda/handler.ts:653-657] [src/adapter/aws-lambda/handler.ts:584-609] # ParamKeys **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2706) ## Definition ```ts Path extends `${infer Component}/${infer Rest}` ? ParamKey | ParamKeys : ParamKey ``` # WSContextInit **Kind:** Interface **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L50) **Part of:** [Helper](subsystem-src-helper) An argument for WSContext class `WSContextInit` is the initialization contract passed to `WSContext`. It groups the underlying WebSocket transport with connection state, endpoint metadata, and no-argument `send` and `close` callbacks. ## Properties | Property | Type | |---|---| | `raw` | `T` | | `readyState` | `WSReadyState` | | `url` | `string | URL | null` | | `protocol` | `string | null` | ## Diagram ```mermaid graph LR Init[WSContextInit] --> Raw[raw: T] Init --> State[readyState: WSReadyState] Init --> URL[url: string | URL | null] Init --> Protocol[protocol: string | null] Init --> Send[send(): void] Init --> Close[close(): void] Init --> Context[WSContext] ``` ## Usage ```ts import { WSContext } from "./helper/websocket"; import type { WSContextInit, WSReadyState } from "./helper/websocket"; const socket = new WebSocket("wss://example.test"); const init: WSContextInit = { raw: socket, readyState: socket.readyState as WSReadyState, url: socket.url, protocol: socket.protocol || null, send: () => socket.send("ping"), close: () => socket.close(), }; const context = new WSContext(init); context.send(); context.close(); ``` ## AI Coding Instructions - Keep `raw` typed as the underlying WebSocket or WebSocket-compatible transport. - Implement `send` and `close` as no-argument callbacks that match the interface signature. - Preserve `null` for `url` and `protocol` when connection metadata is unavailable. - Keep `readyState` aligned with the transport state when creating or updating the context. # combineAfterResponseHooks **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L139) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function combineAfterResponseHooks(hooks: AfterResponseHook | AfterResponseHook[]): AfterResponseHook ``` ## Parameters | Name | Type | |---|---| | `hooks` | `AfterResponseHook | AfterResponseHook[]` | **Returns:** `AfterResponseHook` # CryptoKeyUsage **Kind:** Enum **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L117) **Part of:** [Utils](subsystem-src-utils) ## Values - `Encrypt` - `Decrypt` - `Sign` - `Verify` - `DeriveKey` - `DeriveBits` - `WrapKey` - `UnwrapKey` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoJsonWebKey` — `src/utils/jwt/jws.ts`:23 # ErrorBoundary **Kind:** Function **Source:** [`src/jsx/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/components.ts#L55) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts async function ErrorBoundary({ children, fallback, fallbackRender, onError }) ``` ## Parameters | Name | Type | |---|---| | `{ children, fallback, fallbackRender, onError }` | `any` | # IPRestrictionRules **Kind:** Interface **Source:** [`src/middleware/ip-restriction/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/ip-restriction/index.ts#L172) **Part of:** [Middleware](subsystem-src-middleware) Rules for IP Restriction Middleware `IPRestrictionRules` defines the allow and deny rule collections used by IP Restriction Middleware. The middleware reads `allowList` and `denyList` to determine whether an incoming IP address matches a restriction rule. ## Properties | Property | Type | |---|---| | `denyList` | `IPRestrictionRule[]` | | `allowList` | `IPRestrictionRule[]` | ## Diagram ```mermaid graph LR Rules[IPRestrictionRules] Allow[allowList: IPRestrictionRule[]] Deny[denyList: IPRestrictionRule[]] Rule[IPRestrictionRule] Rules --> Allow Rules --> Deny Allow --> Rule Deny --> Rule ``` ## Usage ```ts import type { IPRestrictionRules } from "./middleware/ip-restriction"; const rules: IPRestrictionRules = { allowList: [], denyList: [], }; // Pass `rules` to the IP Restriction Middleware configuration. ``` ## AI Coding Instructions - Keep both `allowList` and `denyList` present when creating an `IPRestrictionRules` object. - Store only `IPRestrictionRule` entries in each list. - Check middleware behavior when an IP matches entries in both lists. - Keep rule construction consistent with the `IPRestrictionRule` type. # ParamKeyToRecord **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2710) ## Definition ```ts T extends `${infer R}?` ? Record : { [K in T]: string } ``` # serveStatic **Kind:** Function **Source:** [`src/adapter/cloudflare-pages/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-pages/handler.ts#L114) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function serveStatic(): MiddlewareHandler ``` **Returns:** `MiddlewareHandler` # APIGatewayProxyResult **Kind:** Type **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L108) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts { statusCode: number statusDescription?: string body: string cookies?: string[] isBase64Encoded: boolean } & (WithHeaders | WithMultiValueHeaders) ``` # combineBeforeRequestHooks **Kind:** Function **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L118) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function combineBeforeRequestHooks(hooks: BeforeRequestHook | BeforeRequestHook[]): BeforeRequestHook ``` ## Parameters | Name | Type | |---|---| | `hooks` | `BeforeRequestHook | BeforeRequestHook[]` | **Returns:** `BeforeRequestHook` # JwtTokenAudience **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L106) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # PermissionsPolicyDirective **Kind:** Type **Source:** [`src/middleware/secure-headers/permissions-policy.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/permissions-policy.ts#L3) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts | StandardizedFeatures | ProposedFeatures | ExperimentalFeatures ``` # PropsForRenderer **Kind:** Type **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L83) Extracts the props for the renderer. `PropsForRenderer` extracts the prop type expected by a renderer. It lets context and rendering code share the renderer’s input contract without restating prop fields. ## Definition ```ts [...Required>] extends [unknown, infer Props] ? Props : unknown ``` ## Diagram ```mermaid graph LR Renderer[Renderer type] --> PropsForRenderer[PropsForRenderer] PropsForRenderer --> RendererProps[Extracted renderer props] RendererProps --> Context[Context and render calls] ``` ## Usage ```ts import type { PropsForRenderer } from "./context"; const renderer = ({ value, onChange }: { value: string; onChange(value: string): void }) => { return { value, onChange }; }; type RendererProps = PropsForRenderer; const props: RendererProps = { value: "hello", onChange(nextValue) { console.log(nextValue); }, }; ``` ## AI Coding Instructions - Pass the renderer type to `PropsForRenderer` instead of manually duplicating its prop shape. - Keep renderer parameter types explicit so the extracted props remain accurate. - Update call sites when renderer props change; `PropsForRenderer` will reflect the new contract. - Use the extracted type for context values and helpers that forward props to the renderer. # useSyncExternalStore **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L401) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useSyncExternalStore(subscribe: (callback: () => void) => () => void, getSnapshot: () => T, getServerSnapshot: () => T): T ``` ## Parameters | Name | Type | |---|---| | `subscribe` | `(callback: () => void) => () => void` | | `getSnapshot` | `() => T` | | `getServerSnapshot` | `() => T` | **Returns:** `T` # Bindings **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L26) ## Definition ```ts object ``` # bunFileSystemModule **Kind:** Constant **Source:** [`src/adapter/bun/ssg.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/ssg.ts#L13) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts FileSystemModule ``` ## Value ```ts { writeFile: async (path, data) => { await write(path, data) }, mkdir: async () => {}, } ``` # cloneElement **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L440) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function cloneElement(element: T, props: Partial, children: Child[]): T ``` ## Parameters | Name | Type | |---|---| | `element` | `T` | | `props` | `Partial` | | `children` | `Child[]` | **Returns:** `T` # defaultMatch **Kind:** Function **Source:** [`src/helper/accepts/accepts.ts`](https://github.com/honojs/hono/blob/main/src/helper/accepts/accepts.ts#L21) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function defaultMatch(accepts: Accept[], config: acceptsConfig): string ``` ## Parameters | Name | Type | |---|---| | `accepts` | `Accept[]` | | `config` | `acceptsConfig` | **Returns:** `string` # JwtTokenIssuedAt **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L48) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # JwtVariables **Kind:** Type **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L18) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { jwtPayload: T } ``` # BlankEnv **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L29) ## Definition ```ts {} ``` # ClientContext **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L8) **Part of:** [Adapter](subsystem-src-adapter) `ClientContext` defines the request-scoped context passed through the AWS Lambda adapter. It groups the platform client API, environment values, and an open-ended `Custom` field for application-specific context. ## Properties | Property | Type | |---|---| | `client` | `ClientContextClient` | | `Custom` | `any` | | `env` | `ClientContextEnv` | ## Diagram ```mermaid graph LR Context[ClientContext] Client[client: ClientContextClient] Env[env: ClientContextEnv] Custom[Custom: any] Context --> Client Context --> Env Context --> Custom ``` ## Usage ```ts import type { ClientContext } from "./types"; function handleRequest(context: ClientContext) { const region = context.env.region; context.client.log({ message: `Handling request in ${region}`, }); const tenantId = context.Custom?.tenantId; return { tenantId, region, }; } ``` ## AI Coding Instructions - Pass `ClientContext` through Lambda request handling code instead of separately passing `client`, `env`, and custom values. - Access AWS adapter APIs through `context.client` and configuration through `context.env`. - Treat `Custom` as application-defined data; narrow or validate its shape before reading properties. - Keep custom context values request-scoped to avoid sharing mutable state across Lambda invocations. ## How it works `ClientContext` is an exported TypeScript interface that describes the `clientContext` value on an AWS Lambda `LambdaContext`. That enclosing property is optional and may be `undefined`. [src/adapter/aws-lambda/types.ts:8-13](src/adapter/aws-lambda/types.ts#L8-L13) [src/adapter/aws-lambda/types.ts:35-47](src/adapter/aws-lambda/types.ts#L35-L47) Its required members are: - `client`, a `ClientContextClient` object containing string fields for `installationId`, `appTitle`, `appVersionName`, `appVersionCode`, and `appPackageName`. [src/adapter/aws-lambda/types.ts:9](src/adapter/aws-lambda/types.ts#L9) [src/adapter/aws-lambda/types.ts:15-21](src/adapter/aws-lambda/types.ts#L15-L21) - `env`, a `ClientContextEnv` object containing string fields for `platformVersion`, `platform`, `make`, `model`, and `locale`. [src/adapter/aws-lambda/types.ts:12](src/adapter/aws-lambda/types.ts#L12) [src/adapter/aws-lambda/types.ts:23-29](src/adapter/aws-lambda/types.ts#L23-L29) It also declares an optional, capitalized `Custom` member with the `any` type. [src/adapter/aws-lambda/types.ts:11](src/adapter/aws-lambda/types.ts#L11) The interface declares no methods, runtime validation, thrown errors, or side effects. [src/adapter/aws-lambda/types.ts:8-13](src/adapter/aws-lambda/types.ts#L8-L13) The AWS Lambda adapter passes its received `LambdaContext` onward as `context` in `streamHandle` and as `lambdaContext` in `handle`; neither shown path reads `clientContext` directly. [src/adapter/aws-lambda/handler.ts:147-157](src/adapter/aws-lambda/handler.ts#L147-L157) [src/adapter/aws-lambda/handler.ts:252-272](src/adapter/aws-lambda/handler.ts#L252-L272) # createRoot **Kind:** Function **Source:** [`src/jsx/dom/client.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/client.ts#L23) **Part of:** [Jsx](subsystem-src-jsx) Create a root object for rendering `createRoot` creates a root object bound to a DOM container for JSX rendering. Use the returned root to render application content into that container and manage its mounted output. ## Signature ```ts function createRoot(element: HTMLElement | DocumentFragment, options: RootOptions): Root ``` ## Parameters | Name | Type | |---|---| | `element` | `HTMLElement | DocumentFragment` | | `options` | `RootOptions` | **Returns:** `Root` ## Diagram ```mermaid graph LR Container[DOM container] --> CreateRoot[createRoot] CreateRoot --> Root[Root object] Root --> Render[render JSX] Render --> DOM[Rendered DOM] ``` ## Usage ```ts import { createRoot } from "./jsx/dom/client"; const container = document.getElementById("app"); if (container) { const root = createRoot(container); root.render(

Hello, world!
); } ``` ## AI Coding Instructions - Pass a valid DOM container to `createRoot` before rendering JSX. - Keep the returned root instance and call its rendering methods instead of creating a new root for each update. - Create the root at the application entry point where the target container is available. - Ensure JSX output is rendered through the root associated with the intended container. # FileSystemModule **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L34) **Part of:** [Helper](subsystem-src-helper) `FileSystemModule` defines the file-system operations used by the static site generation helper. It abstracts directory creation and file writing so the generator can work with a supplied filesystem implementation. ## Diagram ```mermaid graph LR SSG[SSG helper] --> FS[FileSystemModule] FS --> MKDIR[mkdir()] FS --> WRITE[writeFile()] MKDIR --> Directory[Output directory] WRITE --> File[Generated file] ``` ## Usage ```ts const fileSystem: FileSystemModule = { async mkdir(directoryPath) { return directoryPath; }, async writeFile(filePath, content) { await fs.promises.writeFile(filePath, content); }, }; await fileSystem.mkdir("dist"); await fileSystem.writeFile("dist/index.html", "

Hello

"); ``` ## AI Coding Instructions - Implement `mkdir()` with a return type compatible with `Promise`. - Implement `writeFile()` so it resolves only after the target file has been written. - Create output directories before writing generated files into them. - Keep filesystem-specific behavior inside the `FileSystemModule` implementation. ## How it works `FileSystemModule` is an experimental TypeScript interface that abstracts the two filesystem operations required by the static-site-generation (SSG) writer: creating directories and writing files. Its API may change. [src/helper/ssg/ssg.ts:29-37] It requires these asynchronous methods: - `writeFile(path, data)`: writes a `string` or `Uint8Array` to `path` and resolves with no value. [src/helper/ssg/ssg.ts:34-36] - `mkdir(path, { recursive })`: creates a directory, receives a required `recursive` boolean option, and may resolve with `void` or a `string`. [src/helper/ssg/ssg.ts:34-37] ## Role in SSG generation `toSSG` accepts a `FileSystemModule` as its second argument, then passes it to `saveContentToFile` for every generated route response. [src/helper/ssg/ssg.ts:341-347] [src/helper/ssg/ssg.ts:368-369] [src/helper/ssg/ssg.ts:442-445] Before writing, `saveContentToFile` derives an output filename from the route path, output directory, MIME type, and optional extension map. [src/helper/ssg/ssg.ts:310-315] [src/helper/ssg/ssg.ts:320-322] It rejects a derived path outside the configured output directory by throwing `Error: Path traversal detected: "" is outside the output directory`. [src/helper/ssg/utils.ts:77-86] For each directory path not already recorded in a module-level `Set`, the writer calls `fsModule.mkdir(dirPath, { recursive: true })` and records that directory after the promise resolves. [src/helper/ssg/ssg.ts:309] [src/helper/ssg/ssg.ts:323-327] The directory cache is shared at module scope, rather than being reset per `toSSG` call. [src/helper/ssg/ssg.ts:309] The code then calls `writeFile` with string content unchanged, or converts an `ArrayBuffer` to `Uint8Array` before writing. [src/helper/ssg/ssg.ts:328-332] A rejected `mkdir` or `writeFile` call is caught by the SSG generation flow; `toSSG` returns `{ success: false, files: [], error }`, converting a non-`Error` rejection into `new Error(String(error))`. [src/helper/ssg/ssg.ts:443-445] [src/helper/ssg/ssg.ts:451-463] ## Hook interaction `AfterGenerateHook` receives the same `FileSystemModule` instance supplied to `toSSG`, along with the result and optional SSG options. [src/helper/ssg/ssg.ts:110-116] [src/helper/ssg/ssg.ts:160-172] `toSSG` invokes these hooks after forming either its success or failure result. [src/helper/ssg/ssg.ts:460-469] ## Included adapter implementations The Bun adapter exports `bunFileSystemModule`, whose `writeFile` delegates to `Bun.write`; its `mkdir` method is an async no-op. [src/adapter/bun/ssg.ts:5-18] Its adapter-level `toSSG` passes that module to the shared SSG implementation. [src/adapter/bun/ssg.ts:25-27] The Deno adapter exports `denoFileSystemModule`, whose `writeFile` encodes strings with `TextEncoder` and otherwise wraps the input as `Uint8Array` before calling `Deno.writeFile`; its `mkdir` delegates to `Deno.mkdir` with the passed recursive setting. [src/adapter/deno/ssg.ts:9-18] Its adapter-level `toSSG` likewise passes that module to the shared implementation. [src/adapter/deno/ssg.ts:25-27] # getQueryParam **Kind:** Constant **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L302) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts ( url: string, key?: string ) => string | undefined | Record ``` ## Value ```ts _getQueryParam as ( url: string, key?: string ) => string | undefined | Record ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoRequest` — `src/request.ts`:34 # LanguageVariables **Kind:** Interface **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L47) **Part of:** [Middleware](subsystem-src-middleware) `LanguageVariables` defines the language value used by language middleware. It carries a `language` string so downstream middleware or handlers can read the active language. ## Properties | Property | Type | |---|---| | `language` | `string` | ## Diagram ```mermaid graph LR A[Language middleware] --> B[LanguageVariables] B --> C[language: string] B --> D[Downstream middleware or handlers] ``` ## Usage ```ts import type { LanguageVariables } from './src/middleware/language/language'; const variables: LanguageVariables = { language: 'en', }; function getLanguage({ language }: LanguageVariables): string { return language; } const activeLanguage = getLanguage(variables); ``` ## AI Coding Instructions - Keep the `language` field as a string when creating `LanguageVariables` values. - Pass `LanguageVariables` through middleware context or handler parameters where language state is needed. - Do not rename the `language` property without updating middleware and downstream consumers. - Validate or normalize language input before assigning it to this interface when input comes from requests. ## How it works `LanguageVariables` is an exported TypeScript interface with one context-variable entry: - `language: string` — the selected language value is typed as a string. [src/middleware/language/language.ts:47-49] It is intended for the `Variables` type of a Hono application: the in-file example aliases `LanguageVariables` and passes it as `Variables` when constructing `Hono`. [src/middleware/language/language.ts:274-278] With that typing, `c.get('language')` refers to the `language` variable. [src/middleware/language/language.ts:286-289] Context variable getters and setters map keys in `E['Variables']` to their declared value types. [src/context.ts:95-108] `LanguageVariables` itself has no methods, validation, errors, or runtime side effects. The related `languageDetector` middleware detects a language, stores it as `ctx.set('language', lang)`, then calls the next middleware. [src/middleware/language/language.ts:302-308] The stored value is either the first detected language from the configured detector order or `fallbackLanguage`. [src/middleware/language/language.ts:238-266] # BlankInput **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L49) ## Definition ```ts {} ``` # ClientContextClient **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L15) **Part of:** [Adapter](subsystem-src-adapter) `ClientContextClient` models client application metadata carried by the AWS Lambda adapter. It provides typed fields for the installation, application identity, and version information associated with a request. ## Properties | Property | Type | |---|---| | `installationId` | `string` | | `appTitle` | `string` | | `appVersionName` | `string` | | `appVersionCode` | `string` | | `appPackageName` | `string` | ## Diagram ```mermaid graph LR ClientContextClient --> installationId ClientContextClient --> appTitle ClientContextClient --> appVersionName ClientContextClient --> appVersionCode ClientContextClient --> appPackageName ``` ## Usage ```ts import type { ClientContextClient } from './types'; const client: ClientContextClient = { installationId: 'device-token', appTitle: 'Example App', appVersionName: 'release-name', appVersionCode: 'release-code', appPackageName: 'com.example.app', }; function getClientLabel(context: ClientContextClient): string { return `${context.appTitle} (${context.appPackageName})`; } console.log(getClientLabel(client)); ``` ## AI Coding Instructions - Keep every property as a string, including version codes and installation identifiers. - Preserve the field names when mapping AWS Lambda client-context data into this interface. - Treat client-provided values as request metadata and validate them before using them for authorization or persistence. - Handle missing client context before constructing a `ClientContextClient` value. ## How it works `ClientContextClient` is an exported TypeScript interface describing the `client` portion of a Lambda client context. [`src/adapter/aws-lambda/types.ts:8-20`](src/adapter/aws-lambda/types.ts#L8-L20) An object typed as `ClientContextClient` has five required string fields: - `installationId` — [`src/adapter/aws-lambda/types.ts:16`](src/adapter/aws-lambda/types.ts#L16) - `appTitle` — [`src/adapter/aws-lambda/types.ts:17`](src/adapter/aws-lambda/types.ts#L17) - `appVersionName` — [`src/adapter/aws-lambda/types.ts:18`](src/adapter/aws-lambda/types.ts#L18) - `appVersionCode` — [`src/adapter/aws-lambda/types.ts:19`](src/adapter/aws-lambda/types.ts#L19) - `appPackageName` — [`src/adapter/aws-lambda/types.ts:20](src/adapter/aws-lambda/types.ts#L20) `ClientContext` requires its `client` field to conform to this interface. [`src/adapter/aws-lambda/types.ts:8-13`](src/adapter/aws-lambda/types.ts#L8-L13) `LambdaContext` may contain that enclosing `ClientContext` through its optional `clientContext` field. [`src/adapter/aws-lambda/types.ts:35-45`](src/adapter/aws-lambda/types.ts#L35-L45) The interface declares no methods, runtime validation, error handling, or side effects. [`src/adapter/aws-lambda/types.ts:15-21`](src/adapter/aws-lambda/types.ts#L15-L21) # composeRef **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L24) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function composeRef(ref: RefObject | Function | undefined, cb: (e: T) => void | (() => void)): ((e: T) => () => void) ``` ## Parameters | Name | Type | |---|---| | `ref` | `RefObject | Function | undefined` | | `cb` | `(e: T) => void | (() => void)` | **Returns:** `((e: T) => () => void)` # convertIPv4MappedIPv6ToIPv4 **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L320) **Part of:** [Utils](subsystem-src-utils) Extract the IPv4 portion from an IPv4-mapped IPv6 address `convertIPv4MappedIPv6ToIPv4` extracts the IPv4 address portion from an IPv4-mapped IPv6 address. It is intended for address-handling paths where network inputs may represent IPv4 clients in IPv6 notation. ## Signature ```ts function convertIPv4MappedIPv6ToIPv4(ipv6binary: bigint): bigint ``` ## Parameters | Name | Type | |---|---| | `ipv6binary` | `bigint` | **Returns:** `bigint` ## Diagram ```mermaid graph LR A[Network address input] --> B[convertIPv4MappedIPv6ToIPv4] B --> C[IPv4 address portion] ``` ## Usage ```ts import { convertIPv4MappedIPv6ToIPv4 } from './utils/ipaddr'; const remoteAddress = request.socket.remoteAddress; if (remoteAddress) { const clientAddress = convertIPv4MappedIPv6ToIPv4(remoteAddress); console.log(clientAddress); } ``` ## AI Coding Instructions - Call this function when processing network addresses from sockets, proxies, or request metadata. - Pass the raw address string into the function before comparing it with IPv4 allowlists or blocklists. - Do not treat this function as a general IPv6 parser or formatter. - Add tests for IPv4-mapped IPv6 inputs and address inputs that are not IPv4-mapped. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # inspectRoutes **Kind:** Function **Source:** [`src/helper/dev/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/dev/index.ts#L27) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function inspectRoutes(hono: Hono): RouteData[] ``` ## Parameters | Name | Type | |---|---| | `hono` | `Hono` | **Returns:** `RouteData[]` ## Relationships - IMPORTS → `getColorEnabled` - IMPORTS → `findTargetHandler` - IMPORTS → `isMiddleware` # RequestIdVariables **Kind:** Type **Source:** [`src/middleware/request-id/request-id.ts`](https://github.com/honojs/hono/blob/main/src/middleware/request-id/request-id.ts#L9) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { requestId: string } ``` # BlankSchema **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L48) ## Definition ```ts {} ``` # ClientContextEnv **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L23) **Part of:** [Adapter](subsystem-src-adapter) `ClientContextEnv` describes device and platform details from an AWS Lambda client context. It stores the platform version, platform name, device make and model, and locale for request-aware processing. ## Properties | Property | Type | |---|---| | `platformVersion` | `string` | | `platform` | `string` | | `make` | `string` | | `model` | `string` | | `locale` | `string` | ## Diagram ```mermaid graph LR ClientContextEnv --> platformVersion ClientContextEnv --> platform ClientContextEnv --> make ClientContextEnv --> model ClientContextEnv --> locale ``` ## Usage ```ts import type { ClientContextEnv } from './types'; const environment: ClientContextEnv = { platformVersion: '17.0', platform: 'iOS', make: 'Apple', model: 'iPhone', locale: 'en-US', }; function getDeviceLabel(env: ClientContextEnv): string { return `${env.make} ${env.model} (${env.platform} ${env.platformVersion})`; } console.log(getDeviceLabel(environment)); ``` ## AI Coding Instructions - Keep all `ClientContextEnv` fields as strings when mapping AWS Lambda client context data. - Handle missing client context before creating a `ClientContextEnv` object. - Preserve the source locale value rather than converting it during request parsing. - Use this interface for device and platform metadata passed between the AWS Lambda adapter and request handling code. ## How it works `ClientContextEnv` is an exported TypeScript interface that declares the environment portion of a Lambda client context. It contains five required `string` fields: `platformVersion`, `platform`, `make`, `model`, and `locale`. [src/adapter/aws-lambda/types.ts:23-29] It is the type of the required `env` property on `ClientContext`. [src/adapter/aws-lambda/types.ts:8-13] A `ClientContext` can appear as the optional `clientContext` property of `LambdaContext`, which is passed to handlers as their `context` argument. [src/adapter/aws-lambda/types.ts:35-56] The interface declares no methods, runtime validation, error handling, or side effects. [src/adapter/aws-lambda/types.ts:23-29] # createMiddleware **Kind:** Function **Source:** [`src/helper/factory/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/factory/index.ts#L368) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function createMiddleware(middleware: MiddlewareHandler): MiddlewareHandler ``` ## Parameters | Name | Type | |---|---| | `middleware` | `MiddlewareHandler` | **Returns:** `MiddlewareHandler` # isIPv4MappedIPv6 **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L313) **Part of:** [Utils](subsystem-src-utils) Check if a binary IPv6 address is an IPv4-mapped IPv6 address (::ffff:x.x.x.x) `isIPv4MappedIPv6` checks whether a binary IPv6 address matches the IPv4-mapped IPv6 form: `::ffff:x.x.x.x`. It helps address parsing and routing code identify IPv6 byte arrays that represent embedded IPv4 addresses. ## Signature ```ts function isIPv4MappedIPv6(ipv6binary: bigint): boolean ``` ## Parameters | Name | Type | |---|---| | `ipv6binary` | `bigint` | **Returns:** `boolean` ## Diagram ```mermaid graph LR A[Binary IPv6 address] --> B[isIPv4MappedIPv6] B --> C{Matches ::ffff IPv4-mapped prefix?} C -->|Yes| D[true] C -->|No| E[false] ``` ## Usage ```ts import { isIPv4MappedIPv6 } from './utils/ipaddr.js' function handleAddress(binaryAddress: Uint8Array): void { if (isIPv4MappedIPv6(binaryAddress)) { console.log('Address is an IPv4-mapped IPv6 address') return } console.log('Address is not IPv4-mapped') } ``` ## AI Coding Instructions - Pass the binary IPv6 byte representation; do not pass a textual IP address directly. - Keep this check before extracting or handling the embedded IPv4 portion of an address. - Preserve the byte order produced by the IPv6 parser when passing addresses to this function. - Test both IPv4-mapped and non-mapped IPv6 byte arrays when changing address parsing code. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # jsxAttr **Kind:** Function **Source:** [`src/jsx/jsx-runtime.ts`](https://github.com/honojs/hono/blob/main/src/jsx/jsx-runtime.ts#L16) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function jsxAttr(key: string, v: string | Promise | Record): HtmlEscapedString | Promise ``` ## Parameters | Name | Type | |---|---| | `key` | `string` | | `v` | `string | Promise | Record` | **Returns:** `HtmlEscapedString | Promise` ## Relationships - IMPORTS → `html` - IMPORTS → `html` - IMPORTS → `escapeToBuffer` - IMPORTS → `stringBufferToString` - IMPORTS → `isValidAttributeName` - IMPORTS → `styleObjectForEach` - IMPORTS → `jsxDEV` - IMPORTS → `jsxDEV` # SecureHeadersVariables **Kind:** Type **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L11) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts { secureHeadersNonce?: string } ``` # CloudFrontConfig **Kind:** Interface **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L62) **Part of:** [Adapter](subsystem-src-adapter) `CloudFrontConfig` describes CloudFront metadata extracted from a Lambda@Edge event. It carries the distribution identity, event type, and request identifier so handler code can route, log, or correlate requests. ## Properties | Property | Type | |---|---| | `distributionDomainName` | `string` | | `distributionId` | `string` | | `eventType` | `string` | | `requestId` | `string` | ## Diagram ```mermaid graph LR Event[Lambda@Edge Event] --> Config[CloudFrontConfig] Config --> Domain[distributionDomainName] Config --> Distribution[distributionId] Config --> Type[eventType] Config --> Request[requestId] Config --> Handler[Edge Handler Logic] ``` ## Usage ```ts import type { CloudFrontConfig } from "./handler"; function logCloudFrontRequest(config: CloudFrontConfig): void { console.log({ distributionId: config.distributionId, domainName: config.distributionDomainName, eventType: config.eventType, requestId: config.requestId, }); } const config: CloudFrontConfig = { distributionDomainName: "example.cloudfront.net", distributionId: "E123ABC", eventType: "viewer-request", requestId: "request-id", }; logCloudFrontRequest(config); ``` ## AI Coding Instructions - Keep all `CloudFrontConfig` fields as strings when mapping Lambda@Edge event data. - Read `distributionId` and `distributionDomainName` from the CloudFront event configuration. - Pass `requestId` into logs or error context to correlate handler activity. - Treat `eventType` as event metadata and avoid assuming a single CloudFront trigger type. ## How it works `CloudFrontConfig` is an exported TypeScript interface for the `cf.config` object in a Lambda@Edge event. It requires four string fields: `distributionDomainName`, `distributionId`, `eventType`, and `requestId`. [src/adapter/lambda-edge/handler.ts:62-67] A `CloudFrontEvent` stores this object at `cf.config`, and `CloudFrontEdgeEvent` is an object whose `Records` array contains those events. [src/adapter/lambda-edge/handler.ts:69-79] The Lambda@Edge adapter also re-exports `CloudFrontConfig` as a type from its public entry point. [src/adapter/lambda-edge/index.ts:6-14] When `handle()` processes an event, it passes the first record’s configuration to `app.fetch()` in the environment/bindings object as `config`. [src/adapter/lambda-edge/handler.ts:124-141] Its `distributionDomainName` is also used as the request URL host when the first `host` request header is absent. [src/adapter/lambda-edge/handler.ts:164-170] The interface declares no optional fields, runtime validation, defaults, or error handling. [src/adapter/lambda-edge/handler.ts:62-67] # ContextRenderer **Kind:** Interface **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L62) Interface for context renderer. `ContextRenderer` defines the contract for converting context data into rendered output. Implementations receive context from the surrounding system and return the representation consumed by the next stage. ## Diagram ```mermaid graph LR Context[Context data] --> Renderer[ContextRenderer] Renderer --> Output[Rendered output] ``` ## Usage ```ts import type { ContextRenderer } from "./context"; const renderer: ContextRenderer = { render(context) { return JSON.stringify(context); }, }; const renderedContext = renderer.render({ user: "Ada", action: "create", }); console.log(renderedContext); ``` ## AI Coding Instructions - Implement the `render` method required by `ContextRenderer`. - Keep rendering logic focused on transforming the received context into output. - Do not mutate the input context while rendering. - Pass renderer implementations through the integration point that consumes rendered context. # JwtAlgorithmMismatch **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L20) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # ssgParams **Kind:** Function **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L43) **Part of:** [Helper](subsystem-src-helper) Define SSG Route `ssgParams` defines route parameters for static site generation. It connects route-specific parameter data to the SSG middleware so matching pages can be generated during the build process. ## Signature ```ts function ssgParams(params) ``` ## Parameters | Name | Type | |---|---| | `params` | `any` | ## Diagram ```mermaid graph LR Route[Route definition] --> Params[SSG parameters] Params --> ssgParams[ssgParams] ssgParams --> Middleware[SSG middleware] Middleware --> StaticPage[Generated static page] ``` ## Usage ```ts import { ssgParams } from './helper/ssg/middleware' const params = ssgParams({ slug: 'getting-started', }) export default params ``` ## AI Coding Instructions - Keep SSG parameter values aligned with the dynamic segments declared by the route. - Pass serializable values that can be resolved during static generation. - Add route parameter handling through `ssgParams` instead of duplicating SSG middleware behavior. - Verify that generated parameter values match the paths expected by the router. # Suspense **Kind:** Function **Source:** [`src/jsx/streaming.ts`](https://github.com/honojs/hono/blob/main/src/jsx/streaming.ts#L42) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts async function Suspense({ children, fallback, }) ``` ## Parameters | Name | Type | |---|---| | `{ children, fallback, }` | `any` | # tryGetContext **Kind:** Function **Source:** [`src/middleware/context-storage/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/context-storage/index.ts#L49) **Part of:** [Middleware](subsystem-src-middleware) ## Signature ```ts function tryGetContext(): Context | undefined ``` **Returns:** `Context | undefined` # ALBRequestContext **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L149) **Part of:** [Adapter](subsystem-src-adapter) `ALBRequestContext` describes the Application Load Balancer metadata attached to a request handled by the AWS Lambda adapter. Its `elb.targetGroupArn` field identifies the ALB target group that routed the request. ## Properties | Property | Type | |---|---| | `elb` | `{ targetGroupArn: string }` | ## Diagram ```mermaid graph LR Request[ALB Request] --> Context[ALBRequestContext] Context --> ELB[elb] ELB --> TargetGroupArn[targetGroupArn: string] ``` ## Usage ```ts import type { ALBRequestContext } from "./types"; function getTargetGroupArn(context: ALBRequestContext): string { return context.elb.targetGroupArn; } const context: ALBRequestContext = { elb: { targetGroupArn: "arn:aws:elasticloadbalancing:region:account:targetgroup/example/id", }, }; console.log(getTargetGroupArn(context)); ``` ## AI Coding Instructions - Read the target group ARN from `context.elb.targetGroupArn`. - Keep the `elb` object present when constructing an `ALBRequestContext`. - Treat `targetGroupArn` as an ARN string; do not parse it unless the calling code needs a specific ARN component. - Pass this context through AWS Lambda adapter code when request handling depends on ALB routing metadata. # baseRoutePath **Kind:** Function **Source:** [`src/helper/route/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/route/index.ts#L82) **Part of:** [Helper](subsystem-src-helper) Get the basePath of the as-is route specified by routing. `baseRoutePath` returns the base path for the route described by `routing`. Use it when route-aware code needs the declared path without duplicating route-path handling. ## Signature ```ts function baseRoutePath(c: Context, index: number): string ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `index` | `number` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Routing value] --> B[baseRoutePath] B --> C[Base route path] ``` ## Usage ```ts import { baseRoutePath } from '@/helper/route'; const routing = '/articles/[slug]'; const path = baseRoutePath(routing); // Use the base route path in route-aware logic. console.log(path); ``` ## AI Coding Instructions - Pass the routing value from the route configuration rather than rebuilding its path in calling code. - Keep route parsing and base-path extraction inside `baseRoutePath`. - Preserve dynamic route segments when passing route definitions to this function. - Update callers if the routing value format changes. # ContextVariableMap **Kind:** Interface **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L57) Interface for context variable mapping. `ContextVariableMap` defines the named values stored in a context. Context writers add or update entries in the map, while context consumers read entries by variable name. ## Diagram ```mermaid graph LR Writer[Context Writer] --> Map[ContextVariableMap] Map --> Reader[Context Consumer] ``` ## Usage ```ts function readContextValue( variables: ContextVariableMap, name: string, ) { return variables[name]; } const variables: ContextVariableMap = { locale: "en-US", userName: "Alex", }; const locale = readContextValue(variables, "locale"); ``` ## AI Coding Instructions - Type dynamically keyed context values as `ContextVariableMap`. - Keep variable names consistent between context writers and consumers. - Handle missing values when reading entries from the map. - Update context creation and lookup code together when adding a new variable name. # JwtAlgorithmNotAllowed **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L85) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # RequestContext **Kind:** Constant **Source:** [`src/middleware/jsx-renderer/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jsx-renderer/index.ts#L14) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts JSXContext | null> ``` ## Value ```ts createContext(null) ``` ## Relationships - IMPORTS → `html` - IMPORTS → `html` - IMPORTS → `renderToReadableStream` # useReducer **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L245) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useReducer(reducer: (state: T, action: A) => T, initialArg: T, init: (initialState: T) => T): [T, (action: A) => void] ``` ## Parameters | Name | Type | |---|---| | `reducer` | `(state: T, action: A) => T` | | `initialArg` | `T` | | `init` | `(initialState: T) => T` | **Returns:** `[T, (action: A) => void]` # BunWebSocketData **Kind:** Interface **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L24) **Part of:** [Adapter](subsystem-src-adapter) `BunWebSocketData` stores per-connection metadata for the Bun WebSocket adapter. It keeps the WebSocket event handlers, the requested URL, and the negotiated protocol together so Bun callbacks can access connection context. ## Properties | Property | Type | |---|---| | `events` | `WSEvents` | | `url` | `URL` | | `protocol` | `string` | ## Diagram ```mermaid graph LR WS[Bun WebSocket connection] --> Data[BunWebSocketData] Data --> Events[events: WSEvents] Data --> URL[url: URL] Data --> Protocol[protocol: string] Events --> Handlers[WebSocket event handlers] ``` ## Usage ```ts import type { BunWebSocketData } from "./adapter/bun/websocket"; const connectionData: BunWebSocketData = { events: { open(ws) { ws.send("Connected"); }, message(ws, message) { ws.send(`Received: ${message}`); }, }, url: new URL("wss://example.com/chat"), protocol: "chat", }; // Pass connectionData as WebSocket adapter context where required. ``` ## AI Coding Instructions - Keep `events` bound to the `WSEvents` handlers expected by the WebSocket adapter. - Store the full `URL` object in `url`; do not replace it with a string. - Set `protocol` to the protocol selected for the connection, including an empty string when no protocol is negotiated. - Preserve this data object when forwarding Bun WebSocket callbacks so handlers receive the correct connection context. ## How it works `BunWebSocketData` is a TypeScript interface for the data attached to a Bun server WebSocket by this adapter. It has three fields: `events: WSEvents`, `url: URL`, and `protocol: string`. [src/adapter/bun/websocket.ts:24-28] - `events` holds optional `onOpen`, `onMessage`, `onClose`, and `onError` callbacks. The callback WebSocket context is typed as `WSContext` because `BunWebSocketData` uses `WSEvents` without a type argument. [src/helper/websocket/index.ts:14-19] - `url` is the parsed request URL. During an upgrade, the adapter sets it with `new URL(c.req.url)`. [src/adapter/bun/websocket.ts:61-68] - `protocol` is set to the first value from the `sec-websocket-protocol` request header after splitting on commas and trimming whitespace; it is an empty string when that header is absent. [src/adapter/bun/websocket.ts:65-68] The adapter passes a `BunWebSocketData` object as the `data` option to `server.upgrade`. [src/adapter/bun/websocket.ts:49-55] [src/adapter/bun/websocket.ts:61-69] If no Bun server is available from the context, the upgrade path throws `TypeError('env has to include the 2nd argument of fetch.')`. [src/adapter/bun/websocket.ts:49-59] When creating a `WSContext` for a connected socket, the adapter reads `ws.data.url` and `ws.data.protocol` into the context, and exposes the Bun socket itself as `raw`. [src/adapter/bun/websocket.ts:33-45] The `WSContext` constructor copies a non-null URL into a new `URL` object and maps a missing protocol to `null`; this adapter supplies both fields from `BunWebSocketData`. [src/helper/websocket/index.ts:70-77] The Bun WebSocket handler reads `ws.data.events` on `open`, `close`, and `message`, then calls the corresponding callback only when it is present. [src/adapter/bun/websocket.ts:76-103] `onOpen` receives an `Event('open')`; `onClose` receives a `CloseEvent` containing Bun’s `code` and `reason`; and `onMessage` receives a `MessageEvent` whose data is either the incoming string or `message.buffer`. [src/adapter/bun/websocket.ts:77-102] Although `WSEvents` declares `onError`, this handler has no error method and does not invoke `onError`. [src/helper/websocket/index.ts:14-19] [src/adapter/bun/websocket.ts:76-104] # CacheType **Kind:** Type **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L11) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts 'cookie' ``` # checkUserAgentEquals **Kind:** Function **Source:** [`src/helper/adapter/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/adapter/index.ts#L86) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function checkUserAgentEquals(platform: string): boolean ``` ## Parameters | Name | Type | |---|---| | `platform` | `string` | **Returns:** `boolean` # Data **Kind:** Type **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L26) Data type can be a string, ArrayBuffer, Uint8Array (buffer), or ReadableStream. `Data` represents payload content accepted by the context layer. It can hold text as a `string`, binary content as an `ArrayBuffer` or `Uint8Array`, or streaming content as a `ReadableStream`. ## Definition ```ts string | ArrayBuffer | ReadableStream | Uint8Array ``` ## Diagram ```mermaid graph LR Data[Data] --> Text[string] Data --> Buffer[ArrayBuffer] Data --> Bytes[Uint8Array] Data --> Stream[ReadableStream] ``` ## Usage ```ts import type { Data } from "./context"; function sendPayload(data: Data) { if (typeof data === "string") { return new TextEncoder().encode(data); } return data; } const text: Data = "Hello"; const bytes: Data = new Uint8Array([72, 105]); const buffer: Data = bytes.buffer; sendPayload(text); sendPayload(bytes); sendPayload(buffer); ``` ## AI Coding Instructions - Accept `Data` when an API supports text, binary buffers, or streamed payloads. - Check for `string` before handling binary or stream values. - Keep `Uint8Array` views intact when byte offsets or lengths matter. - Handle `ReadableStream` separately from in-memory data because stream content may only be read once. ## Relationships - IMPORTS → `HonoRequest` - IMPORTS → `HtmlEscapedCallbackPhase` - IMPORTS → `resolveCallback` # form **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L319) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function form(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # JwtAlgorithmNotImplemented **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L6) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `HonoJsonWebKey` — `src/utils/jwt/jws.ts`:23 # CloudFrontResponse **Kind:** Interface **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L56) **Part of:** [Adapter](subsystem-src-adapter) `CloudFrontResponse` represents the response object returned by a Lambda@Edge handler. It carries CloudFront-formatted headers and string status details that CloudFront reads when sending a response. ## Properties | Property | Type | |---|---| | `headers` | `CloudFrontHeaders` | | `status` | `string` | | `statusDescription` | `string` | ## Diagram ```mermaid graph LR Handler[Lambda Edge Handler] --> Response[CloudFrontResponse] Response --> Headers[CloudFrontHeaders] Response --> Status[status] Response --> Description[statusDescription] Response --> CloudFront[CloudFront] ``` ## Usage ```ts import type { CloudFrontHeaders, CloudFrontResponse } from './handler'; function createResponse( headers: CloudFrontHeaders, status: string, statusDescription: string, ): CloudFrontResponse { return { headers, status, statusDescription, }; } const response = createResponse( requestHeaders, responseStatus, responseDescription, ); ``` ## AI Coding Instructions - Return `CloudFrontResponse` from Lambda@Edge handlers when constructing a CloudFront response. - Keep `headers` in the `CloudFrontHeaders` format expected by CloudFront. - Set both `status` and `statusDescription` as strings. - Preserve header names and values required by the response path. ## How it works `CloudFrontResponse` is an exported TypeScript interface for the optional `response` member of a CloudFront event record’s `cf` object. [src/adapter/lambda-edge/handler.ts:56-60](src/adapter/lambda-edge/handler.ts#L56-L60) [src/adapter/lambda-edge/handler.ts:69-75](src/adapter/lambda-edge/handler.ts#L69-L75) - `headers` is required and maps header names to arrays of `{ key, value }` entries, allowing multiple values for one header name. [src/adapter/lambda-edge/handler.ts:10-17](src/adapter/lambda-edge/handler.ts#L10-L17) [src/adapter/lambda-edge/handler.ts:56-58](src/adapter/lambda-edge/handler.ts#L56-L58) - `status` is required and typed as a string. `statusDescription` is optional and typed as a string. [src/adapter/lambda-edge/handler.ts:56-60](src/adapter/lambda-edge/handler.ts#L56-L60) - It declares no body or body-encoding fields. [src/adapter/lambda-edge/handler.ts:56-60](src/adapter/lambda-edge/handler.ts#L56-L60) When `handle()` invokes the Hono application, it places the incoming event’s optional `cf.response` value in the fetch context as `response`. [src/adapter/lambda-edge/handler.ts:128-141](src/adapter/lambda-edge/handler.ts#L128-L141) The adapter does not otherwise read, validate, transform, or return that value in this file; response conversion instead operates on the `Response` returned by the application and creates a separate internal `CloudFrontResult` shape. [src/adapter/lambda-edge/handler.ts:149-162](src/adapter/lambda-edge/handler.ts#L149-L162) # ContentSecurityPolicyOptionHandler **Kind:** Type **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L15) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts (ctx: Context, directive: string) => string ``` # FormValue **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2680) ## Definition ```ts string | Blob ``` # jsxDEV **Kind:** Function **Source:** [`src/jsx/dom/jsx-dev-runtime.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/jsx-dev-runtime.ts#L10) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function jsxDEV(tag: string | Function, props: Props, key: string): JSXNode ``` ## Parameters | Name | Type | |---|---| | `tag` | `string | Function` | | `props` | `Props` | | `key` | `string` | **Returns:** `JSXNode` ## Relationships - IMPORTS → `clearCache` # JwtAlgorithmRequired **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L13) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # routePath **Kind:** Function **Source:** [`src/helper/route/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/route/index.ts#L58) **Part of:** [Helper](subsystem-src-helper) Get the route path registered within the handler `routePath` reads the route path associated with a registered handler. Use it when middleware, diagnostics, or route-aware code needs the path stored on a handler instead of rebuilding it from request data. ## Signature ```ts function routePath(c: Context, index: number): string ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | | `index` | `number` | **Returns:** `string` ## Diagram ```mermaid graph LR Handler[Registered handler] --> RoutePath[routePath] RoutePath --> Path[Registered route path] ``` ## Usage ```ts import { routePath } from './helper/route'; const registeredPath = routePath(userHandler); console.log(`Handler is registered for: ${registeredPath}`); ``` ## AI Coding Instructions - Call `routePath` with the handler that was registered with the router. - Keep route metadata attached to the handler when wrapping or composing handlers. - Do not derive the registered path from the incoming request when handler metadata is available. - Use the returned path for logging, diagnostics, or route-aware middleware behavior. # createFactory **Kind:** Function **Source:** [`src/helper/factory/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/factory/index.ts#L363) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function createFactory(init: { initApp?: InitApp defaultAppOptions?: HonoOptions }): Factory ``` ## Parameters | Name | Type | |---|---| | `init` | `{ initApp?: InitApp defaultAppOptions?: HonoOptions }` | **Returns:** `Factory` # decode **Kind:** Constant **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L189) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts Jwt.decode ``` ## Value ```ts Jwt.decode ``` # Handler **Kind:** Type **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L52) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts ( event: TEvent, context: LambdaContext, callback: Callback ) => void | Promise ``` # JwtHeaderInvalid **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L64) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # KnownResponseFormat **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2632) ## Definition ```ts 'json' | 'text' | 'redirect' ``` # shallowEqual **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L376) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function shallowEqual(a: Props, b: Props): boolean ``` ## Parameters | Name | Type | |---|---| | `a` | `Props` | | `b` | `Props` | **Returns:** `boolean` # DetectorFunction **Kind:** Type **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L194) **Part of:** [Middleware](subsystem-src-middleware) Type for detector functions `DetectorFunction` defines a function that detects the language associated with an incoming request or execution context. Language middleware calls this function to select the language value used by downstream handlers. ## Definition ```ts (c: Context, options: DetectorOptions) => string | undefined ``` ## Diagram ```mermaid graph LR Request[Incoming request] --> Detector[DetectorFunction] Detector --> Language[Detected language] Language --> Middleware[Language middleware] Middleware --> Handler[Downstream handler] ``` ## Usage ```ts import type { DetectorFunction } from "./middleware/language/language"; const detectLanguage: DetectorFunction = (request) => { const header = request.headers.get("accept-language"); if (!header) { return "en"; } return header.split(",")[0].trim(); }; // Pass detectLanguage to the language middleware configuration. ``` ## AI Coding Instructions - Keep detector functions focused on reading request or context data and returning a language value. - Return a fallback language when the expected request data is missing. - Parse headers defensively because language headers can contain multiple values and quality markers. - Keep custom detector logic compatible with the parameter and return types defined by `DetectorFunction`. # getRouterName **Kind:** Function **Source:** [`src/helper/dev/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/dev/index.ts#L76) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function getRouterName(app: Hono): string ``` ## Parameters | Name | Type | |---|---| | `app` | `Hono` | **Returns:** `string` # JwtHeaderRequiresKid **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L71) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # KVAssetOptions **Kind:** Type **Source:** [`src/adapter/cloudflare-workers/utils.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/utils.ts#L5) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts { manifest?: object | string namespace?: unknown } ``` # Layout **Kind:** Type **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L88) ## Definition ```ts (props: T) => any ``` # useActionState **Kind:** Function **Source:** [`src/jsx/dom/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/hooks/index.ts#L79) **Part of:** [Jsx](subsystem-src-jsx) This hook returns the current state and a function to update the state by form action `useActionState` stores state produced by a form action and returns that state with a function for submitting updates. Pass the returned action function to a form’s `action` prop so form data can drive the next state. ## Signature ```ts function useActionState(fn: Function, initialState: T, permalink: string): [T, Function] ``` ## Parameters | Name | Type | |---|---| | `fn` | `Function` | | `initialState` | `T` | | `permalink` | `string` | **Returns:** `[T, Function]` ## Diagram ```mermaid graph LR Form[Form submission] --> Action[Action function] Action --> Hook[useActionState] Hook --> State[Current state] Hook --> FormAction[Form action handler] FormAction --> Form ``` ## Usage ```tsx import { useActionState } from "your-library"; type FormState = { message: string; }; async function saveName( previousState: FormState, formData: FormData, ): Promise { const name = formData.get("name"); if (typeof name !== "string" || name.trim() === "") { return { message: "Enter a name." }; } await saveProfile({ name }); return { message: `Saved ${name}.` }; } export function ProfileForm() { const [state, formAction] = useActionState(saveName, { message: "", }); return (
{state.message &&

{state.message}

}
); } ``` ## AI Coding Instructions - Pass an action function that accepts the previous state and submitted form data, then returns the next state. - Keep the initial state shape aligned with every state returned by the action. - Attach the returned action function directly to a form’s `action` prop. - Validate `FormData` values before using them, since values may be missing or have an unexpected type. # Detectors **Kind:** Type **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L197) **Part of:** [Middleware](subsystem-src-middleware) Type-safe detector map `Detectors` defines the type-safe map of language detector entries used by the language middleware. It keeps detector registration aligned with the detector contract expected by the middleware. ## Definition ```ts Record ``` ## Diagram ```mermaid graph LR Middleware[Language middleware] --> Detectors[Detectors map] Detectors --> Detector[Detector entry] Detector --> Result[Detected language result] ``` ## Usage ```ts import type { Detectors } from './middleware/language/language'; const detectors: Detectors = { // Add detector entries that match the detector contract. }; export function getDetectors(): Detectors { return detectors; } ``` ## AI Coding Instructions - Keep detector map entries compatible with the detector type defined in `language.ts`. - Import `Detectors` with `import type` when it is only used for type checking. - Add new detector registrations through the typed map instead of bypassing type checks with casts. - Update middleware configuration when changing the detector map or detector registration flow. # JwtPayloadRequiresAud **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L99) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # LambdaEvent **Kind:** Type **Source:** [`src/adapter/aws-lambda/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/handler.ts#L23) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts | APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent | LatticeProxyEventV2 ``` ## Relationships - IMPORTS → `decodeBase64` - IMPORTS → `encodeBase64` # NetAddrInfo **Kind:** Type **Source:** [`src/helper/conninfo/types.ts`](https://github.com/honojs/hono/blob/main/src/helper/conninfo/types.ts#L5) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts { transport?: 'tcp' | 'udp' port?: number address?: string addressType?: AddressType } & ( | { address: string addressType: AddressType } | {} ) ``` # Next **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L35) ## Definition ```ts () => Promise ``` # useImperativeHandle **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L388) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useImperativeHandle(ref: RefObject, createHandle: () => T, deps: readonly unknown[]): void ``` ## Parameters | Name | Type | |---|---| | `ref` | `RefObject` | | `createHandle` | `() => T` | | `deps` | `readonly unknown[]` | **Returns:** `void` # DetectorType **Kind:** Type **Source:** [`src/middleware/language/language.ts`](https://github.com/honojs/hono/blob/main/src/middleware/language/language.ts#L10) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts 'path' | 'querystring' | 'cookie' | 'header' ``` ## Relationships - IMPORTS → `setCookie` - IMPORTS → `getCookie` - IMPORTS → `parseAccept` # hydrateRoot **Kind:** Function **Source:** [`src/jsx/dom/client.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/client.ts#L76) **Part of:** [Jsx](subsystem-src-jsx) Create a root object and hydrate app to the target element. In hono/jsx/dom, hydrate is equivalent to render. `hydrateRoot` creates a root object for a target DOM element and hydrates the application into that element. In `hono/jsx/dom`, hydration follows the same rendering behavior as `render`, connecting JSX output to the existing target container. ## Signature ```ts function hydrateRoot(element: HTMLElement | DocumentFragment, reactNode: Child, options: RootOptions): Root ``` ## Parameters | Name | Type | |---|---| | `element` | `HTMLElement | DocumentFragment` | | `reactNode` | `Child` | | `options` | `RootOptions` | **Returns:** `Root` ## Diagram ```mermaid graph LR App[JSX application] --> Hydrate[hydrateRoot] Target[Target DOM element] --> Hydrate Hydrate --> Root[Root object] Root --> DOM[Rendered DOM] ``` ## Usage ```tsx import { hydrateRoot } from 'hono/jsx/dom/client' import { App } from './app' const container = document.getElementById('app') if (container) { hydrateRoot(container, ) } ``` ## AI Coding Instructions - Pass the DOM element that should contain the application as the first argument. - Pass the application JSX node as the second argument. - Keep client entry code responsible for locating the target element before calling `hydrateRoot`. - Treat hydration in `hono/jsx/dom` the same way as rendering when integrating application startup code. # JwtSymmetricAlgorithmNotAllowed **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L78) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # minify **Kind:** Function **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L104) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function minify(css: string): string ``` ## Parameters | Name | Type | |---|---| | `css` | `string` | **Returns:** `string` # NotFoundResponse **Kind:** Interface **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L105) You can extend this interface to define a custom `c.notFound()` Response type. `NotFoundResponse` is a type extension point for the response returned by `c.notFound()`. Extend it through module augmentation to describe the JSON body your application returns for missing routes or resources. ## Diagram ```mermaid graph LR A[Module augmentation] --> B[NotFoundResponse] B --> C[c.notFound()] C --> D[Typed not-found response] ``` ## Usage ```ts import { Hono } from 'hono' declare module 'hono' { interface NotFoundResponse { error: 'NOT_FOUND' resource: string } } const app = new Hono() app.notFound((c) => { return c.json( { error: 'NOT_FOUND', resource: c.req.path, }, 404 ) }) app.get('/posts/:id', (c) => { const post = null if (!post) { return c.notFound() } return c.json(post) }) ``` ## AI Coding Instructions - Extend `NotFoundResponse` with module augmentation instead of replacing the interface. - Keep fields declared on `NotFoundResponse` aligned with the object returned by the configured not-found handler. - Return `c.notFound()` from routes that cannot locate a requested resource. - Define a shared not-found handler with `app.notFound()` when the application needs a consistent response body. # ServeStaticOptions **Kind:** Type **Source:** [`src/adapter/cloudflare-workers/serve-static.ts`](https://github.com/honojs/hono/blob/main/src/adapter/cloudflare-workers/serve-static.ts#L6) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts BaseServeStaticOptions & { namespace?: unknown manifest?: object | string } ``` ## Relationships - IMPORTS → `serveStatic` - IMPORTS → `getContentFromKVAsset` # CognitoIdentity **Kind:** Interface **Source:** [`src/adapter/aws-lambda/types.ts`](https://github.com/honojs/hono/blob/main/src/adapter/aws-lambda/types.ts#L3) **Part of:** [Adapter](subsystem-src-adapter) `CognitoIdentity` describes the Amazon Cognito identity attached to an AWS Lambda request. It carries the identity ID and the Cognito identity pool ID so adapter code can read the caller's Cognito context. ## Properties | Property | Type | |---|---| | `cognitoIdentityId` | `string` | | `cognitoIdentityPoolId` | `string` | ## Diagram ```mermaid graph LR Request[AWS Lambda request] --> Identity[CognitoIdentity] Identity --> IdentityId[cognitoIdentityId] Identity --> PoolId[cognitoIdentityPoolId] ``` ## Usage ```ts import type { CognitoIdentity } from './types' function getIdentityContext(identity: CognitoIdentity) { return { identityId: identity.cognitoIdentityId, poolId: identity.cognitoIdentityPoolId, } } const identity: CognitoIdentity = { cognitoIdentityId: 'identity-value', cognitoIdentityPoolId: 'pool-value', } const context = getIdentityContext(identity) ``` ## AI Coding Instructions - Keep both interface properties as strings. - Read `cognitoIdentityId` when request handling needs the Cognito caller identity. - Read `cognitoIdentityPoolId` when code needs to distinguish the originating identity pool. - Handle missing Cognito context before constructing or consuming this interface when Lambda events may be unauthenticated. ## How it works `CognitoIdentity` is an exported TypeScript interface with two required string fields: - `cognitoIdentityId`: a string. [`src/adapter/aws-lambda/types.ts:3-5`](src/adapter/aws-lambda/types.ts#L3-L5) - `cognitoIdentityPoolId`: a string. [`src/adapter/aws-lambda/types.ts:3-6`](src/adapter/aws-lambda/types.ts#L3-L6) It is used as the optional `identity` member of `LambdaContext`; a handler context may therefore omit it, or contain an object matching this interface. [`src/adapter/aws-lambda/types.ts:35-45`](src/adapter/aws-lambda/types.ts#L35-L45) The interface declares no methods, runtime validation, thrown errors, or side effects. [`src/adapter/aws-lambda/types.ts:3-6`](src/adapter/aws-lambda/types.ts#L3-L6) # directive **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L292) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /` # JwtTokenExpired **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L41) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # ParamIndexMap **Kind:** Type **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L57) Type representing a map of parameter indices. `ParamIndexMap` stores the position associated with each route parameter name. The router uses it to locate parameter values after matching a route path. ## Definition ```ts Record ``` ## Diagram ```mermaid graph LR RoutePattern[Route pattern parameters] --> ParamIndexMap[ParamIndexMap] MatchedValues[Matched parameter values] --> Lookup[Parameter lookup] ParamIndexMap --> Lookup ``` ## Usage ```ts import type { ParamIndexMap } from "./router"; const parameterNames = ["userId", "postSlug"]; const parameterIndices = Object.fromEntries( parameterNames.map((name, index) => [name, index]), ) as ParamIndexMap; function getParameter( values: readonly string[], name: string, ): string | undefined { const index = parameterIndices[name]; return index === undefined ? undefined : values[index]; } ``` ## AI Coding Instructions - Keep parameter names aligned with the names declared in route patterns. - Store indices that refer to positions in the matched parameter value list. - Check for an undefined index before reading from parameter values. - Update the map when route parsing changes the order of captured parameters. # redirectPlugin **Kind:** Function **Source:** [`src/helper/ssg/plugins.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/plugins.ts#L55) **Part of:** [Helper](subsystem-src-helper) The redirect plugin that generates HTML redirect pages for HTTP redirect responses for status codes 301, 302, 303, 307 and 308. When used with `defaultPlugin`, place `redirectPlugin` before it, because `defaultPlugin` skips non-200 responses. ```ts // ✅ Will work as expected toSSG(app, fs, { plugins: [redirectPlugin(), defaultPlugin()] }) // ❌ Will not work as expected toSSG(app, fs, { plugins: [defaultPlugin(), redirectPlugin()] }) ``` `redirectPlugin` generates HTML redirect pages for HTTP redirect responses with status codes 301, 302, 303, 307, and 308 during static site generation. Place it before `defaultPlugin`, because `defaultPlugin` skips responses that are not 200. ## Signature ```ts function redirectPlugin(): SSGPlugin ``` **Returns:** `SSGPlugin` ## Diagram ```mermaid graph LR A[Route response] --> B{Redirect status?} B -->|Yes| C[redirectPlugin] C --> D[Generate HTML redirect page] B -->|No| E[defaultPlugin] D --> E ``` ## Usage ```ts import { toSSG } from "hono/ssg" import { defaultPlugin, redirectPlugin } from "./helper/ssg/plugins" await toSSG(app, fs, { plugins: [ redirectPlugin(), defaultPlugin(), ], }) ``` ## AI Coding Instructions - Use this plugin when application routes return HTTP 301, 302, 303, 307, or 308 redirect responses. - Keep `redirectPlugin()` before `defaultPlugin()` in the `toSSG` plugin list. - Do not place `defaultPlugin()` first; it skips non-200 responses before redirect pages can be generated. - Preserve redirect response headers and destination handling when changing redirect-page generation. # useDeferredValue **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L158) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useDeferredValue(value: T, rest: [T | undefined]): T ``` ## Parameters | Name | Type | |---|---| | `value` | `T` | | `rest` | `[T | undefined]` | **Returns:** `T` # createBunWebSocket **Kind:** Function **Source:** [`src/adapter/bun/websocket.ts`](https://github.com/honojs/hono/blob/main/src/adapter/bun/websocket.ts#L110) **Part of:** [Adapter](subsystem-src-adapter) ## Signature ```ts function createBunWebSocket(): CreateWebSocket ``` **Returns:** `CreateWebSocket` # handler **Kind:** API Endpoint **Source:** [`src/middleware/body-limit/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/body-limit/index.ts#L72) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /content-length` ## Relationships - IMPORTS → `HTTPException` # JwtTokenInvalid **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L27) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # Params **Kind:** Type **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L65) Type representing a map of parameters. `Params` represents a map of parameter names to their values in the router. It is used to pass route-specific data between route matching, navigation, and handler code. ## Definition ```ts Record ``` ## Diagram ```mermaid graph LR Route[Route pattern] --> Match[Route match] Match --> Params[Params] Params --> Handler[Route handler] ``` ## Usage ```ts import type { Params } from "./router"; const params: Params = { userId: "user-value", postSlug: "post-value", }; function handleRoute(routeParams: Params) { const userId = routeParams.userId; const postSlug = routeParams.postSlug; return { userId, postSlug }; } handleRoute(params); ``` ## AI Coding Instructions - Treat `Params` as route-derived data and keep parameter names aligned with the corresponding route pattern. - Check for missing parameter values before relying on them in route handlers. - Pass `Params` through router and handler boundaries instead of creating unrelated parameter object types. - Keep parameter values in the format expected by the router before converting them for application logic. # ToSSGOptions **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L181) **Part of:** [Helper](subsystem-src-helper) `ToSSGOptions` configures static site generation in the SSG helper. It defines the output directory, request and generation hooks, concurrency, extension mappings, and plugins used during generation. ## Properties | Property | Type | |---|---| | `dir` | `string` | | `beforeRequestHook` | `BeforeRequestHook | BeforeRequestHook[]` | | `afterResponseHook` | `AfterResponseHook | AfterResponseHook[]` | | `afterGenerateHook` | `AfterGenerateHook | AfterGenerateHook[]` | | `concurrency` | `number` | | `extensionMap` | `Record` | | `plugins` | `SSGPlugin[]` | ## Diagram ```mermaid graph LR Options[ToSSGOptions] Options --> Dir[dir] Options --> Before[beforeRequestHook] Options --> AfterResponse[afterResponseHook] Options --> AfterGenerate[afterGenerateHook] Options --> Concurrency[concurrency] Options --> Extensions[extensionMap] Options --> Plugins[plugins] ``` ## Usage ```ts import type { ToSSGOptions } from './ssg' const options: ToSSGOptions = { dir: './dist', beforeRequestHook: async () => { // Run before an SSG request. }, afterResponseHook: async () => { // Run after an SSG response. }, afterGenerateHook: async () => { // Run after generated output is written. }, concurrency: 4, extensionMap: { '.html': '.html', '.json': '.json', }, plugins: [], } ``` ## AI Coding Instructions - Set `dir` to the directory where generated files should be written. - Accept either a single hook or an array of hooks for each hook field. - Keep `beforeRequestHook`, `afterResponseHook`, and `afterGenerateHook` aligned with their execution stage. - Set `extensionMap` entries to map generated source extensions to output extensions. - Pass SSG integrations through `plugins` as `SSGPlugin` instances. # useOptimistic **Kind:** Function **Source:** [`src/jsx/dom/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/hooks/index.ts#L52) **Part of:** [Jsx](subsystem-src-jsx) This hook returns the current state and a function to update the state optimistically The current state is updated optimistically and then reverted to the original state when all actions are resolved `useOptimistic` returns the current optimistic state and a function that applies an optimistic update. Updates are shown immediately while related actions are pending, then the state returns to the original value after those actions resolve. ## Signature ```ts function useOptimistic(state: T, updateState: (currentState: T, action: N) => T): [T, (action: N) => void] ``` ## Parameters | Name | Type | |---|---| | `state` | `T` | | `updateState` | `(currentState: T, action: N) => T` | **Returns:** `[T, (action: N) => void]` ## Diagram ```mermaid graph LR A[Current state] --> B[useOptimistic] B --> C[Optimistic state] D[Pending action] --> E[Apply optimistic update] E --> C D --> F[Action resolves] F --> A ``` ## Usage ```tsx import { useOptimistic } from "react"; function LikeButton({ likes }: { likes: number }) { const [optimisticLikes, addOptimisticLike] = useOptimistic( likes, (currentLikes, increment: number) => currentLikes + increment, ); async function handleLike() { addOptimisticLike(1); await fetch("/api/likes", { method: "POST", }); } return ( ); } ``` ## AI Coding Instructions - Pass the confirmed server or parent state as the base value for `useOptimistic`. - Define the update function as a pure function that derives optimistic state from the current state and action input. - Call the optimistic update function as part of the action that performs the related asynchronous work. - Do not treat optimistic state as the source of truth; update the base state when the action result is available. - Handle action failures so the surrounding state remains consistent after optimistic updates are reverted. # Callback **Kind:** Interface **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L83) **Part of:** [Adapter](subsystem-src-adapter) # createCssContext **Kind:** Function **Source:** [`src/jsx/dom/css.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/css.ts#L180) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createCssContext({ id, classNameSlug, onInvalidSlug, }: { id: Readonly classNameSlug?: ClassNameSlug onInvalidSlug?: OnInvalidSlug }): DefaultContextType ``` ## Parameters | Name | Type | |---|---| | `{ id, classNameSlug, onInvalidSlug, }` | `{ id: Readonly classNameSlug?: ClassNameSlug onInvalidSlug?: OnInvalidSlug }` | **Returns:** `DefaultContextType` # handler **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L310) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Vary` ## Relationships - IMPORTS → `cloneRawRequest` - IMPORTS → `sha256` # JwtTokenIssuer **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L57) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # ParamStash **Kind:** Type **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L61) Type representing a stash of parameters. `ParamStash` represents the parameters collected during router matching. It acts as the typed value passed between route matching logic and code that handles the matched route. ## Definition ```ts string[] ``` ## Diagram ```mermaid graph LR Route[Route match] --> Stash[ParamStash] Stash --> Handler[Route handler] ``` ## Usage ```ts import type { ParamStash } from "./router"; function handleMatchedRoute(params: ParamStash): ParamStash { // Pass the matched parameter stash to downstream route logic. return params; } ``` ## AI Coding Instructions - Import `ParamStash` with `import type` when it is only used for TypeScript annotations. - Keep parameter collection and parameter consumption typed as `ParamStash` at router boundaries. - Do not replace `ParamStash` with an untyped object when forwarding matched route parameters. - Update route matching code and handler signatures together when the parameter stash shape changes. # UpgradeWebSocket **Kind:** Interface **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L24) **Part of:** [Helper](subsystem-src-helper) Upgrade WebSocket Type `UpgradeWebSocket` names the contract used by the WebSocket helper when an HTTP request is upgraded to a WebSocket connection. Code can accept or pass this interface without depending on a concrete upgrade implementation. ## Diagram ```mermaid graph LR Request[HTTP Request] --> Upgrade[UpgradeWebSocket] Upgrade --> Connection[WebSocket Connection] Connection --> Handler[Application Handler] ``` ## Usage ```ts import type { UpgradeWebSocket } from './helper/websocket' function registerUpgrade( upgrade: UpgradeWebSocket, ): UpgradeWebSocket { return upgrade } declare const platformUpgrade: UpgradeWebSocket const upgrade = registerUpgrade(platformUpgrade) ``` ## AI Coding Instructions - Import `UpgradeWebSocket` with `import type` when it is only used for type checking. - Pass implementations through this interface instead of depending on platform-specific upgrade objects. - Do not assume members or behavior that are not declared by the interface. - Keep HTTP-to-WebSocket upgrade handling near the WebSocket helper integration. # CloudFrontEdgeEvent **Kind:** Interface **Source:** [`src/adapter/lambda-edge/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/lambda-edge/handler.ts#L77) **Part of:** [Adapter](subsystem-src-adapter) `CloudFrontEdgeEvent` represents the event payload received by the Lambda@Edge adapter. It groups CloudFront event records under `Records`, allowing the handler to access request, response, and distribution data from each `CloudFrontEvent`. ## Properties | Property | Type | |---|---| | `Records` | `CloudFrontEvent[]` | ## Diagram ```mermaid graph LR Edge[CloudFrontEdgeEvent] --> Records[Records] Records --> Event[CloudFrontEvent] Event --> Request[CloudFront Request] Event --> Response[CloudFront Response] ``` ## Usage ```ts import type { CloudFrontEdgeEvent } from './handler' export const handleEdgeEvent = (event: CloudFrontEdgeEvent) => { for (const record of event.Records) { const request = record.cf.request console.log(request.uri) } } ``` ## AI Coding Instructions - Treat `Records` as the source of CloudFront event data and iterate over its entries when processing events. - Read request and response fields from each record's `cf` property rather than assuming event data exists at the root level. - Keep Lambda@Edge request and response mutations compatible with the CloudFront event shape. - Preserve the `CloudFrontEdgeEvent` type at adapter boundaries so handlers receive typed event records. ## How it works `CloudFrontEdgeEvent` is an exported TypeScript interface for the Lambda@Edge event shape accepted by this adapter. It declares one required property, `Records`, containing an array of CloudFront event records. [src/adapter/lambda-edge/handler.ts:77-79] Each record has a `cf` object containing: - `config`: distribution domain name, distribution ID, event type, and request ID. [src/adapter/lambda-edge/handler.ts:62-75] - `request`: client IP, headers, HTTP method, query string, URI, and optional body and origin data. [src/adapter/lambda-edge/handler.ts:41-54] - Optional `response`: headers, status, and optional status description. [src/adapter/lambda-edge/handler.ts:56-60] [src/adapter/lambda-edge/handler.ts:69-75] The Lambda@Edge `handle()` adapter accepts this type as its event argument. It reads only `Records[0]`: it passes that record’s config, request, and optional response into the Hono request environment, then constructs a Fetch `Request` from that record’s request data. [src/adapter/lambda-edge/handler.ts:120-145] [src/adapter/lambda-edge/handler.ts:164-195] For request construction, the adapter takes the first `host` header value when present, otherwise the distribution domain name; combines it with the request URI and optional query string; appends every declared request-header value; and derives a body from the record’s optional body data. [src/adapter/lambda-edge/handler.ts:164-189] Base64 body data is decoded, while `GET` and `HEAD` requests have no body. [src/adapter/lambda-edge/handler.ts:198-212] `getConnInfo()` also expects this event in the context bindings and maps `Records[0].cf.request.clientIp` to the remote address. [src/adapter/lambda-edge/conninfo.ts:5-15] The interface is re-exported from the Lambda@Edge adapter entry point. [src/adapter/lambda-edge/index.ts:6-14] There is no runtime validation of the event structure in the shown adapter code. In particular, it directly indexes `Records[0]`, so a usable runtime event must contain a first record with the nested fields read by the handler or connection-info helper. [src/adapter/lambda-edge/handler.ts:128-141] [src/adapter/lambda-edge/handler.ts:164-179] [src/adapter/lambda-edge/conninfo.ts:11-15] # handler **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L310) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Vary` ## Relationships - IMPORTS → `cloneRawRequest` - IMPORTS → `sha256` # JwtTokenNotBefore **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L34) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # memo **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L406) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function memo(component: FC, propsAreEqual: (prevProps: Readonly, nextProps: Readonly) => boolean): FC ``` ## Parameters | Name | Type | |---|---| | `component` | `FC` | | `propsAreEqual` | `(prevProps: Readonly, nextProps: Readonly) => boolean` | **Returns:** `FC` # ParsedFormValue **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2681) ## Definition ```ts string | File ``` # SSG_DISABLED_RESPONSE **Kind:** Constant **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L13) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts (() => { try { return new Response('SSG is disabled', { status: 404, headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: 'true' }, }) } catch { return null } })() as Response ``` ## Value ```ts (() => { try { return new Response('SSG is disabled', { status: 404, headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: 'true' }, }) } catch { return null } })() as Response ``` # defaultExtensionMap **Kind:** Constant **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L90) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts Record ``` ## Value ```ts { 'text/html': 'html', 'text/xml': 'xml', 'application/xml': 'xml', 'application/atom+xml': 'xml', 'application/rss+xml': 'xml', 'application/yaml': 'yaml', } ``` # flushSync **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L801) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function flushSync(callback: () => void): void ``` ## Parameters | Name | Type | |---|---| | `callback` | `() => void` | **Returns:** `void` # HandleOptions **Kind:** Type **Source:** [`src/adapter/service-worker/handler.ts`](https://github.com/honojs/hono/blob/main/src/adapter/service-worker/handler.ts#L11) **Part of:** [Adapter](subsystem-src-adapter) ## Definition ```ts { fetch?: typeof fetch } ``` # handler **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L310) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Vary` ## Relationships - IMPORTS → `cloneRawRequest` - IMPORTS → `sha256` # JwtTokenSignatureMismatched **Kind:** Class **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L92) **Part of:** [Utils](subsystem-src-utils) **Extends:** `Error` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # RemoveQuestion **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2729) ## Definition ```ts T extends `${infer R}?` ? R : T ``` # disableSSG **Kind:** Function **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L63) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function disableSSG(): MiddlewareHandler ``` **Returns:** `MiddlewareHandler` # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # link **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L298) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function link(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # Renderer **Kind:** Type **Source:** [`src/context.ts`](https://github.com/honojs/hono/blob/main/src/context.ts#L78) Renderer type which can either be a ContextRenderer or DefaultRenderer. `Renderer` represents a rendering callback accepted by the context system. It can be either a `ContextRenderer`, which receives context data, or a `DefaultRenderer`, which renders without context. ## Definition ```ts ContextRenderer extends Function ? ContextRenderer : DefaultRenderer ``` ## Diagram ```mermaid graph LR Renderer[Renderer] --> ContextRenderer[ContextRenderer] Renderer --> DefaultRenderer[DefaultRenderer] ContextRenderer --> Context[Context data] DefaultRenderer --> Output[Rendered output] ContextRenderer --> Output ``` ## Usage ```ts import type { Renderer } from "./context"; const fallbackRenderer: Renderer = () => { return "No context available"; }; function registerRenderer(renderer: Renderer) { return renderer; } registerRenderer(fallbackRenderer); ``` ## AI Coding Instructions - Treat `Renderer` as a union of `ContextRenderer` and `DefaultRenderer`. - Use a context-aware callback when rendering depends on context data. - Use a default callback when rendering does not require context data. - Avoid calling a `Renderer` directly unless the active renderer variant is known. - Keep renderer return values compatible with the output expected by the surrounding context API. # tryDecodeURI **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L104) **Part of:** [Utils](subsystem-src-utils) Try to apply decodeURI() to given string. If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible. `tryDecodeURI` attempts to decode a URI string with `decodeURI()`. If decoding fails because the input contains invalid percent encoding or invalid UTF-8 sequences, it skips the invalid data and decodes the remaining portions where possible. ## Signature ```ts function tryDecodeURI(str: string): string ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | **Returns:** `string` ## Diagram ```mermaid graph LR Input[URI string] --> Decode[Attempt decodeURI] Decode -->|Success| Result[Return decoded string] Decode -->|Failure| Recover[Skip invalid encoding data] Recover --> Partial[Decode remaining portions] Partial --> Result ``` ## Usage ```ts import { tryDecodeURI } from './utils/url'; const value = 'https://example.com/search?q=hello%20world%ZZ'; const decoded = tryDecodeURI(value); console.log(decoded); // https://example.com/search?q=hello world%ZZ ``` ## AI Coding Instructions - Keep this helper focused on tolerant URI decoding behavior. - Use `decodeURI()` rather than `decodeURIComponent()` so URI delimiters retain their expected handling. - Do not throw when malformed percent encoding or invalid UTF-8 data is present. - Preserve undecodable input data while decoding portions that can be decoded. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `ServeStaticOptions` — `src/middleware/serve-static/index.ts`:13 # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # INVALID_IP_ADDRESS_ERROR_CODE **Kind:** Constant **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L41) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 'ERR_INVALID_IP_ADDRESS' ``` ## Value ```ts 'ERR_INVALID_IP_ADDRESS' ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `IPRestrictionRule` — `src/middleware/ip-restriction/index.ts`:38 # ResponseFormat **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L2633) ## Definition ```ts KnownResponseFormat | string ``` # script **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L136) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function script({ children, ...props }) ``` ## Parameters | Name | Type | |---|---| | `{ children, ...props }` | `any` | # ToSSGInterface **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L341) **Part of:** [Helper](subsystem-src-helper) # ConnInfo **Kind:** Interface **Source:** [`src/helper/conninfo/types.ts`](https://github.com/honojs/hono/blob/main/src/helper/conninfo/types.ts#L35) **Part of:** [Helper](subsystem-src-helper) HTTP Connection information `ConnInfo` describes HTTP connection metadata associated with an incoming request. It currently exposes the remote endpoint address through the `remote` field, represented by `NetAddrInfo`. ## Properties | Property | Type | |---|---| | `remote` | `NetAddrInfo` | ## Diagram ```mermaid graph LR Request[Incoming HTTP Request] --> ConnInfo[ConnInfo] ConnInfo --> Remote[remote: NetAddrInfo] ``` ## Usage ```ts import type { ConnInfo } from "./helper/conninfo/types.ts"; function logRemoteAddress(connInfo: ConnInfo) { console.log("Remote address:", connInfo.remote); } // `connInfo` is typically provided by the HTTP server runtime. function handleRequest(request: Request, connInfo: ConnInfo) { logRemoteAddress(connInfo); return new Response("OK"); } ``` ## AI Coding Instructions - Treat `ConnInfo` as request-scoped metadata supplied by the HTTP server layer. - Read the client endpoint from `connInfo.remote`; do not infer it from request headers. - Keep `ConnInfo` fields typed with connection-related types such as `NetAddrInfo`. - Pass `ConnInfo` through handlers when request logic needs remote connection details. # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # Result **Kind:** Type **Source:** [`src/router.ts`](https://github.com/honojs/hono/blob/main/src/router.ts#L98) Type representing the result of a route match. The result can be in one of two formats: 1. An array of handlers with their corresponding parameter index maps, followed by a parameter stash. 2. An array of handlers with their corresponding parameter maps. Example: [[handler, paramIndexMap][], paramArray] ```typescript [ [ [middlewareA, {}], // '*' [funcA, {'id': 0}], // '/user/:id/*' [funcB, {'id': 0, 'action': 1}], // '/user/:id/:action' ], ['123', 'abc'] ] ``` [[handler, params][]] ```typescript [ [ [middlewareA, {}], // '*' [funcA, {'id': '123'}], // '/user/:id/*' [funcB, {'id': '123', 'action': 'abc'}], // '/user/:id/:action' ] ] ``` `Result` represents the output of a route match in the router. It associates matched handlers with either parameter index maps plus a shared parameter array, or with parameter maps containing resolved parameter values. ## Definition ```ts [[T, ParamIndexMap][], ParamStash] | [[T, Params][]] ``` ## Diagram ```mermaid graph LR Match[Route match] --> Result[Result] Result --> Indexed[Handler/index-map pairs + parameter stash] Result --> Resolved[Handler/resolved-params pairs] Indexed --> Handlers[Handler entries] Indexed --> Stash[Parameter array] Resolved --> Params[Parameter maps] ``` ## Usage ```ts import type { Result } from './router' const result: Result = [ [ [middlewareA, {}], [funcA, { id: 0 }], [funcB, { id: 0, action: 1 }], ], ['123', 'abc'], ] // Resolve an indexed parameter map for a matched handler. const [, paramIndexes] = result[0][1] const params = Object.fromEntries( Object.entries(paramIndexes).map(([name, index]) => [ name, result[1][index], ]) ) // params is { id: '123' } ``` ## AI Coding Instructions - Preserve the handler ordering in `Result`; handlers run in route-match order. - When working with the indexed format, read parameter values from the shared parameter stash using each map's index. - Do not treat index-map values as parameter values; they point into the parameter array. - Support the resolved format when consuming match results, where parameter maps already contain string values. - Keep handler and parameter-map entries paired when transforming route match results. # style **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L284) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function style(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # utf8Decoder **Kind:** Constant **Source:** [`src/utils/jwt/utf8.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/utf8.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts TextDecoder ``` ## Value ```ts new TextDecoder() ``` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `TokenHeader` — `src/utils/jwt/jwt.ts`:38 # createHash **Kind:** Function **Source:** [`src/utils/crypto.ts`](https://github.com/honojs/hono/blob/main/src/utils/crypto.ts#L33) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function createHash(data: Data, algorithm: Algorithm): Promise ``` ## Parameters | Name | Type | |---|---| | `data` | `Data` | | `algorithm` | `Algorithm` | **Returns:** `Promise` # CssClassName **Kind:** Interface **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L13) **Part of:** [Helper](subsystem-src-helper) `CssClassName` describes a CSS class definition and its related selector data. It stores the selector text, generated class name, CSS style string, nested selector entries, and external class names that should be associated with the class. ## Properties | Property | Type | |---|---| | `[SELECTOR]` | `string` | | `[CLASS_NAME]` | `string` | | `[STYLE_STRING]` | `string` | | `[SELECTORS]` | `CssClassName[]` | | `[EXTERNAL_CLASS_NAMES]` | `string[]` | ## Diagram ```mermaid graph LR CssClassName[CssClassName] CssClassName --> Selector[SELECTOR: string] CssClassName --> ClassName[CLASS_NAME: string] CssClassName --> StyleString[STYLE_STRING: string] CssClassName --> Selectors[SELECTORS: CssClassName[]] CssClassName --> ExternalClassNames[EXTERNAL_CLASS_NAMES: string[]] Selectors --> NestedSelector[CssClassName] ``` ## Usage ```ts import type { CssClassName } from "./helper/css/common"; const buttonClass: CssClassName = { SELECTOR: ".button", CLASS_NAME: "button", STYLE_STRING: "background: blue; color: white;", SELECTORS: [ { SELECTOR: ".button:hover", CLASS_NAME: "button-hover", STYLE_STRING: "background: navy;", SELECTORS: [], EXTERNAL_CLASS_NAMES: [], }, ], EXTERNAL_CLASS_NAMES: ["btn", "btn-primary"], }; console.log(buttonClass.SELECTOR); console.log(buttonClass.SELECTORS[0].STYLE_STRING); ``` ## AI Coding Instructions - Populate every `CssClassName` field when creating an object; use empty arrays when no nested selectors or external class names exist. - Store CSS selector text in `SELECTOR` and the emitted class token in `CLASS_NAME`; do not treat them as interchangeable. - Add nested or related selector definitions to `SELECTORS` using the same `CssClassName` shape. - Keep `STYLE_STRING` as the CSS declaration content associated with the selector. - Add class names from outside the generated CSS flow to `EXTERNAL_CLASS_NAMES`. # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # title **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L257) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function title(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # Variables **Kind:** Type **Source:** [`src/types.ts`](https://github.com/honojs/hono/blob/main/src/types.ts#L27) ## Definition ```ts object ``` # equal **Kind:** Function **Source:** [`src/utils/buffer.ts`](https://github.com/honojs/hono/blob/main/src/utils/buffer.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function equal(a: ArrayBuffer, b: ArrayBuffer): boolean ``` ## Parameters | Name | Type | |---|---| | `a` | `ArrayBuffer` | | `b` | `ArrayBuffer` | **Returns:** `boolean` ## Relationships - IMPORTS → `sha256` # form **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L182) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function form(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # isSSGContext **Kind:** Function **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L56) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function isSSGContext(c: Context): boolean ``` ## Parameters | Name | Type | |---|---| | `c` | `Context` | **Returns:** `boolean` # getFilePathWithoutDefaultDocument **Kind:** Function **Source:** [`src/utils/filepath.ts`](https://github.com/honojs/hono/blob/main/src/utils/filepath.ts#L32) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getFilePathWithoutDefaultDocument(options: Omit): string | undefined ``` ## Parameters | Name | Type | |---|---| | `options` | `Omit` | **Returns:** `string | undefined` # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # knownUserAgents **Kind:** Constant **Source:** [`src/helper/adapter/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/adapter/index.ts#L43) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts Partial> ``` ## Value ```ts { deno: 'Deno', bun: 'Bun', workerd: 'Cloudflare-Workers', node: 'Node.js', } ``` # render **Kind:** Function **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L796) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function render(jsxNode: Child, container: Container): void ``` ## Parameters | Name | Type | |---|---| | `jsxNode` | `Child` | | `container` | `Container` | **Returns:** `void` # handler **Kind:** API Endpoint **Source:** [`src/middleware/compress/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/compress/index.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Cache-Control` ## Relationships - IMPORTS → `parseAccept` - IMPORTS → `COMPRESSIBLE_CONTENT_TYPE_REGEX` # onlySSG **Kind:** Function **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L77) **Part of:** [Helper](subsystem-src-helper) ## Signature ```ts function onlySSG(): MiddlewareHandler ``` **Returns:** `MiddlewareHandler` # RequestHeader **Kind:** Type **Source:** [`src/utils/headers.ts`](https://github.com/honojs/hono/blob/main/src/utils/headers.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts | 'A-IM' | 'Accept' | 'Accept-Additions' | 'Accept-CH' | 'Accept-Charset' | 'Accept-Datetime' | 'Accept-Encoding' | 'Accept-Features' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Query' | 'Accept-Ranges' | 'Accept-Signature' | 'Access-Control' | 'Access-Control-Allow-Credentials' | 'Access-Control-Allow-Headers' | 'Access-Control-Allow-Methods' | 'Access-Control-Allow-Origin' | 'Access-Control-Expose-Headers' | 'Access-Control-Max-Age' | 'Access-Control-Request-Headers' | 'Access-Control-Request-Method' | 'Activate-Storage-Access' | 'Age' | 'Allow' | 'ALPN' | 'Alt-Svc' | 'Alt-Used' | 'Alternates' | 'AMP-Cache-Transform' | 'Apply-To-Redirect-Ref' | 'Authentication-Control' | 'Authentication-Info' | 'Authorization' | 'Available-Dictionary' | 'C-Ext' | 'C-Man' | 'C-Opt' | 'C-PEP' | 'C-PEP-Info' | 'Cache-Control' | 'Cache-Group-Invalidation' | 'Cache-Groups' | 'Cache-Status' | 'Cal-Managed-ID' | 'CalDAV-Timezones' | 'Capsule-Protocol' | 'CDN-Cache-Control' | 'CDN-Loop' | 'Cert-Not-After' | 'Cert-Not-Before' | 'Clear-Site-Data' | 'Client-Cert' | 'Client-Cert-Chain' | 'Close' | 'CMCD-Object' | 'CMCD-Request' | 'CMCD-Session' | 'CMCD-Status' | 'CMSD-Dynamic' | 'CMSD-Static' | 'Concealed-Auth-Export' | 'Configuration-Context' | 'Connection' | 'Content-Base' | 'Content-Digest' | 'Content-Disposition' | 'Content-Encoding' | 'Content-ID' | 'Content-Language' | 'Content-Length' | 'Content-Location' | 'Content-MD5' | 'Content-Range' | 'Content-Script-Type' | 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only' | 'Content-Style-Type' | 'Content-Type' | 'Content-Version' | 'Cookie' | 'Cookie2' | 'Cross-Origin-Embedder-Policy' | 'Cross-Origin-Embedder-Policy-Report-Only' | 'Cross-Origin-Opener-Policy' | 'Cross-Origin-Opener-Policy-Report-Only' | 'Cross-Origin-Resource-Policy' | 'CTA-Common-Access-Token' | 'DASL' | 'Date' | 'DAV' | 'Default-Style' | 'Delta-Base' | 'Deprecation' | 'Depth' | 'Derived-From' | 'Destination' | 'Detached-JWS' | 'Differential-ID' | 'Dictionary-ID' | 'Digest' | 'DPoP' | 'DPoP-Nonce' | 'Early-Data' | 'EDIINT-Features' | 'ETag' | 'Expect' | 'Expect-CT' | 'Expires' | 'Ext' | 'Forwarded' | 'From' | 'GetProfile' | 'Hobareg' | 'Host' | 'HTTP2-Settings' | 'If' | 'If-Match' | 'If-Modified-Since' | 'If-None-Match' | 'If-Range' | 'If-Schedule-Tag-Match' | 'If-Unmodified-Since' | 'IM' | 'Include-Referred-Token-Binding-ID' | 'Incremental' | 'Isolation' | 'Keep-Alive' | 'Label' | 'Last-Event-ID' | 'Last-Modified' | 'Link' | 'Link-Template' | 'Location' | 'Lock-Token' | 'Man' | 'Max-Forwards' | 'Memento-Datetime' | 'Meter' | 'Method-Check' | 'Method-Check-Expires' | 'MIME-Version' | 'Negotiate' | 'NEL' | 'OData-EntityId' | 'OData-Isolation' | 'OData-MaxVersion' | 'OData-Version' | 'Opt' | 'Optional-WWW-Authenticate' | 'Ordering-Type' | 'Origin' | 'Origin-Agent-Cluster' | 'OSCORE' | 'OSLC-Core-Version' | 'Overwrite' | 'P3P' | 'PEP' | 'PEP-Info' | 'Permissions-Policy' | 'PICS-Label' | 'Ping-From' | 'Ping-To' | 'Position' | 'Pragma' | 'Prefer' | 'Preference-Applied' | 'Priority' | 'ProfileObject' | 'Protocol' | 'Protocol-Info' | 'Protocol-Query' | 'Protocol-Request' | 'Proxy-Authenticate' | 'Proxy-Authentication-Info' | 'Proxy-Authorization' | 'Proxy-Features' | 'Proxy-Instruction' | 'Proxy-Status' | 'Public' | 'Public-Key-Pins' | 'Public-Key-Pins-Report-Only' | 'Range' | 'Redirect-Ref' | 'Referer' | 'Referer-Root' | 'Referrer-Policy' | 'Refresh' | 'Repeatability-Client-ID' | 'Repeatability-First-Sent' | 'Repeatability-Request-ID' | 'Repeatability-Result' | 'Replay-Nonce' | 'Reporting-Endpoints' | 'Repr-Digest' | 'Retry-After' | 'Safe' | 'Schedule-Reply' | 'Schedule-Tag' | 'Sec-Fetch-Dest' | 'Sec-Fetch-Mode' | 'Sec-Fetch-Site' | 'Sec-Fetch-Storage-Access' | 'Sec-Fetch-User' | 'Sec-GPC' | 'Sec-Purpose' | 'Sec-Token-Binding' | 'Sec-WebSocket-Accept' | 'Sec-WebSocket-Extensions' | 'Sec-WebSocket-Key' | 'Sec-WebSocket-Protocol' | 'Sec-WebSocket-Version' | 'Security-Scheme' | 'Server' | 'Server-Timing' | 'Set… ``` # Root **Kind:** Interface **Source:** [`src/jsx/dom/client.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/client.ts#L11) **Part of:** [Jsx](subsystem-src-jsx) `Root` represents a mounted JSX DOM tree created by the client renderer. It exposes methods to render the tree and to remove the mounted tree from its container. ## Diagram ```mermaid graph LR App[JSX application] --> Root[Root] Root --> Render[render()] Root --> Unmount[unmount()] Render --> DOM[DOM container] Unmount --> DOM ``` ## Usage ```ts import { createRoot } from "./jsx/dom/client"; const container = document.getElementById("app"); if (!container) { throw new Error("Missing app container"); } const root = createRoot(container); root.render(); window.addEventListener("beforeunload", () => { root.unmount(); }); ``` ## AI Coding Instructions - Call `render()` after creating a `Root` to mount or update its JSX DOM tree. - Call `unmount()` when the owning application or view is removed. - Keep the `Root` instance associated with the DOM container it was created for. - Do not call `render()` after `unmount()` unless the client renderer supports remounting. ## How it works `Root` is the interface for the object returned by `createRoot`. It has two void-returning lifecycle methods: `render(children: Child)` and `unmount()` ([src/jsx/dom/client.ts:11-14](src/jsx/dom/client.ts#L11-L14)). `Child` includes strings, numbers, JSX nodes, `null`, `undefined`, booleans, promises of strings, and nested child arrays ([src/jsx/base.ts:162-170](src/jsx/base.ts#L162-L170)). - **Creation:** `createRoot` accepts an `HTMLElement` or `DocumentFragment` render target and returns a `Root` ([src/jsx/dom/client.ts:23-26](src/jsx/dom/client.ts#L23-L26)). Passing a non-empty options object writes `createRoot options are not supported yet` to `console.warn` ([src/jsx/dom/client.ts:33-35](src/jsx/dom/client.ts#L33-L35)). - **`render(children)`:** On its first call, the root creates a function node whose state is initialized from the passed value; it retains that state setter for later calls ([src/jsx/dom/client.ts:47-58](src/jsx/dom/client.ts#L47-L58)). The DOM renderer builds this node, applies it into a `DocumentFragment`, then replaces every child of the target container with that fragment ([src/jsx/dom/render.ts:783-794](src/jsx/dom/render.ts#L783-L794)). On later calls, `render` passes the new value to the retained state setter ([src/jsx/dom/client.ts:43-45](src/jsx/dom/client.ts#L43-L45)); the setter changes state only when the new value is not `Object.is`-equal to the current value and then schedules an update ([src/jsx/hooks/index.ts:199-240](src/jsx/hooks/index.ts#L199-L240)). - **`unmount()`:** If the root has rendered, `unmount` calls its stored state setter with `null`, then marks the root as unmounted ([src/jsx/dom/client.ts:61-64](src/jsx/dom/client.ts#L61-L64)). A later `render` call throws `Error('Cannot update an unmounted root')` ([src/jsx/dom/client.ts:38-42](src/jsx/dom/client.ts#L38-L42)). Calling `unmount` before the first render does not invoke a setter, but still marks the root unmounted ([src/jsx/dom/client.ts:27-31](src/jsx/dom/client.ts#L27-L31), [src/jsx/dom/client.ts:61-64](src/jsx/dom/client.ts#L61-L64)). ## Relationships - IMPORTS → `useState` - IMPORTS → `buildNode` - IMPORTS → `renderNode` # handler **Kind:** API Endpoint **Source:** [`src/middleware/cors/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cors/index.ts#L141) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /Content-Type` # script **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L272) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function script(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # SSEMessage **Kind:** Interface **Source:** [`src/helper/streaming/sse.ts`](https://github.com/honojs/hono/blob/main/src/helper/streaming/sse.ts#L6) **Part of:** [Helper](subsystem-src-helper) `SSEMessage` defines the fields of a Server-Sent Events message emitted by the streaming helper. It carries event payload data, an event name, a message identifier, and an optional retry delay value; `data` may be a string or a promise that resolves to a string. ## Properties | Property | Type | |---|---| | `data` | `string | Promise` | | `event` | `string` | | `id` | `string` | | `retry` | `number` | ## Diagram ```mermaid graph LR SSEMessage --> data["data: string | Promise"] SSEMessage --> event["event: string"] SSEMessage --> id["id: string"] SSEMessage --> retry["retry: number"] data --> SSEStream["Server-Sent Events stream"] event --> SSEStream id --> SSEStream retry --> SSEStream ``` ## Usage ```ts import type { SSEMessage } from "./helper/streaming/sse"; const message: SSEMessage = { data: Promise.resolve(JSON.stringify({ status: "complete" })), event: "update", id: "message-1", retry: 3000, }; const body = await message.data; console.log(message.event, message.id, message.retry, body); ``` ## AI Coding Instructions - Set `data` to a string when the payload is already available, or to `Promise` when payload creation is asynchronous. - Serialize object payloads before assigning them to `data`; the interface accepts only string data. - Keep `event` aligned with the event names expected by SSE consumers. - Use `id` values that let clients identify or resume from a streamed message. - Treat `retry` as the client reconnection delay value for the SSE message. ## Relationships - IMPORTS → `HtmlEscapedCallbackPhase` - IMPORTS → `resolveCallback` - IMPORTS → `StreamingApi` - IMPORTS → `isOldBunVersion` # tryDecode **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L81) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function tryDecode(str: string, decoder: Decoder): string ``` ## Parameters | Name | Type | |---|---| | `str` | `string` | | `decoder` | `Decoder` | **Returns:** `string` # expandIPv6 **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L13) **Part of:** [Utils](subsystem-src-utils) Expand IPv6 Address `expandIPv6` expands an IPv6 address that uses compressed notation into its expanded colon-separated form. It is used by IP address handling code when later operations need each address segment represented explicitly. ## Signature ```ts function expandIPv6(ipV6: string): string ``` ## Parameters | Name | Type | |---|---| | `ipV6` | `string` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Compressed IPv6 address] --> B[expandIPv6] B --> C[Split address segments] C --> D[Expand omitted segments] D --> E[Expanded IPv6 address] ``` ## Usage ```ts import { expandIPv6 } from './utils/ipaddr'; const address = 'a::b'; const expandedAddress = expandIPv6(address); console.log(expandedAddress); ``` ## AI Coding Instructions - Pass IPv6 address strings to `expandIPv6` before code that requires explicit address segments. - Keep compressed-address handling inside this utility rather than duplicating expansion logic in callers. - Preserve colon-separated IPv6 formatting when changing this function. - Check how callers handle invalid or already-expanded addresses before changing return behavior. # handler **Kind:** API Endpoint **Source:** [`src/middleware/cors/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cors/index.ts#L141) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /Content-Type` # style **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L151) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function style({ children, ...props }) ``` ## Parameters | Name | Type | |---|---| | `{ children, ...props }` | `any` | # ToSSGAdaptorInterface **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L355) **Part of:** [Helper](subsystem-src-helper) # getFilePath **Kind:** Function **Source:** [`src/utils/filepath.ts`](https://github.com/honojs/hono/blob/main/src/utils/filepath.ts#L12) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getFilePath(options: FilePathOptions): string | undefined ``` ## Parameters | Name | Type | |---|---| | `options` | `FilePathOptions` | **Returns:** `string | undefined` # handler **Kind:** API Endpoint **Source:** [`src/middleware/etag/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/etag/index.ts#L97) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /ETag` ## Relationships - IMPORTS → `generateDigest` # useInsertionEffect **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L294) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useInsertionEffect(effect: () => void | (() => void), deps: readonly unknown[]): void ``` ## Parameters | Name | Type | |---|---| | `effect` | `() => void | (() => void)` | | `deps` | `readonly unknown[]` | **Returns:** `void` # WSEvents **Kind:** Interface **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L14) **Part of:** [Helper](subsystem-src-helper) WebSocket Event Listeners type `WSEvents` defines the event listener callbacks for a WebSocket connection. Each callback receives the browser event and a `WSContext` instance so handlers can inspect or update connection-specific state. ## Properties | Property | Type | |---|---| | `onOpen` | `(evt: Event, ws: WSContext) => void` | | `onMessage` | `(evt: MessageEvent, ws: WSContext) => void` | | `onClose` | `(evt: CloseEvent, ws: WSContext) => void` | | `onError` | `(evt: Event, ws: WSContext) => void` | ## Diagram ```mermaid graph LR WebSocket -->|open| onOpen WebSocket -->|message| onMessage WebSocket -->|close| onClose WebSocket -->|error| onError onOpen --> WSContext onMessage --> WSContext onClose --> WSContext onError --> WSContext ``` ## Usage ```ts import type { WSEvents } from "./helper/websocket"; type ConnectionState = { userId: string; }; const events: WSEvents = { onOpen(_evt, ws) { console.log("WebSocket connected", ws); }, onMessage(evt, ws) { console.log("Received message:", evt.data); console.log("Connection state:", ws); }, onClose(evt, ws) { console.log("WebSocket closed:", evt.code, evt.reason); console.log("Connection state:", ws); }, onError(evt, ws) { console.error("WebSocket error:", evt); console.log("Connection state:", ws); }, }; ``` ## AI Coding Instructions - Keep each handler compatible with its declared browser event type and the shared `WSContext` type. - Read incoming payloads from `evt.data` in `onMessage`; do not assume the payload format without checking `WSMessageReceive`. - Use `onClose` to handle close codes and cleanup related connection state. - Use `onError` for logging or recovery logic, but do not assume it includes close details. - Pass the `WSEvents` object to the WebSocket setup code that accepts event listeners. # Accept **Kind:** Interface **Source:** [`src/helper/accepts/accepts.ts`](https://github.com/honojs/hono/blob/main/src/helper/accepts/accepts.ts#L5) **Part of:** [Helper](subsystem-src-helper) `Accept` represents a parsed accepted media type, including its type string, media parameters, and quality value. It can be used by content negotiation helpers when comparing client preferences against available response formats. ## Properties | Property | Type | |---|---| | `type` | `string` | | `params` | `Record` | | `q` | `number` | ## Diagram ```mermaid graph LR Header[Accept header entry] --> Accept[Accept] Accept --> Type[type: string] Accept --> Params[params: Record] Accept --> Quality[q: number] ``` ## Usage ```ts import type { Accept } from "./helper/accepts/accepts"; const requestedQuality = "0.9"; const acceptedType: Accept = { type: "application/json", params: { charset: "utf-8", }, q: Number.parseFloat(requestedQuality), }; if (acceptedType.type === "application/json") { console.log(`Serving ${acceptedType.type}`); } ``` ## AI Coding Instructions - Keep `type` as the parsed media type, such as `application/json`. - Store media-type parameters in `params` as string values. - Preserve the parsed quality value in `q` for preference comparisons. - Handle missing or invalid quality values in the parsing layer before constructing an `Accept` object. ## Relationships - IMPORTS → `parseAccept` # decodeHeader **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L281) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function decodeHeader(token: string): TokenHeader ``` ## Parameters | Name | Type | |---|---| | `token` | `string` | **Returns:** `TokenHeader` # handler **Kind:** API Endpoint **Source:** [`src/middleware/method-not-allowed/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-not-allowed/index.ts#L133) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /Content-Length` ## Relationships - IMPORTS → `basePath` - IMPORTS → `matchedRoutes` - IMPORTS → `METHOD_NAME_ALL` # useLayoutEffect **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L290) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useLayoutEffect(effect: () => void | (() => void), deps: readonly unknown[]): void ``` ## Parameters | Name | Type | |---|---| | `effect` | `() => void | (() => void)` | | `deps` | `readonly unknown[]` | **Returns:** `void` # acceptsConfig **Kind:** Interface **Source:** [`src/helper/accepts/accepts.ts`](https://github.com/honojs/hono/blob/main/src/helper/accepts/accepts.ts#L11) **Part of:** [Helper](subsystem-src-helper) `acceptsConfig` defines the configuration required for Accept header handling. It stores the parsed `AcceptHeader`, a list of supported content types, and the fallback content type returned when no supported match is found. ## Properties | Property | Type | |---|---| | `header` | `AcceptHeader` | | `supports` | `string[]` | | `default` | `string` | ## Diagram ```mermaid graph LR Config[acceptsConfig] Header[header: AcceptHeader] Supports[supports: string[]] Default[default: string] Config --> Header Config --> Supports Config --> Default ``` ## Usage ```ts import type { acceptsConfig } from './helper/accepts/accepts'; const config: acceptsConfig = { header: requestAcceptHeader, supports: ['application/json', 'text/html'], default: 'application/json', }; function selectContentType(config: acceptsConfig): string { return config.default; } ``` ## AI Coding Instructions - Pass a parsed `AcceptHeader` value through `header`; do not replace it with a raw header string. - Keep `supports` limited to content types the calling code can return. - Set `default` to a value that also exists in `supports`. - Use `acceptsConfig` when passing Accept negotiation settings between request handling code and content-type selection logic. ## How it works `acceptsConfig` is an exported TypeScript interface that describes the required configuration shared by the `accepts` helper and its matching functions. It has three required fields: `header`, `supports`, and `default`. [src/helper/accepts/accepts.ts:11-15] - **`header`** selects the request header that `accepts` reads. Its type is `AcceptHeader`, limited to `'Accept'`, `'Accept-Charset'`, `'Accept-Encoding'`, `'Accept-Language'`, `'Accept-Patch'`, `'Accept-Post'`, or `'Accept-Ranges'`. [src/helper/accepts/accepts.ts:12] [src/utils/headers.ts:345-352] - **`supports`** is a `string[]` of candidate values for matching. [src/helper/accepts/accepts.ts:13] - **`default`** is the `string` returned when the selected header is absent or when the default matcher finds no supported accepted type. [src/helper/accepts/accepts.ts:14] [src/helper/accepts/accepts.ts:21-25] [src/helper/accepts/accepts.ts:40-48] `acceptsOptions` extends this interface with an optional `match` callback. That callback receives parsed accept entries and the same `acceptsConfig` object, and returns a string. [src/helper/accepts/accepts.ts:17-19] When no callback is supplied, `accepts` uses `defaultMatch`. [src/helper/accepts/accepts.ts:45-48] The default matcher sorts parsed entries by descending `q` value, selects the first entry whose `type` occurs in `supports`, and returns that type; otherwise it returns `default`. [src/helper/accepts/accepts.ts:21-25] The matcher calls `.sort()` on its `accepts` argument. [src/helper/accepts/accepts.ts:23] `accepts` reads `c.req.header(options.header)`. If that value is falsy, it returns `options.default`; otherwise, it parses the header and invokes either `options.match` or `defaultMatch` with the parsed entries and configuration. [src/helper/accepts/accepts.ts:40-48] No runtime validation or explicit error handling for the three configuration fields appears in this file. [src/helper/accepts/accepts.ts:11-19] # handler **Kind:** API Endpoint **Source:** [`src/middleware/method-not-allowed/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-not-allowed/index.ts#L133) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /Content-Length` ## Relationships - IMPORTS → `basePath` - IMPORTS → `matchedRoutes` - IMPORTS → `METHOD_NAME_ALL` # isTokenHeader **Kind:** Function **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L44) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function isTokenHeader(obj: unknown): obj is TokenHeader ``` ## Parameters | Name | Type | |---|---| | `obj` | `unknown` | **Returns:** `obj is TokenHeader` # useRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L323) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useRef(initialValue: T | null): RefObject ``` ## Parameters | Name | Type | |---|---| | `initialValue` | `T | null` | **Returns:** `RefObject` # AfterGenerateHook **Kind:** Type **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L112) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts ( result: ToSSGResult, fsModule: FileSystemModule, options?: ToSSGOptions ) => void | Promise ``` # handler **Kind:** API Endpoint **Source:** [`src/middleware/method-not-allowed/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-not-allowed/index.ts#L133) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /Content-Length` ## Relationships - IMPORTS → `basePath` - IMPORTS → `matchedRoutes` - IMPORTS → `METHOD_NAME_ALL` # ResponseHeader **Kind:** Type **Source:** [`src/utils/headers.ts`](https://github.com/honojs/hono/blob/main/src/utils/headers.ts#L266) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts | 'Accept-Query' | 'Access-Control-Allow-Credentials' | 'Access-Control-Allow-Headers' | 'Access-Control-Allow-Methods' | 'Access-Control-Allow-Origin' | 'Access-Control-Expose-Headers' | 'Access-Control-Max-Age' | 'Activate-Storage-Access' | 'Age' | 'Allow' | 'Cache-Control' | 'Cache-Group-Invalidation' | 'Cache-Groups' | 'Clear-Site-Data' | 'Content-Disposition' | 'Content-Encoding' | 'Content-Language' | 'Content-Length' | 'Content-Location' | 'Content-Range' | 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only' | 'Content-Type' | 'Cookie' | 'Cross-Origin-Embedder-Policy' | 'Cross-Origin-Opener-Policy' | 'Cross-Origin-Resource-Policy' | 'Date' | 'ETag' | 'Expires' | 'Incremental' | 'Last-Modified' | 'Location' | 'Permissions-Policy' | 'Pragma' | 'Retry-After' | 'Save-Data' | 'Sec-CH-Prefers-Color-Scheme' | 'Sec-CH-Prefers-Reduced-Motion' | 'Sec-CH-UA' | 'Sec-CH-UA-Arch' | 'Sec-CH-UA-Bitness' | 'Sec-CH-UA-Form-Factor' | 'Sec-CH-UA-Full-Version' | 'Sec-CH-UA-Full-Version-List' | 'Sec-CH-UA-Mobile' | 'Sec-CH-UA-Model' | 'Sec-CH-UA-Platform' | 'Sec-CH-UA-Platform-Version' | 'Sec-CH-UA-WoW64' | 'Sec-Fetch-Dest' | 'Sec-Fetch-Mode' | 'Sec-Fetch-Site' | 'Sec-Fetch-User' | 'Sec-GPC' | 'Server' | 'Server-Timing' | 'Service-Worker-Navigation-Preload' | 'Set-Cookie' | 'Set-Txn' | 'Strict-Transport-Security' | 'Timing-Allow-Origin' | 'Trailer' | 'Transfer-Encoding' | 'Unencoded-Digest' | 'Upgrade' | 'Vary' | 'Want-Unencoded-Digest' | 'Warning' | 'WWW-Authenticate' | 'X-Content-Type-Options' | 'X-DNS-Prefetch-Control' | 'X-Frame-Options' | 'X-Permitted-Cross-Domain-Policies' | 'X-Powered-By' | 'X-Robots-Tag' | 'X-XSS-Protection' ``` # useRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L323) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useRef(initialValue: T | null): RefObject ``` ## Parameters | Name | Type | |---|---| | `initialValue` | `T | null` | **Returns:** `RefObject` # bufferToString **Kind:** Function **Source:** [`src/utils/buffer.ts`](https://github.com/honojs/hono/blob/main/src/utils/buffer.ts#L98) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function bufferToString(buffer: ArrayBuffer): string ``` ## Parameters | Name | Type | |---|---| | `buffer` | `ArrayBuffer` | **Returns:** `string` # handler **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L82) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /content-length` # SSGPlugin **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L175) **Part of:** [Helper](subsystem-src-helper) `SSGPlugin` defines lifecycle hooks for static site generation requests, responses, and generated output. It groups hooks that run before a request, after a response, and after generation completes. ## Properties | Property | Type | |---|---| | `beforeRequestHook` | `BeforeRequestHook | BeforeRequestHook[]` | | `afterResponseHook` | `AfterResponseHook | AfterResponseHook[]` | | `afterGenerateHook` | `AfterGenerateHook | AfterGenerateHook[]` | ## Diagram ```mermaid graph LR Plugin[SSGPlugin] Before[beforeRequestHook] AfterResponse[afterResponseHook] AfterGenerate[afterGenerateHook] Plugin --> Before Plugin --> AfterResponse Plugin --> AfterGenerate Before --> Request[Request processing] Request --> Response[Response processing] Response --> Generated[Static output generation] AfterResponse --> Response AfterGenerate --> Generated ``` ## Usage ```ts import type { SSGPlugin } from "./helper/ssg/ssg"; import { requestLogger } from "./hooks/request-logger"; import { responseCache } from "./hooks/response-cache"; import { outputReporter } from "./hooks/output-reporter"; const plugin: SSGPlugin = { beforeRequestHook: [requestLogger], afterResponseHook: responseCache, afterGenerateHook: [outputReporter], }; export default plugin; ``` ## AI Coding Instructions - Assign a single hook or an array of hooks to each `SSGPlugin` field. - Keep `beforeRequestHook` focused on work that must happen before request processing begins. - Use `afterResponseHook` for response inspection, mutation, caching, or logging after a response is available. - Use `afterGenerateHook` for work that depends on generated static output. - Preserve hook ordering when arrays are used, since hooks run as part of the generation lifecycle. ## How it works `SSGPlugin` is a TypeScript interface for attaching lifecycle hooks to `toSSG` static-site generation. Each hook property is optional and may be one hook or an ordered array of hooks: `beforeRequestHook`, `afterResponseHook`, and `afterGenerateHook`. [src/helper/ssg/ssg.ts:175-179] - `beforeRequestHook` receives a `Request` and may return a replacement `Request`, `false`, or a promise of either. [src/helper/ssg/ssg.ts:110] During generation, it runs before the request used to collect SSG route parameters; returning `false` skips that route’s parameter-collection work. [src/helper/ssg/ssg.ts:234-243] - `afterResponseHook` receives a generated `Response` and may return a replacement `Response`, `false`, or a promise of either. [src/helper/ssg/ssg.ts:111] It runs after the route-content request; returning `false` omits that response from output. [src/helper/ssg/ssg.ts:264-281] - `afterGenerateHook` receives the `ToSSGResult`, the file-system module, and optionally the generation options; it may be synchronous or asynchronous. [src/helper/ssg/ssg.ts:112-116] It runs after generation has produced either a success or failure result. [src/helper/ssg/ssg.ts:460-469] When a hook property is an array, its hooks run sequentially and are awaited. For request and response hooks, each hook receives the current request or response; a returned replacement becomes the input to the next hook, and `false` stops the chain. [src/helper/ssg/ssg.ts:124-136] [src/helper/ssg/ssg.ts:145-157] After-generation hook arrays also run sequentially and are awaited. [src/helper/ssg/ssg.ts:168-172] `toSSG` collects the deprecated hook options first, then appends hooks from `options.plugins` in plugin-array order. [src/helper/ssg/ssg.ts:376-419] If `options.plugins` is absent, it uses `[defaultPlugin()]`; that default plugin rejects every response whose status is not `200`, so those responses are not written. [src/helper/ssg/ssg.ts:372] [src/helper/ssg/plugins.ts:11-19] Passing an empty `plugins` array does not select the default plugin because the empty array is used as-is. [src/helper/ssg/ssg.ts:372] A response accepted by the hook chain is read as text when its `Content-Type` contains `text` or `json`; otherwise it is read as an `ArrayBuffer`. [src/helper/ssg/ssg.ts:74-87] The resulting content is then passed to file writing, which derives an output path from the route path and MIME type, creates its parent directory when first encountered, and writes strings or `ArrayBuffer` content. [src/helper/ssg/ssg.ts:310-334] There is no explicit runtime validation that plugin hook values are callable; `toSSG` only checks whether each hook property is present and whether it is an array before adding it to a hook list. [src/helper/ssg/ssg.ts:397-418] Errors in route collection or file writing are caught and returned as `{ success: false, files: [], error }`. [src/helper/ssg/ssg.ts:420-464] After-generation hooks run outside that `try`/`catch`, so an exception from one rejects the `toSSG` call rather than being added to `ToSSGResult.error`. [src/helper/ssg/ssg.ts:420-469] # useRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L323) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useRef(initialValue: T | null): RefObject ``` ## Parameters | Name | Type | |---|---| | `initialValue` | `T | null` | **Returns:** `RefObject` # convertIPv4BinaryToString **Kind:** Function **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L300) **Part of:** [Utils](subsystem-src-utils) Convert a binary representation of an IPv4 address to a string. `convertIPv4BinaryToString` converts a binary IPv4 address representation into its string form. Use it at boundaries where binary address data must be displayed, logged, serialized, or passed to string-based APIs. ## Signature ```ts function convertIPv4BinaryToString(ipV4: bigint): string ``` ## Parameters | Name | Type | |---|---| | `ipV4` | `bigint` | **Returns:** `string` ## Diagram ```mermaid graph LR A[Binary IPv4 input] --> B[convertIPv4BinaryToString] B --> C[IPv4 string output] ``` ## Usage ```ts import { convertIPv4BinaryToString } from './utils/ipaddr'; type BinaryIPv4 = Parameters[0]; function formatAddress(binaryAddress: BinaryIPv4): string { return convertIPv4BinaryToString(binaryAddress); } ``` ## AI Coding Instructions - Pass input in the binary format expected by `convertIPv4BinaryToString`; do not pass an already formatted address string. - Keep binary-to-string conversion near display, logging, serialization, or API boundaries. - Treat the return value as an IPv4 string suitable for string-based consumers. - Do not assume malformed binary input is validated unless the implementation explicitly checks it. # handler **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L82) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /content-length` # ToSSGResult **Kind:** Interface **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L44) **Part of:** [Helper](subsystem-src-helper) `ToSSGResult` represents the outcome of a static site generation operation. It reports whether generation succeeded, lists generated file paths, and carries an `Error` when the operation fails. ## Properties | Property | Type | |---|---| | `success` | `boolean` | | `files` | `string[]` | | `error` | `Error` | ## Diagram ```mermaid graph LR SSG[Static site generation] --> Result[ToSSGResult] Result --> Success[success: boolean] Result --> Files[files: string[]] Result --> Error[error: Error] ``` ## Usage ```ts import type { ToSSGResult } from "./src/helper/ssg/ssg"; function reportGeneration(result: ToSSGResult): void { if (result.success) { console.log("Generated files:", result.files); return; } console.error("Static site generation failed:", result.error); } const result: ToSSGResult = { success: true, files: ["dist/index.html", "dist/about/index.html"], error: new Error(), }; reportGeneration(result); ``` ## AI Coding Instructions - Return `success`, `files`, and `error` together when creating a `ToSSGResult`. - Check `success` before treating entries in `files` as generated output. - Pass the original failure through the `error` field so callers can log or handle it. - Keep `files` limited to paths produced by the static site generation operation. # useRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L323) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useRef(initialValue: T | null): RefObject ``` ## Parameters | Name | Type | |---|---| | `initialValue` | `T | null` | **Returns:** `RefObject` # ClientErrorStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L10) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 ``` # forwardRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L379) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function forwardRef(Component: (props: P, ref?: RefObject) => JSX.Element): ((props: P & { ref?: RefObject }) => JSX.Element) ``` ## Parameters | Name | Type | |---|---| | `Component` | `(props: P, ref?: RefObject) => JSX.Element` | **Returns:** `((props: P & { ref?: RefObject }) => JSX.Element)` # handler **Kind:** API Endpoint **Source:** [`src/middleware/pretty-json/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/pretty-json/index.ts#L51) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /Content-Type` # WebSocketHelperDefineHandler **Kind:** Type **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L102) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts ( c: Context, events: WSEvents, options?: U ) => Promise | Response | void ``` # acceptsOptions **Kind:** Interface **Source:** [`src/helper/accepts/accepts.ts`](https://github.com/honojs/hono/blob/main/src/helper/accepts/accepts.ts#L17) **Part of:** [Helper](subsystem-src-helper) `acceptsOptions` defines the contract for matching a list of `Accept` values against an `acceptsConfig`. Its `match` method receives the available accept entries and configuration, then returns the selected value as a string. ## Properties | Property | Type | |---|---| | `match` | `(accepts: Accept[], config: acceptsConfig) => string` | ## Diagram ```mermaid graph LR A[Accept[]] --> C[acceptsOptions.match] B[acceptsConfig] --> C C --> D[string] ``` ## Usage ```ts import type { acceptsOptions } from './src/helper/accepts/accepts'; const options: acceptsOptions = { match(accepts, config) { const match = accepts.find((accept) => accept.type === config.type); return match?.type ?? ''; }, }; const selected = options.match(accepts, config); ``` ## AI Coding Instructions - Implement `match` with both the `Accept[]` input and `acceptsConfig` input in mind. - Return a string for every match path, including when no `Accept` entry matches. - Keep matching rules consistent with the `Accept` and `acceptsConfig` types used by the accepts helper. - Avoid mutating the incoming `accepts` array or `config` object during matching. ## How it works `acceptsOptions` is the options interface accepted by `accepts(c, options)`. It extends `acceptsConfig`, so callers must set: - `header`: one of `'Accept'`, `'Accept-Charset'`, `'Accept-Encoding'`, `'Accept-Language'`, `'Accept-Patch'`, `'Accept-Post'`, or `'Accept-Ranges'`. [src/helper/accepts/accepts.ts:11-18](src/helper/accepts/accepts.ts#L11-L18) [src/utils/headers.ts:345-352](src/utils/headers.ts#L345-L352) - `supports`: an array of strings against which parsed accept-value `type` fields are compared. [src/helper/accepts/accepts.ts:11-15](src/helper/accepts/accepts.ts#L11-L15) [src/helper/accepts/accepts.ts:21-24](src/helper/accepts/accepts.ts#L21-L24) - `default`: the string returned when the configured request header is absent or when the selected matcher finds no supported type. [src/helper/accepts/accepts.ts:14](src/helper/accepts/accepts.ts#L14) [src/helper/accepts/accepts.ts:42-44](src/helper/accepts/accepts.ts#L42-L44) [src/helper/accepts/accepts.ts:21-24](src/helper/accepts/accepts.ts#L21-L24) It optionally accepts `match`, a function with the signature `(accepts: Accept[], config: acceptsConfig) => string`. [src/helper/accepts/accepts.ts:17-19](src/helper/accepts/accepts.ts#L17-L19) `accepts` reads `options.header` from the request, parses its value, and calls this function with the parsed values and the same options object when `match` is set; otherwise it calls `defaultMatch`. [src/helper/accepts/accepts.ts:40-48](src/helper/accepts/accepts.ts#L40-L48) Each element passed as the first `match` argument has `type`, `params`, and numeric `q` fields. [src/helper/accepts/accepts.ts:5-9](src/helper/accepts/accepts.ts#L5-L9) The parser initializes missing quality values to `1`, reads a `q` parameter when present, and returns an array of parsed values. [src/utils/accept.ts:163-167](src/utils/accept.ts#L163-L167) [src/utils/accept.ts:211-237](src/utils/accept.ts#L211-L237) Without a custom `match`, `defaultMatch` sorts the parsed array by descending `q`, returns the first entry whose `type` occurs in `supports`, and otherwise returns `default`. [src/helper/accepts/accepts.ts:21-25](src/helper/accepts/accepts.ts#L21-L25) A custom matcher can choose different selection rules; the test demonstrates one that sorts ascending by `q` and returns the first supported type. [src/helper/accepts/accepts.test.ts:89-112](src/helper/accepts/accepts.test.ts#L89-L112) There is no runtime validation of `header`, `supports`, `default`, or the return value of `match` in this code. If the request header is falsy, `accepts` returns `default` immediately and does not parse the header or call `match`. [src/helper/accepts/accepts.ts:41-48](src/helper/accepts/accepts.ts#L41-L48) # handler **Kind:** API Endpoint **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L232) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /X-Powered-By` # JSONParsed **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L53) **Part of:** [Utils](subsystem-src-utils) Convert a type to a JSON-compatible type. Non-JSON values such as `Date` implement `.toJSON()`, so they can be transformed to a value assignable to `JSONObject` `JSON.stringify()` throws a `TypeError` when it encounters a `bigint` value, unless a custom `replacer` function or `.toJSON()` method is provided. This behaviour can be controlled by the `TError` generic type parameter, which defaults to `bigint | ReadonlyArray`. You can set it to `never` to disable this check. `JSONParsed` maps a TypeScript type to the shape produced by JSON serialization. Values with a `.toJSON()` method, such as `Date`, are converted through that method, while `bigint` values are rejected by default because `JSON.stringify()` throws for them. ## Definition ```ts T extends { toJSON(): infer J } ? (() => J) extends () => JSONPrimitive ? J : (() => J) extends () => { toJSON(): unknown } ? {} : JSONParsed : T extends JSONPrimitive ? T : T extends InvalidJSONValue ? never : T extends ReadonlyArray ? { [K in keyof T]: JSONParsed, TError> } extends infer A ? A extends ReadonlyArray ? A : JSONParsed, TError>[] : never : T extends Set | Map | Record ? {} : T extends object ? T[keyof T] extends TError ? never : { [K in keyof OmitSymbolKeys as IsInvalid extends true ? never : K]: boolean extends IsInvalid ? JSONParsed | undefined : JSONParsed } : T extends unknown ? T extends TError ? never : JSONValue : never ``` ## Diagram ```mermaid graph LR T[Input type T] --> P[JSONParsed] P --> J[JSON-compatible type] D[Date or value with toJSON()] --> J B[bigint value] --> E[TError check] E -->|default| R[Rejected] E -->|TError = never| J ``` ## Usage ```ts import type { JSONParsed } from "./utils/types"; type Input = { createdAt: Date; tags: readonly string[]; }; type SerializedInput = JSONParsed; const value: SerializedInput = { createdAt: new Date().toJSON(), tags: ["release"], }; declare const source: { total: bigint }; // bigint is checked by default. type CheckedValue = JSONParsed; // Disable the bigint check when serialization is handled separately. type AllowedValue = JSONParsed; ``` ## AI Coding Instructions - Use `JSONParsed` for types representing data after JSON serialization. - Expect values with `.toJSON()` methods to resolve to their JSON return type. - Keep the default `TError` setting when `bigint` values should be rejected. - Set `TError` to `never` only when `bigint` serialization is handled with a replacer or custom `.toJSON()` method. # link **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L162) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function link({ children, ...props }) ``` ## Parameters | Name | Type | |---|---| | `{ children, ...props }` | `any` | # AddedSSGDataRequest **Kind:** Type **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L36) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts Request & { ssgParams?: SSGParams } ``` # handler **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L209) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /metric` # ParseBodyOptions **Kind:** Type **Source:** [`src/utils/body.ts`](https://github.com/honojs/hono/blob/main/src/utils/body.ts#L43) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { all: boolean dot: boolean } ``` # startViewTransition **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L79) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function startViewTransition(callback: () => void): void ``` ## Parameters | Name | Type | |---|---| | `callback` | `() => void` | **Returns:** `void` # handler **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L209) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /metric` # meta **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L171) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function meta({ children, ...props }) ``` ## Parameters | Name | Type | |---|---| | `{ children, ...props }` | `any` | # SendOptions **Kind:** Interface **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L63) **Part of:** [Helper](subsystem-src-helper) Options for sending message `SendOptions` defines options applied when sending a WebSocket message. Its `compress` property controls whether message compression is enabled for the send operation. ## Properties | Property | Type | |---|---| | `compress` | `boolean` | ## Diagram ```mermaid graph LR Message[WebSocket message] --> Options[SendOptions] Options --> Compress[compress: boolean] Options --> Send[Send operation] ``` ## Usage ```ts import type { SendOptions } from "./helper/websocket"; const options: SendOptions = { compress: true, }; // Pass `options` to the WebSocket message send operation. ``` ## AI Coding Instructions - Set `compress` explicitly when constructing `SendOptions`. - Keep this interface limited to message-send configuration. - Use `SendOptions` as a type annotation for options passed into WebSocket send code. - Do not treat `compress` as message content; it only controls send behavior. # sha1 **Kind:** Function **Source:** [`src/utils/crypto.ts`](https://github.com/honojs/hono/blob/main/src/utils/crypto.ts#L21) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts async function sha1(data: Data): Promise ``` ## Parameters | Name | Type | |---|---| | `data` | `Data` | **Returns:** `Promise` # AddressType **Kind:** Type **Source:** [`src/helper/conninfo/types.ts`](https://github.com/honojs/hono/blob/main/src/helper/conninfo/types.ts#L3) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts 'IPv6' | 'IPv4' | undefined ``` # booleanAttributes **Kind:** Constant **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L85) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts [ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'download', 'formnovalidate', 'hidden', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected', ] ``` ## Value ```ts [ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'download', 'formnovalidate', 'hidden', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected', ] ``` # getQueryStrings **Kind:** Function **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L136) **Part of:** [Utils](subsystem-src-utils) ## Signature ```ts function getQueryStrings(url: string): string ``` ## Parameters | Name | Type | |---|---| | `url` | `string` | **Returns:** `string` # handler **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L209) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /metric` # AfterResponseHook **Kind:** Type **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L111) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts (res: Response) => Response | false | Promise ``` # handler **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L209) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /metric` # JWTPayload **Kind:** Type **Source:** [`src/utils/jwt/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/types.ts#L131) **Part of:** [Utils](subsystem-src-utils) JWT Payload `JWTPayload` describes the decoded payload data carried by a JSON Web Token. JWT parsing, validation, and authorization code can use this type to pass token claims through the application with a shared shape. ## Definition ```ts { [key: string]: unknown exp?: number nbf?: number iat?: number iss?: string aud?: string | string[] } ``` ## Diagram ```mermaid graph LR Token[JWT] -->|decode and validate| Payload[JWTPayload] Payload --> Auth[Authorization logic] Payload --> Request[Request context] ``` ## Usage ```ts import type { JWTPayload } from './utils/jwt/types'; declare function getVerifiedPayload(request: Request): JWTPayload; function authorizeRequest(request: Request) { const payload = getVerifiedPayload(request); // Read claims declared by JWTPayload before making access decisions. return payload; } ``` ## AI Coding Instructions - Import `JWTPayload` with `import type` when it is only used for TypeScript checking. - Only create a `JWTPayload` after the JWT has been decoded and validated. - Keep claim access aligned with the fields declared in `src/utils/jwt/types.ts`. - Do not treat decoded payload data as trusted until JWT signature and expiry checks have completed. # useEffect **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L288) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useEffect(effect: () => void | (() => void), deps: readonly unknown[]): void ``` ## Parameters | Name | Type | |---|---| | `effect` | `() => void | (() => void)` | | `deps` | `readonly unknown[]` | **Returns:** `void` # BeforeRequestHook **Kind:** Type **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L110) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts (req: Request) => Request | false | Promise ``` # header **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L115) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /` # Pool **Kind:** Interface **Source:** [`src/utils/concurrent.ts`](https://github.com/honojs/hono/blob/main/src/utils/concurrent.ts#L8) **Part of:** [Utils](subsystem-src-utils) `Pool` defines an asynchronous work contract that returns a value of type `T`. Its `run` method lets concurrency code invoke pooled work through a shared `Promise`-based interface. ## Diagram ```mermaid graph LR Caller[Caller] --> Pool[Pool] Pool --> Run[run()] Run --> Result[Promise] ``` ## Usage ```ts async function execute(pool: Pool): Promise { return pool.run(); } declare const taskPool: Pool; const result = await execute(taskPool); console.log(result); ``` ## AI Coding Instructions - Treat `run` as asynchronous and await or return its `Promise`. - Preserve the generic `T` type when passing a `Pool` between functions. - Implement `run` so it resolves with the expected result type. - Handle rejected promises at the caller or at the integration boundary. ## How it works `Pool` is an exported TypeScript interface for an object that runs a zero-argument callback and returns a `Promise` for the callback’s result. Its sole member is the generic `run(fn: () => T): Promise` method. [src/utils/concurrent.ts:8-10] `createPool()` returns this interface and implements its concurrency behavior. It defaults an omitted or falsy `concurrency` value to `1024`; a concurrency value of `Infinity` returns a `Pool` whose `run` method immediately invokes the callback through an async function, without tracking active work. [src/utils/concurrent.ts:6,12-25] For finite concurrency, each started callback occupies a marker in an internal `Set`. When the active-marker count is at least the configured limit, `run` creates or reuses a result promise, schedules another attempt with `setTimeout`, and returns that promise without invoking the callback yet. [src/utils/concurrent.ts:28-40] Once a callback can start, `run` awaits it and returns its result. [src/utils/concurrent.ts:39-52] Tests invoke multiple `run` calls and verify that only up to the configured concurrency are running before the blocked callbacks are released. [src/utils/concurrent.test.ts:13-37] When `createPool` receives a truthy `interval`, a completed callback’s marker remains in the active set until a timer deletes it after that many milliseconds; otherwise, the marker is deleted immediately after the callback resolves. [src/utils/concurrent.ts:41-46] Consequently, the interval delays later callbacks after completion, and the tests check that groups of callbacks begin at least approximately one interval apart. [src/utils/concurrent.test.ts:40-67] The visible implementation has no input validation for the callback, concurrency, or interval. [src/utils/concurrent.ts:8-18] It also does not catch callback failures: if `await fn()` throws or rejects, execution exits before marker deletion, so the occupied marker remains in the finite pool. [src/utils/concurrent.ts:39-46] # useTransition **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L126) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useTransition(): [boolean, (callback: () => void | Promise) => void] ``` **Returns:** `[boolean, (callback: () => void | Promise) => void]` # AsymmetricAlgorithm **Kind:** Type **Source:** [`src/utils/jwt/jwa.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwa.ts#L27) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512' | 'EdDSA' ``` # ClassNameSlug **Kind:** Type **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L130) **Part of:** [Helper](subsystem-src-helper) A function that customizes generated CSS class names. `ClassNameSlug` defines a callback for customizing CSS class names generated by the styling layer. It receives the class-generation context and returns the string used as the generated class name, allowing applications to apply consistent naming or scoping rules. ## Definition ```ts (hash: string, label: string, styleString: string) => string ``` ## Diagram ```mermaid graph LR Styles[Style definition] --> Generator[CSS class-name generator] Generator --> Slug[ClassNameSlug callback] Slug --> ClassName[Generated CSS class name] ClassName --> DOM[Rendered element] ``` ## Usage ```ts import type { ClassNameSlug } from './helper/css/common'; const createScopedClassName: ClassNameSlug = (rule, sheet) => { const sheetName = sheet?.options.name ?? 'styles'; return `${sheetName}-${rule.key}`; }; // Pass the callback to the CSS generation configuration. const cssOptions = { classNameSlug: createScopedClassName, }; ``` ## AI Coding Instructions - Return deterministic class names so matching style rules produce stable output. - Keep generated names valid for CSS selectors and avoid whitespace or unsupported characters. - Preserve rule and stylesheet context when adding prefixes or scopes. - Use this callback at the CSS generation configuration boundary rather than rewriting class names after rendering. # headerName **Kind:** API Endpoint **Source:** [`src/middleware/jwk/jwk.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwk/jwk.ts#L81) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /` ## Relationships - IMPORTS → `getCookie` - IMPORTS → `getSignedCookie` - IMPORTS → `HTTPException` - IMPORTS → `Jwt` # NodeObject **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L41) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts { pP: Props | undefined nN: Node | undefined vC: Node[] pC?: Node[] vR: Node[] n?: string f?: boolean s?: boolean c: Container | undefined e: SupportedElement | Text | undefined p?: PreserveNodeType a?: boolean o?: NodeObject [DOM_STASH]: | [ number, any[][], LocalJSXContexts, [Context, Function, NodeObject], ] | [number, any[][]] } & JSXNode ``` # CookieOptions **Kind:** Type **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L17) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { domain?: string expires?: Date httpOnly?: boolean maxAge?: number path?: string secure?: boolean sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none' partitioned?: boolean priority?: 'Low' | 'Medium' | 'High' | 'low' | 'medium' | 'high' prefix?: CookiePrefixOptions } & PartitionedCookieConstraint ``` # CssVariableType **Kind:** Type **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L118) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType ``` # headerName **Kind:** API Endpoint **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L81) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /` ## Relationships - IMPORTS → `getCookie` - IMPORTS → `getSignedCookie` - IMPORTS → `HTTPException` - IMPORTS → `Jwt` # isValidElement **Kind:** Function **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L436) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function isValidElement(element: unknown): element is JSXNode ``` ## Parameters | Name | Type | |---|---| | `element` | `unknown` | **Returns:** `element is JSXNode` # DEFAULT_OUTPUT_DIR **Kind:** Constant **Source:** [`src/helper/ssg/ssg.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/ssg.ts#L27) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts './static' ``` ## Value ```ts './static' ``` ## Relationships - IMPORTS → `replaceUrlParam` - IMPORTS → `createPool` - IMPORTS → `getExtension` - IMPORTS → `SSG_CONTEXT` - IMPORTS → `X_HONO_DISABLE_SSG_HEADER_KEY` - IMPORTS → `defaultPlugin` - IMPORTS → `dirname` - IMPORTS → `ensureWithinOutDir` - IMPORTS → `filterStaticGenerateRoutes` - IMPORTS → `isDynamicRoute` - IMPORTS → `joinPaths` # headerName **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L112) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` # meta **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L314) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function meta(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # VerifyOptions **Kind:** Type **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L78) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { iss?: string | RegExp nbf?: boolean exp?: boolean iat?: boolean aud?: string | string[] | RegExp } ``` # AcceptHeader **Kind:** Type **Source:** [`src/utils/headers.ts`](https://github.com/honojs/hono/blob/main/src/utils/headers.ts#L345) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts | 'Accept' | 'Accept-Charset' | 'Accept-Encoding' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Ranges' ``` # EXTERNAL_CLASS_NAMES **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L10) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts unique symbol ``` ## Value ```ts Symbol() ``` # HTTPExceptionFunction **Kind:** Type **Source:** [`src/middleware/timeout/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timeout/index.ts#L10) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts (context: Context) => HTTPException ``` ## Relationships - IMPORTS → `HTTPException` # startTransition **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L119) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function startTransition(callback: () => void): void ``` ## Parameters | Name | Type | |---|---| | `callback` | `() => void` | **Returns:** `void` # GetConnInfo **Kind:** Type **Source:** [`src/helper/conninfo/types.ts`](https://github.com/honojs/hono/blob/main/src/helper/conninfo/types.ts#L45) **Part of:** [Helper](subsystem-src-helper) Helper type `GetConnInfo` describes the value returned when connection information is requested by helper code. It acts as the shared TypeScript contract between code that obtains connection details and code that consumes them. ## Definition ```ts (c: Context) => ConnInfo ``` ## Diagram ```mermaid graph LR Helper["Connection info helper"] --> Type["GetConnInfo"] Type --> Consumer["Connection setup code"] ``` ## Usage ```ts import type { GetConnInfo } from './helper/conninfo/types'; declare function getConnectionInfo(): GetConnInfo; declare function configureConnection(connInfo: GetConnInfo): void; const connInfo: GetConnInfo = getConnectionInfo(); configureConnection(connInfo); ``` ## AI Coding Instructions - Import `GetConnInfo` with `import type` when it is only used for TypeScript checking. - Keep producers and consumers of connection information typed with `GetConnInfo`. - Do not assume properties on `GetConnInfo` without checking its definition in `src/helper/conninfo/types.ts`. - Update dependent helper and connection setup code when the type definition changes. # IPRestrictionRule **Kind:** Type **Source:** [`src/middleware/ip-restriction/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/ip-restriction/index.ts#L38) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts string | ((addr: { addr: string; type: AddressType }) => boolean) ``` ## Relationships - IMPORTS → `HTTPException` - IMPORTS → `convertIPv4MappedIPv6ToIPv4` - IMPORTS → `convertIPv4ToBinary` - IMPORTS → `convertIPv6BinaryToString` - IMPORTS → `convertIPv6ToBinary` - IMPORTS → `distinctRemoteAddr` - IMPORTS → `isIPv4MappedIPv6` - IMPORTS → `INVALID_IP_ADDRESS_ERROR_CODE` # RequiredKeysOf **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L104) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts Exclude< { [Key in keyof BaseType]: BaseType extends Record ? Key : never }[keyof BaseType], undefined > ``` # useDebugValue **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L373) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useDebugValue(_value: unknown, _formatter: (value: unknown) => string): void ``` ## Parameters | Name | Type | |---|---| | `_value` | `unknown` | | `_formatter` | `(value: unknown) => string` | **Returns:** `void` # Children **Kind:** Constant **Source:** [`src/jsx/children.ts`](https://github.com/honojs/hono/blob/main/src/jsx/children.ts#L5) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts { map: (children: Child[], fn: (child: Child, index: number) => Child): Child[] => toArray(children).map(fn), forEach: (children: Child[], fn: (child: Child, index: number) => void): void => { toArray(children).forEach(fn) }, count: (children: Child[]): number => toArray(children).length, only: (_children: Child[]): Child => { const children = toArray(_children) if (child… ``` ## Value ```ts { map: (children: Child[], fn: (child: Child, index: number) => Child): Child[] => toArray(children).map(fn), forEach: (children: Child[], fn: (child: Child, index: number) => void): void => { toArray(children).forEach(fn) }, count: (children: Child[]): number => toArray(children).length, only: (_children: Child[]): Child => { const children = toArray(_children) if (child… ``` # IS_CSS_ESCAPED **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L21) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts Symbol() ``` ## Value ```ts Symbol() ``` # key **Kind:** API Endpoint **Source:** [`src/middleware/etag/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/etag/index.ts#L126) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` # StatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L63) **Part of:** [Utils](subsystem-src-utils) If you want to use an unofficial status, use `UnofficialStatusCode`. `StatusCode` represents the set of supported official HTTP status codes in the HTTP utilities module. Use it when APIs accept or return standard status values; use `UnofficialStatusCode` when an unofficial status is required. ## Definition ```ts | InfoStatusCode | SuccessStatusCode | RedirectStatusCode | ClientErrorStatusCode | ServerErrorStatusCode | UnofficialStatusCode ``` ## Diagram ```mermaid graph LR Response[HTTP response] --> StatusCode[StatusCode] StatusCode --> Official[Official HTTP status] Unofficial[Unofficial status] --> UnofficialStatusCode[UnofficialStatusCode] ``` ## Usage ```ts import type { StatusCode } from "./utils/http-status"; function setResponseStatus(status: StatusCode) { return { status }; } declare const statusFromHandler: StatusCode; const response = setResponseStatus(statusFromHandler); ``` ## AI Coding Instructions - Use `StatusCode` for standard HTTP status values exposed by handlers, responses, and middleware. - Use `UnofficialStatusCode` instead of widening `StatusCode` when working with an unofficial status. - Keep status-related function parameters typed as `StatusCode` when unofficial values are not supported. - Treat `StatusCode` as a type-only constraint; perform runtime validation at input boundaries when status values come from external data. # Accept **Kind:** Interface **Source:** [`src/utils/accept.ts`](https://github.com/honojs/hono/blob/main/src/utils/accept.ts#L1) **Part of:** [Utils](subsystem-src-utils) `Accept` represents a parsed media type from an HTTP `Accept` header. It stores the media `type`, associated parameters, and the `q` quality value used when selecting a preferred response format. ## Properties | Property | Type | |---|---| | `type` | `string` | | `params` | `Record` | | `q` | `number` | ## Diagram ```mermaid graph LR Header[HTTP Accept header] --> Accept[Accept] Accept --> Type[type: string] Accept --> Params[params: Record<string, string>] Accept --> Quality[q: number] ``` ## Usage ```ts import type { Accept } from "./utils/accept"; const acceptedType: Accept = { type: "application/json", params: { charset: "utf-8", }, q: 1, }; if (acceptedType.type === "application/json" && acceptedType.q > 0) { console.log("Return a JSON response"); } ``` ## AI Coding Instructions - Treat `type` as the parsed media type, such as `application/json` or `text/html`. - Store media-type parameters in `params` as string key-value pairs. - Use `q` when comparing acceptable response formats; higher values indicate higher preference. - Preserve parsed parameter values as strings rather than coercing them to other types. - Keep this interface aligned with the `Accept` header parsing and response content-negotiation code. # Context **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L91) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts | [ PendingType, boolean, UpdateHook, boolean, boolean, [Context, Function, NodeObject][], ] | [PendingType, boolean, UpdateHook, boolean] | [PendingType, boolean, UpdateHook] | [PendingType, boolean] | [PendingType] | [] ``` # isPseudoGlobalSelectorRe **Kind:** Constant **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L3) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`) ``` ## Value ```ts new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`) ``` # key **Kind:** API Endpoint **Source:** [`src/middleware/secure-headers/secure-headers.ts`](https://github.com/honojs/hono/blob/main/src/middleware/secure-headers/secure-headers.ts#L139) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `GET /` ## Relationships - IMPORTS → `encodeBase64` # button **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L426) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function button(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # CookieConstraint **Kind:** Type **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L31) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts Name extends `__Secure-${string}` ? CookieOptions & SecureCookieConstraint : Name extends `__Host-${string}` ? CookieOptions & HostCookieConstraint : CookieOptions ``` # Helper ## What it is responsible for Helper manages request- and response-adjacent decisions and transformations for the codebase. Its entry points include `Accept`, `acceptsConfig`, `acceptsOptions`, and `defaultMatch`; `Accept` matches the accept header with given options, while cookie members read, generate, sign, set, and delete cookies. `GetConnInfo` exposes HTTP Connection information, and selector constants such as `PSEUDO_GLOBAL_SELECTOR`, `DEFAULT_STYLE_ID`, and `SELECTOR` identify CSS-related handling. The subsystem also names route matching and registered-route-path access, basePath lookup, proxy Fetch API wrapping, plugins for recommended behavior and redirect HTML pages, plus WebSocket contexts, listeners, upgrade types, ready states, and [adapter](subsystem-src-adapter) creation. These responsibilities place protocol matching, request metadata, cookies, route helpers, CSS naming hooks, and WebSocket control under a helper boundary. ## What it refuses It rejects: Error (when `value && /[\r\n]/.test(value)`). ## What it needs, and who needs it Helper depends on `Utils`, `src/jsx`, `src/request`, and `src/client`. `src/middleware`, `Adapter`, `src/jsx`, `Utils`, and `src/validator` depend on Helper. Without this subsystem, those consumers lose access to its acceptance matching, cookie operations, connection information, and the other named helper interfaces they call; the evidence does not identify which individual consumer calls which member. ## Notable members `Accept` is a work entry point and matches the accept header with given options. `acceptsConfig` and `acceptsOptions` are also work entry points; their names distinguish configuration and options forms, but the supplied evidence assigns no further behavior to either. `defaultMatch`, the remaining entry point, similarly has no supplied description beyond its name. `GetConnInfo` carries the HTTP Connection information responsibility. Cookie members `getCookie`, `getSignedCookie`, `generateCookie`, `setCookie`, `generateSignedCookie`, `setSignedCookie`, and `deleteCookie` together cover the stated cookie actions, although the evidence does not specify their individual contracts. Their validation behavior is evidenced by the refusal above. 109 entities in `src/helper`. **5 other subsystems depend on it**, which makes it the 2nd most depended-upon part of this codebase. ## What it is made of Its 109 entities sit in 21 files under `src/helper`: 54 functions, 19 constants, 18 interfaces, 15 type aliases and 3 more. `common.ts` holds 20 of them — more than any other file here. ## Where work enters - [`Accept`](interface-accept-2) — `src/helper/accepts/accepts.ts`:5 - [`acceptsConfig`](interface-acceptsconfig) — `src/helper/accepts/accepts.ts`:11 - [`acceptsOptions`](interface-acceptsoptions) — `src/helper/accepts/accepts.ts`:17 - [`defaultMatch`](function-defaultmatch) — `src/helper/accepts/accepts.ts`:21 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. ## Boundaries **5 other subsystems depend on this one** — `Middleware`, `Adapter`, `Jsx`, `Utils`, `Validator`. Changing what it exposes changes them. Those 5 hold 37 edges between them, unevenly: `Jsx` reaches in across 18 edges, while 2 of them hold one each. 37 edges arrive against 27 leaving — more of this repository reaches into it than it reaches out to. What they reach is narrower than the folder: 21 of its 109 members carry every inbound edge — `html` (9), `getCookie` (4) and `defineWebSocketHelper` (3), plus 18 more. Of the 27 it sends out, 23 go to `Utils` — more than to any other. It depends on `Utils`, `Jsx`, `Request`, `Client`, and on nothing else in this repository. # keyframes **Kind:** Constant **Source:** [`src/helper/css/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/index.ts#L248) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts defaultContext.keyframes ``` ## Value ```ts defaultContext.keyframes ``` # methodFormName **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L79) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` ## Relationships - IMPORTS → `parseBody` # button **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L209) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function button(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # methodFormName **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L79) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` ## Relationships - IMPORTS → `parseBody` # OnInvalidSlug **Kind:** Type **Source:** [`src/helper/css/common.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/common.ts#L137) **Part of:** [Helper](subsystem-src-helper) A callback function called when an invalid slug is returned from ClassNameSlug. `OnInvalidSlug` defines the callback invoked when `ClassNameSlug` returns a slug that is not valid. Use it to report the invalid value or stop processing before the generated class name is applied. ## Definition ```ts (slug: string) => void ``` ## Diagram ```mermaid graph LR A[ClassNameSlug] --> B{Slug valid?} B -->|Yes| C[Apply class name] B -->|No| D[OnInvalidSlug callback] D --> E[Report or throw] ``` ## Usage ```ts import type { OnInvalidSlug } from "./helper/css/common"; const onInvalidSlug: OnInvalidSlug = (slug) => { throw new Error(`Invalid CSS class slug returned: ${slug}`); }; // Provide `onInvalidSlug` where the CSS naming configuration accepts it. ``` ## AI Coding Instructions - Type callback implementations as `OnInvalidSlug` so parameter and return types stay aligned with the shared contract. - Treat the received slug as invalid input; do not apply it as a CSS class name. - Throw an error when invalid slugs should stop the build or render path. - Keep `ClassNameSlug` output compatible with the slug rules expected by the CSS naming flow. # TokenHeader **Kind:** Interface **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L38) **Part of:** [Utils](subsystem-src-utils) `TokenHeader` defines the header data for a JWT token. It identifies the signing algorithm, fixes the token type as `'JWT'`, and includes a key identifier for key selection during verification. ## Properties | Property | Type | |---|---| | `alg` | `SignatureAlgorithm` | | `typ` | `'JWT'` | | `kid` | `string` | ## Diagram ```mermaid graph LR Header[TokenHeader] --> Algorithm[alg: SignatureAlgorithm] Header --> Type[typ: JWT] Header --> KeyId[kid: string] Header --> Token[JWT header] ``` ## Usage ```ts import type { TokenHeader } from './utils/jwt/jwt'; import type { SignatureAlgorithm } from './utils/jwt/jwa'; declare function getSigningAlgorithm(): SignatureAlgorithm; const header: TokenHeader = { alg: getSigningAlgorithm(), typ: 'JWT', kid: 'active-signing-key', }; ``` ## AI Coding Instructions - Set `typ` to the exact literal `'JWT'`. - Supply an `alg` value that matches the signing or verification configuration. - Set `kid` to the identifier expected by the key lookup process. - Keep header construction aligned with the JWT signing and verification code paths. ## How it works `TokenHeader` is an exported TypeScript interface for the decoded or constructed header portion of a JWT. It declares a required `alg` signature-algorithm field, plus optional `typ` and `kid` fields. [`src/utils/jwt/jwt.ts:38-42`](src/utils/jwt/jwt.ts#L38-L42) - `alg` must have the `SignatureAlgorithm` type. That type accepts `HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, `ES512`, or `EdDSA`. [`src/utils/jwt/jwa.ts:7-23`](src/utils/jwt/jwa.ts#L7-L23) - `typ`, when present, is the literal string `'JWT'`; `kid`, when present, is a string. [`src/utils/jwt/jwt.ts:38-42`](src/utils/jwt/jwt.ts#L38-L42) JWT signing constructs a header with the selected algorithm and `typ: 'JWT'`. When the signing key is an object containing `alg`, signing replaces the function’s algorithm argument with that key’s `alg` value and also places the key’s `kid` value in the header. The header is JSON-serialized, UTF-8 encoded, Base64URL encoded, and becomes the first dot-separated token part. [`src/utils/jwt/jwt.ts:31-32`](src/utils/jwt/jwt.ts#L31-L32) [`src/utils/jwt/jwt.ts:56-75`](src/utils/jwt/jwt.ts#L56-L75) `isTokenHeader` is the runtime type guard associated with this interface. It returns `true` only for a non-null object that has an `alg` property whose value occurs in `AlgorithmTypes`, and whose `typ` property is either absent or exactly `'JWT'`. [`src/utils/jwt/jwt.ts:44-54`](src/utils/jwt/jwt.ts#L44-L54) It does not check that `kid` is a string, and it does not reject additional properties; its checks are limited to `alg` and `typ`. [`src/utils/jwt/jwt.ts:45-51`](src/utils/jwt/jwt.ts#L45-L51) Decoded headers are cast to `TokenHeader` after Base64URL decoding and JSON parsing; `decode` and `decodeHeader` only reject tokens that do not have exactly three parts or whose decoding/parsing throws. Neither function calls `isTokenHeader`. [`src/utils/jwt/jwt.ts:264-290`](src/utils/jwt/jwt.ts#L264-L290) Signature verification calls `isTokenHeader` and throws `JwtHeaderInvalid` when the decoded header fails that guard. It then requires `header.alg` to equal the caller-selected algorithm, throwing `JwtAlgorithmMismatch` otherwise. [`src/utils/jwt/jwt.ts:123-129`](src/utils/jwt/jwt.ts#L123-L129) JWK-set verification also validates the header, requires a truthy `kid` or throws `JwtHeaderRequiresKid`, rejects symmetric header algorithms, and requires the header algorithm to occur in `options.allowedAlgorithms`. [`src/utils/jwt/jwt.ts:209-225`](src/utils/jwt/jwt.ts#L209-L225) ## Relationships - IMPORTS → `decodeBase64Url` - IMPORTS → `encodeBase64Url` - IMPORTS → `AlgorithmTypes` - IMPORTS → `signing` - IMPORTS → `verifying` - IMPORTS → `JwtAlgorithmMismatch` - IMPORTS → `JwtAlgorithmNotAllowed` - IMPORTS → `JwtAlgorithmRequired` - IMPORTS → `JwtHeaderInvalid` - IMPORTS → `JwtHeaderRequiresKid` - IMPORTS → `JwtPayloadRequiresAud` - IMPORTS → `JwtSymmetricAlgorithmNotAllowed` - IMPORTS → `JwtTokenAudience` - IMPORTS → `JwtTokenExpired` - IMPORTS → `JwtTokenInvalid` - IMPORTS → `JwtTokenIssuedAt` - IMPORTS → `JwtTokenIssuer` - IMPORTS → `JwtTokenNotBefore` - IMPORTS → `JwtTokenSignatureMismatched` - IMPORTS → `utf8Decoder` - IMPORTS → `utf8Encoder` # input **Kind:** Function **Source:** [`src/jsx/dom/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/intrinsic-element/components.ts#L423) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function input(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # name **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L224) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` # Runtime **Kind:** Type **Source:** [`src/helper/adapter/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/adapter/index.ts#L8) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other' ``` # UnionToIntersection **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L12) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never ``` # HtmlEscaped **Kind:** Type **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L17) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { isEscaped: true callbacks?: HtmlEscapedCallback[] } ``` # input **Kind:** Function **Source:** [`src/jsx/intrinsic-element/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-element/components.ts#L207) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function input(props) ``` ## Parameters | Name | Type | |---|---| | `props` | `any` | # name **Kind:** API Endpoint **Source:** [`src/middleware/timing/timing.ts`](https://github.com/honojs/hono/blob/main/src/middleware/timing/timing.ts#L224) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` # SSGParams **Kind:** Type **Source:** [`src/helper/ssg/middleware.ts`](https://github.com/honojs/hono/blob/main/src/helper/ssg/middleware.ts#L27) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts SSGParam[] ``` # queryName **Kind:** API Endpoint **Source:** [`src/middleware/method-override/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/method-override/index.ts#L126) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `DELETE /` # RenderToReadableStreamOptions **Kind:** Interface **Source:** [`src/jsx/dom/server.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/server.ts#L32) **Part of:** [Jsx](subsystem-src-jsx) `RenderToReadableStreamOptions` configures how server-rendered JSX is emitted as a readable stream. It controls identifier and namespace settings, bootstrap scripts, chunking behavior, cancellation through an `AbortSignal`, and error handling. ## Properties | Property | Type | |---|---| | `identifierPrefix` | `string` | | `namespaceURI` | `string` | | `nonce` | `string` | | `bootstrapScriptContent` | `string` | | `bootstrapScripts` | `string[]` | | `bootstrapModules` | `string[]` | | `progressiveChunkSize` | `number` | | `signal` | `AbortSignal` | | `onError` | `(error: unknown) => string | void` | ## Diagram ```mermaid graph LR App[JSX application] --> Render[renderToReadableStream] Options[RenderToReadableStreamOptions] --> Render Options --> IDs[identifierPrefix] Options --> Namespace[namespaceURI] Options --> Scripts[Bootstrap scripts and modules] Options --> Stream[progressiveChunkSize] Options --> Abort[signal] Options --> Errors[onError] Render --> Output[ReadableStream] ``` ## Usage ```ts import { renderToReadableStream } from "react-dom/server"; import type { RenderToReadableStreamOptions } from "react-dom/server"; const controller = new AbortController(); const options: RenderToReadableStreamOptions = { identifierPrefix: "app-", namespaceURI: "http://www.w3.org/2000/svg", nonce: "request-nonce", bootstrapScriptContent: "window.__SSR_READY__ = true;", bootstrapScripts: ["/assets/client.js"], bootstrapModules: ["/assets/client.mjs"], signal: controller.signal, onError(error) { console.error("Server render failed:", error); return "render-error"; }, }; const stream = await renderToReadableStream(, options); return new Response(stream, { headers: { "Content-Type": "text/html", }, }); ``` ## AI Coding Instructions - Pass a stable `identifierPrefix` when multiple rendered roots can appear in the same document. - Set `nonce` when the page uses a Content Security Policy that restricts inline scripts. - Use either `bootstrapScripts` or `bootstrapModules` according to the client asset format being loaded. - Pass a request-scoped `AbortSignal` so rendering stops when the client disconnects or the request is cancelled. - Handle errors in `onError`; return a string when the renderer needs an error identifier, or return `void` after logging the error. ## How it works `RenderToReadableStreamOptions` is the exported TypeScript interface for the optional second argument to `renderToReadableStream`; every member is optional. [src/jsx/dom/server.ts:32-42](src/jsx/dom/server.ts#L32-L42) [src/jsx/dom/server.ts:50-53](src/jsx/dom/server.ts#L50-L53) Its declared members are: - `identifierPrefix?: string` - `namespaceURI?: string` - `nonce?: string` - `bootstrapScriptContent?: string` - `bootstrapScripts?: string[]` - `bootstrapModules?: string[]` - `progressiveChunkSize?: number` - `signal?: AbortSignal` - `onError?: (error: unknown) => string | void` [src/jsx/dom/server.ts:32-42](src/jsx/dom/server.ts#L32-L42) At runtime, `renderToReadableStream` checks the option object’s keys. If it contains any key other than `onError`, it calls `console.warn('options are not supported yet, except onError')`. [src/jsx/dom/server.ts:54-56](src/jsx/dom/server.ts#L54-L56) The function forwards only `options.onError` to the underlying streaming renderer. [src/jsx/dom/server.ts:62](src/jsx/dom/server.ts#L62) Consequently, the source does not show runtime handling for `identifierPrefix`, `namespaceURI`, `nonce`, `bootstrapScriptContent`, `bootstrapScripts`, `bootstrapModules`, `progressiveChunkSize`, or `signal`; their presence triggers the warning above. [src/jsx/dom/server.ts:32-42](src/jsx/dom/server.ts#L32-L42) [src/jsx/dom/server.ts:54-56](src/jsx/dom/server.ts#L54-L56) [src/jsx/dom/server.ts:62](src/jsx/dom/server.ts#L62) `onError` is used by the underlying renderer for errors during stream startup and for rejected deferred callbacks. If absent, that renderer defaults it to `console.trace`. [src/jsx/streaming.ts:146-149](src/jsx/streaming.ts#L146-L149) Rejected deferred callbacks are logged with `console.log`, passed to `onError`, and replaced with an empty string for subsequent processing. [src/jsx/streaming.ts:171-195](src/jsx/streaming.ts#L171-L195) Errors caught while starting the stream are passed to `onError`; after the `try`/`catch`, the stream is closed unless it was cancelled. [src/jsx/streaming.ts:152-167](src/jsx/streaming.ts#L152-L167) [src/jsx/streaming.ts:203-217](src/jsx/streaming.ts#L203-L217) # Style **Kind:** Constant **Source:** [`src/helper/css/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/index.ts#L262) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts defaultContext.Style ``` ## Value ```ts defaultContext.Style ``` # VerifyOptionsWithAlg **Kind:** Type **Source:** [`src/utils/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwt.ts#L91) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { alg: SignatureAlgorithm } & VerifyOptions ``` # BodyData **Kind:** Type **Source:** [`src/utils/body.ts`](https://github.com/honojs/hono/blob/main/src/utils/body.ts#L39) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts SimplifyBodyData< Record> > ``` ## Relationships - IMPORTS → `bufferToFormData` # res **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L321) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `PUT /` ## Relationships - DEPENDS_ON → `key` - DEPENDS_ON → `key` # useViewTransition **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L89) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useViewTransition(): [boolean, (callback: () => void) => void] ``` **Returns:** `[boolean, (callback: () => void) => void]` # viewTransition **Kind:** Constant **Source:** [`src/helper/css/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/css/index.ts#L255) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts defaultContext.viewTransition ``` ## Value ```ts defaultContext.viewTransition ``` # Child **Kind:** Type **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L162) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts | string | Promise | number | JSXNode | null | undefined | boolean | Child[] ``` # HonoJsonWebKey **Kind:** Interface **Source:** [`src/utils/jwt/jws.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jws.ts#L23) **Part of:** [Utils](subsystem-src-utils) `HonoJsonWebKey` represents a JSON Web Key with a required `kid` property. The key identifier lets JWT handling code select the matching key from a key set when processing a token. ## Properties | Property | Type | |---|---| | `kid` | `string` | ## Diagram ```mermaid graph LR JWT[JWT header] --> KID[kid] KID --> JWK[HonoJsonWebKey] JWK --> Verify[JWT verification] ``` ## Usage ```ts import type { HonoJsonWebKey } from 'hono/utils/jwt/jws' const signingKey = { kid: 'active-signing-key', } as HonoJsonWebKey const keys: HonoJsonWebKey[] = [signingKey] const key = keys.find((candidate) => candidate.kid === 'active-signing-key') ``` ## AI Coding Instructions - Set `kid` to the identifier expected by the JWT header. - Keep `kid` values unique within a key set. - Preserve the remaining JSON Web Key fields when passing keys to JWT signing or verification code. - Match keys by `kid` before importing them for cryptographic operations. ## How it works `HonoJsonWebKey` is an exported TypeScript interface that extends the platform `JsonWebKey` type with an optional string `kid` property. [`src/utils/jwt/jws.ts:21-25`](src/utils/jwt/jws.ts#L21-L25) It has no runtime implementation, validation, error path, or direct side effect of its own; it is a type declaration. [`src/utils/jwt/jws.ts:23-25`](src/utils/jwt/jws.ts#L23-L25) It is one accepted member of `SignatureKey`, alongside a string or `CryptoKey`, so it can be passed to JWT signing and verification routines. [`src/utils/jwt/jws.ts:27-37`](src/utils/jwt/jws.ts#L27-L37) [`src/utils/jwt/jws.ts:39-48`](src/utils/jwt/jws.ts#L39-L48) When such an object is imported as a signing or verification key, the code passes it to Web Crypto as a JWK with `crypto.subtle.importKey('jwk', ...)`; import failures are propagated by the awaited Web Crypto call. [`src/utils/jwt/jws.ts:66-75`](src/utils/jwt/jws.ts#L66-L75) [`src/utils/jwt/jws.ts:95-104`](src/utils/jwt/jws.ts#L95-L104) For `Jwt.sign`, if the supplied key is an object containing `alg`, its `alg` value selects the signing algorithm and its `kid` value is written into the JWT header. [`src/utils/jwt/jwt.ts:56-75`](src/utils/jwt/jwt.ts#L56-L75) For JWKS verification, `verifyWithJwks` accepts an array of `HonoJsonWebKey` values, requires the decoded token header to contain `kid`, and selects the first key whose `kid` strictly equals the header’s `kid`. [`src/utils/jwt/jwt.ts:197-216`](src/utils/jwt/jwt.ts#L197-L216) [`src/utils/jwt/jwt.ts:228-251`](src/utils/jwt/jwt.ts#L228-L251) If no matching key exists, it throws `JwtTokenInvalid`; if the selected key declares `alg` and it differs from the JWT header algorithm, it throws `JwtAlgorithmMismatch`. [`src/utils/jwt/jwt.ts:248-256`](src/utils/jwt/jwt.ts#L248-L256) ## Relationships - IMPORTS → `getRuntimeKey` - IMPORTS → `decodeBase64` - IMPORTS → `CryptoKeyUsage` - IMPORTS → `JwtAlgorithmNotImplemented` - IMPORTS → `utf8Encoder` # res **Kind:** API Endpoint **Source:** [`src/middleware/cache/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cache/index.ts#L321) **Part of:** [Middleware](subsystem-src-middleware) ## Endpoint `PUT /` ## Relationships - DEPENDS_ON → `key` - DEPENDS_ON → `key` # WebSocketHelperDefineContext **Kind:** Interface **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L101) **Part of:** [Helper](subsystem-src-helper) # EffectData **Kind:** Type **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L14) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts [ readonly unknown[] | undefined, (() => void | (() => void)) | undefined, (() => void) | undefined, (() => void) | undefined, (() => void) | undefined, ] ``` # InvalidIPAddressError **Kind:** Type **Source:** [`src/utils/ipaddr.ts`](https://github.com/honojs/hono/blob/main/src/utils/ipaddr.ts#L42) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts TypeError & { code: typeof INVALID_IP_ADDRESS_ERROR_CODE } ``` # sign **Kind:** Constant **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L190) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts Jwt.sign ``` ## Value ```ts Jwt.sign ``` # WSMessageReceive **Kind:** Type **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L93) **Part of:** [Helper](subsystem-src-helper) ## Definition ```ts string | Blob | ArrayBufferLike ``` # Fragment **Kind:** Function **Source:** [`src/jsx/dom/jsx-dev-runtime.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/jsx-dev-runtime.ts#L23) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function Fragment(props: Record): JSXNode ``` ## Parameters | Name | Type | |---|---| | `props` | `Record` | **Returns:** `JSXNode` # JSONObject **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L25) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts { [key: string]: JSONPrimitive | JSONArray | JSONObject | object | InvalidJSONValue } ``` # verify **Kind:** Constant **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L188) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts Jwt.verify ``` ## Value ```ts Jwt.verify ``` # WSReadyState **Kind:** Type **Source:** [`src/helper/websocket/index.ts`](https://github.com/honojs/hono/blob/main/src/helper/websocket/index.ts#L45) **Part of:** [Helper](subsystem-src-helper) ReadyState for WebSocket `WSReadyState` represents the current readiness state of a WebSocket connection. It is used by the WebSocket helper to expose connection status to calling code, such as UI state or message-handling logic. ## Definition ```ts 0 | 1 | 2 | 3 ``` ## Diagram ```mermaid graph LR Client[Application code] --> Helper[WebSocket helper] Helper --> Socket[WebSocket connection] Socket --> State[WSReadyState] State --> Client ``` ## Usage ```ts import type { WSReadyState } from './helper/websocket'; function handleReadyState(state: WSReadyState) { console.log('WebSocket ready state:', state); } const state: WSReadyState = websocket.readyState; handleReadyState(state); ``` ## AI Coding Instructions - Treat `WSReadyState` as the status contract between the WebSocket helper and its callers. - Keep state checks aligned with the native `WebSocket.readyState` value returned by the active socket. - Update consumers when changing the type so UI and connection logic handle every supported state. - Do not assume a socket is ready to send messages without checking its current ready state. # jsxEscape **Kind:** Function **Source:** [`src/jsx/jsx-runtime.ts`](https://github.com/honojs/hono/blob/main/src/jsx/jsx-runtime.ts#L51) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function jsxEscape(value: string) ``` ## Parameters | Name | Type | |---|---| | `value` | `string` | # SimplifyDeepArray **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L98) **Part of:** [Utils](subsystem-src-utils) A simple extension of Simplify that will deeply traverse array elements. `SimplifyDeepArray` extends `Simplify` by recursively processing array element types. It preserves the array structure while simplifying each non-array element type, making nested array types easier to inspect and consume. ## Definition ```ts T extends any[] ? { [E in keyof T]: SimplifyDeepArray } : Simplify ``` ## Diagram ```mermaid graph LR Input[Input type] --> Check{Is an array?} Check -->|Yes| Recurse[Apply SimplifyDeepArray to element type] Recurse --> Array[Return array of simplified elements] Check -->|No| Simplify[Apply Simplify] ``` ## Usage ```ts type ApiRecord = { id: string; metadata: { createdBy: string; }; }; type NestedRecords = ApiRecord[][]; type SimplifiedRecords = SimplifyDeepArray; // SimplifiedRecords is: // Array> ``` ## AI Coding Instructions - Use `SimplifyDeepArray` when a type may contain nested arrays whose element types need simplification. - Keep the recursive array check before applying `Simplify` to non-array values. - Do not replace array element recursion with a shallow `Simplify`, or nested array elements will remain unsimplified. - Use `SimplifyDeepArray` for type-level readability only; it does not transform runtime values. # verifyWithJwks **Kind:** Constant **Source:** [`src/middleware/jwt/jwt.ts`](https://github.com/honojs/hono/blob/main/src/middleware/jwt/jwt.ts#L187) **Part of:** [Middleware](subsystem-src-middleware) ## Definition ```ts Jwt.verifyWithJwks ``` ## Value ```ts Jwt.verifyWithJwks ``` # Equal **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false ``` # UpdateHook **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L86) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts ( context: Context, node: Node, cb: (context: Context) => void ) => Promise ``` # Context **Kind:** Interface **Source:** [`src/jsx/context.ts`](https://github.com/honojs/hono/blob/main/src/jsx/context.ts#L8) **Part of:** [Jsx](subsystem-src-jsx) `Context` defines a context container with the available `values` and a React `Provider` component. The provider receives a current `value` and wraps child content so the selected context value can be supplied within the JSX tree. ## Properties | Property | Type | |---|---| | `values` | `T[]` | | `Provider` | `FC>` | ## Diagram ```mermaid graph LR Context["Context<T>"] Values["values: T[]"] Provider["Provider"] Value["value: T"] Children["children"] Context --> Values Context --> Provider Provider --> Value Provider --> Children ``` ## Usage ```tsx import type { FC, PropsWithChildren, ReactNode } from "react"; import type { Context } from "./context"; type Theme = "light" | "dark"; declare const ThemeProvider: FC>; const themeContext: Context = { values: ["light", "dark"], Provider: ThemeProvider, }; function WithTheme({ value, children, }: { value: Theme; children: ReactNode; }) { const Provider = themeContext.Provider; return {children}; } ``` ## AI Coding Instructions - Keep `values` typed as the same generic type passed to `Context`. - Pass a `value` prop to `Provider` whenever rendering it. - Preserve `children` when wrapping content with a context provider. - Define the provider with `FC>` so its value type matches the context values. ## Relationships - IMPORTS → `html` - IMPORTS → `JSXFragmentNode` - IMPORTS → `DOM_RENDERER` - IMPORTS → `createContextProviderFunction` # HasRequiredKeys **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L111) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts RequiredKeysOf extends never ? false : true ``` # PendingType **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L82) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts | 0 | 1 | 2 ``` # RemoveBlankRecord **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L18) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts T extends Record ? (K extends string ? T : never) : never ``` # Auth **Kind:** Type **Source:** [`src/utils/basic-auth.ts`](https://github.com/honojs/hono/blob/main/src/utils/basic-auth.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts (req: Request) => { username: string; password: string } | undefined ``` ## Relationships - IMPORTS → `decodeBase64` # createRef **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L375) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function createRef(): RefObject ``` **Returns:** `RefObject` # BaseMime **Kind:** Type **Source:** [`src/utils/mime.ts`](https://github.com/honojs/hono/blob/main/src/utils/mime.ts#L33) **Part of:** [Utils](subsystem-src-utils) Union types for BaseMime `BaseMime` is a union type that represents the base MIME values defined in `src/utils/mime.ts`. It constrains APIs and variables that work with those MIME values so callers can pass only members of the union. ## Definition ```ts (typeof _baseMimes)[keyof typeof _baseMimes] ``` ## Diagram ```mermaid graph LR Input[Content-Type value] --> BaseMime[BaseMime] BaseMime --> Headers[HTTP headers] BaseMime --> Validation[Type-safe MIME handling] ``` ## Usage ```ts import type { BaseMime } from './utils/mime'; function createHeaders(mime: BaseMime) { return { 'Content-Type': mime, }; } declare const mime: BaseMime; const headers = createHeaders(mime); ``` ## AI Coding Instructions - Import `BaseMime` with `import type` when it is only used as a TypeScript type. - Use `BaseMime` for function parameters, configuration fields, and header builders that accept base MIME values. - Keep MIME literals aligned with the union declared in `src/utils/mime.ts`. - Do not cast arbitrary strings to `BaseMime`; validate external input before passing it to typed APIs. # MemorableFC **Kind:** Type **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L403) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts FC & { [DOM_MEMO]: (prevProps: Readonly, nextProps: Readonly) => boolean } ``` # ContentfulStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L72) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts Exclude ``` # PreserveNodeType **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L37) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts | 1 | 2 ``` # ContentlessStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L71) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 101 | 204 | 205 | 304 ``` # RenderToStringOptions **Kind:** Interface **Source:** [`src/jsx/dom/server.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/server.ts#L11) **Part of:** [Jsx](subsystem-src-jsx) `RenderToStringOptions` configures server-side JSX rendering to a string. Its `identifierPrefix` field sets a prefix for generated identifiers, helping separate IDs when rendering multiple independent trees. ## Properties | Property | Type | |---|---| | `identifierPrefix` | `string` | ## Diagram ```mermaid graph LR Options[RenderToStringOptions] --> Prefix[identifierPrefix: string] Prefix --> Renderer[Server-side JSX renderer] Renderer --> HTML[Rendered HTML string] ``` ## Usage ```ts import { renderToString } from "./jsx/dom/server"; const options: RenderToStringOptions = { identifierPrefix: "profile-", }; const html = renderToString(, options); ``` ## AI Coding Instructions - Pass `identifierPrefix` when rendered output may share a document with other rendered trees. - Keep the prefix stable between server rendering and client hydration when generated IDs must match. - Use distinct prefixes for separate application roots to avoid identifier collisions. - Treat `identifierPrefix` as a string value; do not pass `null` or omit it when the calling API requires options. ## How it works `RenderToStringOptions` is an exported TypeScript interface for the second argument of `renderToString`. It declares one optional string property, `identifierPrefix`. [src/jsx/dom/server.ts:11-13] `renderToString` defaults its `options` argument to `{}`. [src/jsx/dom/server.ts:21] At runtime, it checks whether `options` has any own enumerable keys; when it does, it writes `options are not supported yet` through `console.warn`. [src/jsx/dom/server.ts:22-24] The implementation does not read `identifierPrefix` or otherwise apply an option value while producing the string. [src/jsx/dom/server.ts:21-29] The rendering call can throw `Error('Async component is not supported in renderToString')` if `element?.toString() ?? ''` does not result in a string; this behavior is independent of `RenderToStringOptions`. [src/jsx/dom/server.ts:25-28] ## Relationships - IMPORTS → `renderToReadableStream` # Cookie **Kind:** Type **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts Record ``` ## Relationships - IMPORTS → `tryDecodeURIComponent` # useFormStatus **Kind:** Function **Source:** [`src/jsx/dom/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/hooks/index.ts#L41) **Part of:** [Jsx](subsystem-src-jsx) This hook returns the current form status `useFormStatus` reads the status associated with the nearest parent form while a form action is running. Call it from a component rendered inside that form to update UI based on the current status. ## Signature ```ts function useFormStatus(): FormStatus ``` **Returns:** `FormStatus` ## Diagram ```mermaid graph LR Form[Form] --> Child[Child component] Child --> Hook[useFormStatus] Hook --> Status[Current form status] Status --> UI[Button and feedback UI] ``` ## Usage ```tsx import { useFormStatus } from "react-dom"; function SubmitButton() { const { pending } = useFormStatus(); return ( ); } async function saveProfile(formData: FormData) { await fetch("/api/profile", { method: "POST", body: formData, }); } export function ProfileForm() { return (
); } ``` ## AI Coding Instructions - Call `useFormStatus` from a component nested inside the related `
`. - Do not call the hook in the same component that renders the `` when reading that form’s status. - Use the returned status to disable submit controls while the form action is pending. - Keep status-dependent UI near the form controls that it affects. # AnimationEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L38) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.AnimationEvent ``` # CookiePrefixOptions **Kind:** Type **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L29) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 'host' | 'secure' ``` # ClipboardEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L33) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.ClipboardEvent ``` # CustomHeader **Kind:** Type **Source:** [`src/utils/headers.ts`](https://github.com/honojs/hono/blob/main/src/utils/headers.ts#L355) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts string & {} ``` # CSSProperties **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L12) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts JSX.CSSProperties ``` # decodeURIComponent_ **Kind:** Constant **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L319) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts decodeURIComponent ``` ## Value ```ts decodeURIComponent ``` # DeprecatedStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L8) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 305 | 306 ``` # DOMAttributes **Kind:** Type **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L38) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts HonoJSX.HTMLAttributes ``` # DragEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L40) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.DragEvent ``` # Expect **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts T ``` # ErrorHandler **Kind:** Type **Source:** [`src/jsx/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/components.ts#L47) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts (error: Error) => void ``` # HtmlEscapedCallback **Kind:** Type **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L16) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts (opts: HtmlEscapedCallbackOpts) => Promise | undefined ``` # ErrorHandler **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L32) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts (error: any, retry: () => void) => Child | undefined ``` # HtmlEscapedString **Kind:** Type **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L21) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts string & HtmlEscaped ``` # Event **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L29) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.Event ``` # IfAnyThenEmptyObject **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L21) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 0 extends 1 & T ? {} : T ``` # FallbackRender **Kind:** Type **Source:** [`src/jsx/components.ts`](https://github.com/honojs/hono/blob/main/src/jsx/components.ts#L48) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts (error: Error) => Child ``` # InfoStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 100 | 101 | 102 | 103 ``` # FocusEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L32) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.FocusEvent ``` # InterfaceToType **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L102) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts T extends Function ? T : { [K in keyof T]: InterfaceToType } ``` # HasRenderToDom **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L30) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts FC & { [DOM_RENDERER]: FC } ``` ## Relationships - IMPORTS → `toArray` - IMPORTS → `DOM_ERROR_HANDLER` - IMPORTS → `DOM_INTERNAL_TAG` - IMPORTS → `DOM_MEMO` - IMPORTS → `DOM_RENDERER` - IMPORTS → `DOM_STASH` - IMPORTS → `globalContexts` - IMPORTS → `useContext` - IMPORTS → `STASH_EFFECT` - IMPORTS → `normalizeIntrinsicElementKey` - IMPORTS → `styleObjectForEach` - IMPORTS → `createContext` # InvalidJSONValue **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L28) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts undefined | symbol | ((...args: unknown[]) => unknown) ``` # InputEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L34) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.InputEvent ``` # IsAny **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L114) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts boolean extends (T extends never ? true : false) ? true : false ``` # IntrinsicElements **Kind:** Interface **Source:** [`src/jsx/intrinsic-elements.ts`](https://github.com/honojs/hono/blob/main/src/jsx/intrinsic-elements.ts#L924) **Part of:** [Jsx](subsystem-src-jsx) # JSONArray **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L24) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts (JSONPrimitive | JSONObject | JSONArray)[] ``` # JSONPrimitive **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L23) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts string | boolean | number | null ``` # KeyboardEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L31) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.KeyboardEvent ``` # JSONValue **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L39) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts JSONObject | JSONArray | JSONPrimitive ``` # keyframes **Kind:** Constant **Source:** [`src/jsx/dom/css.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/css.ts#L249) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts defaultContext.keyframes ``` ## Value ```ts defaultContext.keyframes ``` # MouseEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L30) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.MouseEvent ``` # NotEqual **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L10) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts true extends Equal ? false : true ``` # Node **Kind:** Type **Source:** [`src/jsx/dom/render.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/render.ts#L80) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts NodeString | NodeObject ``` # Pattern **Kind:** Type **Source:** [`src/utils/url.ts`](https://github.com/honojs/hono/blob/main/src/utils/url.ts#L6) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts readonly [string, string, RegExp | true] | '*' ``` # PointerEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L35) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.PointerEvent ``` # RedirectStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L9) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 308 ``` # Props **Kind:** Type **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L27) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Record ``` ## Relationships - IMPORTS → `html` - IMPORTS → `escapeToBuffer` - IMPORTS → `resolveCallbackSync` - IMPORTS → `stringBufferToString` - IMPORTS → `DOM_RENDERER` - IMPORTS → `DOM_MEMO` - IMPORTS → `captureRenderContext` - IMPORTS → `createContext` - IMPORTS → `globalContexts` - IMPORTS → `runWithRenderContext` - IMPORTS → `useContext` - IMPORTS → `domRenderers` - IMPORTS → `title` - IMPORTS → `isValidAttributeName` - IMPORTS → `isValidTagName` - IMPORTS → `normalizeIntrinsicElementKey` - IMPORTS → `styleObjectForEach` # ServerErrorStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L40) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ``` # PropsWithChildren **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L11) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts P & { children?: Child | undefined } ``` # SignatureAlgorithm **Kind:** Type **Source:** [`src/utils/jwt/jwa.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwa.ts#L23) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts keyof typeof AlgorithmTypes ``` # reactAPICompatVersion **Kind:** Constant **Source:** [`src/jsx/base.ts`](https://github.com/honojs/hono/blob/main/src/jsx/base.ts#L459) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts '19.0.0-hono-jsx' ``` ## Value ```ts '19.0.0-hono-jsx' ``` # SignatureKey **Kind:** Type **Source:** [`src/utils/jwt/jws.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jws.ts#L27) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts string | HonoJsonWebKey | CryptoKey ``` # RefObject **Kind:** Type **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L318) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts { current: T } ``` # SignedCookie **Kind:** Type **Source:** [`src/utils/cookie.ts`](https://github.com/honojs/hono/blob/main/src/utils/cookie.ts#L9) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts Record ``` # RootOptions **Kind:** Type **Source:** [`src/jsx/dom/client.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/client.ts#L15) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts Record ``` # Simplify **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L93) **Part of:** [Utils](subsystem-src-utils) Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. `Simplify` remaps the properties of `T` into a plain object type, which makes expanded type hints easier to read in editors. It can also convert an interface-shaped type into a type alias shape for assignability checks. ## Definition ```ts { [KeyType in keyof T]: T[KeyType] } & {} ``` ## Diagram ```mermaid graph LR A[Input type T] --> B[Simplify] B --> C[Remapped object properties] C --> D[Clearer editor type hints] C --> E[Type alias assignability] ``` ## Usage ```ts type Simplify = { [Key in keyof T]: T[Key]; }; interface User { id: string; name: string; } type UserRecord = Simplify; const user: UserRecord = { id: "user_123", name: "Ada", }; ``` ## AI Coding Instructions - Apply `Simplify` when an intersection or mapped type produces hard-to-read editor hints. - Keep `Simplify` type-only; it does not transform values at runtime. - Use it near public type boundaries where consumers benefit from a remapped object shape. - Do not expect `Simplify` to change property values, optionality, or readonly modifiers. # StringBuffer **Kind:** Type **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L37) **Part of:** [Utils](subsystem-src-utils) StringBuffer contains string and Promise alternately The length of the array will be odd, the odd numbered element will be a string, and the even numbered element will be a Promise. When concatenating into a single string, it must be processed from the tail. `StringBuffer` stores alternating `string` and `Promise` values for HTML assembly. Its array length is odd: odd-numbered elements are strings, even-numbered elements are `Promise`, and consumers must concatenate entries from the tail to preserve output order. ## Definition ```ts (string | Promise)[] ``` ## Diagram ```mermaid graph LR Start["String segment"] --> Async["Promise<string>"] Async --> End["String segment"] End --> Tail["Process from tail"] Tail --> HTML["Combined HTML string"] ``` ## Usage ```ts import type { StringBuffer } from './utils/html'; const buffer: StringBuffer = [ '
', Promise.resolve('

Loaded content

'), '
', ]; async function joinBuffer(buffer: StringBuffer): Promise { let html = ''; for (const entry of [...buffer].reverse()) { html = `${await entry}${html}`; } return html; } const html = await joinBuffer(buffer); //

Loaded content

``` ## AI Coding Instructions - Keep entries alternating between `string` and `Promise`, with strings at the beginning and end. - Preserve the odd-length array shape when creating or transforming a `StringBuffer`. - Concatenate entries from the tail; processing from the head can produce incorrect ordering around async content. - Await promise entries before prepending their resolved HTML to the accumulated output. # Style **Kind:** Constant **Source:** [`src/jsx/dom/css.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/css.ts#L263) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts defaultContext.Style ``` ## Value ```ts defaultContext.Style ``` # StringBufferWithCallbacks **Kind:** Type **Source:** [`src/utils/html.ts`](https://github.com/honojs/hono/blob/main/src/utils/html.ts#L38) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts StringBuffer & { callbacks: HtmlEscapedCallback[] } ``` # TouchEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L36) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.TouchEvent ``` # StringLiteralUnion **Kind:** Type **Source:** [`src/utils/types.ts`](https://github.com/honojs/hono/blob/main/src/utils/types.ts#L120) **Part of:** [Utils](subsystem-src-utils) String literal types with auto-completion `StringLiteralUnion` combines a set of string literal values with `string` while preserving editor autocomplete for the known literals. It is used when an API accepts predefined string options but must also allow custom string values. ## Definition ```ts T | (string & Record) ``` ## Diagram ```mermaid graph LR A[Known string literals] --> C[StringLiteralUnion] B[Custom string values] --> C C --> D[Autocomplete for known values] C --> E[Accepts any string] ``` ## Usage ```ts import type { StringLiteralUnion } from "../utils/types"; type Theme = StringLiteralUnion<"light" | "dark">; const defaultTheme: Theme = "light"; const customTheme: Theme = "system"; ``` ## AI Coding Instructions - Use `StringLiteralUnion` for string options that have known values and allow arbitrary custom values. - Keep the known options as string literal unions, such as `"light" | "dark"`. - Do not replace this type with `string` when autocomplete for known values is expected. - Use the type in public option and configuration definitions where custom string extensions are valid. # TransitionEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L39) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.TransitionEvent ``` # SuccessStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L7) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226 ``` # useId **Kind:** Function **Source:** [`src/jsx/hooks/index.ts`](https://github.com/honojs/hono/blob/main/src/jsx/hooks/index.ts#L370) **Part of:** [Jsx](subsystem-src-jsx) ## Signature ```ts function useId(): string ``` **Returns:** `string` # SymmetricAlgorithm **Kind:** Type **Source:** [`src/utils/jwt/jwa.ts`](https://github.com/honojs/hono/blob/main/src/utils/jwt/jwa.ts#L25) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts 'HS256' | 'HS384' | 'HS512' ``` # viewTransition **Kind:** Constant **Source:** [`src/jsx/dom/css.ts`](https://github.com/honojs/hono/blob/main/src/jsx/dom/css.ts#L256) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts defaultContext.viewTransition ``` ## Value ```ts defaultContext.viewTransition ``` # UnOfficalStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L58) **Part of:** [Utils](subsystem-src-utils) ## Definition ```ts UnofficialStatusCode ``` # WheelEvent **Kind:** Type **Source:** [`src/jsx/types.ts`](https://github.com/honojs/hono/blob/main/src/jsx/types.ts#L37) **Part of:** [Jsx](subsystem-src-jsx) ## Definition ```ts globalThis.WheelEvent ``` # UnofficialStatusCode **Kind:** Type **Source:** [`src/utils/http-status.ts`](https://github.com/honojs/hono/blob/main/src/utils/http-status.ts#L52) **Part of:** [Utils](subsystem-src-utils) `UnofficialStatusCode` can be used to specify an unofficial status code. `UnofficialStatusCode` represents HTTP status codes that are not part of the standard status-code set. Use it when an API response or error path needs to declare an unofficial HTTP status value with type checking. ## Definition ```ts -1 ``` ## Diagram ```mermaid graph LR Application[Application code] --> Status[UnofficialStatusCode] Status --> Response[HTTP response status] ``` ## Usage ```ts import type { UnofficialStatusCode } from './utils/http-status'; type ErrorResponse = { statusCode: UnofficialStatusCode; message: string; }; const response: ErrorResponse = { statusCode: 419, message: 'Session expired', }; ``` ## AI Coding Instructions - Use `UnofficialStatusCode` for response paths that return a supported unofficial HTTP status value. - Keep standard HTTP status codes typed through the corresponding standard status-code type. - Do not cast arbitrary numbers to `UnofficialStatusCode`; add a value only when it belongs in the type definition. - Preserve the type when passing status codes through response helpers and error handlers. # Jsx ## Overview Jsx is the rendering layer that turns JSX elements and function components into either escaped HTML for server output or mutable browser DOM. Its public JSX entrypoint exports element construction, fragments, context, error boundaries, suspense, children [helpers](subsystem-src-helper), and hook APIs; it also exposes a React-compatibility version string. [src/jsx/index.ts:6-73; src/jsx/base.ts:459] The common representation is `JSXNode`, which holds a string tag or function tag, props, optional key, and children. Construction rejects invalid non-function tag names before rendering starts. [src/jsx/base.ts:171-184] A child may be text, a promise of text, a number, a JSX node, nullish or boolean content, or nested child arrays. [src/jsx/base.ts:162-170] `jsx` attaches explicit children to props, removes `key` from the props passed to rendering, delegates node selection to `jsxFn`, and stores the key on the resulting node. [src/jsx/base.ts:327-339] `jsxFn` distinguishes function components, special intrinsic-element component functions, namespace roots, and ordinary HTML tags. [src/jsx/base.ts:342-373] The same JSX tree can therefore enter a string-rendering path through `JSXNode.toString()` or a browser-rendering path through `createRoot`, `render`, or `hydrateRoot`. [src/jsx/base.ts:196-207; src/jsx/dom/client.ts:23-65; src/jsx/dom/render.ts:783-799] ## How it works ## Server HTML rendering A `JSXNode.toString()` call creates a callback-aware string buffer and runs serialization inside `runWithRenderContext`. A synchronous buffer returns directly; a buffer containing deferred work goes through `stringBufferToString`. [src/jsx/base.ts:196-207] Element serialization writes the opening tag, normalizes intrinsic keys, ignores invalid attribute names, escapes text attribute values, converts style objects into CSS declarations, and writes allowed true boolean attributes as empty attributes. [src/jsx/base.ts:209-249] The serializer rejects simultaneous children and `dangerouslySetInnerHTML`, replaces children with raw `__html` when that property is used alone, and rejects function-valued props unless their name begins with `on` or is `ref`. Event handlers and refs are ignored in server component output rather than emitted as attributes. [src/jsx/base.ts:250-267] Void tags without children close immediately; other tags serialize their children and emit a closing tag. [src/jsx/base.ts:271-280] Child processing escapes strings, omits booleans and nullish values, appends numbers, recursively descends into arrays, preserves callback lists on already escaped HTML, and inserts promises into the buffer for later resolution. [src/jsx/base.ts:135-159] A function component receives copied props with children injected, then its return value is handled as omitted content, deferred output, a nested JSX node, a child array, escaped HTML, a number, or escaped text. [src/jsx/base.ts:284-317] Async function-component results that resolve to nodes or child arrays are rendered under a captured render context when contexts exist, so deferred subtree serialization resumes with the values observed before suspension. [src/jsx/base.ts:116-133; src/jsx/base.ts:298-304] `Fragment` is a node whose buffer serialization writes only its children. [src/jsx/base.ts:321-324; src/jsx/base.ts:421-434] The `hono/jsx/server` compatibility surface offers string and readable-stream renderers. `renderToString` invokes the element’s string conversion and throws when that conversion is asynchronous. [src/jsx/dom/server.ts:21-29] `renderToReadableStream` converts non-object content to text and delegates the result plus its error callback to the JSX streaming implementation. [src/jsx/dom/server.ts:50-63] The streaming renderer first resolves callbacks scheduled before streaming, enqueues the initial encoded HTML, then executes stream-phase callbacks and enqueues their resolved output. Promise failures in deferred callbacks are logged, passed to `onError`, and replaced with empty output; failures in stream startup are also passed to `onError` before the stream closes unless cancelled. [src/jsx/streaming.ts:146-219] `Suspense` examines child results while retaining render context for a thrown promise. When work is pending, it writes a template marker and fallback initially, then emits a template-and-script replacement payload once the child results settle. [src/jsx/streaming.ts:42-85; src/jsx/streaming.ts:87-136] `StreamingContext` carries an optional script nonce, and suspense uses it on generated replacement scripts. [src/jsx/streaming.ts:18-32; src/jsx/streaming.ts:50; src/jsx/streaming.ts:105-117] The experimental server `ErrorBoundary` renders fallback content for synchronous child failures or rejected deferred work. For streamed deferred content, it installs marker replacement callbacks and emits a replacement script when an error arrives after the initial output. [src/jsx/components.ts:50-125; src/jsx/components.ts:128-180] ## Context during rendering `createContext` creates a callable provider with a default-value stack, aliases `Provider` to that callable context, records the context globally, and attaches a DOM-specific provider renderer through a symbol. [src/jsx/context.ts:213-250] On the server, a provider pushes its value, stringifies its child or fragment, then pops the value on completion, error, or promise settlement. [src/jsx/context.ts:215-240] `useContext` reads the top value for the current render store, or the default if no value was installed in that store. [src/jsx/context.ts:98-107; src/jsx/context.ts:253-261] Render stores use `AsyncLocalStorage` when the runtime can load `node:async_hooks` through supported process APIs. [src/jsx/context.ts:34-67] With that storage, `runWithRenderContext` installs a fresh weak-map store and propagation continues across awaits. [src/jsx/context.ts:161-172] Without it, the fallback store exists only during synchronous work; an async context read after an await falls back to the default value and emits a warning once while fallback async renders are in flight. [src/jsx/context.ts:73-80; src/jsx/context.ts:174-188] ## Browser rendering and updates `createRoot` returns `render` and `unmount` methods for an element or document fragment. Its initial render builds a wrapper component whose state contains the JSX tree; subsequent `render` calls update that state, while calls after `unmount` throw. [src/jsx/dom/client.ts:23-65] `hydrateRoot` creates that root and immediately calls `render`, so hydration follows the same behavior as rendering in this implementation. [src/jsx/dom/client.ts:68-84] The DOM renderer transforms primitive children into text nodes and attaches hook storage to function nodes. It also wraps `svg` and `math` descendants in a namespace context with the corresponding namespace URI. [src/jsx/dom/render.ts:667-703] Building a function node selects its DOM-specific renderer symbol when present, merges default props when defined, and calls the selected function while the node sits on `buildDataStack`. [src/jsx/dom/render.ts:274-290] During reconciliation, old children are matched by text status, or by key and tag when keyed, or by tag otherwise. Matched function components can skip rebuilding when their memo comparator reports equal props and their captured context values are unchanged. [src/jsx/dom/render.ts:541-583] `memo` attaches that comparator and the source component through renderer symbols, with shallow prop comparison as the default. [src/jsx/base.ts:376-418] Applying nodes creates text nodes or namespaced/plain elements, applies props, recurses into children, positions elements in the container, and then runs insertion effects, layout effects, and scheduled effects in that order. [src/jsx/dom/render.ts:387-480] Property application attaches and removes event listeners, writes `dangerouslySetInnerHTML`, invokes callback or object refs with cleanup handling, updates style strings or objects, and handles form value, checked, selected, and ordinary attributes separately. [src/jsx/dom/render.ts:164-272] `useState` stores each hook’s state by call position in the current function node’s stash. A changed state value schedules a renderer update; outside a build stack, it returns the initial value and a no-op setter. [src/jsx/hooks/index.ts:182-243] `use` caches fulfilled or rejected promise outcomes and throws an unresolved promise, allowing DOM `Suspense` to register a retry after settlement and return its fallback. [src/jsx/hooks/index.ts:336-350; src/jsx/dom/components.ts:25-38] DOM error boundaries rethrow promises, but invoke `onError` and return fallback content for non-promise errors. [src/jsx/dom/components.ts:7-23] ## Configuration This part does not read an application environment variable or configuration file in the examined paths. Its runtime-sensitive setting is availability of `AsyncLocalStorage`, discovered through process APIs; the fallback behavior is a synchronous-only context store and a warning for post-await context reads. [src/jsx/context.ts:34-80; src/jsx/context.ts:161-188] The server compatibility options declare familiar fields, but string rendering warns whenever any options are passed. [src/jsx/dom/server.ts:11-29] Readable-stream rendering accepts an error callback; it warns when passed any option other than `onError`. [src/jsx/dom/server.ts:32-62] Client root options are accepted as a generic record but currently only cause a warning when nonempty. [src/jsx/dom/client.ts:15-35] CSS context creation takes a required style-element identifier and optional class-name slug and invalid-slug callback. [src/jsx/dom/css.ts:171-188] In the browser, the resulting CSS object locates `style#`, throws asynchronously if that stylesheet cannot be found, and inserts a rule only when its class name has not already been added. [src/jsx/dom/css.ts:77-113] On the server-side CSS helper path, the same identifier is used to locate or append generated CSS to the style element, and an optional nonce is retained for generated append scripts. [src/helper/css/index.ts:72-86; src/helper/css/index.ts:88-121; src/helper/css/index.ts:192-206] ## Wiring The server boundary is the base node serializer plus HTML helpers for raw escaped values, escaping buffers, callback resolution, and buffer-to-string conversion. [src/jsx/base.ts:1-14; src/jsx/base.ts:196-207] Streaming builds on those escaped HTML callbacks and calls `childrenToString`, context capture, DOM suspense rendering metadata, and DOM build-stack support for promise suspension. [src/jsx/streaming.ts:6-16] The browser boundary begins at `src/jsx/dom`: its client root calls the DOM renderer, while the renderer consumes shared base node types, child normalization, context, hooks, and symbol contracts. [src/jsx/dom/client.ts:6-9; src/jsx/dom/render.ts:1-16] Symbols isolate cross-layer renderer metadata: DOM renderer overrides, error handlers, hook stashes, internal tags, memo comparators, and form-action permalinks. [src/jsx/constants.ts:1-6] Intrinsic metadata elements are intercepted by `jsxFn` through the intrinsic tag map. [src/jsx/base.ts:342-359] Their server path records emitted title, script, style, link, and meta markup against the rendering context, removes duplicates according to per-tag keys, and inserts retained markup before `` when that closing tag is present. [src/jsx/intrinsic-element/components.ts:17-91; src/jsx/intrinsic-element/common.ts:3-23] The ordinary element path remains `JSXNode` serialization, which is why metadata behavior is conditional rather than global. [src/jsx/intrinsic-element/components.ts:93-119; src/jsx/base.ts:209-280] The CSS helper outside this directory depends directly on JSX DOM symbols and CSS DOM objects: it attaches a DOM renderer to its `Style` component so browser rendering can create the style element while server rendering uses HTML callbacks to collect rules. [src/helper/css/index.ts:6-10; src/helper/css/index.ts:81-84; src/helper/css/index.ts:192-206] This is the practical boundary: JSX owns tree construction, string rendering, context, streaming, and DOM reconciliation; CSS generation and HTML escaping remain in their respective helper modules. [src/jsx/base.ts:1-24; src/jsx/dom/render.ts:1-16; src/helper/css/index.ts:6-28] 147 entities in `src/jsx`. **2 other subsystems depend on it**, which makes it the 3rd most depended-upon part of this codebase. ## What it is made of Its 147 entities sit in 24 files under `src/jsx`: 87 functions, 31 type aliases, 22 constants, 5 interfaces and 2 more. `index.ts` holds 26 of them — more than any other file here. ## Where work enters - [`RenderToStringOptions`](interface-rendertostringoptions) — `src/jsx/dom/server.ts`:11 - [`RenderToReadableStreamOptions`](interface-rendertoreadablestreamoptions) — `src/jsx/dom/server.ts`:32 - [`Props`](type-props) — `src/jsx/base.ts`:27 - [`DOMAttributes`](type-domattributes) — `src/jsx/base.ts`:38 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. ## Boundaries **2 other subsystems depend on this one** — `Middleware`, `Helper`. Changing what it exposes changes them. Those 2 hold 3 edges between them, unevenly: `Helper` reaches in across 2 edges, while another holds one. 27 edges leave it against 3 arriving — it reads more of this repository than this repository reads of it. What they reach is narrower than the folder: 3 of its 147 members carry every inbound edge — `renderToReadableStream` (1), `DOM_RENDERER` (1) and `createCssJsxDomObjects` (1). Of the 27 it sends out, 18 go to `Helper` — more than to any other. It depends on `Helper`, `Utils`, and on nothing else in this repository. ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `use*` | exported symbols | 22 | `useId`, `useRef`, `useMemo`, `useState` | | `create*` | exported symbols | 8 | `createRef`, `createRoot`, `createPortal`, `createContext` | | `jsx*` | exported symbols | 5 | `jsxFn`, `jsxDEV`, `jsxAttr`, `jsxEscape` | # Middleware ## Overview Middleware in this directory is made of factories that return handlers operating on Hono’s request `Context` and its downstream `next` continuation. Some act before calling `next`, such as authentication, request-body limiting, language selection, request IDs, and method rewriting; others inspect or modify the completed response after `next` returns, such as compression, ETags, cache storage, security headers, logging, timing, and URL canonicalization. [src/middleware/basic-auth/index.ts:105-152; src/middleware/compress/index.ts:88-135; src/middleware/etag/index.ts:84-131; src/middleware/secure-headers/secure-headers.ts:221-234] The central data path is therefore a mutable context: middleware reads request method, URL, headers, body, route information, and runtime execution context; it may set context variables, replace `c.req.raw`, replace `c.res`, return a response early, or throw an `HTTPException`. [src/middleware/body-limit/index.ts:61-109; src/middleware/language/language.ts:304-307; src/middleware/request-id/request-id.ts:46-58; src/middleware/method-not-allowed/index.ts:64-140] The part contains middleware intended for cross-cutting HTTP concerns rather than application controllers. Its exported handlers are attached by the application or router, and their effect depends on registration order because many surround the downstream chain with `await next()`. [src/middleware/cors/index.ts:96-156; src/middleware/cache/index.ts:266-323; src/middleware/powered-by/index.ts:30-34] ## How it works A typical request can first be rejected or transformed before route handling. `bodyLimit` passes requests without a body through, compares a trustworthy `Content-Length` against the configured limit when present, or reads an unbounded or transfer-encoded stream into chunks, rejects once the accumulated size exceeds the limit, and reconstructs `c.req.raw` before continuing. [src/middleware/body-limit/index.ts:61-109] `csrf` only examines unsafe form-style requests; it continues when either the configured `Sec-Fetch-Site` policy or the configured origin policy accepts the request, otherwise it throws a forbidden response. [src/middleware/csrf/index.ts:94-150] Authentication middleware follows the same gate pattern. Basic authentication parses the incoming credentials, either invokes `verifyUser` or compares against configured users with `timingSafeEqual`, invokes an optional success callback, and only then calls `next`; otherwise it throws an unauthorized response with a `WWW-Authenticate` challenge. [src/middleware/basic-auth/index.ts:105-152] Bearer authentication reads a configurable header, validates its scheme and token syntax, checks the token through a verifier or timing-safe comparison, and distinguishes malformed credentials from an invalid token through separate HTTP exceptions. [src/middleware/bearer-auth/index.ts:156-220] JWT and JWK middleware similarly read a bearer token from a configurable header, with an optional cookie fallback. JWT verifies against the configured secret and algorithm, while JWK verification can combine supplied keys with keys fetched from a configured JWKS location; both place a verified payload in `jwtPayload` before continuing. [src/middleware/jwt/jwt.ts:78-161; src/middleware/jwk/jwk.ts:78-172] JWK authentication may allow a missing token when `allow_anon` is set, but malformed credentials and missing tokens otherwise result in unauthorized responses. [src/middleware/jwk/jwk.ts:81-135] Request-scoped state is added directly to the context. `requestId` accepts a valid inbound identifier or generates one, stores it as `requestId`, and emits it in the configured response header. [src/middleware/request-id/request-id.ts:41-58] `languageDetector` merges caller options with defaults, validates them, tries configured detectors in order, optionally caches a found language in a cookie, writes the final or fallback language to `language`, and then invokes the downstream handler. [src/middleware/language/language.ts:221-267; src/middleware/language/language.ts:292-307] In Node environments, `contextStorage` runs the downstream continuation in `AsyncLocalStorage`, allowing code later in that asynchronous chain to retrieve the current context. [src/middleware/context-storage/index.ts:6-10; src/middleware/context-storage/index.ts:43-58] The downstream response is then available to wrapping middleware. `compress` checks response status, existing encodings, request method, content length, content type, and `Cache-Control`; if compression is applicable, it adds `Vary: Accept-Encoding`, negotiates a supported content encoding from the request, pipes the body through `CompressionStream`, removes `Content-Length`, and weakens a strong ETag. [src/middleware/compress/index.ts:88-135] `etag` applies only to successful GET, HEAD, or QUERY responses, accepts an existing ETag or derives one from a cloned response body, and replaces a matching response with a bodyless not-modified response containing retained headers. [src/middleware/etag/index.ts:79-131] Cache middleware first bypasses cache lookup for methods other than GET or QUERY and for requests carrying `Authorization`. For eligible requests it builds a cache key from the request URL or custom key, includes a content digest and representation metadata for QUERY requests, incorporates configured `Vary` request-header values, and returns a cache match immediately. [src/middleware/cache/index.ts:95-152; src/middleware/cache/index.ts:266-304] After a miss, it only stores configured cacheable statuses and declines storage when response `Vary` is incompatible with configuration, cache-control prevents caching, or the response sets a cookie. [src/middleware/cache/index.ts:72-80; src/middleware/cache/index.ts:306-322] Composition [helpers](subsystem-src-helper) alter this control flow. `some` tries handlers in order, proceeding after the first non-failing result and rethrowing the most recent error if none succeeds. [src/middleware/combine/index.ts:38-68] `every` composes every supplied handler while treating a `false` result as an unmet condition, and `except` turns path patterns and predicate conditions into an exclusion around that composition. [src/middleware/combine/index.ts:99-116; src/middleware/combine/index.ts:141-165] ## API surface The HTTP surface is middleware-oriented: its handlers are registered on application routes rather than acting as standalone controllers. The parsed surface records that most declared endpoints have no guard or middleware of their own, which is consistent with these factories being attached around application handlers rather than replacing them. [parsed surface] Authentication factories validate required setup at construction time. `basicAuth` requires either credential fields or `verifyUser`; `bearerAuth` requires configured token material or `verifyToken`; JWT requires a secret and algorithm; and JWK requires keys or a JWKS location plus Web Crypto key import support. [src/middleware/basic-auth/index.ts:80-103; src/middleware/bearer-auth/index.ts:104-120; src/middleware/jwt/jwt.ts:54-76; src/middleware/jwk/jwk.ts:49-76] Authentication failures return challenges with request-specific or configured realm data, while a failed JWK verification can rethrow an ordinary `Error` originating from key retrieval or verification rather than converting it to an unauthorized response. [src/middleware/jwt/jwt.ts:145-184; src/middleware/jwk/jwk.ts:153-195] CORS accepts fixed, list-based, or callback-based origin and method policies. It sets origin, credential, and exposed-header fields before proceeding, but answers OPTIONS directly with an empty response after setting allowed methods, requested or configured headers, optional maximum age, and relevant `Vary` fields. [src/middleware/cors/index.ts:63-94; src/middleware/cors/index.ts:96-156] IP restriction accepts a connection-info function or direct address function and supports wildcard, literal-address, CIDR, and predicate rules. Deny rules take precedence; an allow-list permits only matches when nonempty; absent or invalid client addresses become forbidden responses unless a custom error handler supplies the response. [src/middleware/ip-restriction/index.ts:51-166; src/middleware/ip-restriction/index.ts:218-278] Method handling can re-dispatch a reconstructed request through the supplied application. `methodOverride` ignores GET, then reads the override from a form field, header, or query parameter, removes the source value where applicable, and calls `app.fetch` with the revised method. [src/middleware/method-override/index.ts:60-138] `methodNotAllowed` waits for a downstream not-found response, builds a route-method matcher from the application’s routes, and replaces the response with a method-not-allowed response and `Allow` header when the path exists but the requested method is unsupported. [src/middleware/method-not-allowed/index.ts:64-140] Static serving is deliberately runtime-adapter-facing: callers supply `getContent` and may supply path joining and directory inspection. It rejects undecodable or traversal-like request paths by invoking `onNotFound` and continuing; for found data it sets a MIME type, can select a precompressed representation from `Accept-Encoding`, invokes `onFound`, and returns the body. [src/middleware/serve-static/index.ts:13-21; src/middleware/serve-static/index.ts:35-48; src/middleware/serve-static/index.ts:54-125] Response presentation middleware changes completed responses. `prettyJSON` formats JSON when a configured query parameter is present or formatting is forced. [src/middleware/pretty-json/index.ts:46-55] `poweredBy` sets `X-Powered-By` after downstream handling, whereas `secureHeaders` sets its selected headers after downstream handling and can remove that header. [src/middleware/powered-by/index.ts:30-34; src/middleware/secure-headers/secure-headers.ts:179-234] [JSX](subsystem-src-jsx) rendering installs a context renderer and layout; its renderer either returns HTML or produces a readable stream with caller-selected stream headers. [src/middleware/jsx-renderer/index.ts:31-78; src/middleware/jsx-renderer/index.ts:114-127] Timeout races downstream execution against a timer and rejects with the configured exception when the timer wins. [src/middleware/timeout/index.ts:38-57] Logger emits an incoming line before calling `next` and an outgoing line containing response status and elapsed time afterward. [src/middleware/logger/index.ts:81-94] Trailing-slash middleware redirects GET and HEAD requests to the selected canonical path either before routing when configured to do so or only after a not-found result. [src/middleware/trailing-slash/index.ts:44-74; src/middleware/trailing-slash/index.ts:128-158] ## Configuration This part reads factory options and HTTP inputs rather than process environment variables. Cache reads the Cache Storage and Web Crypto globals; without Cache Storage it logs or reports the reason and returns a pass-through handler, while missing Web Crypto disables QUERY caching but does not stop ordinary cache operation. [src/middleware/cache/index.ts:183-228] Language settings include detector order, query and cookie names, header name, path index, supported and fallback languages, case handling, optional conversion, cookie options, and debug output. Validation rejects a fallback absent from the supported set, a negative path index, or an unknown detector type. [src/middleware/language/language.ts:13-68; src/middleware/language/language.ts:204-216] Security-header configuration merges caller options with defaults and supports content-security policy directives, report endpoints, transport and cross-origin headers, permissions policy, and removal of `X-Powered-By`. The exported `NONCE` handler creates a cryptographically random value when the context does not already hold one, stores it as `secureHeadersNonce`, and formats it for policy directives. [src/middleware/secure-headers/secure-headers.ts:69-145; src/middleware/secure-headers/secure-headers.ts:179-234] ## Wiring The boundary of this part is the Hono context and middleware-handler abstractions imported from the surrounding framework. Middleware depends on context request and response mutation, framework exceptions, router and composition primitives, helpers for cookies and route matching, and lower-level utilities for cryptography, compression, MIME lookup, body parsing, IP parsing, and URL decoding. [src/middleware/basic-auth/index.ts:6-10; src/middleware/cache/index.ts:6-10; src/middleware/method-not-allowed/index.ts:6-11; src/middleware/serve-static/index.ts:6-11] Several modules also require platform capabilities at runtime. Context storage imports Node’s asynchronous-local-storage API; compression constructs a platform `CompressionStream`; secure headers uses `crypto.getRandomValues`; ETag digesting relies on Web Crypto when no custom digest generator is passed; and static serving delegates actual file or asset retrieval to adapter-supplied `getContent`. [src/middleware/context-storage/index.ts:6-10; src/middleware/compress/index.ts:124-128; src/middleware/secure-headers/secure-headers.ts:131-145; src/middleware/etag/index.ts:38-54; src/middleware/serve-static/index.ts:32-48] Applications depend on this directory by registering returned handlers around routes and by reading values placed on the context, such as `jwtPayload`, `language`, `requestId`, timing metrics, and the secure-header nonce. [src/middleware/jwt/jwt.ts:145-161; src/middleware/language/language.ts:304-307; src/middleware/request-id/request-id.ts:46-58; src/middleware/timing/timing.ts:85-124; src/middleware/secure-headers/secure-headers.ts:11-15; src/middleware/secure-headers/secure-headers.ts:137-145] 110 entities in `src/middleware`. **1 other subsystem depends on it**, which makes it the 4th most depended-upon part of this codebase. ## What it is made of Its 110 entities sit in 29 files under `src/middleware`: 45 functions, 40 HTTP endpoints, 14 type aliases, 8 constants and 3 more. `language.ts` holds 16 of them — more than any other file here. ## Where work enters It publishes 40 HTTP endpoints — 24 `GET`, 13 `DELETE`, 2 `PUT` and 1 `ALL`. 2 of them declare a guard — `key` on 2 — and 38 declare none. - [`handler`](api-endpoint-handler) — `src/middleware/basic-auth/index.ts`:118 - [`handler`](api-endpoint-handler-2) — `src/middleware/body-limit/index.ts`:72 - [`handler`](api-endpoint-handler-5) — `src/middleware/cache/index.ts`:79 - [`header`](api-endpoint-header) — `src/middleware/cache/index.ts`:115 - [`handler`](api-endpoint-handler-5) — `src/middleware/cache/index.ts`:233 - [`directive`](api-endpoint-directive) — `src/middleware/cache/index.ts`:292 ## Boundaries **1 other subsystem depends on this one** — `Adapter`. Changing what it exposes changes them. They hold 3 edges into it between them. 33 edges leave it against 3 arriving — it reads more of this repository than this repository reads of it. What they reach is narrower than the folder: 1 of its 110 members carries every inbound edge — `serveStatic` (3). Of the 33 it sends out, 22 go to `Utils` — more than to any other. It depends on `Utils`, `Helper`, `Jsx`, and on nothing else in this repository. # Client ## Overview Client turns a Hono application schema into a chainable HTTP client at compile time and turns property access on that chain into a request at runtime. `hc` accepts a base URL and optional request options, then returns a `Proxy` cast to the schema-derived `Client` type. [src/client/client.ts:133-137; src/client/client.ts:232] The `Client` type walks schema paths into nested property names, with each terminal path mapped to a `ClientRequest` that exposes HTTP-method calls plus `$url` and `$path`. [src/client/types.ts:294-318; src/client/types.ts:67-118] The runtime proxy collects string property accesses as path segments. Accessing a property creates another proxy; invoking that proxy calls a callback with the accumulated path and invocation arguments. The proxy deliberately returns `undefined` for `then`, preventing a client chain from being treated as a thenable. [src/client/client.ts:15-31] An endpoint call returns the underlying Fetch `Response`, typed as `ClientResponse` according to the endpoint’s declared output, status, and output format. The interface mirrors response body and metadata fields and exposes standard body readers, while its `ok` type narrows to `true` or `false` when the status type is known to be successful or unsuccessful. [src/client/types.ts:120-154] `parseResponse` is the optional consuming layer: it accepts either a response or a response promise, parses its body, and rejects non-OK responses with `DetailedError`. [src/client/utils.ts:84-114; src/client/fetch-result-please.ts:14-44] ## How it works ## From chain access to a request When an invoked path ends with a dollar-prefixed segment, `hc` strips the prefix to obtain the method name; all earlier segments are joined with slashes and merged with the base URL. [src/client/client.ts:161-170] For ordinary method calls, the callback creates `ClientRequestImpl` with that URL, method, and the selected query serializer. [src/client/client.ts:214-229] `ClientRequestImpl.fetch` accepts Hono validation-target-shaped arguments with optional query, form, JSON, parameter, header, and cookie inputs. [src/client/client.ts:53-58] Query input is passed to the configured search-parameter builder. [src/client/client.ts:59-62] The default builder creates `URLSearchParams`, skips `undefined` values, appends every array element under the same key, and sets scalar values. [src/client/utils.ts:26-44] Form input becomes a `FormData` body. Undefined form entries are skipped, while array values are appended once per element. [src/client/client.ts:64-79] JSON input is serialized with `JSON.stringify` and sets `Content-Type` to `application/json`. [src/client/client.ts:81-84] Path parameters are retained for URL substitution. [src/client/client.ts:86-88] The request combines argument headers with option headers. Option headers may be a record or a synchronous or asynchronous function; the function result is awaited before `Headers` is constructed. [src/client/client.ts:93-96; src/client/types.ts:57-65] Cookie arguments are serialized individually through the shared cookie serializer and joined into the `Cookie` header. [src/client/client.ts:98-104] A JSON body’s content type is then assigned to that header map. [src/client/client.ts:106-110] Before dispatch, the implementation removes a terminal `/index` representation, substitutes declared path tokens, and appends the serialized query string when one exists. [src/client/client.ts:111-118] `replaceUrlParam` recognizes `:name`, optional parameters, and parameter segments with an attached brace expression; a missing parameter value removes the matched segment. [src/client/utils.ts:18-24] `removeIndexString` treats an absolute root `/index` specially by retaining its slash, while other terminal `/index` text is removed. [src/client/utils.ts:55-60] The method is uppercased. GET and HEAD calls omit the constructed body; other methods pass it to Fetch. [src/client/client.ts:91-92; src/client/client.ts:119-128] Dispatch uses the per-request `fetch` option when present and otherwise the ambient `fetch`. [src/client/client.ts:122-128] `init` is spread after the generated body, method, and headers, so fields in `init` can replace those generated values. [src/client/client.ts:122-128; src/client/types.ts:35-41] Base options and per-call options are recursively merged before dispatch. When both layers contain headers, `hc` replaces the per-call headers with an async function that combines base headers first and request headers afterward; `deepMerge` recursively merges object-valued properties and otherwise takes the source value. [src/client/client.ts:217-229; src/client/utils.ts:62-82] ## URL and path jobs A chain ending in `$url` does not issue a request. It constructs the merged URL, optionally substitutes parameters and appends query data, removes the index representation, and returns `new URL(result)`. [src/client/client.ts:169-185] `$path` follows the same construction but removes the normalized base URL and returns a leading-slash path. [src/client/client.ts:171-186] At the type level, `$url` can return a `TypedURL` when the base prefix is a literal absolute URL. `TypedURL` narrows `protocol`, host fields, pathname, search, origin, and `href` from the supplied prefix, route path, parameter argument, and query argument; a nonliteral prefix instead yields `URL`. [src/client/types.ts:168-193; src/client/types.ts:215-230] `$path` is typed as a template-literal path whose parameter placeholders can be resolved when their values are string literals, and whose query component becomes `?${string}` when a nonempty query input exists. [src/client/types.ts:156-166; src/client/types.ts:194-213] ## WebSocket jobs A chain ending in `$ws` takes a separate branch. It substitutes path parameters, changes an HTTP-style protocol to its WebSocket counterpart, constructs a `URL`, and writes query values into `targetUrl.searchParams`; array query values are appended individually. [src/client/client.ts:187-203; src/client/utils.ts:46-53] It calls an optional `webSocket` constructor from client options when supplied, otherwise it instantiates the ambient `WebSocket`. [src/client/client.ts:204-211; src/client/types.ts:32-34] The `$ws` member exists in the client type only when the route’s GET schema declares `outputFormat: 'ws'`. [src/client/types.ts:112-118] ## Response consumption and failure behavior `parseResponse` delegates directly to `fetchRP`. [src/client/utils.ts:92-114] `fetchRP` awaits the response, checks for a body or polyfill `_bodyInit`, and does not consume bodies for the listed no-body response statuses. [src/client/fetch-result-please.ts:7; src/client/fetch-result-please.ts:14-31] For other bodies, it chooses `json()` only when the content type matches the JSON media-type expression, including structured JSON suffixes; absent or other content types use `text()`. [src/client/fetch-result-please.ts:77-95] After parsing, a non-OK response causes `fetchRP` to throw `DetailedError` with a message composed from status and status text, a `statusCode`, and detail containing the parsed data and status text. [src/client/fetch-result-please.ts:33-40] `DetailedError` extends `Error` and records optional `detail`, `code`, `log`, and `statusCode` fields. [src/client/fetch-result-please.ts:46-75] Transport failures from Fetch are not caught or wrapped by this path; the test suite distinguishes a failed Fetch from an HTTP response parsed by `parseResponse`. [src/client/fetch-result-please.ts:14-44; src/client/utils.test.ts:305-321] The return type of `parseResponse` filters client response unions to content-bearing statuses that are not client or server error statuses, then infers JSON output, declared string output, or `string`; if no qualifying response remains, it resolves to `undefined`. [src/client/utils.ts:92-111; src/utils/http-status.ts:6-72] This is a type-level filter only: at runtime, any non-OK Fetch response still throws `DetailedError`. [src/client/utils.ts:92-114; src/client/fetch-result-please.ts:33-44] ## Configuration `hc` reads client-level `headers`, `fetch`, `webSocket`, `init`, and `buildSearchParams` from `ClientRequestOptions`. [src/client/types.ts:32-65] Per-call options use the same option type and are merged with the client-level options before the Fetch call. [src/client/types.ts:234-237; src/client/client.ts:217-229] `buildSearchParams` is the customization point for query serialization. If no custom function is passed, `hc` uses the local default builder; if one is passed, both request dispatch and `$url`/`$path` generation use that function. [src/client/client.ts:137-139; src/client/client.ts:171-180; src/client/client.ts:214-216] The default convention emits repeated keys for array values. [src/client/utils.ts:26-44] A custom `fetch` can be either the platform Fetch function or Hono’s request method type, which permits in-process request execution rather than a network call. [src/client/types.ts:28-34] The testing [helper](subsystem-src-helper) applies that option by wrapping `app.request` and handing the wrapper to `hc` with a localhost base URL. [src/helper/testing/index.ts:16-27] ## Wiring The public client module exports `hc`, `parseResponse`, `DetailedError`, and the request, response, inference, and schema-transformation types. [src/client/index.ts:6-17] The root package separately re-exports request and response inference types together with `ClientRequestOptions`. [src/index.ts:46-48] Runtime request construction depends on the shared cookie serializer for cookie header values and on browser-compatible globals including `FormData`, `Headers`, `URLSearchParams`, Fetch, `URL`, and, on the WebSocket branch, `WebSocket`. [src/client/client.ts:3; src/client/client.ts:65-78; src/client/client.ts:110; src/client/client.ts:122-128; src/client/client.ts:192-211] Response typing depends on Hono schema and endpoint types, router method constants, HTTP status types, and utility types imported from adjacent framework modules. [src/client/types.ts:1-6] The schema boundary is explicit in the `Client` type: it accepts a `HonoBase`, extracts its schema, and transforms route strings into the nested client chain. [src/client/types.ts:311-318] `ApplyGlobalResponse` and `PickResponseByStatusCode` operate on an app type by rewriting or filtering its extracted endpoint schema, allowing the resulting app type to be passed to `hc`. [src/client/types.ts:332-363; src/client/types.ts:365-393] Outside this directory, the testing helper consumes `hc` and its client option types to create an in-process client, while static-site generation imports only `replaceUrlParam` for route substitution. [src/helper/testing/index.ts:6-27; src/helper/ssg/ssg.ts:1-15] 25 entities in `src/client`. **1 other subsystem depends on it**, which makes it the 5th most depended-upon part of this codebase. ## What it is made of Its 25 entities sit in 3 files under `src/client`: 13 type aliases, 8 functions, 3 interfaces and 1 class. `types.ts` holds 16 of them — more than any other file here. `ClientResponse` declares 8 methods, the widest surface here. ## Where work enters - [`BuildSearchParamsFn`](type-buildsearchparamsfn) — `src/client/types.ts`:30 - [`ClientRequestOptions`](type-clientrequestoptions) — `src/client/types.ts`:32 - [`ClientRequest`](type-clientrequest) — `src/client/types.ts`:67 - [`ClientResponse`](interface-clientresponse) — `src/client/types.ts`:128 ## Boundaries **1 other subsystem depends on this one** — `Helper`. Changing what it exposes changes them. They hold 1 edge into it between them. What they reach is narrower than the folder: 1 of its 25 members carries every inbound edge — `replaceUrlParam` (1). **It depends on no other subsystem in this repository** — it is a leaf. # Docs ## Overview The `docs` part is a human-facing policy and guidance surface: the code of conduct defines participation standards and reporting, the contribution guide describes how to prepare and submit work, and the migration guide records upgrade-specific source changes. [docs/CODE_OF_CONDUCT.md:3-13; docs/CONTRIBUTING.md:3-10; docs/MIGRATION.md:3-19] Nothing in these Markdown files receives an HTTP request, dispatches a job, or imports application modules; their operational role is to tell contributors and application maintainers what actions to take outside this directory. [docs/CODE_OF_CONDUCT.md:39-67; docs/CONTRIBUTING.md:27-60; docs/MIGRATION.md:25-295] For a contributor, the material starts with accepted ways to participate: opening an issue, submitting a pull request, creating external middleware, sharing feedback, or building an application with Hono. [docs/CONTRIBUTING.md:3-10] The guide also sets expectations about acceptance: the project began as Yusuke Wada’s hobby proposal, and an idea may not be accepted even when it is considered good. [docs/CONTRIBUTING.md:12-19] For an existing Hono user, the migration document is organized by source and target release ranges, then narrows into concrete API, import, middleware, type, and deployment changes. [docs/MIGRATION.md:3-19; docs/MIGRATION.md:21-57; docs/MIGRATION.md:59-123] For a community participant reporting misconduct, the code of conduct routes a report to the listed enforcement contact and describes review, investigation, privacy expectations, and possible moderation consequences. [docs/CODE_OF_CONDUCT.md:59-67; docs/CODE_OF_CONDUCT.md:69-113] ## How it works ## Contribution path A contributor first chooses a participation route, with issues intended for feature proposals and bug reports, while pull requests cover bug fixes, typos, and refactoring. [docs/CONTRIBUTING.md:3-8] Before working locally, the guide tells developers to install Bun because the project uses it as its package manager. [docs/CONTRIBUTING.md:27-31] Dependency setup then runs `bun install --frozen-lockfile`, and the local-development example combines cloning the repository, changing into it, and running that same install command. [docs/CONTRIBUTING.md:33-35; docs/CONTRIBUTING.md:56-60] The stated pre-submission check is `bun run test`; the guide asks that pull requests pass that command. [docs/CONTRIBUTING.md:37-39] The AI policy applies whether or not AI was actually used: a contribution must not waste maintainer time or make the work unpleasant, and a maintainer may close a pull request without notice and block the account. [docs/CONTRIBUTING.md:21-25] Middleware that depends on other libraries or only works in a particular environment is explicitly outside the core boundary described here. [docs/CONTRIBUTING.md:41-44] The guide names GraphQL Server, Firebase Auth, and Sentry as examples, says developers can create such middleware independently, and directs prospective work toward an issue and the `honojs/middleware` monorepo. [docs/CONTRIBUTING.md:43-54] This means that a contribution in that category follows a different destination than a core-code change: it may live under the `honojs` organization and the `@honojs` namespace rather than in the core. [docs/CONTRIBUTING.md:50-54] ## Upgrade path The migration guide works as a decision record keyed by the version boundary being crossed. [docs/MIGRATION.md:3-7; docs/MIGRATION.md:21-25; docs/MIGRATION.md:59-62] At the newer Deno boundary, it says the module is no longer published from `deno.land/x`, directs users to JSR, and shows replacing the URL import with `jsr:@hono/hono`. [docs/MIGRATION.md:5-19] For the major-version upgrade section, the guide first lists removed or obsolete APIs and their replacements. [docs/MIGRATION.md:25-37] Examples include switching the Next.js adapter import from `hono/nextjs` to `hono/vercel`, using `c.json()` rather than `c.jsonT()`, accessing request-native properties through `req.raw`, and using `app.fetch()` rather than `app.handleEvent()`. [docs/MIGRATION.md:27-37] It separately states that `app.get()` implicitly handles `HEAD`, so an application should not retain a separate `app.head()` usage from the older API. [docs/MIGRATION.md:32-35] The Cloudflare Workers static-file migration has a concrete configuration consequence: the `serve-static` call needs a `manifest` option, with the example importing `__STATIC_CONTENT_MANIFEST` and passing it alongside the asset root. [docs/MIGRATION.md:39-49] Other changes in that same upgrade include a changed default for JSX renderer `docType`, the absence of `children` from `FC`, removed MIME types, and type-sensitive route and validator chaining. [docs/MIGRATION.md:51-57] The earlier major-version guidance changes the meaning of `c.req`: it becomes `HonoRequest`, while code that needs the underlying platform `Request` must use `c.req.raw`. [docs/MIGRATION.md:64-74] It marks `StaticRouter` unavailable, describes a changed validator API, and directs static serving imports to runtime adapters such as the Cloudflare Workers, Bun, or Deno adapter paths. [docs/MIGRATION.md:76-103] For Cloudflare Workers, the guide marks `serveStatic` in Service Worker mode obsolete, identifies that mode with `app.fire()`, and recommends Module Worker mode using `export default app`. [docs/MIGRATION.md:105-110] Type migration is treated as source editing rather than runtime configuration: the guide requires a `type` declaration, not an `interface`, when declaring generics for `new Hono`. [docs/MIGRATION.md:112-123] Another example describes the generic constructor’s `Variables` and `Bindings`: bindings type Cloudflare Workers environment values, while variables type values stored and read through `c.set` and `c.get`. [docs/MIGRATION.md:184-210] The migration guide also records behavioral failure cases that callers must correct. [docs/MIGRATION.md:150-182] Nested Basic Auth or Bearer Auth middleware must return `auth(c, next)` rather than await it in the shown handler pattern. [docs/MIGRATION.md:154-163] `c.req.parseBody()` is limited to multipart and URL-encoded form data in the documented change; JSON, text, and array-buffer bodies instead go through `c.req.json()`, `c.req.text()`, and `c.req.arrayBuffer()`. [docs/MIGRATION.md:169-182] The oldest covered instructions preserve historical alternatives but label several middleware paths obsolete. [docs/MIGRATION.md:217-295] Deno middleware imports move out of `hono/mod.ts` to `hono/middleware.ts`; cookie handling and request-body parsing move to request or context methods in the examples; GraphQL Server and Mustache middleware are identified as obsolete. [docs/MIGRATION.md:217-231; docs/MIGRATION.md:233-295] ## Conduct and enforcement path The code of conduct begins by committing community members, contributors, and leaders to harassment-free participation and to an open, welcoming, diverse, inclusive, and healthy community. [docs/CODE_OF_CONDUCT.md:3-13] It distinguishes constructive conduct, such as empathy, respect, feedback, accountability, and focus on the community, from unacceptable conduct including sexualized behavior, attacks, harassment, publishing private information without permission, and other professionally inappropriate behavior. [docs/CODE_OF_CONDUCT.md:15-37] When a standards issue occurs, community leaders are assigned responsibility for clarification, enforcement, and corrective action. [docs/CODE_OF_CONDUCT.md:39-44] They may remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that do not align with the policy, and they communicate moderation reasons when appropriate. [docs/CODE_OF_CONDUCT.md:46-49] The policy applies both in community spaces and when an individual officially represents the community publicly. [docs/CODE_OF_CONDUCT.md:51-57] A report of abusive, harassing, or otherwise unacceptable behavior goes to `yusuke@kamawada.com`, after which complaints are reviewed and investigated promptly and fairly. [docs/CODE_OF_CONDUCT.md:59-64] Leaders must respect the reporter’s privacy and security. [docs/CODE_OF_CONDUCT.md:66-67] The stated consequence path ranges from a private written correction, through a warning that restricts interaction, to a temporary ban and a permanent ban for sustained or severe patterns of violation. [docs/CODE_OF_CONDUCT.md:74-113] ## Configuration The documentation itself does not declare environment-variable readers, command-line flag parsing, or a runtime settings format; its actionable setup instruction is the Bun dependency-install command with the frozen lockfile option. [docs/CONTRIBUTING.md:27-35] The migration examples describe application-side settings that may require source changes during an upgrade. [docs/MIGRATION.md:39-49; docs/MIGRATION.md:184-210] In particular, Cloudflare static serving takes a `manifest` option, and the generic `Bindings` type is described as the type surface for Cloudflare Workers environment values such as `KV` and `Storage`. [docs/MIGRATION.md:39-49; docs/MIGRATION.md:186-210] The contribution guide’s test command is a contributor workflow requirement, not a setting read by the documentation. [docs/CONTRIBUTING.md:37-39] ## Wiring The repository README is the visible entry point into this part for migration and contribution work: it links directly to `docs/MIGRATION.md` under its Migration section and to `docs/CONTRIBUTING.md` under its Contributing section. [README.md:53-55; README.md:61-71] The README points general product documentation to `hono.dev`, which separates the repository-local migration and contribution guides from the broader documentation site. [README.md:49-55] Within the contribution guide, Bun is an external package-management dependency named for local setup. [docs/CONTRIBUTING.md:27-35] The third-party middleware route points outward to the `honojs/middleware` monorepo and describes possible distribution in the `@honojs` namespace. [docs/CONTRIBUTING.md:50-54] The migration guide also points outward to the Deno getting-started page and to the Hono documentation for validator details. [docs/MIGRATION.md:19; docs/MIGRATION.md:80-84] The conduct document’s boundary is community governance rather than application execution: its inputs are reports and contributions in community spaces, and its outputs are investigation, moderation, correction, interaction restrictions, or bans. [docs/CODE_OF_CONDUCT.md:46-67; docs/CODE_OF_CONDUCT.md:74-113] Its text attributes the policy to Contributor Covenant and links to that project’s FAQ and translations, while its enforcement ladder is described as inspired by Mozilla’s code-of-conduct enforcement ladder. [docs/CODE_OF_CONDUCT.md:115-128] 73 entities in `docs`. Nothing else in this repository depends on it. ## What it is made of Its 73 entities sit in 3 files under `docs`: 70 doc comments and 3 markdown docs. ## Where work enters - `Contributor Covenant Code of Conduct` — `docs/CODE_OF_CONDUCT.md`:1 - `Contribution Guide` — `docs/CONTRIBUTING.md`:1 - `Migration Guide` — `docs/MIGRATION.md`:1 # Adapter ## What it is responsible for Adapter turns application handling into environment-specific adapter behavior, with AWS Lambda conversion explicitly documented and connection information extracted across Lambda event sources. `getConnInfo` reads client IP information from API Gateway v1, API Gateway v2, and other documented Lambda sources, while `LambdaEvent` is a work entry point for Lambda event handling. The subsystem also addresses Bun, Cloudflare Pages, Deno, Netlify, and Service Worker connection or request adaptation, as indicated by its documented adapter comments. ## What it needs, and who needs it Adapter depends on `Utils`, `src/middleware`, and `Helper`. No subsystem is recorded as depending on Adapter. Without those dependencies, Adapter’s documented Lambda conversion, connection-information extraction, and environment-specific adapters would lack their listed supporting modules; the evidence does not identify a more specific failure mode. ## Notable members `getConnInfo` is the direct connection-information path: its comment says it extracts client IP addresses from various AWS Lambda event sources, including API Gateway v1 and v2. `LambdaEvent` is a documented work entry point and is associated with converting a Hono application to an AWS Lambda handler. `defaultIsContentTypeBinary` checks whether a content type is binary; `isContentEncodingBinary` names the related content-encoding binary check. Processor symbols include `EventV2Processor`, `EventV1Processor`, `ALBProcessor`, and `LatticeV2Processor`; available evidence does not state how `getProcessor` selects them at runtime. 71 entities in `src/adapter`. Nothing else in this repository depends on it. ## What it is made of Its 71 entities sit in 26 files under `src/adapter`: 31 functions, 22 interfaces, 7 type aliases, 6 constants and 5 more. `handler.ts` holds 16 of them — more than any other file here. `EventProcessor` declares 11 methods, the widest surface here. ## Where work enters - [`getConnInfo`](function-getconninfo-2) — `src/adapter/aws-lambda/conninfo.ts`:45 - [`LambdaEvent`](type-lambdaevent) — `src/adapter/aws-lambda/handler.ts`:23 - [`LatticeProxyEventV2`](interface-latticeproxyeventv2) — `src/adapter/aws-lambda/handler.ts`:29 - [`APIGatewayProxyEventV2`](interface-apigatewayproxyeventv2) — `src/adapter/aws-lambda/handler.ts`:41 ## How it refuses and fails 1 of its components records a refusal or a failure handler. It refuses work outright, under a condition written into the component itself. ## Boundaries It depends on `Utils`, `Middleware`, `Helper`, and on nothing else in this repository. # Router ## Overview Router maps an HTTP method and an already-extracted request path to an ordered set of handlers plus route parameters. Its common contract is `add(method, path, handler)` followed by `match(method, path)`, and a match result either carries handler-specific parameter maps directly or pairs parameter-index maps with a captured-value stash. [src/router.ts:29-52; src/router.ts:54-98] `HonoBase` registers each route after uppercasing its method and merging its path with the application base path; it passes the handler together with route metadata into the configured router. During dispatch, it obtains the request path, calls `router.match`, and places the resulting match data in the request `Context` before invoking the matching handler chain. [src/hono-base.ts:386-398; src/hono-base.ts:407-451] A default `Hono` instance creates a `SmartRouter` whose candidates are `RegExpRouter` followed by `TrieRouter`, unless the caller supplies a router in the constructor options. [src/hono.ts:26-33] `SmartRouter` records registrations until its first match, then attempts to add the complete recorded route set to each candidate in order; it selects and caches the first candidate that does not throw `UnsupportedPathError`. [src/router/smart-router/router.ts:13-19; src/router/smart-router/router.ts:21-60] The matching contract returns all applicable handlers rather than a single endpoint. This lets registrations such as a wildcard middleware route and an exact route both participate in the same request, while retaining registration order for the returned handlers. [src/router/common.case.test.ts:129-139; src/router/common.case.test.ts:193-210] The dispatcher either invokes the single matched handler directly or composes the returned handler list when more than one handler matched. [src/hono-base.ts:430-466] ## How it works ## Registration and route syntax All router implementations receive a method string, a path string, and an opaque handler value through the shared interface. [src/router.ts:29-52] `METHOD_NAME_ALL` is the string `ALL`; implementations compare a route’s method against the requested method and also include `ALL` registrations. [src/router.ts:6-17; src/router/linear-router/router.ts:25-40; src/router/trie-router/node.ts:94-111] The path utility expands a terminal optional named segment into paths with and without that segment. A route ending in an optional label therefore becomes separate route entries before `LinearRouter`, `TrieRouter`, or `RegExpRouter` store it. [src/[utils](subsystem-src-utils)/url.ts:171-206; src/router/linear-router/router.ts:15-23; src/router/trie-router/router.ts:13-23; src/router/reg-exp-router/router.ts:122-139] `TrieRouter` is the general fallback implementation. Registration splits a route into slash-separated routing segments while preserving brace-delimited expressions, asks `getPattern` whether each segment is a named parameter, constrained parameter, or wildcard, and inserts the resulting sequence into a node tree. [src/router/trie-router/router.ts:13-27; src/router/trie-router/node.ts:44-84; src/utils/url.ts:16-21; src/utils/url.ts:50-78] Each terminal node stores the handler, the parameter keys that may apply to it, and an insertion score used later to restore registration order. [src/router/trie-router/node.ts:6-14; src/router/trie-router/node.ts:76-84] At match time, the trie splits the request path and tracks candidate nodes. It first follows a literal child where present, then evaluates wildcard and parameter-pattern children; named values are accumulated into a parameter object for the relevant branch. [src/router/trie-router/node.ts:114-163; src/router/trie-router/node.ts:165-229] A terminal node selects the request method or its `ALL` entry, copies applicable values into that handler’s parameter map, and the final list is sorted by registration score when necessary. [src/router/trie-router/node.ts:87-112; src/router/trie-router/node.ts:237-244] A trailing wildcard has special treatment in the trie: when a literal branch reaches the last request segment, the search also checks a child wildcard, so a route ending in `/*` can match both its prefix and descendants. [src/router/trie-router/node.ts:136-146] A wildcard in the middle of a route consumes a segment and remains a candidate for later segments. [src/router/trie-router/node.ts:149-163] Constrained labels use regular expressions constructed by `getPattern`; when a following literal segment exists, the helper builds a lookahead for that next segment. [src/utils/url.ts:60-74; src/router/trie-router/node.ts:171-208] ## The compiled regular-expression path `RegExpRouter` initially keeps separate method-indexed maps for middleware-like wildcard routes, normal routes, and a `Trie` used to construct matchers. Its constructor creates each of those structures under `ALL`. [src/router/reg-exp-router/router.ts:47-57] When a method is first seen, it creates method-specific maps, clones existing `ALL` handler entries, and inserts the corresponding paths into that method’s trie. [src/router/reg-exp-router/router.ts:75-84] For a path ending in a wildcard, `RegExpRouter` builds a wildcard regular expression, inserts the route into matching method tries, and appends the handler to already-known middleware and route paths that satisfy that wildcard. [src/router/reg-exp-router/router.ts:86-119] For an ordinary route, it expands an optional terminal parameter, inserts each expanded path, carries forward matching wildcard middleware, and records how many named parameters belong to each handler. [src/router/reg-exp-router/router.ts:122-139] The internal regular-expression trie tokenizes dynamic paths, retains a path-to-handler-index and parameter-association entry for dynamic paths, and treats every character of static paths as a literal node. [src/router/reg-exp-router/trie.ts:10-17; src/router/reg-exp-router/trie.ts:20-56] Its nodes order alternatives so literals precede constrained patterns, ordinary labels, and wildcards; that ordering is encoded by `compareKey` before the tree emits a regular-expression string. [src/router/reg-exp-router/node.ts:13-42; src/router/reg-exp-router/node.ts:137-167] When `RegExpRouter` first matches, the shared `match` function calls `buildAllMatchers`, replaces the instance’s `match` method with a closure over the built matcher map, and immediately delegates the current request to that closure. [src/router/reg-exp-router/matcher.ts:10-33] Building a matcher separates exact static paths into a direct lookup map and converts dynamic path data into a regular expression, a handler-data array, and parameter-index mappings. [src/router/reg-exp-router/router.ts:160-210] Subsequent matches first check the static map; otherwise they run the generated expression, locate the handler list using the empty marker’s capture position, and return that list with the expression’s captured values. [src/router/reg-exp-router/matcher.ts:14-29] Matcher construction releases `RegExpRouter`’s mutable registration maps and clears its wildcard-expression cache after compilation. [src/router/reg-exp-router/router.ts:144-157] Consequently, adding a route after matcher construction throws the shared “matcher is already built” error. [src/router/reg-exp-router/router.ts:67-73; src/router.ts:19-22] The regular-expression trie rejects route sets it cannot represent without ambiguity. It throws its private path marker for duplicate terminals, conflicting literal and dynamic branches, incompatible dynamic branches, named patterns containing unsupported capturing groups, a named `.*` pattern, and ambiguous single-character meta-character patterns. [src/router/reg-exp-router/node.ts:51-135] `RegExpRouter` converts that marker to `UnsupportedPathError`, which is the signal `SmartRouter` catches when choosing the next candidate. [src/router/reg-exp-router/router.ts:59-65; src/router/smart-router/router.ts:32-44] ## Other implementations `LinearRouter` keeps registered triples in an array and scans them on every match. It recognizes exact paths, whole-path wildcards, wildcard-containing paths, and named labels; it accepts a trailing slash for exact and label routes. [src/router/linear-router/router.ts:11-23; src/router/linear-router/router.ts:25-70; src/router/linear-router/router.ts:70-143] A label with a brace expression is executed as a regular expression against the remaining path, while ordinary labels consume through the next slash. [src/router/linear-router/router.ts:80-116] A route containing both labels and wildcards causes `UnsupportedPathError` in this implementation. [src/router/linear-router/router.ts:135-142] `PatternRouter` converts each registered path into one anchored regular expression and stores it with the method and handler. It converts labels into named capture groups, escapes literal expression metacharacters, makes a terminal wildcard unanchored, and recursively registers the shortened form of a terminal optional segment. [src/router/pattern-router/router.ts:8-42] A malformed generated expression becomes `UnsupportedPathError`; matching executes each same-method or `ALL` expression and returns its named capture groups as parameters. [src/router/pattern-router/router.ts:33-59] `PreparedRegExpRouter` is for a precomputed matcher shape. Its constructor accepts matcher data and a relocation map, and its `add` operation attaches handlers only to paths known by that relocation map, except whole-path wildcard registrations. [src/router/reg-exp-router/prepared-router.ts:9-17; src/router/reg-exp-router/prepared-router.ts:47-86] An unknown non-wildcard path throws an error stating that the path is not registered. [src/router/reg-exp-router/prepared-router.ts:73-76] `buildInitParams` constructs that data by temporarily registering the input paths in a `RegExpRouter`, extracting matchers, deriving relocation entries, and clearing handler arrays; `serializeInitParams` renders the matcher and relocation data as JavaScript-source text while preserving regular-expression literals. [src/router/reg-exp-router/prepared-router.ts:95-154; src/router/reg-exp-router/prepared-router.ts:156-165] ## Configuration This part does not read environment variables, feature flags, or process-level settings in the router implementations inspected here; router selection instead comes from the optional `router` field in `Hono` options, while `SmartRouter` receives its candidate routers through constructor input. [src/hono.ts:26-33; src/router/smart-router/router.ts:4-11] The caller can substitute any implementation satisfying the `Router` interface, including the exported `RegExpRouter`, `PreparedRegExpRouter`, `TrieRouter`, `SmartRouter`, `LinearRouter`, and `PatternRouter` entry points. [src/router.ts:29-52; src/router/reg-exp-router/index.ts:6-7; src/router/trie-router/index.ts:6; src/router/smart-router/index.ts:6; src/router/linear-router/index.ts:6; src/router/pattern-router/index.ts:6] ## Wiring The inbound boundary is route registration from `HonoBase` and request matching during `HonoBase` dispatch. `HonoBase` owns method normalization and base-path merging before calling `add`, owns request-path acquisition before calling `match`, and owns creation of the execution `Context`. [src/hono-base.ts:386-398; src/hono-base.ts:407-428] The outbound boundary is the `Result` consumed by dispatch and composition. Router implementations return handler values with either direct parameter maps or parameter-index maps plus a captured-value stash; `Context` receives that result, and dispatch passes the handler list to either direct invocation or `compose`. [src/router.ts:67-98; src/hono-base.ts:419-451] Internally, `TrieRouter` depends on the URL helpers for route segmentation and parameter patterns, while `RegExpRouter` depends on its trie and matcher modules to turn registrations into static lookups and compiled regular expressions. [src/router/trie-router/node.ts:1-4; src/router/reg-exp-router/router.ts:7-11; src/router/reg-exp-router/matcher.ts:1-9] `SmartRouter` depends only on the shared router interface and `UnsupportedPathError`, allowing it to switch from the compiled regular-expression strategy to the trie strategy without changing the dispatch boundary. [src/router/smart-router/router.ts:1-2; src/router/smart-router/router.ts:26-60] 21 entities in `src/router`. Nothing else in this repository depends on it. ## What it is made of Its 21 entities sit in 10 files under `src/router`: 9 classes, 6 type aliases, 3 functions, 2 constants and 1 more. `matcher.ts` holds 6 of them — more than any other file here. `PreparedRegExpRouter` declares 4 methods, the widest surface here. ## Where work enters - [`LinearRouter`](class-linearrouter) — `src/router/linear-router/router.ts`:11 - [`PatternRouter`](class-patternrouter) — `src/router/pattern-router/router.ts`:8 - [`HandlerData`](type-handlerdata) — `src/router/reg-exp-router/matcher.ts`:4 - [`StaticMap`](type-staticmap) — `src/router/reg-exp-router/matcher.ts`:5 ## How it refuses and fails 7 of its components record a refusal or a failure handler. 6 of them refuse work outright, under a condition written into the component itself. Their `catch` blocks handle a failure that already happened in 3 places. ## Boundaries It depends on `Utils`, and on nothing else in this repository.