# Working with agents (/docs/agents) hono-bento's layout is designed so a coding agent can work in it without exploring the codebase first. Each convention answers a question an agent would otherwise have to search for: | Question | Answer | | -------------------------------- | --------------------------------------------------------------------------------------- | | Where is `PATCH /v1/todos/:id`? | Its contract in `features/todos/spec.ts`, its handler in the `.ts` it names. | | Where does a new endpoint go? | A contract in that feature's `spec.ts` and a handler file beside it. | | What types does a handler use? | Its contract's: `defineHandler>`. | | Where do request shapes go? | `packages/schemas/src/.ts`. | | How do I register a new feature? | One line in `specs.ts`. | | What may this code import? | Its own folder, app-level code and packages. Never another feature. | Because a change stays inside one folder, an agent's diff is small and easy to review. And because the rules are tested, an agent that breaks one finds out at once, from a message that tells it what to do. ## Give your app an AGENTS.md [#give-your-app-an-agentsmd] The example ships an [`AGENTS.md`](https://github.com/bento-api/hono-bento/blob/main/examples/todos/AGENTS.md) written to be copied into your app. It has the layout, the rules, and step-by-step checklists for adding an endpoint and adding a feature. Most coding agents read `AGENTS.md` automatically. For Claude Code, add a `CLAUDE.md` that imports it: ```md title="CLAUDE.md" @AGENTS.md ``` ## Let the checks do the reviewing [#let-the-checks-do-the-reviewing] [`hono-bento check`](/docs/layout#enforce-it-with-hono-bento-check), run by the example's `structure.test.ts`, fails with instructions, not just assertions: ```txt src/features/projects/create.ts handler-file: Put the handler for POST /v1/projects/ in this file. ``` Tell agents to run the tests before they finish. A layout mistake then gets fixed in the same session rather than in code review. ## Type errors that say what's wrong [#type-errors-that-say-whats-wrong] When a handler drifts from its route, `route()` reports the problem in words, with what the route provides next to what the handler declares: ```txt Type 'RouteHandler' is not assignable to type 'HandlerMismatch<"The route allows anonymous callers, so the handler must accept a null identity: declare it with defineHandler, or from this route's contract.", Session | null, Session>'. ``` ## Startup checks [#startup-checks] Some mistakes are caught when the app boots, before any request: - `mountSpecs` throws if two routes share a method and path, or an operation id. That's what happens when a feature folder is copied without being renamed. - Routes that require `scopes` throw if no authorizer is configured, so a missing permission check can't ship unnoticed. - A route that names an unregistered strategy, needs authentication with no strategies configured, or allows anonymous callers while requiring scopes, throws too. And with `validateResponses` on in tests, a handler whose response doesn't match its documented schema fails its feature test. ## These docs, for agents [#these-docs-for-agents] This site serves machine-readable versions of every page: - [`/llms.txt`](/llms.txt) is an index of every page. - [`/llms-full.txt`](/llms-full.txt) has the full text of the docs in one file. - Any docs page with `.md` appended, such as [`/docs/layout.md`](/docs/layout.md), returns that page as Markdown. Requests that prefer `text/markdown` get Markdown from the normal URL too. Point your agent at `https://honobento.com/llms-full.txt` when it's building with hono-bento for the first time. # The CLI (/docs/cli) The `hono-bento` command comes with the package. It has three jobs: - **`init`** writes a new app in [the layout](/docs/layout). - **`add`** adds a feature or an endpoint to an app, in the same layout. - **`check`** checks that an app still follows the layout's rules. Run it with any package manager: ```npm npx hono-bento --help ``` `add` and `check` read the app's `hono-bento.config.ts`, so they need a runtime that runs TypeScript: Bun, or Node 22.18 and later. `check` also imports the app's own modules. If those imports leave out file extensions, as the apps `init` writes do, run `check` with `bun --bun hono-bento check`. The `check` script `init` writes does that for you. ## `hono-bento init` [#hono-bento-init] ```txt hono-bento init [dir] [--db prisma] [--monorepo [--scope @acme]] [--force] ``` Writes a new app into `dir` (default: the current folder). The app has: - one `notes` feature, with `list`, `create` and `retrieve` routes; - its schemas, its tests, and a `structure.test.ts` that runs `hono-bento check`; - an `AGENTS.md` with the layout's rules, for you and your agents. The package is named after the folder. | Option | What it does | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--db prisma` | Keeps the data in Postgres through Prisma, with a Docker Compose file for a local database and a Postgres schema per test run. Without it, the data lives in memory. | | `--monorepo` | Puts the schemas (and, with Prisma, the database client) in workspace packages, so other apps can import them. Without it, everything is one package. See [Monorepo](/docs/monorepo). | | `--scope @acme` | Names the workspace packages (`@acme/schemas`). Only with `--monorepo`. It defaults to `@` plus the folder's name. | | `--force` | Writes into a folder that isn't empty, replacing any files with the same names. Without it, `init` refuses a folder with files in it. | When it's done, it prints the next steps: install, then `setup` with Prisma, then `dev`. ```npm npx hono-bento init my-api --db prisma ``` ## `hono-bento add feature` [#hono-bento-add-feature] ```txt hono-bento add feature [--routes list,create,retrieve,update,delete] [--model ] [--config ] ``` Adds a feature. Its name is lowercase words joined by dashes, like `invoices` or `invoice-items`. It writes: | File | What's in it | | -------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `/.ts` | The model's schema and its list schema, with a `TODO` where the fields go. Kept as it is if it already exists. | | `features//spec.ts` | The feature's contracts and spec, under `/v1/` (or the prefix the other features use). | | `features//.ts` | One handler per route. | | `features//store.ts` | The feature's queries. With a `list` route, a `list` query that returns an empty list until you write it. | | `features//.test.ts` | One `it.todo` per route. | | `specs.ts` | Gets the feature's import and its entry in `specs`. | Where `features/` and the schemas go comes from `hono-bento.config.ts`, so the same command works in one package (imports from `#schemas/`) and in a monorepo (imports from `@acme/schemas/`). | Option | What it does | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--routes` | The routes to start with, from `list`, `create`, `retrieve`, `update` and `delete`. Default `list`. Add any other route afterwards with `add endpoint`. | | `--model` | The singular, when dropping the `s` gets it wrong: `--model person` for `people`. It names the schemas (`personSchema`) and the type (`Person`). | | `--config ` | The config to read. Default `hono-bento.config.ts` in the current folder. | `list` answers straight away with an empty list. Each of the other routes answers `501 not_implemented` until you write its handler. The routes ask for the scopes `.read` (for `GET`) and `.write` (for everything else). No caller has those yet, so grant them in `auth.ts`. The command prints the scopes when it's done: ```npm npx hono-bento add feature invoices --routes list,create ``` ```txt wrote src/features/invoices/create.ts wrote src/features/invoices/invoices.test.ts wrote src/features/invoices/list.ts wrote src/features/invoices/spec.ts wrote src/features/invoices/store.ts wrote src/schemas/invoices.ts edited src/specs.ts Next: Grant 'invoices.read', 'invoices.write' to the callers that need them (auth.ts). Fill in the TODOs, then run your tests and hono-bento check. ``` [Add a feature](/docs/guides/add-a-feature) walks through the same files by hand. ## `hono-bento add endpoint` [#hono-bento-add-endpoint] ```txt hono-bento add endpoint [--method post] [--path /:id/archive] [--config ] ``` Adds a route to an existing feature. The operation is camelCase, like `archive` or `markPaid`. It names the route's contract and its handler's file. The command: - writes `.ts`, a handler typed from the contract that answers `501` until you write it; - adds the contract to `contracts` and the route to `routes` in `spec.ts`, with their imports; - adds an `it.todo` to the feature's test file. | Option | What it does | | ----------------- | ------------------------------------------------------------------------- | | `--method` | The route's method: `get`, `post`, `put`, `patch` or `delete`. | | `--path` | The route's path, after the feature's `basePath`, like `/:id/archive`. | | `--config ` | The config to read. Default `hono-bento.config.ts` in the current folder. | A standard operation gets its usual method, path and response. Any other gets `POST /:id/` unless you pass `--method` or `--path`: | Operation | Method | Path | Response | Body | | ------------- | -------- | ------------------ | ------------------------ | --------------------- | | `list` | `GET` | `/` | 200, `ListSchema` | | | `create` | `POST` | `/` | 201, `Schema` | `CreateSchema` | | `retrieve` | `GET` | `/:id` | 200, `Schema` | | | `update` | `PATCH` | `/:id` | 200, `Schema` | `UpdateSchema` | | `delete` | `DELETE` | `/:id` | 200, `Schema` | | | anything else | `POST` | `/:id/` | 200, `Schema` | | The model comes from the spec's `model`. The response schema must already be exported from the feature's schemas file. A body schema that isn't is added there, with a `TODO` for its fields. A route that takes any other body needs `validation: { body }` added to its contract by hand. ```npm npx hono-bento add endpoint invoices archive ``` [Add an endpoint](/docs/guides/add-an-endpoint) covers what's still yours to write: the schema changes, the query in `store.ts`, and the test. ### How `add` edits your files [#how-add-edits-your-files] `add` parses each file it changes and inserts its lines at the right spot: the end of `contracts`, `routes` or `specs`, and next to the other imports. The rest of the file, with its formatting and comments, stays as it was. It finds those spots in the shape that `init` and the guides write. If a file is in another shape, say `specs` built by a function call, `add` prints the lines to paste and where they go, and exits with code 1. Anything else that would stop it, like an operation that already exists or a missing response schema, stops it before it writes anything. ## `hono-bento check` [#hono-bento-check] ```txt hono-bento check [--config ] hono-bento check --rules ``` Checks the app in this folder against the layout's rules. For each problem, it prints the file, the line and what to change. It exits with code 1 when it finds any. `--rules` lists the rules and what each checks. | Option | What it does | | ----------------- | ------------------------------------------------------------------------- | | `--config ` | The config to read. Default `hono-bento.config.ts` in the current folder. | | `--rules` | Lists the rules, and checks nothing. | [Enforce it with `hono-bento check`](/docs/layout#enforce-it-with-hono-bento-check) covers the config file, the rules and how to run them from your tests with `check()`. # Authentication (/docs/concepts/auth) hono-bento doesn't know how your identities work. You provide two small interfaces, and each route declares its requirements. ## Strategies [#strategies] A strategy turns a request into your identity type: ```ts interface AuthStrategy { name: string; authenticate(c: Context): Identity | null | Promise; } ``` - **Return an identity** when the request authenticates with this strategy. - **Return `null`** when the request isn't for this strategy, for example because its header is missing. The next strategy is tried. - **Throw an `HttpError`** when the credential is present but invalid. The request is rejected at once. ```ts title="auth.ts" fragment export const apiKeyStrategy: AuthStrategy = { name: 'apiKey', async authenticate(c) { const key = c.req.header('x-api-key'); if (!key) return null; const match = await findApiKey(key); if (!match) throw HttpError.unauthorized('Unknown API key.'); return { type: 'apiKey', subject: match.id, role: match.role }; }, }; ``` ## Authorizer [#authorizer] The authorizer decides whether an identity meets a route's requirements. The framework gives `scopes` no meaning; your authorizer interprets them as roles, permissions or key capabilities. ```ts interface Authorizer { authorize(identity: Identity, requirements: AuthRequirements, c: Context): boolean | Promise; } ``` Return `false` to send `403 forbidden`, or throw an `HttpError` for a custom error. ## Checked at startup [#checked-at-startup] `mountSpecs` throws at startup, rather than serving a route whose auth can't work as configured, when a route: - declares `scopes` but you didn't pass an `authorizer`, so nothing would check them and any authenticated caller would get through; - requires authentication but no `strategies` are configured, so it could never be called; - names a strategy in `auth.strategies` that isn't registered, such as a typo; - sets `allowAnonymous` and also requires `scopes`. An anonymous caller has no identity to check, so it would skip the scopes while signed-in callers without them got a `403`. Drop one, and check the identity in the handler if the route behaves differently for signed-in callers. ## Route requirements [#route-requirements] Routes require authentication by default. Only `allowAnonymous: true` makes a route public, so forgetting `auth` can't ship an open endpoint. ```ts auth: { scopes: ['todos.write'] } // any strategy, with the scope auth: { strategies: ['apiKey'], scopes: ['admin'] } // API keys only auth: {} // anyone authenticated // no `auth` at all // the same: anyone authenticated auth: { allowAnonymous: true } // public: identity may be null ``` ## The flow [#the-flow] For every route: 1. Each eligible strategy runs in the order you registered them, until one returns an identity. 2. If none does, the request gets `401 unauthorized`, unless the route has `allowAnonymous`. 3. The identity and the strategy's name are stored on the context. 4. The authorizer checks the requirements. If it returns `false`, the request gets `403 forbidden`. ## Resource-level authorization [#resource-level-authorization] The authorizer runs before the handler, with the route's requirements and no data. It can say whether a caller may update todos, but not whether they may update _this_ todo: that needs the row. Check ownership in the query instead. The example keeps one app-level helper that every feature imports, and spreads it into each `where`: ```ts title="access.ts" import type { Session } from './auth'; /** * Which rows a caller may see and change: spread into a query's `where`, as in * `db.todo.update({ where: { id, ...owner } })`. Admins see every row; anyone * else, only their own. * * The authorizer in auth.ts runs before the handler, so it can say whether a * caller may update todos, not whether they may update this one. Ownership * lives in the query instead: someone else's todo matches no row, so it * answers 404 exactly like a todo that doesn't exist, and the API never * confirms that another user's id is real. */ export interface Owner { ownerId?: string; } export function ownerScope(session: Session): Owner { return session.role === 'admin' ? {} : { ownerId: session.subject }; } ``` ```ts title="features/todos/store.ts" fragment async update(db: Database, owner: Owner, id: string, input: TodoUpdate): Promise { return toTodo(await db.todo.update({ where: { id, ...owner }, data: input })); }, ``` Someone else's todo matches no row, so Prisma throws `P2025` and [`mapPrismaError`](/docs/concepts/database#error-mapping) answers `404`, the same as for a todo that doesn't exist. The API never confirms that another user's id is real, and no handler has to remember an ownership check: a store function that takes `owner` can't be called without one. Use `403` for what the caller's role can't do at all (the authorizer's job), and `404` for rows they can't see. ## OpenAPI [#openapi] Pass `securitySchemes` to `generateOpenApiDocument`, and `securityByStrategy` to say which scheme each strategy implements. Each route that isn't `allowAnonymous` then lists only the schemes of the strategies it accepts. See [OpenAPI](/docs/concepts/openapi). # Database (/docs/concepts/database) hono-bento doesn't wrap your database. Use Prisma, Drizzle, Kysely or a raw driver as you normally would. The framework adds two things: - **`deps`**: a typed object every handler receives, built per request by a provider you pass to `mountSpecs`. Put your database client in it. - **`mapError`**: turns the errors your ORM throws for client mistakes (a missing record, a duplicate value) into `404`s and `409`s instead of `500`s. ## Register the type [#register-the-type] Declare what handlers receive once, in the app: ```ts title="apps/api/src/deps.ts" import type { Database } from '@todos/db'; import type { ChangeFeed, TodoChange } from './changes'; export interface Deps { db: Database; /** Changes to todos, which the todos feature publishes and its `changes` stream sends. */ todoChanges: ChangeFeed; } declare module 'hono-bento' { interface Register { deps: Deps; } } ``` Every handler's `deps` now has this type, with nothing to pass to `defineHandler`. Once it's registered, `mountSpecs` **requires** a `deps` provider, so an app can't start without its database wired in. Forgetting it is a type error. `Register` is augmented for the whole TypeScript program. If one monorepo has two hono-bento APIs with different deps, typecheck each app with its own `tsconfig.json`. ## Provide it [#provide-it] ```ts title="apps/api/src/app.ts" import type { Database } from '@todos/db'; import { Hono } from 'hono'; import { mountSpecs } from 'hono-bento'; import { mapPostgresError, mapPrismaError } from 'hono-bento/db'; import { roleAuthorizer, strategies } from './auth'; import { createChangeFeed } from './changes'; import type { Deps } from './deps'; import { specs } from './specs'; export function createApp({ db }: { db: Database }) { // Built once per app, and the same for every request. const deps: Deps = { db, todoChanges: createChangeFeed() }; const app = new Hono(); mountSpecs(app, specs, { strategies, authorizer: roleAuthorizer, deps: () => deps, mapError: [mapPrismaError, mapPostgresError], }); return app; } ``` The app receives its database rather than importing it. `server.ts` connects and passes the client in: ```ts title="apps/api/src/server.ts" import { createDatabase, databaseUrl } from '@todos/db'; import { createApp } from './app'; const db = createDatabase(databaseUrl()); const app = createApp({ db }); ``` ### Per-request databases [#per-request-databases] The provider runs after authentication, with the identity, so it can choose a database per caller: a tenant's database, or live versus test data. ```ts deps: ({ identity }) => ({ db: identity?.livemode ? liveDb : sandboxDb }), ``` It runs once per request, and only for requests that passed authentication. It may be `async`, and an `HttpError` it throws is sent like any other. ## Use it [#use-it] Handlers pass `deps.db` to their feature's store, which holds the queries: ```ts title="features/todos/update.ts" export const updateTodo = defineHandler( async ({ deps, identity, params, body, respond }) => { const { todo, ownerId } = await store.update(deps.db, ownerScope(identity), params.id, body); deps.todoChanges.publish({ type: 'updated', ownerId, todo }); return respond(200, todo); } ); ``` ```ts title="features/todos/store.ts" import type { Database, Todo as TodoRow } from '@todos/db'; import type { Todo, TodoUpdate } from '@todos/schemas/todos'; import type { Owner } from '../../access'; /** Rows never leave the store: each one is mapped to the API's wire shape. */ export function toTodo(row: TodoRow): Todo { return { object: 'todo', id: row.id, title: row.title, done: row.done, project: row.projectId, created: Math.floor(row.createdAt.getTime() / 1000), }; } export const store = { // `owner` scopes the update to rows the caller may change: see Auth's resource-level authorization. async update(db: Database, owner: Owner, id: string, input: TodoUpdate): Promise<{ todo: Todo; ownerId: string }> { const row = await db.todo.update({ where: { id, ...owner }, data: input }); return { todo: toTodo(row), ownerId: row.ownerId }; }, }; ``` Two rules keep this clean, and both are checked: - **Only `store.ts` touches the database, and only through types.** The connection is made in `server.ts` and in tests, never in a feature, so tests can hand the app any database. Features never read the environment either. [`hono-bento check`](/docs/layout#enforce-it-with-hono-bento-check) enforces both. - **Storage models never reach a response.** The store maps each row to its `@todos/schemas` shape, so renaming a column can't change the API by accident. `respond` only accepts the wire shape, so passing it a row (with its `Date`s) is a type error, and `validateResponses` checks every response at runtime. ## Error mapping [#error-mapping] ```ts import { mapPostgresError, mapPrismaError } from 'hono-bento/db'; mountSpecs(app, specs, { ..., mapError: [mapPrismaError, mapPostgresError] }); ``` | Mapper | Error | Response | | ------------------ | ------------------------------------------------------------- | -------------------------------------------- | | `mapPrismaError` | `P2025`: the record an update, delete or `…OrThrow` needed | `404 not_found` | | | `P2002`: unique constraint | `409 conflict`, code `unique_violation` | | | `P2003`: foreign key constraint | `409 conflict`, code `foreign_key_violation` | | `mapPostgresError` | SQLSTATE `23505`: unique violation | `409 conflict`, code `unique_violation` | | | `23503`: foreign key violation | `409 conflict`, code `foreign_key_violation` | | | `23502` (not null), `22P02` (malformed value, such as a UUID) | `400 invalid_request` | `mapPostgresError` works with anything on Postgres: `pg`, postgres.js, PGlite, and the ORMs built on them (Drizzle, Kysely, TypeORM, MikroORM). It looks through `error.cause`, since Drizzle wraps the driver's error. Neither mapper imports a database library. When it can, the `409` names the field in `param`, read from the error's metadata. Messages are generic: they never include SQL, constraint names or values. The original error still goes to your logger, as `cause`. With `P2025` mapped, a handler doesn't need to check that the record exists before updating or deleting it. Let the ORM throw. A `findUnique` returns `null` rather than throwing, so a `retrieve` handler still throws `HttpError.notFound` itself. ## Transactions [#transactions] A feature owns its operations, not its tables. When an operation changes rows that another feature serves, its store writes them through `deps.db` like any other row, and never imports the other feature. When the write touches more than one table, it runs in one transaction. In the example, deleting a project deletes its todos. The projects feature's store does both: ```ts title="features/projects/store.ts" fragment async remove(db: Database, owner: Owner, id: string): Promise { return db.$transaction(async (tx) => { const { count } = await tx.todo.deleteMany({ where: { projectId: id } }); await tx.project.delete({ where: { id, ...owner } }); return count; }); }, ``` The project's delete is scoped to the caller. For anyone else's project it throws `P2025`, the handler answers `404`, and the transaction rolls the todos back. The schema declares `onDelete: Restrict`, so the database refuses to orphan todos even if a store forgets them. Prisma's nested writes are atomic too: creating a project with `todos: { create: [...] }` inserts all or nothing, with no explicit transaction. Other ORMs have their own (`db.transaction()` in Drizzle and Kysely). Keep the transaction inside one store function, so a handler never holds one open. ## Testing [#testing] Because the app receives its database, a test builds the app with whichever database it wants. No module mocking is needed: ```ts title="features/todos/todos.test.ts" fragment import { createApp } from '../../app'; import { testDb } from '../../test-db'; const app = createApp({ db: testDb, log: false }); // Each test starts from an empty table. beforeEach(async () => { await testDb.todo.deleteMany(); }); ``` The example's tests run against Postgres: the server at `DATABASE_URL` when it's set (Docker locally, a service container in CI), else [PGlite](https://pglite.dev), Postgres compiled to WebAssembly, started in the test process and served on a local port, so a fresh clone runs every test with no Docker. Each test run gets **its own schema**. A test preload (`test-setup.ts`, wired up in `bunfig.toml`) creates and migrates `test__