docs(website): align guides with router behavior

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-02 21:11:08 -05:00
1 parent 934fbd4c19
commit fcd3df7022
11 files changed
+63 -30

No files matched your search

+2
View File
@@ -7,6 +7,8 @@ export default defineConfig({
base: '/docs',
integrations: [
starlight({
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
disable404Route: true,
title: 'Green Tea.',
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
+11
View File
@@ -0,0 +1,11 @@
---
title: Page not found
description: "The requested Green Tea documentation page does not exist."
template: splash
hero:
tagline: The documentation page you requested could not be found.
actions:
- text: Back to documentation
link: /docs/
icon: right-arrow
---
+3 -3
View File
@@ -46,12 +46,12 @@ throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
```typescript
import { isHttpError } from '@green-tea/core';
import { HttpError } from '@green-tea/core';
const app = createApp({
modules: [ApiModule],
onError(error, req) {
const status = isHttpError(error) ? error.status : 500;
const status = error instanceof HttpError ? error.status : 500;
// negotiate: HTML for browsers, JSON for API clients
if (String(req.headers.accept).includes('text/html')) {
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
@@ -61,7 +61,7 @@ const app = createApp({
});
```
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
:::note
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
+2 -2
View File
@@ -67,7 +67,7 @@ Same filesystem requirement as file mode: Node/Deno/Bun only.
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`
handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
handler: a 500 `TransportMismatchError`, not a silent raw stream.
:::
@@ -145,7 +145,7 @@ Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/
@Html
ticks() { /* ... */ }
// throws at createApp(): "@Html on GET /ticks is not allowed —
// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)"
// @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)"
```
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
+5 -5
View File
@@ -94,17 +94,17 @@ Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not
## One teapot per route
A route must be exported by exactly **one** teapot. If two export the same `method + pattern`, the boot **fails**, naming the route and both teapots:
A route must be exported by exactly **one** teapot. If two export the same method and effective match shape — including patterns that differ only by parameter name, such as `/:id` and `/:name` — boot **fails**, naming both patterns and both teapots:
```
mesh: route 'GET /api/svc/ping' is exported by more than one teapot
(ws://a/__mesh__/control and ws://b/__mesh__/control) — load balancing across
teapots is not implemented yet, so green-tea will not choose one for you.
mesh: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
across teapots is not implemented yet, so green-tea will not choose one for you.
```
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
**Local routes win.** If you declare a route locally *and* import it from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
**Local routes win.** If you declare a route locally *and* import the same effective method/shape from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
```
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
+4 -2
View File
@@ -15,14 +15,16 @@ const spec = app.openapi({ title: 'My API', version: '1.0.0' });
It reads the routes and handler signatures and produces, for each route:
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`;
- the **method**;
- the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
- the **explicitly declared method**, including `@Head` and `@Options`;
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
- a **request body** entry for routes that read `@body()`;
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
WebSocket routes are omitted (they aren't request/response).
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
## Serve it — `devOpenapi`
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
+23 -13
View File
@@ -1,6 +1,6 @@
---
title: Routing
description: "Route patterns, the catch-all, specificity precedence, and 405 handling."
description: "Route constraints, specificity, HEAD and OPTIONS semantics, and path validation."
---
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
@@ -9,7 +9,7 @@ Routes are declared with method decorators on a `@Route`-prefixed controller. Pa
| Decorator | Method / transport |
|---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | buffered HTTP response |
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
| `@Sse` | server-sent events (`text/event-stream`) |
| `@Ws` | WebSocket duplex |
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
@@ -28,37 +28,47 @@ The path a route matches is `joinPath(module.mountpoint, route.path)` — a cont
- **Static** — `users` matches exactly.
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
```typescript
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
```
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
## Precedence
When more than one route matches the same path, the **most specific wins** — `static ▸ :param ▸ catch-all` — compared segment by segment, **independent of registration order**. Genuine ties (two equally-specific patterns) fall back to registration order.
When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
```typescript
@Get('/a/b') // wins for /a/b
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
@Get('/a/:id') // wins for /a/x
@Get('/a/:rest*') // wins for /a/x/y
```
## 404 vs 405
Two routes under the same method cannot have the same effective shape: `/users/:id` and `/users/:name` are ambiguous and make boot fail with both declarations named. The same rule applies after mesh routes join. Different methods may reuse a shape.
## HEAD and OPTIONS
An explicit `@Head` or `@Options` route always wins. Without an explicit HEAD route, HEAD falls back to a matching **buffered** GET handler, preserves its status and headers, and suppresses the body. Streaming GET routes do not become implicit HEAD routes.
Without an explicit OPTIONS route, OPTIONS on an existing path returns `204` with a canonical `Allow` header. GET implies HEAD, and any existing path implies OPTIONS, so a GET/POST path reports `GET, HEAD, POST, OPTIONS`. A CORS preflight (OPTIONS with `Access-Control-Request-Method`) is handled before explicit or automatic OPTIONS when CORS is configured.
## Path policy and 404 vs 405
`/path` and `/path/` are equivalent. Repeated slashes such as `/path//item` are rejected rather than collapsed, and malformed percent encoding is rejected; both return `400 Bad Request` with the configured security/CORS headers. Query strings do not participate in route matching.
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
:::note
A bare `OPTIONS` request (without an `Access-Control-Request-Method` header — i.e. not a CORS preflight) to an existing path therefore returns `405` with `Allow`. CORS preflights are handled separately; see [Transport security](/docs/guides/security/).
:::
## Matcher scale
## Not yet
The matcher is intentionally small for beta. **Not built** (on the roadmap):
- Regex / typed param constraints such as `:id(\d+)`.
- Route matching is a **linear scan** — fine for typical route tables, but a radix-tree matcher for very large ones isn't implemented.
Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
+3 -1
View File
@@ -44,7 +44,9 @@ const app = createApp({
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204.
request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
route or the router's automatic `204` + `Allow` response.
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
+1 -1
View File
@@ -109,7 +109,7 @@ A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never
| Declare | Handler must return | Otherwise |
|---|---|---|
| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
| `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
@@ -28,6 +28,7 @@ const app = createApp(options);
| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/docs/guides/html/)) |
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
| `warnGraphDepth` | `number \| false` | `20` | warn when one route resolves to more than this many steps; `false` disables the design warning |
### `RequestLimits`
@@ -63,14 +64,17 @@ const app = createApp(options);
|---|---|---|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
| `ready()` | `Promise<void>` | resolves the graph and mesh links without booting providers |
| `fetch(request)` | `Promise<Response>` | Web-Standards HTTP/SSE handler for Node, Deno, Bun, and edge |
| `upgrade(request, socket)` | `Promise<void>` | neutral WebSocket upgrade used by non-Node adapters |
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
| `graph()` | `GraphView` | the full node + route graph |
| `toMermaid()` / `toDOT()` | `string` | render the graph |
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) |
| `degraded()` | `string[]` | optional providers running degraded (empty until providers boot through `fetch`, `upgrade`, or `listen`) |
| `bus` | `Bus` | lifecycle + request event bus |
:::note
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available **after** `listen()` — the graph is finalized once remote scopes connect.
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available after `ready()` or the first serving call — the graph is finalized once remote scopes connect.
:::
@@ -64,7 +64,7 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
| Decorator | Method | Transport |
|---|---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response |
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | as named | buffered response |
| `@Sse` | GET | `text/event-stream` |
| `@Ws` | GET | WebSocket duplex |
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
@@ -77,6 +77,8 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
`@Head` and `@Options` declare explicit handlers. When they are absent, the router can provide an implicit buffered-GET HEAD response or an automatic `204` OPTIONS response; those fallbacks are runtime behavior, not decorator metadata.
## Arguments
A handler's signature declares exactly what it wants, in any order.