# The layout (/docs/layout)

This layout is the main opinion in hono-bento. It comes in two shapes, with
the same rules. Only where the schemas and the database client live changes.

## One package [#one-package]

For an API on its own, everything lives in one package. The schemas get their
own folder, `src/schemas`, and code imports them by name, as
`#schemas/<feature>`, through a
[subpath import](https://nodejs.org/api/packages.html#subpath-imports) in
`package.json`. `hono-bento init` writes this shape.

<Files>
<Folder name="src" defaultOpen>
<Folder name="features" defaultOpen>
<Folder name="todos" defaultOpen>
<File name="spec.ts" />

<File name="list.ts" />

<File name="create.ts" />

<File name="store.ts" />

<File name="todos.test.ts" />
</Folder>
</Folder>

<Folder name="schemas" defaultOpen>
<File name="todos.ts" />
</Folder>

<File name="specs.ts" />

<File name="app.ts" />

<File name="deps.ts" />

<File name="db.ts" />

<File name="auth.ts" />

<File name="server.ts" />

<File name="structure.test.ts" />
</Folder>

<File name="hono-bento.config.ts" />

<File name="package.json" />

<File name="AGENTS.md" />
</Files>

```json title="package.json" fragment
{
  "imports": {
    "#schemas/*": "./src/schemas/*.ts",
    "#db": "./src/db.ts"
  }
}
```

## A monorepo [#a-monorepo]

When another app (a CLI, a web client, a second service) needs the schemas,
they move into a workspace package, and so does the database. Code imports
`@todos/schemas/<feature>` instead of `#schemas/<feature>`, and nothing else
changes. [Monorepo setup](/docs/monorepo#moving-from-one-package) has the
steps. The [example](https://github.com/bento-api/hono-bento/tree/main/examples/todos)
is shaped like this, and so is `hono-bento init --monorepo`:

<Files>
<Folder name="apps" defaultOpen>
<Folder name="api" defaultOpen>
<Folder name="src" defaultOpen>
<Folder name="features" defaultOpen>
<Folder name="todos" defaultOpen>
<File name="spec.ts" />

<File name="list.ts" />

<File name="create.ts" />

<File name="retrieve.ts" />

<File name="update.ts" />

<File name="delete.ts" />

<File name="store.ts" />

<File name="todos.test.ts" />
</Folder>

<Folder name="me">
<File name="spec.ts" />

<File name="retrieve.ts" />

<File name="me.test.ts" />
</Folder>
</Folder>

<File name="specs.ts" />

<File name="app.ts" />

<File name="deps.ts" />

<File name="auth.ts" />

<File name="server.ts" />

<File name="structure.test.ts" />
</Folder>
</Folder>

<Folder name="cli">
<Folder name="src">
<File name="client.ts" />
</Folder>
</Folder>
</Folder>

<Folder name="packages" defaultOpen>
<Folder name="schemas" defaultOpen>
<Folder name="src" defaultOpen>
<File name="todos.ts" />

<File name="me.ts" />
</Folder>
</Folder>

<Folder name="db">
<Folder name="prisma">
<File name="schema.prisma" />

<Folder name="migrations" />
</Folder>

<Folder name="src">
<File name="client.ts" />
</Folder>
</Folder>
</Folder>

<File name="AGENTS.md" />
</Files>

| Path                                   | What goes there                                                                                                                               |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `features/<feature>/spec.ts`           | The feature's routing table: each route's contract (auth, validation, responses). It exports `contracts` and `spec`, and holds no logic.      |
| `features/<feature>/<operation>.ts`    | One handler per route, named after the route's `operation`, typed from its contract.                                                          |
| `features/<feature>/store.ts`          | The feature's queries, as functions taking `deps.db`, mapping rows to schema objects. Private to the folder.                                  |
| `features/<feature>/<feature>.test.ts` | The feature's tests, calling the real app.                                                                                                    |
| `specs.ts`                             | The only list of features.                                                                                                                    |
| `app.ts`                               | Builds the app: `mountSpecs`, `/openapi.json`, docs.                                                                                          |
| `deps.ts`                              | The `Deps` every handler receives, such as `{ db }`, registered with hono-bento.                                                              |
| `auth.ts`                              | App-level code that features share: the identity type, strategies and authorizer.                                                             |
| `server.ts`                            | Connects to the database and starts the server: one of the only two places that connect (tests are the other).                                |
| `packages/schemas/src/<feature>.ts`    | The feature's Zod schemas and inferred types: its wire contract. In one package, `src/schemas/<feature>.ts`.                                  |
| `packages/db`                          | Storage models, migrations and the client (Prisma here; any ORM works). In one package, `src/db.ts`. See [Database](/docs/concepts/database). |

## The rules [#the-rules]

<Steps>
<Step>
**Each feature is a folder.** It lives at `features/<feature>/`, and its
`spec.ts` exports `contracts` and `spec`.
</Step>

<Step>
**Each route's handler lives in `<operation>.ts`**, declared with
`defineHandler<Session, typeof contracts.<operation>>`. The `create` route's
handler is in `create.ts`, the `retrieve` route's in `retrieve.ts`, and so on.
Custom operations work the same way: an `archive` route's handler goes in
`archive.ts`. The handler takes its types from its contract, so it never
restates them.
</Step>

<Step>
**`spec.ts` declares and never does.** It declares each route's contract,
imports the handlers, and joins them with `route()`. Logic goes in handler
files.
</Step>

<Step>
**Features are self-contained.** Nothing outside a feature imports its files,
except `specs.ts`, which imports each feature's `spec.ts`. Features never
import each other. When two features need the same code, it moves up to the
app level (like `auth.ts`) or into a package.
</Step>

<Step>
**Schemas stand apart.** A feature's schemas live in `<feature>.ts` in the
schemas folder (`src/schemas`) or package (`packages/schemas`), and are
imported by name (`#schemas/todos` or `@todos/schemas/todos`), never by path.
They import nothing but Zod and `hono-bento/zod`, so they can move from one to
the other, or be shared with another app, unchanged.
</Step>

<Step>
**`specs.ts` is the only list.** It's passed to `mountSpecs` and to
`generateOpenApiDocument`. Never mount a router or list a spec anywhere else.
</Step>

<Step>
**Features reach the database through `deps`.** Handlers use `deps.db`, and
files in `features/` import only types from the db package. Each feature's
`store.ts` maps rows to its schema objects, so storage models never reach a
response.
</Step>
</Steps>

## Why these rules [#why-these-rules]

- **The blast radius of a change is the folder.** If a feature only changes
  inside its folder, you can review it, revert it or delete it in one place.
- **File names are an index.** To find the code behind `PATCH /v1/todos/:id`,
  open `features/todos/spec.ts`, find the route with `operation: 'update'`, and
  open `update.ts`. No search needed, which matters most for agents.
- **The contract can't fork.** When the server and its clients import the same
  schemas, a breaking change fails the typecheck in every app at once, not
  later in production.
- **Docs can't drift.** Routing and OpenAPI read the same `specs` list, so an
  undocumented route can't exist.

## Writing across features [#writing-across-features]

Features don't import each other, but their data can still meet:

- **One operation, several tables.** A store may read and write any model
  through `deps.db`. In the example, the projects feature's store deletes a
  project's todos with it, in one
  [transaction](/docs/concepts/database#transactions). The todos feature's
  store checks that a todo's `project` belongs to the caller. Neither imports
  the other.
- **Logic two features share** moves up to the app level, like `access.ts`,
  which scopes every query to the rows a caller may see (see
  [resource-level authorization](/docs/concepts/auth#resource-level-authorization)),
  or into a package.
- **Wire shapes stay with their feature.** The projects feature returns a
  `todo_count`, not todos, so it never needs the todos feature's mapper. A
  response that embeds another feature's object imports that schema from the
  schemas, which any feature may do.

## Enforce it with `hono-bento check` [#enforce-it-with-hono-bento-check]

hono-bento checks these rules for you: the layout above, the contracts
(each keyed by its `operation`, used by exactly one route, with a `summary`
and a documented success schema), and the data access (features import only
types from the database package, and only in `store.ts`, and never read the
environment). It reads your source with a real parser
([oxc-parser](https://oxc.rs), an optional peer dependency), so a string, a
comment or a regex literal is never mistaken for code. Each finding says what
to change:

```txt
src/specs.ts feature-spec: Add `import { spec as billing } from './features/billing/spec'` and list it in `specs`.
src/features/billing/create.ts handler-file: Put the handler for POST /v1/billing/ in this file.
src/features/todos/list.ts:4 db-imports: Only store.ts works with the database's types. Move this into store.ts, and have it return the wire types from the schemas.
src/features/billing/spec.ts:12 public-reason: Say why anyone may call this route, in a `// public: <reason>` comment on the line above.
```

Install the parser next to hono-bento, as a dev dependency:

```npm
npm install -D oxc-parser
```

Tell it where things are in `hono-bento.config.ts`, next to the app's `src/`:

```ts title="apps/api/hono-bento.config.ts"
import { defineConfig } from 'hono-bento/check';

export default defineConfig({
  schemas: { dir: '../../packages/schemas/src', package: '@todos/schemas' },
  db: { package: '@todos/db' },
});
```

In one package, the schemas and the database are subpath imports:

```ts title="hono-bento.config.ts" fragment
import { defineConfig } from 'hono-bento/check';

export default defineConfig({
  schemas: { dir: 'src/schemas', package: '#schemas' },
  db: { package: '#db' },
});
```

Then run it in your tests, so it fails with everything else:

```ts title="apps/api/src/structure.test.ts"
import { expect, it } from 'bun:test';
import { join } from 'node:path';

import { check, formatFinding } from 'hono-bento/check';

import config from '../hono-bento.config';

it('follows the hono-bento rules', async () => {
  const findings = await check(config, { root: join(import.meta.dir, '..') });
  expect(findings.map(formatFinding)).toEqual([]);
});
```

Or from the command line: `bun --bun hono-bento check` in the app's folder,
and `hono-bento check --rules` to list the rules. It imports your spec and
handler modules to read the real routes, so it needs a runtime that runs your
TypeScript.

`mountSpecs` adds a runtime check on top: it throws at startup if two routes
share a method and path, or share an operation id.

## Variations [#variations]

- **Features that only belong to one app**, like an internal admin endpoint,
  can still keep their schemas in the package. Mark the spec or route
  `private: true` to leave it out of the public OpenAPI document.
- **Bigger features** can have subfolders, such as `features/billing/lib/`.
  The boundary rule applies to the whole folder.
- **Grouping.** Set `group` on specs to split the OpenAPI output by audience
  with `generateOpenApiDocumentsByGroup`.